text stringlengths 14 6.51M |
|---|
unit UFrmConfig;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, System.Win.Registry,
Vcl.FileCtrl, ShellAPI, Vcl.Menus, Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnPopup, Vcl.ComCtrls, Vcl.Buttons;
type
TFrmConfig = class(TForm)
PopActionBar: TPopupActionBar;
PA_DeletDir: TMenuItem;
PM_AddDir: TMenuItem;
LVDir: TListView;
LblTxtEditors: TLabel;
BtnApply: TButton;
edTxtEditor: TEdit;
SpBtnOpenDlg: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure BtnApplyOnClick(Sender: TObject);
procedure AddDirToList;
procedure SaveDirToRegistry;
procedure ReadDirListFromRegistry;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure PA_DeletDirClick(Sender: TObject);
procedure PM_AddDirClick(Sender: TObject);
procedure SpBtnOpenDlgClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmConfig: TFrmConfig;
Reg: TRegistry;
Dir: string;
st: TStrings;
NewItem: TListItem;
i: integer;
const
SELDIRHELP = 1000;
implementation
Uses UFrmMain;
{$R *.dfm}
procedure TFrmConfig.AddDirToList;
var
Options: TSelectDirExtOpts;
ChosenDirectory: String;
begin
Options := [sdShowShares, sdNewUI];
if Not SelectDirectory('Укажите директорию', '', ChosenDirectory, Options, Nil) then Exit;
if ChosenDirectory = '' then Exit;
for i := 0 to LVDir.Items.Count - 1 do
begin
if LVDir.Items[i].Caption = ChosenDirectory then
begin
MessageBox(Handle,
PChar('Такая директория уже существует в списке.'),
PChar(MB_CAPTION), MB_ICONINFORMATION);
Exit;
end;
end;
NewItem := LVDir.Items.Add;
NewItem.Caption := ChosenDirectory;
NewItem.ImageIndex := 0;
NewItem.Checked := True;
end;
procedure TFrmConfig.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ReadDirListFromRegistry;
end;
procedure TFrmConfig.FormCreate(Sender: TObject);
begin
// ReadSettings;
ReadDirListFromRegistry;
FrmMain.UpdateCbBoxDirList;
end;
procedure TFrmConfig.BtnApplyOnClick(Sender: TObject);
begin
SaveDirToRegistry;
MessageBox(Handle, PChar('Праметры были успешно сохранены.'),
PChar(MB_CAPTION), MB_ICONINFORMATION);
Close;
end;
procedure TFrmConfig.PA_DeletDirClick(Sender: TObject);
begin
if MessageBox(Handle,
PChar('Вы действительно хотите удалить выделенные директории?' + #13#10 +
'Для удаления нажмите ДА, для отмены Нет.'), PChar(MB_CAPTION),
MB_YESNO or MB_ICONWARNING) = ID_NO Then
Exit;
LVDir.DeleteSelected;
end;
procedure TFrmConfig.PM_AddDirClick(Sender: TObject);
begin
AddDirToList;
end;
procedure TFrmConfig.ReadDirListFromRegistry;
begin
LVDir.Clear;
try
st := TStringList.Create;
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\Software\CryptoNote\CryptoDirectories', false) then
begin
Reg.GetValueNames(st);
if st.Count = 0 then Exit;
for i := 0 to st.Count - 1 do
begin
NewItem := LVDir.Items.Add;
NewItem.Caption := st.Strings[i];
NewItem.ImageIndex := 0;
NewItem.Checked := Reg.ReadBool(st.Strings[i]);
end;
Reg.CloseKey;
end;
if Reg.OpenKey('\Software\CryptoNote', True) then
begin
edTxtEditor.Text := Reg.ReadString('OldTxtEditor');
Reg.CloseKey;
end;
finally
st.Free;
Reg.Free;
end;
end;
procedure TFrmConfig.SaveDirToRegistry;
begin
if LVDir.Items.Count = 0 then Exit;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
Reg.DeleteKey('\Software\CryptoNote\CryptoDirectories');
if Reg.OpenKey('\Software\CryptoNote\CryptoDirectories', True) then
begin
for i := 0 to LVDir.Items.Count - 1 do
Reg.WriteBool(LVDir.Items[i].Caption, LVDir.Items[i].Checked);
Reg.CloseKey;
end;
if Reg.OpenKey('\Software\CryptoNote', True) then
begin
Reg.WriteString('OldTxtEditor', edTxtEditor.Text);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure TFrmConfig.SpBtnOpenDlgClick(Sender: TObject);
begin
FrmMain.OpenDialog.Filter := 'EXE File (*.exe)|*.exe';
end;
end.
|
{************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 2009/8/23 16:24:12 }
{ Generated from: F:\Projects\WAPMail..CC\bin\WebConfig.xml }
{ Settings stored in: F:\Projects\WAPMail..CC\bin\WebConfig.xdb }
{ }
{************************************************************************}
unit WebConfig;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLConfigurationType = interface;
IXMLAppSettingsType = interface;
IXMLAddType = interface;
IXMLConnectionStringsType = interface;
IXMLSystemwebType = interface;
IXMLCompilationType = interface;
IXMLAssembliesType = interface;
IXMLAuthenticationType = interface;
IXMLCustomErrorsType = interface;
IXMLSessionStateType = interface;
{ IXMLConfigurationType }
IXMLConfigurationType = interface(IXMLNode)
['{C2EE29E8-0D57-42A7-AADF-9AB9B0B8E278}']
{ Property Accessors }
function Get_AppSettings: IXMLAppSettingsType;
function Get_ConnectionStrings: IXMLConnectionStringsType;
function Get_Systemweb: IXMLSystemwebType;
{ Methods & Properties }
property AppSettings: IXMLAppSettingsType read Get_AppSettings;
property ConnectionStrings: IXMLConnectionStringsType read Get_ConnectionStrings;
property Systemweb: IXMLSystemwebType read Get_Systemweb;
end;
{ IXMLAppSettingsType }
IXMLAppSettingsType = interface(IXMLNodeCollection)
['{5EC536BF-78DB-4ADB-8278-797A9F52F21A}']
{ Property Accessors }
function Get_Add(Index: Integer): IXMLAddType;
{ Methods & Properties }
function Add: IXMLAddType;
function Insert(const Index: Integer): IXMLAddType;
property Add[Index: Integer]: IXMLAddType read Get_Add; default;
end;
{ IXMLAddType }
IXMLAddType = interface(IXMLNode)
['{E9ED491C-084E-404E-BE3E-DED3DFEBF053}']
{ Property Accessors }
function Get_Key: WideString;
function Get_Value: WideString;
function Get_Name: WideString;
function Get_ConnectionString: WideString;
function Get_ProviderName: WideString;
function Get_Assembly: WideString;
procedure Set_Key(Value: WideString);
procedure Set_Value(Value: WideString);
procedure Set_Name(Value: WideString);
procedure Set_ConnectionString(Value: WideString);
procedure Set_ProviderName(Value: WideString);
procedure Set_Assembly(Value: WideString);
{ Methods & Properties }
property Key: WideString read Get_Key write Set_Key;
property Value: WideString read Get_Value write Set_Value;
property Name: WideString read Get_Name write Set_Name;
property ConnectionString: WideString read Get_ConnectionString write Set_ConnectionString;
property ProviderName: WideString read Get_ProviderName write Set_ProviderName;
property Assembly: WideString read Get_Assembly write Set_Assembly;
end;
{ IXMLConnectionStringsType }
IXMLConnectionStringsType = interface(IXMLNode)
['{077B8DCC-90DC-4392-ABEF-A39C5D066A14}']
{ Property Accessors }
function Get_Add: IXMLAddType;
{ Methods & Properties }
property Add: IXMLAddType read Get_Add;
end;
{ IXMLSystemwebType }
IXMLSystemwebType = interface(IXMLNode)
['{29EF1FB7-F650-4E0E-A24E-EE70916D0FCE}']
{ Property Accessors }
function Get_Compilation: IXMLCompilationType;
function Get_Authentication: IXMLAuthenticationType;
function Get_CustomErrors: IXMLCustomErrorsType;
function Get_SessionState: IXMLSessionStateType;
{ Methods & Properties }
property Compilation: IXMLCompilationType read Get_Compilation;
property Authentication: IXMLAuthenticationType read Get_Authentication;
property CustomErrors: IXMLCustomErrorsType read Get_CustomErrors;
property SessionState: IXMLSessionStateType read Get_SessionState;
end;
{ IXMLCompilationType }
IXMLCompilationType = interface(IXMLNode)
['{58D1D7D6-1F89-4A06-A2E7-184F164A5A1B}']
{ Property Accessors }
function Get_Debug: WideString;
function Get_Assemblies: IXMLAssembliesType;
procedure Set_Debug(Value: WideString);
{ Methods & Properties }
property Debug: WideString read Get_Debug write Set_Debug;
property Assemblies: IXMLAssembliesType read Get_Assemblies;
end;
{ IXMLAssembliesType }
IXMLAssembliesType = interface(IXMLNodeCollection)
['{39BBE2C9-6B83-4B0C-98EC-C6D3282E2912}']
{ Property Accessors }
function Get_Add(Index: Integer): IXMLAddType;
{ Methods & Properties }
function Add: IXMLAddType;
function Insert(const Index: Integer): IXMLAddType;
property Add[Index: Integer]: IXMLAddType read Get_Add; default;
end;
{ IXMLAuthenticationType }
IXMLAuthenticationType = interface(IXMLNode)
['{17EF1923-EB11-45B4-AB73-93A78C101C8E}']
{ Property Accessors }
function Get_Mode: WideString;
procedure Set_Mode(Value: WideString);
{ Methods & Properties }
property Mode: WideString read Get_Mode write Set_Mode;
end;
{ IXMLCustomErrorsType }
IXMLCustomErrorsType = interface(IXMLNode)
['{6DC96564-F03E-43D2-8164-696D9B639CF5}']
{ Property Accessors }
function Get_Mode: WideString;
function Get_DefaultRedirect: WideString;
procedure Set_Mode(Value: WideString);
procedure Set_DefaultRedirect(Value: WideString);
{ Methods & Properties }
property Mode: WideString read Get_Mode write Set_Mode;
property DefaultRedirect: WideString read Get_DefaultRedirect write Set_DefaultRedirect;
end;
{ IXMLSessionStateType }
IXMLSessionStateType = interface(IXMLNode)
['{7797E719-6658-4224-B6FE-FA6931010130}']
{ Property Accessors }
function Get_Timeout: Integer;
procedure Set_Timeout(Value: Integer);
{ Methods & Properties }
property Timeout: Integer read Get_Timeout write Set_Timeout;
end;
{ Forward Decls }
TXMLConfigurationType = class;
TXMLAppSettingsType = class;
TXMLAddType = class;
TXMLConnectionStringsType = class;
TXMLSystemwebType = class;
TXMLCompilationType = class;
TXMLAssembliesType = class;
TXMLAuthenticationType = class;
TXMLCustomErrorsType = class;
TXMLSessionStateType = class;
{ TXMLConfigurationType }
TXMLConfigurationType = class(TXMLNode, IXMLConfigurationType)
protected
{ IXMLConfigurationType }
function Get_AppSettings: IXMLAppSettingsType;
function Get_ConnectionStrings: IXMLConnectionStringsType;
function Get_Systemweb: IXMLSystemwebType;
public
procedure AfterConstruction; override;
end;
{ TXMLAppSettingsType }
TXMLAppSettingsType = class(TXMLNodeCollection, IXMLAppSettingsType)
protected
{ IXMLAppSettingsType }
function Get_Add(Index: Integer): IXMLAddType;
function Add: IXMLAddType;
function Insert(const Index: Integer): IXMLAddType;
public
procedure AfterConstruction; override;
end;
{ TXMLAddType }
TXMLAddType = class(TXMLNode, IXMLAddType)
protected
{ IXMLAddType }
function Get_Key: WideString;
function Get_Value: WideString;
function Get_Name: WideString;
function Get_ConnectionString: WideString;
function Get_ProviderName: WideString;
function Get_Assembly: WideString;
procedure Set_Key(Value: WideString);
procedure Set_Value(Value: WideString);
procedure Set_Name(Value: WideString);
procedure Set_ConnectionString(Value: WideString);
procedure Set_ProviderName(Value: WideString);
procedure Set_Assembly(Value: WideString);
end;
{ TXMLConnectionStringsType }
TXMLConnectionStringsType = class(TXMLNode, IXMLConnectionStringsType)
protected
{ IXMLConnectionStringsType }
function Get_Add: IXMLAddType;
public
procedure AfterConstruction; override;
end;
{ TXMLSystemwebType }
TXMLSystemwebType = class(TXMLNode, IXMLSystemwebType)
protected
{ IXMLSystemwebType }
function Get_Compilation: IXMLCompilationType;
function Get_Authentication: IXMLAuthenticationType;
function Get_CustomErrors: IXMLCustomErrorsType;
function Get_SessionState: IXMLSessionStateType;
public
procedure AfterConstruction; override;
end;
{ TXMLCompilationType }
TXMLCompilationType = class(TXMLNode, IXMLCompilationType)
protected
{ IXMLCompilationType }
function Get_Debug: WideString;
function Get_Assemblies: IXMLAssembliesType;
procedure Set_Debug(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLAssembliesType }
TXMLAssembliesType = class(TXMLNodeCollection, IXMLAssembliesType)
protected
{ IXMLAssembliesType }
function Get_Add(Index: Integer): IXMLAddType;
function Add: IXMLAddType;
function Insert(const Index: Integer): IXMLAddType;
public
procedure AfterConstruction; override;
end;
{ TXMLAuthenticationType }
TXMLAuthenticationType = class(TXMLNode, IXMLAuthenticationType)
protected
{ IXMLAuthenticationType }
function Get_Mode: WideString;
procedure Set_Mode(Value: WideString);
end;
{ TXMLCustomErrorsType }
TXMLCustomErrorsType = class(TXMLNode, IXMLCustomErrorsType)
protected
{ IXMLCustomErrorsType }
function Get_Mode: WideString;
function Get_DefaultRedirect: WideString;
procedure Set_Mode(Value: WideString);
procedure Set_DefaultRedirect(Value: WideString);
end;
{ TXMLSessionStateType }
TXMLSessionStateType = class(TXMLNode, IXMLSessionStateType)
protected
{ IXMLSessionStateType }
function Get_Timeout: Integer;
procedure Set_Timeout(Value: Integer);
end;
{ Global Functions }
function Getconfiguration(Doc: IXMLDocument): IXMLConfigurationType;
function Loadconfiguration(const FileName: WideString): IXMLConfigurationType;
function Newconfiguration: IXMLConfigurationType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function Getconfiguration(Doc: IXMLDocument): IXMLConfigurationType;
begin
Result := Doc.GetDocBinding('configuration', TXMLConfigurationType, TargetNamespace) as IXMLConfigurationType;
end;
function Loadconfiguration(const FileName: WideString): IXMLConfigurationType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('configuration', TXMLConfigurationType, TargetNamespace) as IXMLConfigurationType;
end;
function Newconfiguration: IXMLConfigurationType;
begin
Result := NewXMLDocument.GetDocBinding('configuration', TXMLConfigurationType, TargetNamespace) as IXMLConfigurationType;
end;
{ TXMLConfigurationType }
procedure TXMLConfigurationType.AfterConstruction;
begin
RegisterChildNode('appSettings', TXMLAppSettingsType);
RegisterChildNode('connectionStrings', TXMLConnectionStringsType);
RegisterChildNode('system.web', TXMLSystemwebType);
inherited;
end;
function TXMLConfigurationType.Get_AppSettings: IXMLAppSettingsType;
begin
Result := ChildNodes['appSettings'] as IXMLAppSettingsType;
end;
function TXMLConfigurationType.Get_ConnectionStrings: IXMLConnectionStringsType;
begin
Result := ChildNodes['connectionStrings'] as IXMLConnectionStringsType;
end;
function TXMLConfigurationType.Get_Systemweb: IXMLSystemwebType;
begin
Result := ChildNodes['system.web'] as IXMLSystemwebType;
end;
{ TXMLAppSettingsType }
procedure TXMLAppSettingsType.AfterConstruction;
begin
RegisterChildNode('add', TXMLAddType);
ItemTag := 'add';
ItemInterface := IXMLAddType;
inherited;
end;
function TXMLAppSettingsType.Get_Add(Index: Integer): IXMLAddType;
begin
Result := List[Index] as IXMLAddType;
end;
function TXMLAppSettingsType.Add: IXMLAddType;
begin
Result := AddItem(-1) as IXMLAddType;
end;
function TXMLAppSettingsType.Insert(const Index: Integer): IXMLAddType;
begin
Result := AddItem(Index) as IXMLAddType;
end;
{ TXMLAddType }
function TXMLAddType.Get_Key: WideString;
begin
Result := AttributeNodes['key'].Text;
end;
procedure TXMLAddType.Set_Key(Value: WideString);
begin
SetAttribute('key', Value);
end;
function TXMLAddType.Get_Value: WideString;
begin
Result := AttributeNodes['value'].Text;
end;
procedure TXMLAddType.Set_Value(Value: WideString);
begin
SetAttribute('value', Value);
end;
function TXMLAddType.Get_Name: WideString;
begin
Result := AttributeNodes['name'].Text;
end;
procedure TXMLAddType.Set_Name(Value: WideString);
begin
SetAttribute('name', Value);
end;
function TXMLAddType.Get_ConnectionString: WideString;
begin
Result := AttributeNodes['connectionString'].Text;
end;
procedure TXMLAddType.Set_ConnectionString(Value: WideString);
begin
SetAttribute('connectionString', Value);
end;
function TXMLAddType.Get_ProviderName: WideString;
begin
Result := AttributeNodes['providerName'].Text;
end;
procedure TXMLAddType.Set_ProviderName(Value: WideString);
begin
SetAttribute('providerName', Value);
end;
function TXMLAddType.Get_Assembly: WideString;
begin
Result := AttributeNodes['assembly'].Text;
end;
procedure TXMLAddType.Set_Assembly(Value: WideString);
begin
SetAttribute('assembly', Value);
end;
{ TXMLConnectionStringsType }
procedure TXMLConnectionStringsType.AfterConstruction;
begin
RegisterChildNode('add', TXMLAddType);
inherited;
end;
function TXMLConnectionStringsType.Get_Add: IXMLAddType;
begin
Result := ChildNodes['add'] as IXMLAddType;
end;
{ TXMLSystemwebType }
procedure TXMLSystemwebType.AfterConstruction;
begin
RegisterChildNode('compilation', TXMLCompilationType);
RegisterChildNode('authentication', TXMLAuthenticationType);
RegisterChildNode('customErrors', TXMLCustomErrorsType);
RegisterChildNode('sessionState', TXMLSessionStateType);
inherited;
end;
function TXMLSystemwebType.Get_Compilation: IXMLCompilationType;
begin
Result := ChildNodes['compilation'] as IXMLCompilationType;
end;
function TXMLSystemwebType.Get_Authentication: IXMLAuthenticationType;
begin
Result := ChildNodes['authentication'] as IXMLAuthenticationType;
end;
function TXMLSystemwebType.Get_CustomErrors: IXMLCustomErrorsType;
begin
Result := ChildNodes['customErrors'] as IXMLCustomErrorsType;
end;
function TXMLSystemwebType.Get_SessionState: IXMLSessionStateType;
begin
Result := ChildNodes['sessionState'] as IXMLSessionStateType;
end;
{ TXMLCompilationType }
procedure TXMLCompilationType.AfterConstruction;
begin
RegisterChildNode('assemblies', TXMLAssembliesType);
inherited;
end;
function TXMLCompilationType.Get_Debug: WideString;
begin
Result := AttributeNodes['debug'].Text;
end;
procedure TXMLCompilationType.Set_Debug(Value: WideString);
begin
SetAttribute('debug', Value);
end;
function TXMLCompilationType.Get_Assemblies: IXMLAssembliesType;
begin
Result := ChildNodes['assemblies'] as IXMLAssembliesType;
end;
{ TXMLAssembliesType }
procedure TXMLAssembliesType.AfterConstruction;
begin
RegisterChildNode('add', TXMLAddType);
ItemTag := 'add';
ItemInterface := IXMLAddType;
inherited;
end;
function TXMLAssembliesType.Get_Add(Index: Integer): IXMLAddType;
begin
Result := List[Index] as IXMLAddType;
end;
function TXMLAssembliesType.Add: IXMLAddType;
begin
Result := AddItem(-1) as IXMLAddType;
end;
function TXMLAssembliesType.Insert(const Index: Integer): IXMLAddType;
begin
Result := AddItem(Index) as IXMLAddType;
end;
{ TXMLAuthenticationType }
function TXMLAuthenticationType.Get_Mode: WideString;
begin
Result := AttributeNodes['mode'].Text;
end;
procedure TXMLAuthenticationType.Set_Mode(Value: WideString);
begin
SetAttribute('mode', Value);
end;
{ TXMLCustomErrorsType }
function TXMLCustomErrorsType.Get_Mode: WideString;
begin
Result := AttributeNodes['mode'].Text;
end;
procedure TXMLCustomErrorsType.Set_Mode(Value: WideString);
begin
SetAttribute('mode', Value);
end;
function TXMLCustomErrorsType.Get_DefaultRedirect: WideString;
begin
Result := AttributeNodes['defaultRedirect'].Text;
end;
procedure TXMLCustomErrorsType.Set_DefaultRedirect(Value: WideString);
begin
SetAttribute('defaultRedirect', Value);
end;
{ TXMLSessionStateType }
function TXMLSessionStateType.Get_Timeout: Integer;
begin
Result := AttributeNodes['timeout'].NodeValue;
end;
procedure TXMLSessionStateType.Set_Timeout(Value: Integer);
begin
SetAttribute('timeout', Value);
end;
end. |
unit Domain.Entity.Veiculo;
interface
uses
System.Classes, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types,
EF.Mapping.Atributes, Domain.Consts;
type
[Table('Veiculos')]
TVeiculo = class( TEntityBase )
private
FPlaca: TString;
FClienteId: TInteger;
public
published
[Column('Placa',varchar10,false)]
property Placa: TString read FPlaca write FPlaca;
[Column('ClienteId',Int,true)]
[ForeignKey('ClienteId','Clientes', rlCascade, rlCascade )]
property ClienteId: TInteger read FClienteId write FClienteId;
end;
implementation
{ TVeiculo }
initialization RegisterClass(TVeiculo);
finalization UnRegisterClass(TVeiculo);
end.
|
{ DO NOT USE THIS UNIT IF YOU INTEND TO USE HARDWARE FLOATING
POINT. This unit is "fast" only if you use software floating
point operations. With Hardware floating point, use NRAND1.PAS.
For software floating point, NRAND1 takes 2.3 times as long
as NRAND0. Recommended directives: N+,E+. }
unit nrand0;
{ fast implementations of exponential, cauchy, and normal
random variate generators }
{ Copyright, 1988, by J. W. Rider }
{ Based upon algorithms found in J. H. Ahrens and U. Dieter,
"Efficient Table-Free Sampling Methods for Exponential,
Cauchy, and Normal Distributions", Communications of the ACM,
vol 31, no 11, NOV 88, pp 1330-1337. }
{ My "contribution" to this work consists only of translating
the A&D algorithms into Pascal. A&D would probably frown upon
this attempt; they seem to prefer writing their implementations
in assembly language. }
{ The normal generator uses the exponential and cauchy generators.
Those two CANNOT be eliminated from the unit implementation.
However, the functions could be eliminated from the interface
for applications where they are not needed. }
interface
function xrandom: real;
{ XRANDOM returns a exponentially distributed random variate.
The "conventional" practice is to implement it as
"xrandom:=-log(random);" }
function crandom(u:real): real;
{ CRANDOM returns a cauchy distributed random variate.
The "conventional" practice is to implement it as
"x:=pi*(random-0.5); crandom:=sin(x)/cos(x);" }
function nrandom: real;
{ NRANDOM returns a gaussian distributed random variate
with zero mean and unit variance. The "conventional"
practice is to implement a variation of the "Box-Muller"
or "sine-cosine" algorithm that generates pairs of
normal variates: "a:=sqrt(-2*log(random)); b:=random*2*pi;
nrandom:=a*sin(b)" followed by "nrandom:=a*cos(b)". Here,
NRANDOM is implemented as a "cauchy-exponential" algorithm:
"a:=xrandom; b:=crandom; nrandom:=sqrt(a/(1+b*b))" followed
by "nrandom:=b*sqrt(a/(1+b*b))" with care being taken to
determine the signs of variates randomly. }
{ The argument in crandom is should be set to a uniformly
distributed variate between 0 and 1. The rationale for
handling it this way is so that the nrandom can use an
extra bit for determining the sign of its variates. In
practice, the call should be "crandom(random)". }
implementation
{ In each of the function bodies, the "step" in the original
A&D algorithm is referenced at the beginning of the line.
This should permit easy comparison with the source material. }
var naf:boolean; { is there not a spare normal variate? }
nay:real; { spare normal variate }
function xrandom:real; { A&D algorithm EA }
const ln2 = 0.6931471805599453;
a1 = 5.7133631526454228;
b1 = 3.4142135623730950; { A&D article is wrong here ! }
c = -1.6734053240284925;
p = 0.9802581434685472;
a2 = 5.6005707569738080;
b2 = 3.3468106480569850;
h = 0.0026106723602095;
d = 0.0857864376269050;
var u,g,y,u2:real; begin
{ EA.1 } u:=random; g:=c;
{ EA.2 } u:=u+u; while u<1 do begin
{ EA.3 } g:=g+ln2;
{ EA.2 } u:=u+u; end;
{ EA.4 } u:=u-1; if u<=p then
{ EA.5 } xrandom:=g+a2/(b2-u)
else begin repeat
{ EA.6 } u:=random; y:=a1/(b1-u);
{ EA.7 } u2:=random;
{ EA.7 } until (u2*h+d)*(b1-u)*(b1-u)<=exp(-y-c);
{ EA.8 } xrandom:=g+y; end; end;
function crandom(u:real):real; { A&D algorithm CA }
const a1 = 0.6380631366077803;
b1 = 0.5959486060529070;
q = 0.9339962957603656;
w = 0.2488702280083841;
a2 = 0.6366197723675813;
b2 = 0.5972997593539963;
h = 0.0214949004570452;
p = 4.9125013953033204;
var t,s,u2,x:real; begin
{ CA.1 } { "u" is assumed to be a uniform random variate 0..1 }
{ CA.1 } t:=u-0.5; s:=w-t*t; if s>0 then
{ CA.2 } crandom:=t*(a2/s+b2)
else begin repeat
{ CA.3 } u:=random; t:=u-0.5; s:=0.25-t*t; x:=t*(a1/s+b1);
{ CA.4 } u2:=random;
{ CA.4 } until s*s*((1+x*x)*(h*u2+p)-q)+s <= 0.5;
{ CA.5 } crandom:=x; end; end;
function nrandom:real; { A&D algorithm NA }
var b:boolean; u,e,s,c,x:real; begin
{ NA.1 } naf:=not naf; if naf then nrandom:=nay
else begin
{ NA.2 } u:=random; b:=u<0.5;
{ NA.3 } e:=xrandom; s:=e+e;
{ NA.4 } if b then c:=crandom(u+u) else c:=crandom(u+u-1);
{ NA.5 } x:=sqrt(s/(1+c*c)); nay:=c*x;
{ NA.6 } if b then nrandom:=x else nrandom:= -x; end; end;
begin
{ NA.0 } naf:=true;
end. |
unit Classes.Calculos;
interface
type
TCalculo = class
public
class function ObtemValorImposto(ABaseCalculo, AAliquota: Currency)
: Currency;
class function CalculaSugestaoPrecoDeVenda(APrecoLitro, AValorImposto,
AMargem: Currency): Currency;
class function CalculaQuantidadesNaVenda(APreco: Currency; AQtd:Currency): Currency;
end;
implementation
{ TCalculo }
class function TCalculo.CalculaQuantidadesNaVenda(APreco: Currency;
AQtd: Currency): Currency;
begin
Result := APreco * AQtd;
end;
class function TCalculo.CalculaSugestaoPrecoDeVenda(APrecoLitro, AValorImposto,
AMargem: Currency): Currency;
var
vPrecoSugerido: Currency;
begin
vPrecoSugerido := (APrecoLitro + AValorImposto);
vPrecoSugerido := vPrecoSugerido + ((vPrecoSugerido*AMargem)/100);
Result := vPrecoSugerido;
end;
class function TCalculo.ObtemValorImposto(ABaseCalculo, AAliquota: Currency)
: Currency;
begin
Result := ((ABaseCalculo*AAliquota)/100);
end;
end.
|
unit smuFuncoesSistema;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, smuFuncoesBasico, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uQuery, aduna_ds_list,
uTypes, uEnviarEmail, uUtils, System.Generics.Collections, dmuPrincipal;
type
TsmFuncoesSistema = class(TsmFuncoesBasico)
qNotificacao_Pessoa: TRFQuery;
qNotificacao_PessoaID_PESSOA: TIntegerField;
qNotificacao_PessoaNOTIFICACAO_SISTEMA: TSmallintField;
qNotificacao_PessoaNOTIFICACAO_EMAIL: TSmallintField;
qNotificacao_PessoaEMAIL: TStringField;
private
function fpvVerificarNotificacoesAgendaPessoal(ipIdPessoa: integer; ipNotificacaoEmail, ipNotificacaoSistema: Boolean;
ipDataSetNotificacao, ipDataSetNotificacaoPessoa: TRFQuery): TList<TNotificacao>;
{ Private declarations }
public
function fpuValidarTipoNotificacao(ipIdNotificacao, ipTipo: integer): Boolean;
/// Verifica toda as notificações cadastradas
/// ipId - Se diferente de -1 significa que é para gerar a notificacação somente desse ID
/// ipIdPessoa - Se diferente de -1 significa que é para verificar somente as notificaões configuradas para essa pessoa
/// ipTipo - Tipo da Notificação a ser verificada. Informe -1 para verificar todas.
function fpuVerificarNotificacoes(ipId, ipIdPessoa: integer; ipTipo: integer; ipNotificacaoEmail, ipNotificacaoSistema: Boolean)
: TadsObjectlist<TNotificacao>;
procedure ppuCriarAgendaPessoal(ipIdPessoa: integer);
function fpuRegistrarAparelhoExterno(ipNome, ipIMEI: String): integer;
end;
var
smFuncoesSistema: TsmFuncoesSistema;
implementation
uses
smuFuncoesEstoque;
{$R *.dfm}
{ TsmFuncoesSistema }
function TsmFuncoesSistema.fpuVerificarNotificacoes(ipId, ipIdPessoa: integer; ipTipo: integer; ipNotificacaoEmail, ipNotificacaoSistema: Boolean)
: TadsObjectlist<TNotificacao>;
var
vaDataSetNotificacao, vaDataSet: TRFQuery;
vaNotificacao: TNotificacao;
vaNotificacoes: TList<TNotificacao>;
vaTipoNotificacao: TTipoNotificacao;
vaMsg: String;
procedure plEnviarEmails(ipTipo: TTipoNotificacao; ipMsg: String);
begin
if ipNotificacaoEmail then
begin
qNotificacao_Pessoa.First;
while not qNotificacao_Pessoa.Eof do
begin
if (qNotificacao_Pessoa.FieldByName('Notificacao_Email').AsInteger = 1) and
(qNotificacao_Pessoa.FieldByName('Email').AsString <> '') then
begin
ppuEnviarEmail(TiposNotificacao[ipTipo], ipMsg, qNotificacao_Pessoa.FieldByName('Email').AsString, '', nil);
end;
qNotificacao_Pessoa.next;
end;
end;
end;
procedure plVerificarContaPagarVencendo;
var
vaConta: TConta;
begin
vaDataSet.close;
vaDataSet.SQL.Text := 'select Conta_Pagar.Id,' +
' Conta_Pagar.Descricao || '' ('' || Conta_Pagar_Parcela.Parcela || ''/'' ||(select count(*)' +
' from Conta_Pagar_Parcela' +
' where Conta_Pagar_Parcela.Id_Conta_Pagar = Conta_Pagar.Id)||'')'' as Descricao, '
+
' Conta_Pagar_Parcela.Valor, ' +
' Conta_Pagar_Parcela.Vencimento ' +
' from Conta_Pagar_Parcela' +
' inner join Conta_Pagar on (Conta_Pagar_Parcela.Id_Conta_Pagar = Conta_Pagar.Id)' +
' where ((Conta_Pagar_Parcela.Status is null) or (Conta_Pagar_Parcela.Status = 0)) and' +
' dateadd(day, :DIAS, CURRENT_DATE) >= Conta_Pagar_Parcela.Vencimento ';
vaDataSet.ParamByName('DIAS').AsInteger := vaDataSetNotificacao.FieldByName('Tempo_Antecedencia').AsInteger;
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1 then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(tnContaPagarVencendo);
vaConta := TConta.Create;
vaConta.Descricao := vaDataSet.FieldByName('DESCRICAO').AsString;
vaConta.Valor := vaDataSet.FieldByName('VALOR').AsFloat;
vaConta.Vencimento := vaDataSet.FieldByName('VENCIMENTO').AsDateTime;
vaNotificacao.Info := vaConta;
Result.Add(vaNotificacao);
end;
vaMsg := vaMsg + 'A conta ' + vaDataSet.FieldByName('DESCRICAO').AsString + ' no valor de ' +
FormatFloat('R$ ,0.00', vaDataSet.FieldByName('VALOR').AsFloat);
if Date > vaDataSet.FieldByName('VENCIMENTO').AsDateTime then
vaMsg := vaMsg + ' venceu na data ' + vaDataSet.FieldByName('VENCIMENTO').AsString + ' e não foi paga.'
else
vaMsg := vaMsg + ' irá vencer em ' + vaDataSet.FieldByName('VENCIMENTO').AsString + ' e ainda não foi paga.';
vaMsg := vaMsg + '<br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnContaPagarVencendo, vaMsg);
end;
procedure plVerificarContaReceberVencida;
var
vaConta: TConta;
begin
vaDataSet.close;
vaDataSet.SQL.Text := 'select Conta_Receber.Id,' +
' Conta_Receber.Descricao || '' ('' || Conta_Receber_Parcela.Parcela || ''/'' ||(select count(*)' +
' from Conta_Receber_Parcela' +
' where Conta_Receber_Parcela.Id_Conta_Receber = Conta_Receber.Id)||'')'' as Descricao, '
+
' Conta_Receber_Parcela.Valor, ' +
' Conta_Receber_Parcela.Vencimento ' +
' from Conta_Receber_Parcela' +
' inner join Conta_Receber on (Conta_Receber_Parcela.Id_Conta_Receber = Conta_Receber.Id)' +
' where ((Conta_Receber_Parcela.Status is null) or (Conta_Receber_Parcela.Status = 0)) and' +
' CURRENT_DATE >= dateadd(day, :DIAS, Conta_Receber_Parcela.Vencimento) ';
vaDataSet.ParamByName('DIAS').AsInteger := vaDataSetNotificacao.FieldByName('Tempo_Antecedencia').AsInteger;
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1 then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(tnContaReceberVencida);
vaConta := TConta.Create;
vaConta.Descricao := vaDataSet.FieldByName('DESCRICAO').AsString;
vaConta.Valor := vaDataSet.FieldByName('VALOR').AsFloat;
vaConta.Vencimento := vaDataSet.FieldByName('VENCIMENTO').AsDateTime;
vaNotificacao.Info := vaConta;
Result.Add(vaNotificacao);
end;
vaMsg := vaMsg + 'A conta ' + vaDataSet.FieldByName('DESCRICAO').AsString + ' no valor de ' +
FormatFloat('R$ ,0.00', vaDataSet.FieldByName('VALOR').AsFloat) + ' venceu na data ' + vaDataSet.FieldByName('VENCIMENTO').AsString +
' e não foi recebida.' + '<br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnContaReceberVencida, vaMsg);
end;
procedure plVerificarRubricas;
var
vaRubrica: TRubrica;
begin
vaDataSet.close;
vaDataSet.SQL.Text := 'select View_Rubrica_Projeto.Id_Rubrica, ' +
' View_Rubrica_Projeto.Id_Projeto, ' +
' View_Rubrica_Projeto.Nome_Projeto,' +
' View_Rubrica_Projeto.Nome_Rubrica,' +
' case' +
' when view_rubrica_projeto.valor_gasto_transferido > view_rubrica_projeto.valor_recebido_transferido then' +
' view_rubrica_projeto.valor_gasto + (view_rubrica_projeto.valor_gasto_transferido - view_rubrica_projeto.valor_recebido_transferido)'
+
' else' +
' view_rubrica_projeto.valor_gasto' +
' end as VALOR_GASTO,' +
' case' +
' when view_rubrica_projeto.valor_gasto_transferido < view_rubrica_projeto.valor_recebido_transferido then' +
' view_rubrica_projeto.valor_recebido + (view_rubrica_projeto.valor_recebido_transferido - view_rubrica_projeto.valor_gasto_transferido)'
+
' else' +
' view_rubrica_projeto.valor_recebido' +
' end as VALOR_RECEBIDO,' +
' View_Rubrica_Projeto.Saldo_Real ' +
' from View_Rubrica_Projeto' +
' where (View_Rubrica_Projeto.Valor_Gasto > View_Rubrica_Projeto.Valor_Recebido) or' +
' (((View_Rubrica_Projeto.Valor_Gasto / View_Rubrica_Projeto.Valor_Recebido)*100) >= :PERCENTUAL_NOTIFICACAO)';
vaDataSet.ParamByName('PERCENTUAL_NOTIFICACAO').AsFloat := vaDataSetNotificacao.FieldByName('VALOR_GATILHO').AsFloat;
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1 then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID_PROJETO').AsInteger;
vaNotificacao.Tipo := Ord(tnRubricaAtigindoSaldo);
vaRubrica := TRubrica.Create;
vaRubrica.Id := vaDataSet.FieldByName('ID_RUBRICA').AsInteger;
vaRubrica.IdProjeto := vaDataSet.FieldByName('ID_PROJETO').AsInteger;
vaRubrica.NomeRubrica := vaDataSet.FieldByName('NOME_RUBRICA').AsString;
vaRubrica.NomeProjeto := vaDataSet.FieldByName('NOME_PROJETO').AsString;
vaRubrica.PercentualGasto := (vaDataSet.FieldByName('VALOR_GASTO').AsFloat / vaDataSet.FieldByName('VALOR_RECEBIDO').AsFloat) * 100;
vaRubrica.SaldoReal := vaDataSet.FieldByName('SALDO_REAL').AsFloat;
vaNotificacao.Info := vaRubrica;
Result.Add(vaNotificacao);
end;
vaMsg := vaMsg + 'A rubrica ' + vaDataSet.FieldByName('NOME_RUBRICA').AsString + ' do projeto ' +
vaDataSet.FieldByName('NOME_PROJETO').AsString + ' está prestes a atingir o seu limite. <br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnRubricaAtigindoSaldo, vaMsg);
end;
procedure plVerificarFundo;
var
vaFundo: TFundo;
begin
vaDataSet.close;
vaDataSet.SQL.Text := ' select Fundo.Id,' +
' Fundo.Id_Organizacao, ' +
' Organizacao.nome as nome_organizacao, ' +
' Fundo.Nome,' +
' Fundo.Saldo' +
' from Fundo' +
' inner join organizacao on (organizacao.id = fundo.id_organizacao)' +
' where Fundo.Saldo < :GATILHO';
vaDataSet.ParamByName('GATILHO').AsFloat := vaDataSetNotificacao.FieldByName('VALOR_GATILHO').AsFloat;
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1 then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID_ORGANIZACAO').AsInteger;
vaNotificacao.Tipo := Ord(tnFundoFicandoSemSaldo);
vaFundo := TFundo.Create;
vaFundo.Id := vaDataSet.FieldByName('ID').AsInteger;
vaFundo.Nome := vaDataSet.FieldByName('NOME').AsString;
vaFundo.NomeOrganizacao := vaDataSet.FieldByName('NOME_ORGANIZACAO').AsString;
vaFundo.Saldo := vaDataSet.FieldByName('SALDO').AsFloat;
vaNotificacao.Info := vaFundo;
Result.Add(vaNotificacao);
end;
vaMsg := vaMsg + 'O fundo ' + vaDataSet.FieldByName('NOME').AsString + ' da organização ' +
vaDataSet.FieldByName('NOME_ORGANIZACAO').AsString + ' está ficando sem saldo. <br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnFundoFicandoSemSaldo, vaMsg);
end;
procedure plVerificarAtividade(ipTipoNotificacao: TTipoNotificacao);
var
vaAtividade: TAtividade;
vaDataSetEnvolvidos: TRFQuery;
begin
vaDataSet.close;
vaDataSet.SQL.Text := 'select Atividade.Id,' +
' Atividade.Nome,' +
' Atividade.status,' +
' Coalesce(Projeto.Nome,''SEM PROJETO'') as Nome_Projeto' +
' from Atividade' +
' left join Projeto on (Atividade.Id_Projeto = Projeto.Id) ';
if ipTipoNotificacao = tnAtividadeVencendo then
begin
vaDataSet.SQL.Text := vaDataSet.SQL.Text + ' where (dateadd(day, :DIAS, current_date) >= Atividade.Data_Final) and ' +
' (Atividade.status not in (' + Ord(saFinalizada).ToString + ',' + Ord(saCancelada).ToString + '))';
vaDataSet.ParamByName('DIAS').AsInteger := vaDataSetNotificacao.FieldByName('TEMPO_ANTECEDENCIA').AsInteger
end
else
begin
if ipTipoNotificacao = tnAtividadeAlterada then
vaDataSet.SQL.Text := vaDataSet.SQL.Text + ' where Atividade.Data_Alteracao >= (dateadd(day, :DIAS, current_date))'
else // atividade cadastrada
vaDataSet.SQL.Text := vaDataSet.SQL.Text + ' where Atividade.Data_Cadastro >= (dateadd(day, :DIAS, current_date))';
vaDataSet.ParamByName('DIAS').AsInteger := vaDataSetNotificacao.FieldByName('TEMPO_ANTECEDENCIA').AsInteger * -1;
end;
vaDataSet.Open;
vaMsg := '';
if not vaDataSet.Eof then
begin
pprCriarDataSet(vaDataSetEnvolvidos);
try
vaDataSetEnvolvidos.SQL.Text := ' select Atividade.Id_Solicitante,' +
' Solicitante.email as email_solicitante, ' +
' Atividade.Id_Responsavel,' +
' Responsavel.email as email_responsavel, ' +
' Atividade_pessoa.id_pessoa as ID_PESSOA_ENVOLVIDA, ' +
' Envolvido.email as email_envolvido ' +
' from atividade' +
' left join atividade_pessoa on (atividade.id = atividade_pessoa.id_pessoa)' +
' left join pessoa solicitante on (solicitante.id = atividade.id_solicitante) ' +
' left join pessoa responsavel on (responsavel.id = atividade.id_responsavel) ' +
' left join pessoa envolvido on (envolvido.id = Atividade_pessoa.id_pessoa) ' +
' where atividade.id = :ID';
while not vaDataSet.Eof do
begin
vaDataSetEnvolvidos.close;
vaDataSetEnvolvidos.ParamByName('ID').AsInteger := vaDataSet.FieldByName('ID').AsInteger;
vaDataSetEnvolvidos.Open();
if (vaDataSetEnvolvidos.Locate('ID_SOLICITANTE', ipIdPessoa, []) or
vaDataSetEnvolvidos.Locate('ID_RESPONSAVEL', ipIdPessoa, []) or
vaDataSetEnvolvidos.Locate('ID_PESSOA_ENVOLVIDA', ipIdPessoa, [])) or
((ipIdPessoa = qNotificacao_Pessoa.FieldByName('ID_PESSOA').AsInteger) and
(qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1)) then
begin
// Notificacao de alteracao de atividade sempre serao enviadas aos responsaveis e envolvidos
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(ipTipoNotificacao);
vaAtividade := TAtividade.Create;
vaAtividade.Id := vaDataSet.FieldByName('ID').AsInteger;
vaAtividade.Nome := vaDataSet.FieldByName('NOME').AsString;
vaAtividade.NomeProjeto := vaDataSet.FieldByName('NOME_PROJETO').AsString;
vaAtividade.Status := vaDataSet.FieldByName('STATUS').AsInteger;
vaNotificacao.Info := vaAtividade;
Result.Add(vaNotificacao);
end;
if ipTipoNotificacao = tnAtividadeAlterada then
begin
if not vaDataSetEnvolvidos.FieldByName('ID_SOLICITANTE').IsNull then
begin
if not qNotificacao_Pessoa.Locate('ID_PESSOA', vaDataSetEnvolvidos.FieldByName('ID_SOLICITANTE').AsInteger, []) then
begin
qNotificacao_Pessoa.Append;
qNotificacao_Pessoa.FieldByName('ID_PESSOA').AsInteger := vaDataSetEnvolvidos.FieldByName('ID_SOLICITANTE').AsInteger;
qNotificacao_Pessoa.FieldByName('Notificacao_Email').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('EMAIL').AsString := vaDataSetEnvolvidos.FieldByName('EMAIL_SOLICITANTE').AsString;
qNotificacao_Pessoa.Post;
end;
end;
if not vaDataSetEnvolvidos.FieldByName('ID_RESPONSAVEL').IsNull then
begin
if not qNotificacao_Pessoa.Locate('ID_PESSOA', vaDataSetEnvolvidos.FieldByName('ID_RESPONSAVEL').AsInteger, []) then
begin
qNotificacao_Pessoa.Append;
qNotificacao_Pessoa.FieldByName('ID_PESSOA').AsInteger := vaDataSetEnvolvidos.FieldByName('ID_SOLICITANTE').AsInteger;
qNotificacao_Pessoa.FieldByName('Notificacao_Email').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('EMAIL').AsString := vaDataSetEnvolvidos.FieldByName('EMAIL_RESPONSAVEL').AsString;
qNotificacao_Pessoa.Post;
end;
end;
vaDataSetEnvolvidos.First;
while not vaDataSetEnvolvidos.Eof do
begin
if not vaDataSetEnvolvidos.FieldByName('ID_PESSOA_ENVOLVIDA').IsNull then
begin
if not qNotificacao_Pessoa.Locate('ID_PESSOA', vaDataSetEnvolvidos.FieldByName('ID_PESSOA_ENVOLVIDA').AsInteger, []) then
begin
qNotificacao_Pessoa.Append;
qNotificacao_Pessoa.FieldByName('ID_PESSOA').AsInteger := vaDataSetEnvolvidos.FieldByName('ID_PESSOA_ENVOLVIDA').AsInteger;
qNotificacao_Pessoa.FieldByName('Notificacao_Email').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger := 1;
qNotificacao_Pessoa.FieldByName('EMAIL').AsString := vaDataSetEnvolvidos.FieldByName('EMAIL_ENVOLVIDO').AsString;
qNotificacao_Pessoa.Post;
end;
end;
vaDataSetEnvolvidos.next;
end;
end;
if ipTipoNotificacao = tnAtividadeVencendo then
vaMsg := vaMsg + 'A atividade ' + vaDataSet.FieldByName('NOME').AsString + ' do projeto ' +
vaDataSet.FieldByName('NOME_PROJETO').AsString + ' está prestes a vencer seu prazo de execução. <br/><br/>'
else if ipTipoNotificacao = tnAtividadeAlterada then
vaMsg := vaMsg + 'Houve modificações na atividade ' + vaDataSet.FieldByName('NOME').AsString + ' do projeto ' +
vaDataSet.FieldByName('NOME_PROJETO').AsString + '. <br/><br/>'
else
vaMsg := vaMsg + 'Foi cadastrada a atividade ' + vaDataSet.FieldByName('NOME').AsString + ' para o projeto ' +
vaDataSet.FieldByName('NOME_PROJETO').AsString + '. <br/><br/>';
vaDataSet.next;
end;
finally
vaDataSetEnvolvidos.close;
vaDataSetEnvolvidos.Free;
end;
end;
if vaMsg <> '' then
plEnviarEmails(ipTipoNotificacao, vaMsg);
end;
procedure plVerificarSolicitacaoCompra();
var
vaSolicitacao: TSolicitacaoCompra;
begin
vaDataSet.close;
vaDataSet.SQL.Text := ' select Solicitacao_Compra.id, ' +
' Solicitacao_Compra.Data,' +
' Pessoa.nome as Solicitante, ' +
' Solicitacao_Compra.Status,' +
' Solicitacao_Compra.Data_Analise, ' +
' Solicitacao_Compra.Motivo_Negacao, ' +
' list(coalesce(Especie.Nome, Item.Nome), '', '') as Itens' +
' from Solicitacao_Compra' +
' inner join Solicitacao_Compra_Item on (Solicitacao_Compra.Id = Solicitacao_Compra_Item.Id_Solicitacao_Compra)' +
' inner join pessoa on (pessoa.id = Solicitacao_Compra.id_pessoa_solicitou) ' +
' inner join Item on (Item.Id = Solicitacao_Compra_Item.Id_Item)' +
' left join Especie on (Especie.Id = Solicitacao_Compra_Item.Id_Especie)' +
' where (((Solicitacao_Compra.Status = 0) and' +
' (dateadd(day, :Dias, Solicitacao_Compra.Data) >= current_date)) or ' +
' ((Solicitacao_Compra.Status <> 0) and' +
' (dateadd(day, :Dias, Solicitacao_Compra.Data_Analise) >= current_date)))';
if ipId <> -1 then
vaDataSet.SQL.Text := vaDataSet.SQL.Text + ' and (solicitacao_compra.id = :ID) ';
vaDataSet.SQL.Text := vaDataSet.SQL.Text +
' group by Solicitacao_Compra.id, Solicitacao_Compra.Data, Pessoa.nome, ' +
' Solicitacao_Compra.Status, Solicitacao_Compra.Data_Analise, Solicitacao_Compra.Motivo_Negacao ';
vaDataSet.ParamByName('DIAS').AsInteger := vaDataSetNotificacao.FieldByName('TEMPO_ANTECEDENCIA').AsInteger;
if ipId <> -1 then
vaDataSet.ParamByName('ID').AsInteger := ipId;
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if ipNotificacaoSistema and (qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1) then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(tnSolicitacaoCompra);
vaSolicitacao := TSolicitacaoCompra.Create;
vaSolicitacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaSolicitacao.Itens := vaDataSet.FieldByName('ITENS').AsString;
vaSolicitacao.DataSolicitacao := vaDataSet.FieldByName('DATA').AsDateTime;
vaSolicitacao.DataAnalise := vaDataSet.FieldByName('DATA_ANALISE').AsDateTime;
vaSolicitacao.Status := vaDataSet.FieldByName('STATUS').AsInteger;
vaSolicitacao.Solicitante := vaDataSet.FieldByName('SOLICITANTE').AsString;
vaNotificacao.Info := vaSolicitacao;
Result.Add(vaNotificacao);
end;
if vaDataSet.FieldByName('STATUS').AsInteger = Ord(sscSolicitacada) then
vaMsg := vaMsg + 'Houve uma solicitação de compra dos seguintes itens: ' + vaDataSet.FieldByName('ITENS').AsString + ' <br/><br/>'
else if vaDataSet.FieldByName('STATUS').AsInteger = Ord(sscAprovada) then
vaMsg := vaMsg + 'A solicitação dos itens ' + vaDataSet.FieldByName('ITENS').AsString + ' foi aprovada.' + ' <br/><br/>'
else if vaDataSet.FieldByName('STATUS').AsInteger = Ord(sscNegada) then
vaMsg := vaMsg + 'A solicitação dos itens ' + vaDataSet.FieldByName('ITENS').AsString + ' foi negada pelo seguinte motivo: <br/>' +
vaDataSet.FieldByName('MOTIVO_NEGACAO').AsString + ' <br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnSolicitacaoCompra, vaMsg);
end;
procedure plVerificarAniversarios();
var
vaPessoa: TPessoa;
begin
vaDataSet.close;
vaDataSet.SQL.Text := ' select Pessoa.Id,' +
' Pessoa.Nome,' +
' Pessoa.Data_Nascimento' +
' from Pessoa' +
' where Pessoa.Tipo in (' + Ord(trpFuncionario).ToString + ',' + Ord(trpMembroDiretoria).ToString + ','
+ Ord(trpParceiro).ToString + ',' + Ord(trpEstagiario).ToString + ',' + Ord(trpVoluntario).ToString + ') and' +
// func, membro diretoria, estagiario
' extract(day from current_date) = extract(day from Pessoa.Data_Nascimento) and' +
' extract(month from current_date) = extract(month from Pessoa.Data_Nascimento)';
vaDataSet.Open;
vaMsg := '';
while not vaDataSet.Eof do
begin
if qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1 then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSet.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(tnAniversario);
vaPessoa := TPessoa.Create;
vaPessoa.Id := vaDataSet.FieldByName('ID').AsInteger;
vaPessoa.Nome := vaDataSet.FieldByName('NOME').AsString;
vaPessoa.DataNascimento := vaDataSet.FieldByName('DATA_NASCIMENTO').AsDateTime;
vaNotificacao.Info := vaPessoa;
Result.Add(vaNotificacao);
end;
vaMsg := vaMsg + 'Hoje é aniversário do ' + vaDataSet.FieldByName('NOME').AsString + '. <br/><br/>';
vaDataSet.next;
end;
if vaMsg <> '' then
plEnviarEmails(tnAniversario, vaMsg);
end;
begin
Result := TadsObjectlist<TNotificacao>.Create;
pprCriarDataSet(vaDataSetNotificacao);
vaDataSetNotificacao.CachedUpdates := true;
pprCriarDataSet(vaDataSet);
try
// vamos ver os tipos de notificacoes configurados
vaDataSetNotificacao.SQL.Text := ' select Notificacao.ID, ' +
' Notificacao.Tipo,' +
' Notificacao.Tempo_Antecedencia, ' +
' Notificacao.VALOR_GATILHO ' +
' from Notificacao ';
vaDataSetNotificacao.Open;
while not vaDataSetNotificacao.Eof do
begin
if (ipTipo = -1) or (vaDataSetNotificacao.FieldByName('TIPO').AsInteger = ipTipo) then
begin
qNotificacao_Pessoa.close;
qNotificacao_Pessoa.SQL.Text := 'Select Notificacao_Pessoa.id_pessoa, ' +
' Notificacao_Pessoa.Notificacao_Sistema,' +
' Notificacao_Pessoa.Notificacao_Email,' +
' Pessoa.Email ' +
' from notificacao_pessoa ' +
' inner join Pessoa on (Pessoa.Id = Notificacao_Pessoa.Id_Pessoa) ' +
' where ((notificacao_pessoa.id_pessoa = :ID_PESSOA) or (:ID_PESSOA IS NULL)) and' +
' notificacao_pessoa.id_notificacao = :ID_NOTIFICACAO';
qNotificacao_Pessoa.ParamByName('ID_NOTIFICACAO').AsInteger := vaDataSetNotificacao.FieldByName('ID').AsInteger;
if ipIdPessoa <> -1 then
qNotificacao_Pessoa.ParamByName('ID_PESSOA').AsInteger := ipIdPessoa
else
qNotificacao_Pessoa.ParamByName('ID_PESSOA').Clear;
qNotificacao_Pessoa.Open;
vaTipoNotificacao := TTipoNotificacao(vaDataSetNotificacao.FieldByName('TIPO').AsInteger);
if ((not qNotificacao_Pessoa.Eof) and
((qNotificacao_Pessoa.FieldByName('Notificacao_Email').AsInteger = 1) or
(qNotificacao_Pessoa.FieldByName('Notificacao_Sistema').AsInteger = 1))) or
(vaTipoNotificacao = tnAtividadeAlterada) then // atividade alterada sempre vai avisar os envolvidos mesmo q nao tenha nenhum usuario configurado
begin
case vaTipoNotificacao of
tnContaPagarVencendo:
plVerificarContaPagarVencendo;
tnContaReceberVencida:
plVerificarContaReceberVencida;
tnRubricaAtigindoSaldo:
plVerificarRubricas;
tnFundoFicandoSemSaldo:
plVerificarFundo;
tnAtividadeCadastrada, tnAtividadeAlterada, tnAtividadeVencendo:
plVerificarAtividade(vaTipoNotificacao);
tnSolicitacaoCompra:
plVerificarSolicitacaoCompra;
tnAniversario:
plVerificarAniversarios;
tnEventoAgenda:
begin
vaNotificacoes := fpvVerificarNotificacoesAgendaPessoal(ipIdPessoa, ipNotificacaoEmail, ipNotificacaoSistema,
vaDataSetNotificacao, qNotificacao_Pessoa);
if Assigned(vaNotificacoes) then
begin
Result.AddRange(vaNotificacoes);
vaNotificacoes.Free;
end;
end;
end;
end;
end;
vaDataSetNotificacao.next;
end;
finally
if qNotificacao_Pessoa.ChangeCount > 0 then
qNotificacao_Pessoa.CancelUpdates;
qNotificacao_Pessoa.close;
vaDataSetNotificacao.close;
vaDataSetNotificacao.Free;
vaDataSet.close;
vaDataSet.Free;
end;
if not ipNotificacaoSistema then
FreeAndNil(Result);
end;
function TsmFuncoesSistema.fpvVerificarNotificacoesAgendaPessoal(ipIdPessoa: integer; ipNotificacaoEmail, ipNotificacaoSistema: Boolean;
ipDataSetNotificacao, ipDataSetNotificacaoPessoa: TRFQuery)
: TList<TNotificacao>;
var
vaDataSetAgenda, vaDataSetAgendaRegistro, vaDataSetAgendaPessoa: TRFQuery;
vaNotificacao: TNotificacao;
vaAgenda: TAgenda;
vaEvento: TEventoAgenda;
vaMsg: String;
begin
Result := nil;
if ipNotificacaoSistema then
Result := TList<TNotificacao>.Create;
pprCriarDataSet(vaDataSetAgenda);
pprCriarDataSet(vaDataSetAgendaRegistro);
pprCriarDataSet(vaDataSetAgendaPessoa);
try
vaDataSetAgendaPessoa.SQL.Text := 'Select agenda_pessoa.id ' +
' from agenda_pessoa' +
' where agenda_pessoa.id_agenda = :ID_AGENDA and' +
' agenda_pessoa.id_pessoa = :ID_PESSOA';
vaDataSetAgendaRegistro.SQL.Text := ' select Agenda_Registro.Id, ' +
' Agenda_Registro.Titulo,' +
' Agenda_Registro.Data_Inicio,' +
' Agenda_Registro.Data_Fim' +
' from Agenda_Registro' +
' where Agenda_Registro.id_agenda = :ID_AGENDA and ' +
' ((Agenda_Registro.Event_Type = 1) or ' +
' (current_date between dateadd(day, :Dias, Agenda_Registro.Data_Inicio) and Agenda_Registro.Data_fim)) ' +
' UNION ALL ' +
' select cast(Atividade.Id*-1 as integer) as ID,' +
' Atividade.Nome as titulo,' +
' Atividade.Data_Inicial as data_inicio,' +
' Atividade.Data_Final as data_fim' +
' from Agenda' +
' inner join Atividade on (Atividade.Id_Projeto = Agenda.Id_Projeto)' +
' where Agenda.Id = :ID_AGENDA and' +
' (current_date between dateadd(day, :Dias, Atividade.Data_Inicial) and Atividade.Data_Final) ';
vaDataSetAgenda.SQL.Text := 'select Agenda.Id,' +
' Agenda.Nome, ' +
' Agenda.tipo ' +
' from Agenda' +
' where ((:Id_Pessoa is null) or ((select count(*)' +
' from Agenda_Pessoa' +
' where Agenda_Pessoa.Id_Agenda = Agenda.Id and' +
' Agenda_Pessoa.Id_Pessoa = :Id_Pessoa) > 0))';
if ipIdPessoa <> -1 then
vaDataSetAgenda.ParamByName('ID_PESSOA').AsInteger := ipIdPessoa
else
vaDataSetAgenda.ParamByName('ID_PESSOA').Clear;
vaDataSetAgenda.Open;
while not vaDataSetAgenda.Eof do
begin
vaDataSetAgendaRegistro.close;
vaDataSetAgendaRegistro.ParamByName('ID_AGENDA').AsInteger := vaDataSetAgenda.FieldByName('ID').AsInteger;
vaDataSetAgendaRegistro.ParamByName('DIAS').AsInteger := ipDataSetNotificacao.FieldByName('Tempo_Antecedencia').AsInteger * -1;
vaDataSetAgendaRegistro.Open();
if not vaDataSetAgendaRegistro.Eof then
begin
if ipNotificacaoSistema and (ipDataSetNotificacaoPessoa.FieldByName('NOTIFICACAO_SISTEMA').AsInteger = 1) then
begin
vaNotificacao := TNotificacao.Create;
vaNotificacao.Id := vaDataSetAgenda.FieldByName('ID').AsInteger;
vaNotificacao.Tipo := Ord(tnEventoAgenda);
vaAgenda := TAgenda.Create;
vaAgenda.Id := vaDataSetAgenda.FieldByName('ID').AsInteger;
vaAgenda.Nome := vaDataSetAgenda.FieldByName('NOME').AsString;
while not vaDataSetAgendaRegistro.Eof do
begin
vaEvento := TEventoAgenda.Create;
vaEvento.Id := vaDataSetAgendaRegistro.FieldByName('ID').AsInteger;
vaEvento.Titulo := vaDataSetAgendaRegistro.FieldByName('TITULO').AsString;
vaEvento.DataHoraInicio := vaDataSetAgendaRegistro.FieldByName('DATA_INICIO').AsDateTime;
vaEvento.DataHoraFim := vaDataSetAgendaRegistro.FieldByName('DATA_FIM').AsDateTime;
vaAgenda.Eventos.Add(vaEvento);
vaDataSetAgendaRegistro.next;
end;
vaNotificacao.Info := vaAgenda;
Result.Add(vaNotificacao);
end;
if ipNotificacaoEmail then
begin
vaMsg := 'Os seguintes eventos da agenda <b>' + vaDataSetAgenda.FieldByName('NOME').AsString + '</b> estão próximos: ' +
coQuebraLinhaHtml;
vaDataSetAgendaRegistro.First;
while not vaDataSetAgendaRegistro.Eof do
begin
vaMsg := vaMsg + vaDataSetAgendaRegistro.FieldByName('TITULO').AsString + coQuebraLinhaHtml;
vaMsg := vaMsg + 'De ' + vaDataSetAgendaRegistro.FieldByName('DATA_INICIO').AsString + ' até ' +
vaDataSetAgendaRegistro.FieldByName('DATA_FIM').AsString + coQuebraLinhaHtml + coQuebraLinhaHtml;
vaDataSetAgendaRegistro.next;
end;
ipDataSetNotificacaoPessoa.First;
while not ipDataSetNotificacaoPessoa.Eof do
begin
if (ipDataSetNotificacaoPessoa.FieldByName('Notificacao_Email').AsInteger = 1) and
(ipDataSetNotificacaoPessoa.FieldByName('Email').AsString <> '') then
begin
// se diferente de -1 significa que no proprio select da agenda ja foi feito o filtro para garantir
// que somente pessoas autorizadas vejam o agendamento
if ipIdPessoa = -1 then
begin
vaDataSetAgendaPessoa.close;
vaDataSetAgendaPessoa.ParamByName('ID_AGENDA').AsInteger := vaDataSetAgenda.FieldByName('ID').AsInteger;
vaDataSetAgendaPessoa.ParamByName('ID_PESSOA').AsInteger := ipDataSetNotificacaoPessoa.FieldByName('ID_PESSOA').AsInteger;
vaDataSetAgendaPessoa.Open;
end;
// se for o server q estiver solicitanto o envio de email eu irei enviar somente os eventos das agendas
// publicas e da propria agenda pessoal
if (ipIdPessoa <> -1) or (not vaDataSetAgendaPessoa.Eof) then
ppuEnviarEmail(TiposNotificacao[tnEventoAgenda], vaMsg, ipDataSetNotificacaoPessoa.FieldByName('Email').AsString, '', nil);
end;
ipDataSetNotificacaoPessoa.next;
end;
end;
end;
vaDataSetAgenda.next;
end;
finally
vaDataSetAgenda.close;
vaDataSetAgenda.Free;
vaDataSetAgendaRegistro.close;
vaDataSetAgendaRegistro.Free;
vaDataSetAgendaPessoa.close;
vaDataSetAgendaPessoa.Free;
end;
end;
procedure TsmFuncoesSistema.ppuCriarAgendaPessoal(ipIdPessoa: integer);
begin
pprEncapsularConsulta(
procedure(ipDataSet: TRFQuery)
var
vaId: integer;
begin
ipDataSet.SQL.Text := 'select Pessoa.Nome, ' +
' Agenda.Nome as Nome_Agenda, ' +
' Agenda.Tipo ' +
' from Pessoa ' +
' left join Agenda_Pessoa on (Agenda_Pessoa.Id_Pessoa = Pessoa.Id) ' +
' left join Agenda on (Agenda.Id = Agenda_Pessoa.Id_Agenda) ' +
' where Pessoa.Id = :Id_Pessoa';
ipDataSet.ParamByName('ID_PESSOA').AsInteger := ipIdPessoa;
ipDataSet.Open;
if not ipDataSet.Locate('TIPO', Ord(taPessoal), []) then
begin
vaId := fpuGetId('AGENDA');
Connection.ExecSQL('insert into Agenda (Agenda.Id, Agenda.Nome, Agenda.Tipo, Agenda.ativo) ' +
'values (:ID, :NOME, :TIPO,0)', [vaId, 'Agenda Pessoal', Ord(taPessoal)]);
Connection.ExecSQL
('insert into Agenda_Pessoa (Agenda_Pessoa.Id, Agenda_Pessoa.Id_Agenda, Agenda_Pessoa.Id_Pessoa, Agenda_Pessoa.Somente_Visualizacao) ' +
'values (next value for Gen_Agenda_Pessoa, :Id_Agenda, :Id_Pessoa, 0)', [vaId, ipIdPessoa]);
if Connection.InTransaction then
Connection.Commit;
end;
end);
end;
function TsmFuncoesSistema.fpuRegistrarAparelhoExterno(ipNome, ipIMEI: String): integer;
var
vaId: integer;
begin
pprEncapsularConsulta(
procedure(ipDataSet: TRFQuery)
begin
ipDataSet.SQL.Text := 'select Aparelho_externo.Id,' +
' Aparelho_externo.Nome,' +
' Aparelho_externo.Serial' +
' from Aparelho_externo ' +
' where aparelho_externo.serial = :SERIAL';
ipDataSet.ParamByName('SERIAL').AsString := ipIMEI;
ipDataSet.Open();
if not ipDataSet.Eof then
vaId := ipDataSet.FieldByName('ID').AsInteger
else
begin
vaId := fpuGetId('APARELHO_EXTERNO');
Connection.ExecSQL('insert into aparelho_externo values (:ID,:NOME, :SERIAL)', [vaId, ipNome, ipIMEI]);
if Connection.InTransaction then
Connection.Commit;
end;
end);
Result := vaId;
end;
function TsmFuncoesSistema.fpuValidarTipoNotificacao(ipIdNotificacao,
ipTipo: integer): Boolean;
begin
Result := fprValidarCampoUnico('NOTIFICACAO', 'TIPO', ipIdNotificacao, ipTipo.ToString());
end;
end.
|
unit FBase;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Controls.Presentation,
FMX.ScrollBox,
FMX.Memo;
type
TFrameBase = class(TFrame)
Memo: TMemo;
ToolBar: TToolBar;
LabelCaption: TLabel;
private
{ Private declarations }
protected
procedure Log(const AMsg: String); overload;
procedure Log(const AMsg: String; const AArgs: array of const); overload;
public
{ Public declarations }
end;
implementation
{$R *.fmx}
{ TFrameBase }
procedure TFrameBase.Log(const AMsg: String);
begin
Memo.Lines.Add(AMsg);
Memo.SelStart := Integer.MaxValue; // Scroll to end
end;
procedure TFrameBase.Log(const AMsg: String; const AArgs: array of const);
begin
Log(Format(AMsg, AArgs));
end;
end.
|
unit BancoService;
interface
uses
System.SysUtils, System.Generics.Collections, ServiceBase, Banco;
type
TBancoService = class(TServiceBase)
public
class function ConsultarLista: TObjectList<TBanco>;
class function ConsultarListaFiltroValor(campo: string; valor: string): TObjectList<TBanco>;
class function ConsultarObjeto(const AId: Integer): TBanco;
class procedure Inserir(var ABanco: TBanco);
class function Alterar(ABanco: TBanco): Integer;
class function Excluir(ABanco: TBanco): Integer;
end;
var
sql: string;
implementation
uses
FireDAC.Stan.Option, FireDAC.Comp.Client, FireDAC.Stan.Param,
MVCFramework.FireDAC.Utils, MVCFramework.DataSet.Utils,
MVCFramework.Serializer.Commons, MVCFramework.Commons;
{ TBancoService }
class function TBancoService.ConsultarLista: TObjectList<TBanco>;
begin
sql := 'SELECT * FROM BANCO ORDER BY ID';
try
Result := GetQuery(sql).AsObjectList<TBanco>;
finally
Query.Close;
Query.Free;
end;
end;
class function TBancoService.ConsultarListaFiltroValor(campo, valor: string): TObjectList<TBanco>;
begin
sql := 'SELECT * FROM BANCO where ' + campo + ' like "%' + valor + '%"';
try
Result := GetQuery(sql).AsObjectList<TBanco>;
finally
Query.Close;
Query.Free;
end;
end;
class function TBancoService.ConsultarObjeto(const AId: Integer): TBanco;
begin
sql := 'SELECT * FROM BANCO WHERE ID = ' + IntToStr(AId);
try
GetQuery(sql);
if not Query.Eof then
Result := Query.AsObject<TBanco>
else
Result := nil;
finally
Query.Close;
Query.Free;
end;
end;
class procedure TBancoService.Inserir(var ABanco: TBanco);
begin
ABanco.ValidarInsercao;
ABanco.Id := InserirBase(ABanco, 'BANCO');
end;
class function TBancoService.Alterar(ABanco: TBanco): Integer;
begin
ABanco.ValidarAlteracao;
Result := AlterarBase(ABanco, 'BANCO');
end;
class function TBancoService.Excluir(ABanco: TBanco): Integer;
begin
ABanco.ValidarExclusao;
Result := ExcluirBase(ABanco.Id, 'BANCO');
end;
end.
|
unit uAppParams;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXPanels, Vcl.ExtCtrls,
Vcl.WinXCtrls, Vcl.StdCtrls, Vcl.Themes,
Vcl.Styles, uDMCore, Ora, Data.DB, MemDS, DBAccess;
type
TfrmAppParams = class(TForm)
oqGetConfigValue: TOraQuery;
oqSetConfigValue: TOraQuery;
spnlConfigControls: TStackPanel;
chkUseStyles: TCheckBox;
lblApplyStyle: TLabel;
cmbStyles: TComboBox;
pnlDescription: TPanel;
procedure cmbStylesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure SetCommonParams(var qry: TOraQuery);
procedure SetConfigValue(const name, descr, Value: string;
var qry: TOraQuery);
function GetStyle: string;
procedure SetStyle(const Value: string);
public
FStyle: string;
property Style: string read GetStyle write SetStyle;
end;
var
frmAppParams: TfrmAppParams;
implementation
{$R *.dfm}
uses uGlobals;
procedure TfrmAppParams.cmbStylesChange(Sender: TObject);
begin
FStyle := cmbStyles.Text;
TStyleManager.SetStyle(FStyle);
SetConfigValue('STYLE', 'User VCL Style', FStyle, oqSetConfigValue);
end;
procedure TfrmAppParams.SetCommonParams(var qry: TOraQuery);
begin
if qry.Active then
qry.CLose;
qry.ParamByName('pappname').asString :=
ExtractFileName(lowerCase(Application.ExeName));
qry.ParamByName('puser').asString := gvUserInfo.OSName;
end;
procedure TfrmAppParams.SetConfigValue(const name, descr, Value: string;
var qry: TOraQuery);
begin
SetCommonParams(qry);
qry.ParamByName('pname').asString := name;
qry.ParamByName('pdescr').asString := descr;
qry.ParamByName('pvalue').asString := Value;
qry.Open;
qry.CLose;
end;
procedure TfrmAppParams.FormShow(Sender: TObject);
var
StyleName: string;
begin
for StyleName in TStyleManager.StyleNames do
cmbStyles.Items.Add(StyleName);
cmbStyles.ItemIndex := cmbStyles.Items.IndexOf
(TStyleManager.ActiveStyle.name);
end;
function TfrmAppParams.GetStyle: string;
begin
oqGetConfigValue.CLose;
SetCommonParams(oqGetConfigValue);
oqGetConfigValue.ParamByName('pname').asString := 'STYLE';
oqGetConfigValue.Open;
result := oqGetConfigValue.Fields[0].asString;
if result = emptyStr then
result := 'Aqua Light Slate'; // by default
end;
procedure TfrmAppParams.SetStyle(const Value: string);
begin
FStyle := Value;
end;
end.
|
unit Expedicao.Models.uCombustivel;
interface
uses
System.JSON;
type
TCombustivel = class
private
FCombustivelOID: Integer;
FDescricao: string;
FValor: Currency;
FUnidadeDeMedidaOID: Integer;
procedure SetCombustivelOID(const Value: Integer);
procedure SetDescricao(const Value: string);
procedure SetValor(const Value: Currency);
procedure SetUnidadeDeMedidaOID(const Value: Integer);
public
constructor Create(pCombustivelJSON: TJSONObject); overload;
property CombustivelOID: Integer read FCombustivelOID write SetCombustivelOID;
property Descricao: string read FDescricao write SetDescricao;
property Valor: Currency read FValor write SetValor;
property UnidadeDeMedidaOID: Integer read FUnidadeDeMedidaOID write SetUnidadeDeMedidaOID;
end;
implementation
uses
System.SysUtils,
Rest.Json;
{ TCombustivel }
constructor TCombustivel.Create(pCombustivelJSON: TJSONObject);
begin
inherited Create;
Self.CombustivelOID := TJSONNumber(pCombustivelJSON.GetValue('CombustivelOID')).AsInt;
Self.Descricao := TJSONString(pCombustivelJSON.GetValue('Descricao')).Value;
Self.Valor := TJSONNumber(pCombustivelJSON.GetValue('Valor')).AsDouble;
Self.UnidadeDeMedidaOID := TJSONNumber(pCombustivelJSON.GetValue('UnidadeDeMediddaOID')).AsInt;
end;
procedure TCombustivel.SetCombustivelOID(const Value: Integer);
begin
FCombustivelOID := Value;
end;
procedure TCombustivel.SetDescricao(const Value: string);
begin
FDescricao := Value;
end;
procedure TCombustivel.SetUnidadeDeMedidaOID(const Value: Integer);
begin
FUnidadeDeMedidaOID := Value;
end;
procedure TCombustivel.SetValor(const Value: Currency);
begin
FValor := Value;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiWebDriver }
{ }
{ Copyright 2017 inpwtepydjuf@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 Commands.GetEnabled;
interface
uses
CommandRegistry,
Vcl.Forms,
HttpServerCommand;
type
/// <summary>
/// Handles 'GET' '/session/(.*)/element/(.*)/enabled'
/// </summary>
TGetEnabledCommand = class(TRESTCommand)
private
function OKResponse(const SessionID: String; enabled: boolean): String;
public
class function GetCommand: String; override;
class function GetRoute: String; override;
procedure Execute(AOwner: TForm); override;
end;
implementation
uses
Vcl.Controls,
System.SysUtils,
System.Classes,
Vcl.ComCtrls,
Vcl.ExtCtrls,
Vcl.Buttons,
Vcl.StdCtrls,
System.StrUtils,
System.JSON,
System.JSON.Types,
System.JSON.Writers,
System.JSON.Builders,
utils;
procedure TGetEnabledCommand.Execute(AOwner: TForm);
var
comp: TComponent;
ctrl: TWinControl;
handle: Integer;
values : TStringList;
value: boolean;
parent: TComponent;
const
Delimiter = '.';
begin
ctrl := nil;
comp := nil;
if (isNumber(self.Params[2])) then
begin
handle := StrToInt(self.Params[2]);
ctrl := FindControl(handle);
ResponseJSON(OKResponse(self.Params[1], ctrl.Enabled))
end
else
if (ContainsText(self.Params[2], Delimiter)) then
begin
values := TStringList.Create;
try
values.Delimiter := Delimiter;
values.StrictDelimiter := True;
values.DelimitedText := self.Params[2];
// Get parent
parent := AOwner.FindComponent(values[0]);
if (parent is TToolBar) then
begin
value := (parent as TToolBar).Buttons[StrToInt(values[1])].enabled;
end;
// Now send it back please
ResponseJSON(OKResponse(self.Params[2], value));
finally
values.free;
end;
end
else
begin
comp := AOwner.FindComponent(self.Params[2]);
if (comp <> nil) then
begin
if (comp is TSpeedButton) then
OKResponse(self.Params[1], (comp as TSpeedButton).enabled)
else if (comp is TLabel) then
OKResponse(self.Params[1], (comp as TLabel).enabled);
ResponseJSON(OKResponse(self.Params[2], value));
end
else
Error(404);
end;
end;
class function TGetEnabledCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetEnabledCommand.GetRoute: String;
begin
result := '/session/(.*)/element/(.*)/enabled';
end;
function TGetEnabledCommand.OKResponse(const SessionID: String; enabled: boolean): String;
var
Builder: TJSONObjectBuilder;
Writer: TJsonTextWriter;
StringWriter: TStringWriter;
StringBuilder: TStringBuilder;
value: Variant;
begin
StringBuilder := TStringBuilder.Create;
StringWriter := TStringWriter.Create(StringBuilder);
Writer := TJsonTextWriter.Create(StringWriter);
Writer.Formatting := TJsonFormatting.Indented;
Builder := TJSONObjectBuilder.Create(Writer);
value := enabled;
Builder
.BeginObject()
.Add('sessionId', sessionId)
.Add('status', 0)
.Add('value', value)
.EndObject;
result := StringBuilder.ToString;
end;
end.
|
unit FluentUI.Dialog;
interface
uses
FMX.Forms,
FMX.Objects,
System.Classes,
FMX.Types,
FMX.StdCtrls,
FMX.Layouts,
FMX.Controls;
type
{$SCOPEDENUMS ON}
TDialogType = (Normal, LargeHeader, Close);
TContentDialogButton = (None, Primary);
{$SCOPEDENUMS OFF}
IFluentDialog = interface
['{D71BE646-52F3-4B0E-8878-9C0DB0009B49}']
end;
/// <summary>
/// A dialog box (Dialog) is a temporary pop-up that takes focus from the page or
/// app and requires people to interact with it. It’s primarily used for confirming
/// actions, such as deleting a file, or asking people to make a choice.
/// </summary>
TFluendDialogContent = class(TComponent)
private
FOverlayRect: TRectangle;
FDialogRect: TRectangle;
FIsDark: Boolean;
FTitleUI: TLabel;
FDialogType: TDialogType;
FContent: TControl;
FPrimaryButton: TButton;
FSecondaryButtonText: string;
FCloseButtonText: string;
FButtonsLayout: TLayout;
function GetPrimaryButtonText: string;
function GetTitle: string;
procedure SetContent(const Value: TControl);
procedure SetPrimaryButtonText(const Value: string);
procedure SetTitle(const Value: string);
protected
procedure OnOverlayRectClick(Sender: TObject);
procedure UpdateParentForm;
procedure BuildButtons;
procedure BuildPrimaryButton(const AText: string);
procedure BuildTitle(const AText: string);
procedure BuildContent;
procedure BuildDialogRect;
public
procedure Show;
procedure Close;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Title: string read GetTitle write SetTitle;
property PrimaryButtonText: string read GetPrimaryButtonText write SetPrimaryButtonText;
property SecondaryButtonText: string read FSecondaryButtonText write FSecondaryButtonText;
property CloseButtonText: string read FCloseButtonText write FCloseButtonText;
property IsDark: Boolean read FIsDark write FIsDark;
property DialogType: TDialogType read FDialogType write FDialogType;
property Content: TControl read FContent write SetContent;
end;
TFluendDialog = class(TFluendDialogContent)
private
FSubTextUI: TLabel;
function GetSubText: String;
procedure SetSubText(const Value: String);
protected
procedure BuildSubTitle(const AText: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property SubText: String read GetSubText write SetSubText;
end;
procedure Register;
implementation
uses
FMX.Graphics;
procedure Register;
begin
RegisterComponents('FluentUI', [TFluendDialogContent]);
end;
{ TFluendDialog }
procedure TFluendDialogContent.BuildButtons;
begin
if not Assigned(FButtonsLayout) then
FButtonsLayout := TLayout.Create(FDialogRect);
FButtonsLayout.Parent := FDialogRect;
FButtonsLayout.Align := TAlignLayout.Top;
FButtonsLayout.Margins.Right := -4;
FButtonsLayout.Height := 32;
//
BuildPrimaryButton('Primary');
end;
procedure TFluendDialogContent.BuildContent;
begin
if not Assigned(FContent) then
Exit;
FContent.Align := TAlignLayout.Top;
end;
procedure TFluendDialogContent.BuildDialogRect;
begin
FDialogRect := TRectangle.Create(FOverlayRect);
FDialogRect.Fill.Color := $FFFFFFFF;
FDialogRect.Align := TAlignLayout.Center;
FDialogRect.Parent := FOverlayRect;
FDialogRect.Height := 172;
FDialogRect.Width := 288;
FDialogRect.Sides := [];
FDialogRect.Padding.Top := 16;
FDialogRect.Padding.Right := 46;
FDialogRect.Padding.Bottom := 20;
FDialogRect.Padding.Left := 24;
FDialogRect.XRadius := 2;
FDialogRect.YRadius := 2;
FDialogRect.Stroke.Kind := TBrushKind.None;
end;
procedure TFluendDialogContent.BuildPrimaryButton(const AText: string);
begin
if not Assigned(FPrimaryButton) then
FPrimaryButton := TButton.Create(FButtonsLayout);
FPrimaryButton.Parent := FButtonsLayout;
FPrimaryButton.Align := TAlignLayout.Right;
FPrimaryButton.Text := AText;
FPrimaryButton.StyleLookup := 'FluentButtonPrimary';
end;
procedure TFluendDialogContent.BuildTitle(const AText: string);
begin
if not Assigned(FTitleUI) then
FTitleUI := TLabel.Create(FDialogRect);
FTitleUI.Align := TAlignLayout.Top;
FTitleUI.Parent := FDialogRect;
FTitleUI.AutoSize := True;
FTitleUI.Text := AText;
FTitleUI.StyledSettings := [TStyledSetting.Style];
FTitleUI.TextSettings.FontColor := $FF323130;
FTitleUI.TextSettings.Font.Size := 20;
FTitleUI.TextSettings.Font.Family := 'Segoe UI';
end;
procedure TFluendDialogContent.Close;
begin
FOverlayRect.Parent := nil;
end;
constructor TFluendDialogContent.Create(AOwner: TComponent);
begin
inherited;
FDialogType := TDialogType.Normal;
FOverlayRect := TRectangle.Create(Self);
FOverlayRect.Align := TAlignLayout.Client;
FOverlayRect.Sides := [];
FOverlayRect.Fill.Color := $66000000;
FOverlayRect.OnClick := OnOverlayRectClick;
//
//
BuildDialogRect;
//
BuildButtons;
//
BuildContent;
//
BuildTitle(Title);
//
end;
destructor TFluendDialogContent.Destroy;
begin
inherited;
end;
function TFluendDialogContent.GetPrimaryButtonText: string;
begin
Result := FPrimaryButton.Text;
end;
function TFluendDialogContent.GetTitle: string;
begin
Result := FTitleUI.Text;
end;
procedure TFluendDialogContent.OnOverlayRectClick(Sender: TObject);
begin
Close;
end;
procedure TFluendDialogContent.SetContent(const Value: TControl);
begin
FContent := Value;
end;
procedure TFluendDialogContent.SetPrimaryButtonText(const Value: string);
begin
FPrimaryButton.Text := Value;
end;
procedure TFluendDialogContent.SetTitle(const Value: string);
begin
FTitleUI.Text := Value;
end;
procedure TFluendDialogContent.Show;
begin
UpdateParentForm;
BuildButtons;
//
BuildContent;
//
BuildTitle('Hello world');
end;
procedure TFluendDialogContent.UpdateParentForm;
begin
FOverlayRect.Parent := Screen.ActiveForm;
end;
{ TFluendDialog }
procedure TFluendDialog.BuildSubTitle(const AText: string);
begin
if not Assigned(FSubTextUI) then
FSubTextUI := TLabel.Create(FDialogRect);
FSubTextUI.Align := TAlignLayout.Top;
FSubTextUI.AutoSize := True;
FSubTextUI.Text := AText;
FSubTextUI.StyledSettings := [TStyledSetting.Style];
FSubTextUI.TextSettings.FontColor := $FF323130;
FSubTextUI.TextSettings.Font.Size := 20;
FSubTextUI.TextSettings.Font.Family := 'Segoe UI';
end;
constructor TFluendDialog.Create(AOwner: TComponent);
begin
inherited;
BuildSubTitle('Do you want to send this message without a subject?');
Content := FSubTextUI;
end;
destructor TFluendDialog.Destroy;
begin
inherited;
end;
function TFluendDialog.GetSubText: String;
begin
Result := FSubTextUI.Text;
end;
procedure TFluendDialog.SetSubText(const Value: String);
begin
FSubTextUI.Text := Value;
end;
end.
|
unit HideModuleUnit;
interface
uses Windows, Messages, SysUtils, Classes, TlHelp32;
type
TVirtualAlloc = function (lpvAddress: Pointer; dwSize, flAllocationType, flProtect: DWORD): Pointer; stdcall;
TVirtualProtect = function (lpAddress: Pointer; dwSize, flNewProtect: DWORD; var OldProtect: DWORD): BOOL; stdcall;
TVirtualFree = function (lpAddress: Pointer; dwSize, dwFreeType: DWORD): BOOL; stdcall;
TWriteProcessMemory = function (hProcess: THandle; const lpBaseAddress: Pointer; lpBuffer: Pointer; nSize: DWORD; var lpNumberOfBytesWritten: DWORD): BOOL; stdcall;
TGetCurrentProcess = function : THandle; stdcall;
TFreeLibrary = function (hLibModule: HMODULE): BOOL; stdcall;
THideModuleRec = record
pModule: pointer;
pVirtualAlloc: TVirtualAlloc;
pVirtualProtect: TVirtualProtect;
pVirtualFree: TVirtualFree;
pWriteProcessMemory: TWriteProcessMemory;
pGetCurrentProcess: TGetCurrentProcess;
pFreeLibrary: TFreeLibrary;
end;
PHideModuleRec = ^THideModuleRec;
procedure HideModule(hModule: THandle);
implementation
procedure ExecuteHide(HM: THideModuleRec);
var
pBakMemory: pointer;
ImageOptionalHeader: TImageOptionalHeader32;
ImageDosHeader: TImageDosHeader;
td: dword;
i: Integer;
begin
{ 取得映象数据 }
ImageDosHeader := PImageDosHeader(HM.pModule)^;
ImageOptionalHeader := PImageOptionalHeader32(Pointer(integer(HM.pModule) + ImageDosHeader._lfanew + SizeOf(dword) + SizeOf(TImageFileHeader)))^;
{ 申请内存以备份原始模块数据 }
pBakMemory := HM.pVirtualAlloc(nil, ImageOptionalHeader.SizeOfImage, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if pBakMemory = nil then
exit;
{ 修改原始内存为可读写属性 }
HM.pVirtualProtect(HM.pModule, ImageOptionalHeader.SizeOfImage,
PAGE_EXECUTE_READWRITE, td);
{ 备份原始模块数据 }
HM.pWriteProcessMemory(HM.pGetCurrentProcess, pBakMemory, HM.pModule,
ImageOptionalHeader.SizeOfImage, td);
{ 修改原DllEntryPoint为retn,防止FreeLibrary时的一些卸载操作 }
pByte(integer(HM.pModule) + ImageOptionalHeader.AddressOfEntryPoint)^ := $C3;
{ 卸载原模块,这里多次卸载防止因为LoadCount的关系一次卸载不掉 }
//HM.pFreeLibrary(integer(HM.pModule));
i := 0;
repeat
Inc(i);
until not HM.pFreeLibrary(integer(HM.pModule)) or (i >= 30);
{ 申请dll原始加载地址空间 }
HM.pModule := HM.pVirtualAlloc(HM.pModule, ImageOptionalHeader.SizeOfImage,
MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if HM.pModule = nil then
exit;
{ 写回原始数据 }
HM.pWriteProcessMemory(HM.pGetCurrentProcess, HM.pModule, pBakMemory,
ImageOptionalHeader.SizeOfImage, td);
{ 释放备份时用的内存 }
HM.pVirtualFree(pBakMemory, 0, MEM_RELEASE);
end;
(*注意该间隔处不能添加任何代码, 且不能改变上下2个函数位置
因为下面使用了2个函数入口来计算上一函数Size*)
procedure LockedAllModule(CurrentModuleHandle: THandle);
var
ModuleList: THandle;
pm: tagMODULEENTRY32;
begin
pm.dwSize := sizeof(tagMODULEENTRY32);
ModuleList := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0);
if not Module32First(ModuleList, pm) then
begin
CloseHandle(ModuleList);
exit;
end;
//不处理第一个模块,因为那是主模块
{ 对每个模块LoadLibrary一次,是为了把LoadCount加1 }
while Module32Next(ModuleList, pm) do
begin
if pm.hModule <> CurrentModuleHandle then
LoadLibrary(PWideChar(@GetModuleName(pm.hModule)[1]));
end;
CloseHandle(ModuleList);
end;
type
TExecuteHide = procedure (HM: THideModuleRec);
procedure HideModule(hModule: THandle);
var
HM: THideModuleRec;
pExecuteHide: pointer;
ExecuteHideSize: integer;
MyExecuteHide: TExecuteHide;
td: dword;
Module_kernel32: integer;
begin
Module_kernel32 := GetModuleHandle('kernel32.dll');
HM.pModule := pointer(hModule);
HM.pVirtualAlloc := GetProcAddress(Module_kernel32, 'VirtualAlloc');
HM.pVirtualProtect := GetProcAddress(Module_kernel32, 'VirtualProtect');
HM.pVirtualFree := GetProcAddress(Module_kernel32, 'VirtualFree');
HM.pWriteProcessMemory := GetProcAddress(Module_kernel32, 'WriteProcessMemory');
HM.pGetCurrentProcess := GetProcAddress(Module_kernel32, 'GetCurrentProcess');
HM.pFreeLibrary := GetProcAddress(Module_kernel32, 'FreeLibrary');
ExecuteHideSize := integer(@LockedAllModule) - Integer(@ExecuteHide);
pExecuteHide := VirtualAlloc(nil, ExecuteHideSize, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if pExecuteHide = nil then
Exit;
{ 防止系统将需要的Dll卸载掉 }
LockedAllModule(integer(HM.pModule));
CopyMemory(pExecuteHide, @ExecuteHide, ExecuteHideSize);
MyExecuteHide := pExecuteHide;
MyExecuteHide(HM);
end;
end.
|
type
maze = array of array of boolean;
function solvable(m: maze): boolean;
const
dx: array[0..3] of integer = (1, -1, 0, 0);
dy: array[0..3] of integer = (0, 0, 1, -1);
var
width, height: integer;
visited: array of array of boolean;
function valid(x, y: integer): boolean;
begin
exit((0 <= x) and (x < width) and (0 <= y) and (y < height));
end;
procedure visit(x, y: integer);
var
dir, x1, y1: integer;
begin
visited[x, y] := true;
for dir := 0 to 3 do
begin
x1 := x + dx[dir];
y1 := y + dy[dir];
if valid(x1, y1) and not visited[x1, y1] then
visit(x1, y1);
end;
end;
begin
width := length(m);
height := length(m[0]);
setLength(visited, width, height);
visit(0, 0);
exit(visited[width - 1, height - 1]);
end;
var
m:maze;
i,j:integer;
begin
setLength(m,3,3);
{ for i := 0 to 2 do begin
for j := 0 to 2 do begin
m[i][j]:=true;
end
end;
for j := 0 to 2 do begin
m[1][j]:= false;
end; }
writeln(solvable(m));
end. |
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE.
Description: MD5 self test routine for OverByteIcsMD5 unit.
Creation: Aug 01, 2007
Version: 7.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2007 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Dec 21, 2008 V1.01 F.Piette added a string cast in RunButtonClick to avoid
a warning when compiling with Delphi 2009.
Apr 16, 2009 V7.00 Angus allow choose specific file, compare buffered and
non-buffered MD5 and CRC32B
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsMD5Test1;
{$I OverbyteIcsDefs.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OverbyteIcsMD5, OverbyteIcsCrc, OverbyteIcsFtpSrvT;
type
TForm1 = class(TForm)
Memo1: TMemo;
RunButton: TButton;
Button1: TButton;
Button2: TButton;
OpenDialog: TOpenDialog;
TestFileName: TEdit;
dpFtpFileMd5: TButton;
doFileMd5: TButton;
doSelectFile: TButton;
doFileCrcB: TButton;
doFtpFileCrcB: TButton;
procedure RunButtonClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure doSelectFileClick(Sender: TObject);
procedure doFileMd5Click(Sender: TObject);
procedure dpFtpFileMd5Click(Sender: TObject);
procedure doFileCrcBClick(Sender: TObject);
procedure doFtpFileCrcBClick(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
// Strings to test MD5. Expected checksums are below.
// If you change strings, be sure tochange also expected checksums.
MD5TestStrings : array [0..6] of String = (
'' ,
'a' ,
'abc' ,
'message digest' ,
'abcdefghijklmnopqrstuvwxyz' ,
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ,
'12345678901234567890123456789012345678901234567890123456789012' +
'345678901234567890');
// Expected MD5 checksum for the above strings
MD5TestResults : array [0..6] of String = (
'D41D8CD98F00B204E9800998ECF8427E',
'0CC175B9C0F1B6A831C399E269772661',
'900150983CD24FB0D6963F7D28E17F72',
'F96B697D7CB7938D525A2F31AAF161D0',
'C3FCD3D76192E4007DFB496CCA67E13B',
'D174AB98D277D9F5A5611C2C9F419D9F',
'57EDF4A22BE3C955AC49DA2E2107B67A');
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function MD5SelfTest(Verbose : Boolean) : Boolean;
var
I : Integer;
MD5Sum : String;
Buf : String;
begin
for I := 0 to 6 do begin
if Verbose then
Buf := 'MD5 test #' + IntToStr(I + 1) + ': ';
MD5Sum := StrMD5(MD5TestStrings[I]);
if not SameText(MD5Sum, MD5TestResults[I]) then begin
if Verbose then
Form1.Memo1.Lines.Add(Buf + 'failed');
Result := TRUE;
Exit;
end;
if Verbose then
Form1.Memo1.Lines.Add(Buf + 'passed');
end;
Result := FALSE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.Button1Click(Sender: TObject);
var
MD5Context : TMD5Context;
I : Integer;
begin
FillChar(MD5Context, SizeOf(TMD5Context), #0);
MD5Context.BufLong[0] := $12345678;
for I := 0 to 3 do
Memo1.Lines.Add(IntToHex(MD5GetBufChar(MD5Context, I), 2)
{$IFNDEF SAFE}
+ ' ' + IntToHex(MD5Context.BufChar[I], 2)
{$ENDIF}
);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
MD5Context : TMD5Context;
I : Integer;
begin
FillChar(MD5Context, SizeOf(TMD5Context), #0);
MD5Context.BufLong[0] := $12345678;
for I := 0 to 3 do begin
MD5SetBufChar(MD5Context, I, MD5GetBufChar(MD5Context, I));
Memo1.Lines.Add(IntToHex(MD5Context.BufLong[0], 8));
end;
MD5SetBufChar(MD5Context, 0, $78);
MD5SetBufChar(MD5Context, 1, $56);
MD5SetBufChar(MD5Context, 2, $34);
MD5SetBufChar(MD5Context, 3, $12);
Memo1.Lines.Add(IntToHex(MD5Context.BufLong[0], 8));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.doFileCrcBClick(Sender: TObject);
var
starttick: longword ;
filesize: int64 ;
begin
filesize := IcsGetFileSize (TestFileName.Text) ;
if filesize < 0 then
begin
Form1.Memo1.Lines.Add('File not found: ' + TestFileName.Text) ;
exit ;
end;
Form1.Memo1.Lines.Add ('Starting non-buffered CRC32B for: ' + TestFileName.Text +
', Size ' + IntToKbyte (filesize)) ;
starttick := IcsGetTickCountX ;
Form1.Memo1.Lines.Add ('FileCRC32B: ' + FileCRC32B(TestFileName.Text)) ;
Form1.Memo1.Lines.Add ('Took ' + IntToStr (IcsElapsedMSecs (starttick)) + 'ms') ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.doFileMd5Click(Sender: TObject);
var
starttick: longword ;
filesize: int64 ;
begin
filesize := IcsGetFileSize (TestFileName.Text) ;
if filesize < 0 then
begin
Form1.Memo1.Lines.Add('File not found: ' + TestFileName.Text) ;
exit ;
end;
Form1.Memo1.Lines.Add ('Starting non-buffered MD5 for: ' + TestFileName.Text +
', Size ' + IntToKbyte (filesize)) ;
starttick := IcsGetTickCountX ;
Form1.Memo1.Lines.Add ('FileMD5: ' + String(FileMD5(TestFileName.Text))) ;
Form1.Memo1.Lines.Add ('Took ' + IntToStr (IcsElapsedMSecs (starttick)) + 'ms') ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.doFtpFileCrcBClick(Sender: TObject);
var
starttick: longword ;
filesize: int64 ;
begin
filesize := IcsGetFileSize (TestFileName.Text) ;
if filesize < 0 then
begin
Form1.Memo1.Lines.Add('File not found: ' + TestFileName.Text) ;
exit ;
end;
Form1.Memo1.Lines.Add ('Starting buffered CRC32B for: ' + TestFileName.Text +
', Size ' + IntToKbyte (filesize)) ;
starttick := IcsGetTickCountX ;
Form1.Memo1.Lines.Add ('FtpFileCRC32B: ' + FtpFileCRC32B(TestFileName.Text)) ;
Form1.Memo1.Lines.Add ('Took ' + IntToStr (IcsElapsedMSecs (starttick)) + 'ms') ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.doSelectFileClick(Sender: TObject);
begin
OpenDialog.FileName := TestFileName.Text ;
if OpenDialog.Execute then
TestFileName.Text := OpenDialog.FileName ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.dpFtpFileMd5Click(Sender: TObject);
var
starttick: longword ;
filesize: int64 ;
begin
filesize := IcsGetFileSize (TestFileName.Text) ;
if filesize < 0 then
begin
Form1.Memo1.Lines.Add('File not found: ' + TestFileName.Text) ;
exit ;
end;
Form1.Memo1.Lines.Add ('Starting buffered MD5 for: ' + TestFileName.Text +
', Size ' + IntToKbyte (filesize)) ;
starttick := IcsGetTickCountX ;
Form1.Memo1.Lines.Add ('FtpFileMD5: ' + FtpFileMD5(TestFileName.Text)) ;
Form1.Memo1.Lines.Add ('Took ' + IntToStr (IcsElapsedMSecs (starttick)) + 'ms') ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TForm1.RunButtonClick(Sender: TObject);
var
FileName : String;
Stream : TFileStream;
I : Integer;
begin
Form1.Memo1.Clear;
{$IFDEF SAFE}
Form1.Memo1.Lines.Add('SAFE version');
{$ENDIF}
if MD5SelfTest(TRUE) then
Form1.Memo1.Lines.Add('MD5 library failed')
else
Form1.Memo1.Lines.Add('MD5 library passed');
FileName := 'Test.txt';
Stream := TFileStream.Create(FileName, fmCreate);
for I := 1 to Length(MD5TestStrings[3]) do
Stream.Write(MD5TestStrings[3][I], 1);
Stream.Free;
if not SameText(MD5TestResults[3],
String(FileMD5(FileName))) then
Form1.Memo1.Lines.Add('FileMD5 failed')
else
Form1.Memo1.Lines.Add('FileMD5 passed');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit SourceManage;
interface
uses Classes, SysUtils, Graphics, Controls, Comctrls, GospelEditor,
mwGeneralSyn, mwCustomEdit;
const
IncludeExt = '.gos';
ApplicationExt = '.gaf';
ProjectExt = '.gpr';
DefaultApp = 'Application1';
DefaultModule = 'Module';
Untitled = 'Untitled';
imCodeLine = 15;
imBreakpointEnable = 16;
imBreakPointInvalid = 17;
imBreakpointValid = 18;
imExecution = 21;
type
ESourceManage = class(Exception);
TSourceManager =
class
private
FEditionList: TStringList;
FContainer: TPageControl;
FOnEditorMoveCaret: TCaretMoveEvent;
FActiveModule: string;
FSearchPath: string;
FOutputDirectory: string;
FAppName: string;
FAppDirectory: string;
FActiveEditor: TCodeEdit;
FFontSize: integer;
FFontName: TFontName;
mwGeneralSyn: TmwGeneralSyn;
function GetEditor(const i: integer): TCodeEdit;
procedure SetActiveModule(const Value: string);
procedure SetAppDirectory(const Value: string);
procedure SetAppName(const Value: string);
function NewEditor(const Name: string): TCodeEdit;
function GetDefaultName: string;
procedure SetFontName(const Value: TFontName);
procedure SetFontSize(const Value: integer);
procedure UpDateEditFonts;
procedure OnPageChange(Sender: TObject);
function ExtractFileNameWithoutExt(const FileName: TFileName): string;
function GetEditCount: integer;
function GetModule(const i: integer): string;
procedure SetModule(const i: integer; const Value: string);
function GetApplicationModified: boolean;
function BuildFileName(const Dir, Name, Ext: string): string;
function GetHasApplication: boolean;
function GetSource(const ModuleName: string): string;
function FindInclude(const ModuleName: string; var Path: string): boolean;
procedure TabSheetEnter(Sender: TObject);
procedure InitilizeSyntaxHighLighter;
procedure EditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure PutImage(Edit: TCodeEdit; const aLine, Image: integer);
public
constructor Create(aContainer: TPageControl; anOnEditorMoveCaret: TCaretMoveEvent);
destructor Destroy; override;
procedure NewModule;
procedure NewApplication;
procedure OpenModule(const Name: string);
procedure OpenApplication(const FileName: TFileName);
procedure OpenFile(const FileName: TFileName);
procedure SaveProjectAs(const FileName: TFileName);
procedure SaveApplication(Editor: TCodeEdit; const FileName: TFileName);
procedure SaveModule(Editor: TCodeEdit; const FileName: TFileName);
procedure Save(Editor: TCodeEdit; const FileName: TFileName);
procedure CloseActiveModule;
procedure CloseAll;
function IsOpen(const Name: string): boolean;
function GetFileOpen(const FileName: TFileName): integer;
function EditorNumber(const Name: string): integer;
procedure SaveProjectFile;
procedure LoadProjectFile;
procedure MarkCodeLines(Edit: TCodeEdit);
procedure RemoveCodeMarks;
procedure CheckBreakPoint;
procedure PutBreakPoint;
property Editor[const i: integer]: TCodeEdit read GetEditor;
property EditingModule[const i: integer]: string read GetModule write SetModule;
property ActiveModule: string read FActiveModule write SetActiveModule;
property ActiveEditor: TCodeEdit read FActiveEditor;
property OnEditorMoveCaret: TCaretMoveEvent read FOnEditorMoveCaret write FOnEditorMoveCaret;
property SearchPath: string read FSearchPath write FSearchPath;
property OutputDirectory: string read FOutputDirectory write FOutputDirectory;
property AppDirectory: string read FAppDirectory write SetAppDirectory;
property AppName: string read FAppName write SetAppName;
property FontName: TFontName read FFontName write SetFontName;
property FontSize: integer read FFontSize write SetFontSize;
property EditCount: integer read GetEditCount;
property ApplicationModified: boolean read GetApplicationModified;
property HasApplication: boolean read GetHasApplication;
property Source[const ModuleName: string]: string read GetSource;
end;
implementation
uses Constants, PrjManager, Parser, ReMain, Kernel;
{ TSourceManager }
procedure TSourceManager.CloseActiveModule;
var
i: integer;
begin
i := FEditionList.IndexOf(FContainer.ActivePage.Caption);
if FContainer.PageCount = 1
then FContainer.ActivePage := nil;
TTabSheet(Editor[i].Parent).free;
FEditionList.Delete(i);
if FEditionList.Count > 0
then ActiveModule := FEditionList[FContainer.ActivePage.PageIndex];
if FContainer.PageCount = 0
then FActiveEditor := nil;
end;
procedure TSourceManager.CloseAll;
var
i: integer;
begin
for i := 1 to EditCount do
CloseActiveModule;
FActiveModule := '';
FAppName := '';
FAppDirectory := '';
end;
constructor TSourceManager.Create(aContainer: TPageControl; anOnEditorMoveCaret: TCaretMoveEvent);
begin
inherited Create;
FContainer := aContainer;
FContainer.OnChange := OnPageChange;
FEditionList := TStringList.Create;
OnEditorMoveCaret := anOnEditorMoveCaret;
InitilizeSyntaxHighLighter;
end;
destructor TSourceManager.Destroy;
begin
FEditionList.free;
inherited;
end;
function TSourceManager.ExtractFileNameWithoutExt(const FileName: TFileName): string;
begin
Result := ExtractFileName(FileName);
Result := Copy(Result, 1, pred(Pos('.', Result)));
end;
function TSourceManager.GetApplicationModified: boolean;
var
i: integer;
begin
i := 0;
Result := false;
while (i < EditCount) and not Result do
begin
Result := Editor[i].Modified;
inc(i);
end;
end;
function TSourceManager.GetDefaultName: string;
var
i: integer;
begin
i := 1;
while FEditionList.IndexOf(DefaultModule + IntToStr(i)) <> -1
do inc(i);
Result := DefaultModule + IntToStr(i);
end;
function TSourceManager.GetEditCount: integer;
begin
Result := FEditionList.Count;
end;
function TSourceManager.GetEditor(const i: integer): TCodeEdit;
begin
if FEditionList.Count = 0
then Result := nil
else Result := TCodeEdit(FEditionList.Objects[i]);
end;
function TSourceManager.GetModule(const i: integer): string;
begin
Result := FEditionList[i];
end;
function TSourceManager.GetFileOpen(const FileName: TFileName): integer;
var
Found: boolean;
begin
Found := false;
Result := 0;
while (Result < EditCount) and not Found do
begin
Found := Editor[Result].FileName = FileName;
inc(Result);
end;
dec(Result);
if not Found
then Result := -1;
end;
function TSourceManager.IsOpen(const Name: string): boolean;
begin
Result := FEditionList.IndexOf(Name) <> -1;
end;
procedure TSourceManager.NewApplication;
var
Editor: TCodeEdit;
begin
FAppName := DefaultApp;
FAppDirectory := GetCurrentDir;
Editor := NewEditor(FAppName);
Editor.FileName := BuildFileName(FAppDirectory, FAppName, ApplicationExt);
Editor.Lines.Add('program ' + FAppName + ';');
Editor.Lines.Add('');
Editor.Lines.Add('begin');
Editor.Lines.Add('end.');
Editor.Lines.Add('');
ProjectManager.Add(FAppDirectory, FAppName, ApplicationExt);
end;
function TSourceManager.NewEditor(const Name: string): TCodeEdit;
var
TabSheet: TTabSheet;
begin
TabSheet := TTabSheet.Create(FContainer);
TabSheet.Visible := false;
TabSheet.Caption := Name;
TabSheet.PageControl := FContainer;
TabSheet.OnEnter := TabSheetEnter;
Result := TCodeEdit.Create(TabSheet);
Result.Parent := TabSheet;
Result.Align := alClient;
Result.OnCaretMove := OnEditorMoveCaret;
Result.Lines.Clear;
Result.Font.Name := FontName;
Result.Font.Size := FontSize;
Result.HighLighter := mwGeneralSyn;
Result.BookMarkImages := ReMain.CompilerIDE.ImageList1;
Result.OnMouseUp := EditMouseUp;
FEditionList.AddObject(Name, Result);
ActiveModule := Name;
end;
procedure TSourceManager.NewModule;
var
Editor: TCodeEdit;
Name: string;
begin
Name := GetDefaultName;
Editor := NewEditor(Name);
Editor.FileName := BuildFileName(FAppDirectory, Name, IncludeExt);
Editor.Lines.Add('module ' + Name + ';');
Editor.Lines.Add('');
Editor.Lines.Add('begin');
Editor.Lines.Add('end.');
Editor.Lines.Add('');
if HasApplication
then ProjectManager.Add(FAppDirectory, Name, IncludeExt);
end;
procedure TSourceManager.OnPageChange(Sender: TObject);
begin
ActiveModule := FEditionList[FContainer.ActivePage.Pageindex];
end;
procedure TSourceManager.OpenFile(const FileName: TFileName);
var
Editor: TCodeEdit;
FileIndex: integer;
Name: string;
begin
FileIndex := GetFileOpen(FileName);
if FileIndex >= 0
then ActiveModule := EditingModule[FileIndex]
else
begin
Name := ExtractFileNameWithoutExt(FileName);
Editor := NewEditor(Name);
try
Editor.Lines.LoadFromFile(FileName);
Editor.Modified := False;
Editor.FileName := FileName;
Editor.Filed := true;
except
Editor.free;
raise;
end;
end;
end;
procedure TSourceManager.OpenModule(const Name: string);
var
Path: string;
begin
if FindInclude(Name, Path)
then OpenFile(Path)
else raise ESourceManage.Create(Format(emFileNotFound, [Name]));
end;
procedure TSourceManager.Save(Editor: TCodeEdit; const FileName: TFileName);
begin
if TTabSheet(Editor.Parent).Caption = FAppName
then SaveApplication(Editor, FileName)
else SaveModule(Editor, FileName);
end;
procedure TSourceManager.SaveApplication(Editor: TCodeEdit; const FileName: TFileName);
begin
FAppName := ExtractFileNameWithoutExt(FileName);
FAppDirectory := ExtractFileDir(FileName);
SetCurrentDir(FAppDirectory);
SaveModule(Editor, FileName);
SaveProjectFile;
end;
procedure TSourceManager.SaveModule(Editor: TCodeEdit; const FileName: TFileName);
var
i: integer;
Name: string;
begin
i := FEditionList.IndexOfObject(Editor);
Name := ExtractFileNameWithoutExt(FileName);
if Editor.FileName <> FileName
then ProjectManager.Replace(EditingModule[i] +
ExtractFileExt(Editor.FileName), ExtractFileDir(FileName),
Name + ExtractFileExt(FileName));
Editor.Lines.SaveToFile(FileName);
EditingModule[i] := Name;
Editor.FileName := FileName;
Editor.Modified := false;
Editor.Filed := true;
end;
procedure TSourceManager.SetActiveModule(const Value: string);
var
i: integer;
begin
i := FEditionList.IndexOf(Value);
if i >= 0
then
begin
FActiveEditor := Editor[i];
FContainer.ActivePage := TTabSheet(Editor[i].Parent);
FActiveModule := Value;
end;
end;
procedure TSourceManager.SetAppDirectory(const Value: string);
begin
FAppDirectory := Value;
end;
procedure TSourceManager.SetAppName(const Value: string);
begin
FAppName := Value;
end;
procedure TSourceManager.SetFontName(const Value: TFontName);
begin
if Value <> FFontName
then
begin
FFontName := Value;
UpDateEditFonts;
end;
end;
procedure TSourceManager.SetFontSize(const Value: integer);
begin
if Value <> FFontSize
then
begin
FFontSize := Value;
UpDateEditFonts;
end;
end;
procedure TSourceManager.SetModule(const i: integer; const Value: string);
begin
if FEditionList[i] <> Value
then
begin
FEditionList[i] := Value;
TTabSheet(Editor[i].Parent).Caption := Value;
end;
end;
procedure TSourceManager.UpDateEditFonts;
var
i: integer;
begin
for i := 0 to pred(FEditionList.Count) do
begin
Editor[i].Font.Name := FontName;
Editor[i].Font.Size := FontSize;
end;
end;
procedure TSourceManager.OpenApplication(const FileName: TFileName);
begin
OpenFile(FileName);
FAppName := ExtractFileNameWithoutExt(FileName);
FAppDirectory := ExtractFileDir(FileName);
SetCurrentDir(FAppDirectory);
LoadProjectFile;
end;
function TSourceManager.BuildFileName(const Dir, Name, Ext: string): string;
begin
Result := Dir + '\' + Name + Ext;
end;
procedure TSourceManager.SaveProjectFile;
var
i: integer;
Data: TStringList;
begin
if (ProjectManager.FileCount > 0) and HasApplication
then
begin
Data := TStringList.Create;
for i := 0 to pred(ProjectManager.FileCount) do
Data.Add(ProjectManager.FileName[i]);
Data.SaveToFile(BuildFileName(FAppDirectory, FAppName, ProjectExt));
Data.free;
end;
end;
procedure TSourceManager.LoadProjectFile;
var
i: integer;
Data: TStringList;
begin
Data := TStringList.Create;
try
Data.LoadFromFile(BuildFileName(FAppDirectory, FAppName, ProjectExt));
if Data.Count > 0
then
for i := 0 to pred(Data.Count) do
ProjectManager.Add(ExtractFileDir(Data[i]), ExtractFileNameWithoutExt(Data[i]), ExtractFileExt(Data[i]));
except
ProjectManager.Add(FAppDirectory, FAppName, ApplicationExt);
end;
Data.free;
end;
procedure TSourceManager.SaveProjectAs(const FileName: TFileName);
var
Index: integer;
Data: TStringList;
begin
Index := FEditionList.IndexOf(AppName);
if Index <> -1
then SaveApplication(Editor[Index], FileName)
else
begin
Data := TStringList.Create;
Data.LoadFromFile(BuildFileName(AppDirectory, AppName, ApplicationExt));
if BuildFileName(AppDirectory, AppName, ApplicationExt) <> FileName
then ProjectManager.Replace(BuildFileName('', AppName, ApplicationExt),
ExtractFileDir(FileName), ExtractFileName(FileName));
FAppName := ExtractFileNameWithoutExt(FileName);
FAppDirectory := ExtractFileDir(FileName);
SetCurrentDir(FAppDirectory);
Data.SaveToFile(FileName);
SaveProjectFile;
Data.free;
end;
end;
function TSourceManager.GetHasApplication: boolean;
begin
Result := AppName <> '';
end;
function TSourceManager.GetSource(const ModuleName: string): string;
var
Index: integer;
S: TStringList;
Path: string;
begin
Index := FEditionList.IndexOf(ModuleName);
if Index >= 0
then Result := Editor[Index].Lines.Text
else
begin
S := TStringList.Create;
try
Index := ProjectManager.GetModuleIndex(ModuleName);
if Index >= 0
then S.LoadFromFile(ProjectManager.FileName[Index])
else
if FindInclude(ModuleName, Path)
then S.LoadFromFile(Path)
else raise ESourceManage.Create(Format(emFileNotFound, [ModuleName]));
Result := S.Text;
finally
S.free;
end;
end;
end;
function TSourceManager.EditorNumber(const Name: string): integer;
begin
Result := FEditionList.IndexOf(Name);
end;
function TSourceManager.FindInclude(const ModuleName: string; var Path: string): boolean;
var
Dir: string;
begin
Path := '';
if FileExists(BuildFileName(FAppDirectory, ModuleName, IncludeExt))
then Path := BuildFileName(FAppDirectory, ModuleName, IncludeExt)
else
begin
Dir := FileSearch(BuildFileName('', ModuleName, IncludeExt), FSearchPath);
if Dir <> ''
then Path := BuildFileName(Dir, ModuleName, IncludeExt);
end;
Result := Path <> '';
end;
procedure TSourceManager.TabSheetEnter(Sender: TObject);
var
Ed: TCodeEdit;
begin
Ed := TCodeEdit(TTabSheet(Sender).Controls[0]);
OnEditorMoveCaret(Ed, Ed.CaretX, Ed.CaretY);
TCodeEdit(TTabSheet(Sender).Controls[0]).SetFocus;
end;
procedure TSourceManager.InitilizeSyntaxHighLighter;
var
i: integer;
begin
mwGeneralSyn := TmwGeneralSyn.Create(FContainer);
with mwGeneralSyn do
begin
for i := 0 to pred(ReservedWords.Count) do
KeyWords.Add(ReservedWords.Strings[i]);
NumberAttri.ForeGround := clBlue;
CommentAttri.ForeGround := clNavy;
StringAttri.ForeGround := clRed;
Comments := [csPasStyle, csAnsiStyle];
end;
end;
procedure TSourceManager.PutBreakPoint;
var
BreakPoint: TBreakPoint;
Statement: TStatement;
Marks: TMarks;
begin
BreakPoint := ActiveEditor.BreakPoints.GetBreakPointFromLine(ActiveEditor.CaretY);
if CompilerIDE.GospelCompiler.Runner.Runing
then Statement := TStatement(ActiveEditor.Lines.Objects[ActiveEditor.CaretY])
else Statement := nil;
if BreakPoint = nil
then
begin
BreakPoint := TBreakPoint.Create(ActiveEditor);
BreakPoint.Line := ActiveEditor.CaretY;
ActiveEditor.Marks.GetMarksForLine(BreakPoint.Line, Marks);
if (Marks[1] <> nil) and (Marks[1].ImageIndex = imCodeLine)
then Marks[1].Visible := false;
ActiveEditor.BreakPoints.Add(BreakPoint);
if CompilerIDE.GospelCompiler.Runner.Runing
then
if Statement <> nil
then
begin
Statement.HasBreakPoint := true;
BreakPoint.ImageIndex := imBreakpointValid;
end
else
begin
BreakPoint.ImageIndex := imBreakpointInvalid;
BreakPoint.ForeGround := clLime;
BreakPoint.BackGround := clOlive;
end
else BreakPoint.ImageIndex := imBreakpointEnable;
end
else // Remove the BreakPoint
begin
ActiveEditor.BreakPoints.Remove(BreakPoint);
ActiveEditor.Marks.GetMarksForLine(BreakPoint.Line, Marks);
if (Marks[1] <> nil) and (Marks[1].ImageIndex = imCodeLine)
then Marks[1].Visible := true;
BreakPoint.free;
if CompilerIDE.GospelCompiler.Runner.Runing and (Statement <> nil)
then Statement.HasBreakPoint := false;
end;
end;
procedure TSourceManager.EditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if X < ActiveEditor.GutterWidth
then PutBreakPoint;
end;
procedure TSourceManager.MarkCodeLines(Edit: TCodeEdit);
var
i: integer;
begin
for i := 0 to pred(Edit.Lines.Count) do
if Edit.Lines.Objects[i] <> nil
then PutImage(Edit, i, imCodeLine);
end;
procedure TSourceManager.PutImage(Edit: TCodeEdit; const aLine, Image: integer);
var
mark: TMark;
begin
with Edit do
begin
mark := TMark.Create(Edit);
with mark do
begin
Line := aLine;
Column := 0;
ImageIndex := Image;
IsBookmark := false;
if Edit.BreakPoints.GetBreakPointFromLine(aLine) = nil
then Visible := true
else Visible := false;
PaintLine := false;
InternalImage := false;
end;
Marks.Insert(0, mark); //Marks.Place(mark);
end;
end;
procedure TSourceManager.RemoveCodeMarks;
var
i, j: integer;
Marks: TMarks;
begin
for i := 0 to pred(EditCount) do
for j := 0 to pred(Editor[i].Lines.Count) do
if Editor[i].Lines.Objects[j] <> nil
then
begin
Editor[i].Marks.GetMarksForLine(j, Marks);
if (Marks[1] <> nil) and (Marks[1].ImageIndex = imCodeLine)
then Editor[i].Marks.Remove(Marks[1]);
end;
end;
procedure TSourceManager.CheckBreakPoint;
var
i, j: integer;
Statement: TStatement;
begin
for i := 0 to pred(EditCount) do
for j := 0 to pred(Editor[i].BreakPoints.Count) do
if Editor[i].Lines.Objects[Editor[i].BreakPoints[j].Line] <> nil
then
begin
Editor[i].BreakPoints[j].ImageIndex := imBreakPointValid;
Statement := TStatement(Editor[i].Lines.Objects[Editor[i].BreakPoints[j].Line]);
Statement.HasBreakPoint := true;
end
else
begin
Editor[i].BreakPoints[j].ImageIndex := imBreakPointInvalid;
Editor[i].BreakPoints[j].ForeGround := clLime;
Editor[i].BreakPoints[j].BackGround := clOlive;
end;
end;
end.
|
unit MandelbrotGenerator;
{$SCOPEDENUMS ON}
interface
uses
System.Classes;
type
TPrecision = (Single, Double, DoubleDouble, QuadDouble);
type
TSurface = record
public
Width: Integer;
Height: Integer;
Data: TArray<Integer>;
end;
type
TMandelbrotGenerator = class(TThread)
public const
WIDTH = 300;
HEIGHT = 300;
private
FSurface: TSurface;
FMaxIterations: Integer;
FMagnification: Double;
FPrecision: TPrecision;
private
procedure GenerateSingle;
procedure GenerateDouble;
procedure GenerateDoubleDouble;
procedure GenerateQuadDouble;
protected
procedure Execute; override;
public
constructor Create(const AMaxIterations: Integer;
const AMagnification: Double; const APrecision: TPrecision);
property Surface: TSurface read FSurface;
end;
implementation
uses
System.SysUtils,
Neslib.MultiPrecision;
const
CENTER_RE = '-0.00677652295833245729642263781984627256356509565412970431582937';
CENTER_IM = '1.00358346588202262420197968965648988617755127635794148856757956';
var
USFormatSettings: TFormatSettings;
{ TMandelbrotGenerator }
constructor TMandelbrotGenerator.Create(const AMaxIterations: Integer;
const AMagnification: Double; const APrecision: TPrecision);
begin
inherited Create(False);
FMaxIterations := AMaxIterations;
FMagnification := AMagnification;
FPrecision := APrecision;
FSurface.Width := WIDTH;
FSurface.Height := HEIGHT;
SetLength(FSurface.Data, WIDTH * HEIGHT);
end;
procedure TMandelbrotGenerator.Execute;
begin
case FPrecision of
TPrecision.Single : GenerateSingle;
TPrecision.Double : GenerateDouble;
TPrecision.DoubleDouble: GenerateDoubleDouble;
TPrecision.QuadDouble : GenerateQuadDouble;
end;
end;
procedure TMandelbrotGenerator.GenerateDouble;
var
CenterRe, CenterIm, Radius, XStart, YStart, X, Y, Step: Double;
ZRe, ZIm, ZReSq, ZImSq, NewIm: Double;
Row, Col, Iter, MaxIter: Integer;
Data: PInteger;
begin
CenterRe := StrToFloat(CENTER_RE, USFormatSettings);
CenterIm := StrToFloat(CENTER_IM, USFormatSettings);
Radius := 2.5 / FMagnification;
MaxIter := FMaxIterations;
XStart := CenterRe - (Radius * 0.5);
YStart := CenterIm - (Radius * 0.5);
Step := Radius / FSurface.Width;
Data := @FSurface.Data[0];
for Row := 0 to FSurface.Height - 1 do
begin
Y := YStart + (Row * Step);
for Col := 0 to FSurface.Width - 1 do
begin
X := XStart + (Col * Step);
ZRe := X;
ZIm := Y;
Iter := 0;
while (Iter < MaxIter) do
begin
ZReSq := ZRe * ZRe;
ZImSq := ZIm * ZIm;
if ((ZReSq + ZImSq) > 4) then
Break;
NewIm := 2 * ZRe * ZIm;
ZRe := X + (ZReSq - ZImSq);
ZIm := Y + NewIm;
Inc(Iter);
end;
if (Iter = MaxIter) then
Data^ := -1
else
Data^ := Iter;
Inc(Data);
if (Terminated) then
Exit;
end;
end;
end;
procedure TMandelbrotGenerator.GenerateDoubleDouble;
var
CenterRe, CenterIm, Radius, XStart, YStart, X, Y, Step: DoubleDouble;
ZRe, ZIm, ZReSq, ZImSq, NewIm: DoubleDouble;
Row, Col, Iter, MaxIter: Integer;
Data: PInteger;
begin
MultiPrecisionInit;
CenterRe := CENTER_RE;
CenterIm := CENTER_IM;
Radius := Divide(2.5, FMagnification);
MaxIter := FMaxIterations;
XStart := CenterRe - (Radius * 0.5);
YStart := CenterIm - (Radius * 0.5);
Step := Radius / FSurface.Width;
Data := @FSurface.Data[0];
for Row := 0 to FSurface.Height - 1 do
begin
Y := YStart + (Row * Step);
for Col := 0 to FSurface.Width - 1 do
begin
X := XStart + (Col * Step);
ZRe := X;
ZIm := Y;
Iter := 0;
while (Iter < MaxIter) do
begin
ZReSq := ZRe * ZRe;
ZImSq := ZIm * ZIm;
if ((ZReSq + ZImSq).ToDouble > 4) then
Break;
NewIm := 2 * ZRe * ZIm;
ZRe := X + (ZReSq - ZImSq);
ZIm := Y + NewIm;
Inc(Iter);
end;
if (Iter = MaxIter) then
Data^ := -1
else
Data^ := Iter;
Inc(Data);
if (Terminated) then
Exit;
end;
end;
end;
procedure TMandelbrotGenerator.GenerateQuadDouble;
var
CenterRe, CenterIm, Radius, XStart, YStart, X, Y, Step: QuadDouble;
ZRe, ZIm, ZReSq, ZImSq, NewIm: QuadDouble;
Row, Col, Iter, MaxIter: Integer;
Data: PInteger;
begin
MultiPrecisionInit;
CenterRe := CENTER_RE;
CenterIm := CENTER_IM;
Radius.Init(2.5 / FMagnification);
MaxIter := FMaxIterations;
XStart := CenterRe - (Radius * 0.5);
YStart := CenterIm - (Radius * 0.5);
Step := Radius / FSurface.Width;
Data := @FSurface.Data[0];
for Row := 0 to FSurface.Height - 1 do
begin
Y := YStart + (Row * Step);
for Col := 0 to FSurface.Width - 1 do
begin
X := XStart + (Col * Step);
ZRe := X;
ZIm := Y;
Iter := 0;
while (Iter < MaxIter) do
begin
ZReSq := ZRe * ZRe;
ZImSq := ZIm * ZIm;
if ((ZReSq + ZImSq).ToDouble > 4) then
Break;
NewIm := 2 * ZRe * ZIm;
ZRe := X + (ZReSq - ZImSq);
ZIm := Y + NewIm;
Inc(Iter);
end;
if (Iter = MaxIter) then
Data^ := -1
else
Data^ := Iter;
Inc(Data);
if (Terminated) then
Exit;
end;
end;
end;
procedure TMandelbrotGenerator.GenerateSingle;
var
CenterRe, CenterIm, Radius, XStart, YStart, X, Y, Step: Single;
ZRe, ZIm, ZReSq, ZImSq, NewIm: Single;
Row, Col, Iter, MaxIter: Integer;
Data: PInteger;
begin
CenterRe := StrToFloat(CENTER_RE, USFormatSettings);
CenterIm := StrToFloat(CENTER_IM, USFormatSettings);
Radius := 2.5 / FMagnification;
MaxIter := FMaxIterations;
XStart := CenterRe - (Radius * 0.5);
YStart := CenterIm - (Radius * 0.5);
Step := Radius / FSurface.Width;
Data := @FSurface.Data[0];
for Row := 0 to FSurface.Height - 1 do
begin
Y := YStart + (Row * Step);
for Col := 0 to FSurface.Width - 1 do
begin
X := XStart + (Col * Step);
ZRe := X;
ZIm := Y;
Iter := 0;
while (Iter < MaxIter) do
begin
ZReSq := ZRe * ZRe;
ZImSq := ZIm * ZIm;
if ((ZReSq + ZImSq) > 4) then
Break;
NewIm := 2 * ZRe * ZIm;
ZRe := X + (ZReSq - ZImSq);
ZIm := Y + NewIm;
Inc(Iter);
end;
if (Iter = MaxIter) then
Data^ := -1
else
Data^ := Iter;
Inc(Data);
if (Terminated) then
Exit;
end;
end;
end;
initialization
USFormatSettings := TFormatSettings.Create('en-US');
USFormatSettings.DecimalSeparator := '.';
USFormatSettings.ThousandSeparator := ',';
end.
|
unit KDictDescriptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, KInfoDictionaryFrame, ExtCtrls, KAllDicts, StdCtrls, Buttons;
type
TfrmDicts = class(TForm)
frmAllDicts: TfrmAllDicts;
Splitter1: TSplitter;
Panel1: TPanel;
btnOK: TBitBtn;
frmInfoDictionary: TfrmInfoDictionary;
procedure btnOKClick(Sender: TObject);
procedure frmAllDictslstAllDictsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure DoOnObjectAdd(Sender: TObject);
procedure DoOnObjectDelete(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
end;
var
frmDicts: TfrmDicts;
implementation
uses Facade;
{$R *.dfm}
{ TfrmDicts }
constructor TfrmDicts.Create(AOwner: TComponent);
begin
inherited;
frmAllDicts.GUIAdapter.OnAfterDelete := DoOnObjectDelete;
frmAllDicts.GUIAdapter.OnAfterAdd := DoOnObjectAdd;
end;
procedure TfrmDicts.DoOnObjectAdd(Sender: TObject);
begin
frmInfoDictionary.ActiveDict := frmAllDicts.ActiveDict;
end;
procedure TfrmDicts.DoOnObjectDelete(Sender: TObject);
begin
frmInfoDictionary.ActiveDict := nil;
end;
procedure TfrmDicts.btnOKClick(Sender: TObject);
begin
frmInfoDictionary.GUIAdapter.ChangeMade := true;
end;
procedure TfrmDicts.frmAllDictslstAllDictsClick(Sender: TObject);
begin
frmInfoDictionary.ActiveDict := frmAllDicts.ActiveDict;
if frmInfoDictionary.ActiveDict.Name = 'Литология (нередактируемый справочник)' then
frmInfoDictionary.SetActiveElements(false)
else frmInfoDictionary.SetActiveElements(true);
end;
procedure TfrmDicts.FormClose(Sender: TObject; var Action: TCloseAction);
begin
(TMainFacade.GetInstance as TMainFacade).ClearWords;
end;
end.
|
object EditOrderByteForm: TEditOrderByteForm
Left = 214
Top = 142
BorderStyle = bsToolWindow
Caption = 'Edit Byte Order'
ClientHeight = 103
ClientWidth = 325
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poDesktopCenter
DesignSize = (
325
103)
PixelsPerInch = 96
TextHeight = 13
object labInfo: TLabel
Left = 168
Top = 8
Width = 153
Height = 41
Alignment = taCenter
Anchors = [akLeft, akTop, akRight, akBottom]
AutoSize = False
Layout = tlCenter
WordWrap = True
end
object bnOk: TButton
Left = 49
Top = 74
Width = 75
Height = 25
Anchors = [akLeft, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 2
OnClick = bnOkClick
end
object bnCancel: TButton
Left = 201
Top = 74
Width = 75
Height = 25
Anchors = [akLeft, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 3
OnClick = bnCancelClick
end
object cbCommented: TCheckBox
Left = 194
Top = 56
Width = 97
Height = 17
Anchors = [akLeft, akBottom]
Caption = '&Commented'
TabOrder = 1
end
object cbRepeating: TCheckBox
Left = 50
Top = 56
Width = 97
Height = 17
Anchors = [akLeft, akBottom]
Caption = '&Repeating'
TabOrder = 0
end
end
|
unit TNT_Vector;
// Gestion du calcul vectoriel
// ---------------------------
// TVector: vecteur (x,y,z)
// Add, Sub, Dot, Cross, Norm, Normalize
interface
uses
OpenGL12;
type
TVector = record
x, y, z: GLfloat;
end;
function Vector(px, py, pz: GLfloat): TVector;
function Add(u, v: TVector): TVector;
function Sub(u, v: TVector): TVector;
function Dot(u, v: TVector): GLfloat;
function Cross(u, v: TVector): TVector;
function Norm(u: TVector): GLfloat;
procedure Normalize(var u: TVector);
implementation
function Vector(px, py, pz: GLfloat): TVector;
begin
Result.x := px;
Result.y := py;
Result.z := pz;
end;
function Add(u, v: TVector): TVector;
begin
Result.x := u.x + v.x;
Result.y := u.y + v.y;
Result.z := u.z + v.z;
end;
function Sub(u, v: TVector): TVector;
begin
Result.x := u.x - v.x;
Result.y := u.y - v.y;
Result.z := u.z - v.z;
end;
function Dot(u, v: TVector): GLfloat;
begin
Result := u.x*v.x + u.y*v.y + u.z*v.z;
end;
function Cross(u, v: TVector): TVector;
begin
Result.x := u.y*v.z - u.z*v.y;
Result.y := u.z*v.x - u.x*v.z;
Result.z := u.x*v.y - u.y*v.x;
end;
function Norm(u: TVector): GLfloat;
begin
Result := sqrt(u.x*u.x + u.y*u.y + u.z*u.z);
end;
procedure Normalize(var u: TVector);
var
t: GLfloat;
begin
t := Norm(u);
u.x := u.x/t;
u.y := u.y/t;
u.z := u.z/t;
end;
end.
|
unit networkConfig;
{$mode DELPHI}
interface
uses
{$ifdef darwin}
macport,
{$endif}
{$ifdef windows}
jwawindows, windows,
{$endif}
Classes, SysUtils, FileUtil, Forms, Controls, Graphics,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Menus, resolve, Sockets, ctypes,
registry, betterControls, Types;
type
{ TfrmNetworkConfig }
TfrmNetworkConfig = class(TForm)
btnConnect: TButton;
Button2: TButton;
edtFriendlyName: TEdit;
edtHost: TEdit;
edtPort: TEdit;
GroupBox1: TGroupBox;
ctsImageList: TImageList;
Label1: TLabel;
Label2: TLabel;
lblOptionalName: TLabel;
lvIPList: TListView;
miRefresh: TMenuItem;
miDelete: TMenuItem;
Panel1: TPanel;
Panel2: TPanel;
PopupMenu1: TPopupMenu;
procedure btnConnectClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvIPListDblClick(Sender: TObject);
procedure lvIPListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure miDeleteClick(Sender: TObject);
procedure miRefreshClick(Sender: TObject);
procedure PopupMenu1Popup(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
procedure requestlist;
end;
var
frmNetworkConfig: TfrmNetworkConfig;
var
host: THostAddr;
port: integer;
networkcompression: integer;
procedure CEConnect(hostname: string; p: integer);
implementation
{$R *.lfm}
uses networkInterfaceApi, mainunit2;
resourcestring
rsHost = 'host:';
rsCouldNotBeResolved = ' could not be resolved';
rsFailureCreatingSocket = 'Failure creating socket';
rsFailedConnectingToTheServer = 'Failed connecting to the server';
type
THistoryEntry=class
public
ip: string;
port: string;
name: string;
end;
TDiscovery=class(tthread)
private
s: cint;
server: record
ip: string;
port: word;
end;
procedure addip;
public
procedure execute; override;
procedure Terminate;
constructor create(suspended: boolean);
destructor destroy; override;
end;
var Discovery: TDiscovery;
constructor TDiscovery.create(suspended: boolean);
begin
s:=fpsocket(PF_INET, SOCK_DGRAM, 0);
inherited create(suspended);
end;
destructor TDiscovery.destroy;
begin
if s<>cint(INVALID_SOCKET) then
closeSocket(s);
end;
procedure TDiscovery.terminate;
var olds: cint;
begin
if s<>cint(INVALID_SOCKET) then
begin
olds:=s;
s:=cint(INVALID_SOCKET);
CloseSocket(olds);
end;
inherited terminate;
end;
procedure TDiscovery.addip;
var li: tlistitem;
begin
if frmNetworkConfig<>nil then
begin
li:=frmNetworkConfig.lvIPList.Items.Insert(0); //add to the top
li.Caption:=server.ip;
li.SubItems.Add(inttostr(server.port));
end;
end;
procedure TDiscovery.execute;
var
v: BOOL;
sin: sockaddr_in;
Y: word;
sout: sockaddr_in;
i: integer;
//l: socklen_t;
srecv: sockaddr_in;
recvsize: integer;
packet: packed record
checksum: dword;
port: word;
end;
begin
//send a broadcast asking which devices (port 3296)
if s>=0 then
begin
v:=true;
if fpsetsockopt(s, SOL_SOCKET, SO_BROADCAST, @v, sizeof(v)) >=0 then
begin
zeromemory(@sin, sizeof(sin));
sin.sin_family:=PF_INET;
sin.sin_addr.s_addr:=htonl(INADDR_ANY);
sin.sin_port:=htons(3296);
i:=fpbind(s, @sin, sizeof(sin));
if (i>=0) then
begin
zeromemory(@sout, sizeof(sout));
sout.sin_family:=PF_INET;
sout.sin_addr.s_addr:=htonl(INADDR_BROADCAST);
sout.sin_port:=htons(3296);
packet.checksum:=random(100);
i:=fpsendto(s, @packet, sizeof(packet),0, @sout, sizeof(sout));
y:=packet.checksum*$ce;
if (i>0) then
repeat
recvsize:=sizeof(srecv);
ZeroMemory(@srecv, recvsize);
i:=fprecvfrom(s, @packet, sizeof(packet), 0, @srecv, @recvsize);
if (i>0) and (not terminated) then
begin
// showmessage('packet.checksum='+inttohex(packet.checksum,8)+' - y='+inttohex(y,8));
if packet.checksum=y then
begin
// showmessage('address='+inttohex(srecv.sin_addr.s_addr,8)+' port='+inttostr(packet.port));
//add to list
server.ip:=NetAddrToStr(srecv.sin_addr);
server.port:=packet.port;
if not terminated then
synchronize(addip);
end;
end
until (i<=0) or (terminated);
end;
end;
end;
if s<>cint(INVALID_SOCKET) then
begin
closesocket(s);
s:=cint(invalid_socket);
end;
end;
procedure CEconnect(hostname: string; p: integer);
var hr: THostResolver;
begin
hr:=THostResolver.Create(nil);
try
host:=StrToNetAddr(hostname);
if host.s_bytes[4]=0 then
begin
if hr.NameLookup(hostname) then
host:=hr.NetHostAddress
else
raise exception.create(rsHost+hostname+rsCouldNotBeResolved);
end;
finally
hr.free;
end;
port:=ShortHostToNet(p);
if getConnection=nil then
begin
if host.s_addr<>0 then //it's 0 when it terminated earlier
begin
host.s_addr:=0;
if MainThreadID=GetCurrentThreadId then
MessageDlg(rsFailedConnectingToTheServer, mtError, [mbOK],0);
end;
exit;
end;
InitializeNetworkInterface;
end;
{ TfrmNetworkConfig }
procedure TfrmNetworkConfig.requestlist;
var
i: integer;
begin
if discovery<>nil then
begin
discovery.Terminate;
discovery.WaitFor;
freeandnil(discovery);
end;
//delete discovered entries
for i:=lvIPList.items.count-1 downto 0 do
begin
if lvIPList.items[i].Data=nil then
lvIPList.items[i].Delete;
end;
discovery:=TDiscovery.Create(false);
end;
procedure TfrmNetworkConfig.FormShow(Sender: TObject);
begin
requestlist;
edtHost.Width:=canvas.GetTextWidth('1234.1234.1234.1234');
edtPort.Width:=canvas.GetTextWidth(' 99999 ');
end;
procedure TfrmNetworkConfig.btnConnectClick(Sender: TObject);
var
reg: Tregistry;
i: integer;
name, ip: string;
he: THistoryEntry;
li: TListitem;
begin
CEconnect(trim(edtHost.text), strtoint(trim(edtPort.text)));
//check if this is in the list
he:=nil;
li:=nil;
ip:=edtHost.text;
name:=edtFriendlyName.text;
for i:=0 to lvIPList.items.count-1 do
begin
he:=lvIPList.items[i].data;
if (name<>'') and (he<>nil) then
begin
if he.name=name then
begin
li:=lvIPList.items[i];
break;
end;
end
else
begin
if lvIPList.items[i].caption=ip then
begin
li:=lvIPList.items[i];
break;
end;
end;
end;
if li=nil then
begin
li:=lvIPList.items.insert(0);
li.data:=THistoryEntry.create;
li.SubItems.add('');
end;
if li.data=nil then //update a found entry to history entry
li.data:=THistoryEntry.create;
he:=THistoryEntry(li.data);
if he<>nil then
begin
he.ip:=edtHost.text;
he.port:=edtport.text;
he.name:=edtFriendlyName.text;
if he.name<>'' then
li.Caption:=he.name+' ('+he.ip+')'
else
li.caption:=he.ip;
li.subitems[0]:=he.port;
end;
//still here so the connection is made
reg:=tregistry.create;
try
if reg.OpenKey('\Software\'+strCheatEngine+'\',false) then
begin
reg.WriteString('Last Connect IP', edtHost.text);
reg.WriteString('Last Connect Port', edtport.text);
reg.WriteString('Last Connect Name', edtFriendlyName.text);
end;
finally
reg.free;
end;
modalresult:=mrok;
end;
procedure TfrmNetworkConfig.FormCreate(Sender: TObject);
var
reg: tregistry;
sl: TStringlist;
li: tlistitem;
i: integer;
ip: string;
port: string;
name: string;
he: THistoryEntry;
begin
reg:=tregistry.create;
try
if reg.OpenKey('\Software\'+strCheatEngine+'\',false) then
begin
if reg.ValueExists('Last Connect IP') then
edtHost.text:=reg.ReadString('Last Connect IP');
if reg.ValueExists('Last Connect Port') then
edtport.text:=reg.ReadString('Last Connect Port');
sl:=tstringlist.create;
reg.ReadStringList('History',sl);
for i:=0 to sl.count-1 do
begin
case i mod 3 of
0: ip:=sl[i];
1: port:=sl[i];
2:
begin
name:=sl[i];
he:=THistoryEntry.create;
he.ip:=ip;
he.port:=port;
he.name:=name;
li:=lvIPList.Items.add;
if name<>'' then
li.caption:=name+' ('+ip+')'
else
li.caption:=ip;
li.SubItems.add(port);
li.Data:=he;
end;
end;
end;
sl.free;
end;
finally
reg.free;
end;
end;
procedure TfrmNetworkConfig.FormDestroy(Sender: TObject);
var
i: integer;
reg: Tregistry;
he: THistoryEntry;
sl: tstringlist;
count: integer;
begin
reg:=tregistry.create;
try
if reg.OpenKey('\Software\'+strCheatEngine+'\',true) then
begin
sl:=tstringlist.create;
count:=0;
for i:=0 to lvIPList.items.count-1 do
begin
if lvIPList.items[i].Data<>nil then
begin
he:=lvIPList.items[i].Data;
inc(count);
if count<=10 then //limit to 10 entries
begin
sl.add(he.ip);
sl.add(he.port);
sl.add(he.name);
end;
he.free;
lvIPList.items[i].Data:=nil;
end;
end;
reg.WriteStringList('History',sl);
sl.free;
end;
finally
reg.free;
end;
end;
procedure TfrmNetworkConfig.lvIPListDblClick(Sender: TObject);
begin
if lvIPList.selected<>nil then
begin
if lvIPList.selected.Data<>nil then
begin
edthost.text:=THistoryEntry(lvIPList.selected.Data).ip;
edtFriendlyName.text:=THistoryEntry(lvIPList.selected.Data).name;
end
else
edthost.text:=lvIPList.selected.caption;
edtport.text:=lvIPList.selected.subitems[0];
btnConnect.click;
end;
end;
procedure TfrmNetworkConfig.lvIPListSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if selected then
begin
if item.data<>nil then
begin
edtHost.text:=THistoryEntry(item.data).ip;
edtFriendlyName.text:=THistoryEntry(item.data).name;
end
else
edthost.text:=item.caption;
edtport.text:=item.subitems[0];
end;
end;
procedure TfrmNetworkConfig.miDeleteClick(Sender: TObject);
begin
if (lvIPList.selected<>nil) and (lvIPList.selected.data<>nil) then
begin
THistoryEntry(lvIPList.selected.data).free;
lvIPList.selected.data:=nil;
lvIPList.selected.Delete;
end;
end;
procedure TfrmNetworkConfig.miRefreshClick(Sender: TObject);
begin
requestlist;
end;
procedure TfrmNetworkConfig.PopupMenu1Popup(Sender: TObject);
begin
midelete.enabled:=(lvIPList.Selected<>nil) and (lvIPList.Selected.Data<>nil);
end;
end.
|
unit SettingsForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynHighlighterXML, SynEdit, Forms, Controls,
Graphics, Dialogs, StdCtrls, ComCtrls, ButtonPanel, Weather;
type
{ TSettingsDialog }
TSettingsDialog = class(TForm)
btnGo: TButton;
pnlButtons: TButtonPanel;
cbStates: TComboBox;
cbStations: TComboBox;
gbState: TGroupBox;
gbStations: TGroupBox;
gbStations1: TGroupBox;
synWeatherDataXML: TSynEdit;
tsWeatherData: TTabSheet;
txtWeather: TMemo;
synWeatherStationXML: TSynEdit;
SynXMLSyn1: TSynXMLSyn;
tsWeatherStationXML: TTabSheet;
tsWeather: TTabSheet;
tpMain: TPageControl;
procedure btnGoClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure cbStatesChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
private
public
State: string;
WeatherStationName: string;
end;
var
SettingsDialog: TSettingsDialog;
StationsXML: string;
WeatherStations: TWeatherStationArray;
implementation
{$R *.lfm}
{ TSettingsDialog }
procedure TSettingsDialog.FormCreate(Sender: TObject);
var
Station: TWeatherStation;
StateAbbreviation: string;
begin
StationsXML := GetAllWeatherStationsXML();
WeatherStations := GetAllWeatherStations(StationsXML);
synWeatherStationXML.Caption := StationsXML;
for StateAbbreviation in StateAbreviations do begin
cbStates.Items.Add(StateAbbreviation);
end;
for Station in WeatherStations do begin
cbStations.Items.Add(Station.Name);
end;
end;
procedure TSettingsDialog.FormShow(Sender: TObject);
begin
if State <> '' then begin
cbStates.Text := State;
end;
if WeatherStationName <> '' then begin
cbStations.Text := WeatherStationName;
end;
end;
procedure TSettingsDialog.OKButtonClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TSettingsDialog.cbStatesChange(Sender: TObject);
const
StateSep: string = '----';
var
Station: TWeatherStation;
FilteredStations: TWeatherStationArray;
begin
if cbStates.Text <> StateSep then begin
FilteredStations := GetStationsForState(WeatherStations, cbStates.Text);
cbStations.Clear;
for Station in FilteredStations do begin
cbStations.Items.Add(Station.Name);
end;
end;
end;
procedure TSettingsDialog.btnGoClick(Sender: TObject);
var
SelectedStation: TWeatherStation;
Weather: TWeatherData;
begin
if cbStations.Text = '' then exit;
SelectedStation := GetStationByName(WeatherStations, cbStations.Text);
synWeatherDataXML.Caption := GetWeatherDataXML(SelectedStation);
Weather := GetWeatherData(SelectedStation);
txtWeather.Text := PrintWeatherReport(Weather);
end;
procedure TSettingsDialog.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
unit UWordBox;
interface
uses
UxlClasses, UxlExtClasses, UxlList;
type
TWord = record
word: widestring;
exp: widestring;
level: integer;
end;
TWordBox = class
private
FBoxSize: integer;
FNewDict: widestring;
FAllWordCount: integer;
FCurrentDict: widestring;
FWordList: TxlStrList;
FDeleteList: TxlStrList;
FTempr: TxlStrList;
procedure Save ();
function GetWord (index: integer): TWord;
procedure SetWord (index: integer; const value: TWord);
procedure SetDictFile (const value: widestring);
public
constructor Create ();
destructor Destroy (); override;
procedure NewBox (index: integer);
function BoxCount (): integer;
procedure DeleteWord (index: integer);
procedure Export (o_list: TxlStrList);
property BoxSize: integer read FBoxSize write FBoxSize;
property DictFile: widestring read FNewDict write SetDictFile;
property Word [index: integer]: TWord read GetWord write SetWord; default;
function WordCount (): integer;
end;
implementation
uses SysUtils, UxlMath, UGlobalObj, UxlFunctions, UxlFile, UxlStrUtils;
constructor TWordBox.Create ();
begin
FWordList := TxlStrList.Create;
FDeleteList := TxlStrList.Create;
FTempr := TxlStrList.Create;
FTempr.Separator := #9;
end;
destructor TWordBox.Destroy ();
begin
Save;
FWordList.Free;
FDeleteList.Free;
FTempr.Free;
inherited;
end;
procedure TWordBox.SetDictFile (const value: widestring);
var s: widestring;
n: integer;
begin
FNewDict := value;
if not PathFileExists (FNewDict) then exit;
with TxlTextFile.Create (FNewDict, fmRead) do
begin
ReadLn (s);
Free;
end;
n := firstpos ('//', s);
if n > 0 then s := leftstr (s, n - 1);
FAllWordCount := StrToIntDef (s);
end;
procedure TWordBox.NewBox (index: integer);
var i: integer;
s: widestring;
o_file: TxlTextFile;
begin
Save;
FWordList.Clear;
if not PathFileExists (FNewDict) then exit;
FWordList.MinSize := FBoxSize;
o_file := TxlTextFile.Create (FNewDict, fmRead);
try
o_file.ReadLn (s);
for i := 0 to BoxSize * index - 1 do
o_file.ReadLn (s);
while FWordList.Count < BoxSize do
begin
if o_file.EOF then // »Øµ½¿ªÍ·
begin
o_file.Locate (0);
o_file.ReadLn (s);
end;
o_file.ReadLn (s);
s := Trim(s);
if (s = '') or (LeftStr(s, 2) = '//') then continue;
FWordList.Add (s);
end;
finally
o_file.Free;
end;
FCurrentdict := FNewDict;
ClearMemory;
end;
function TWordBox.BoxCount (): integer;
begin
result := Ceil (FAllWordCount / BoxSize);
end;
procedure TWordBox.Save ();
begin
if not PathFileExists (FCurrentDict) then exit;
end;
function TWordBox.GetWord (index: integer): TWord;
function f_GetString (const s: widestring): widestring;
begin
result := ReplaceStr (s, '\n', #13#10);
result := ReplaceStr (result, '\t', #9);
end;
begin
FTempr.Text := FWordList[index];
with result do
begin
Word := f_GetString (FTempr[0]);
Exp := f_GetString (FTempr[1]);
Level := StrToIntDef (FTempr[2]);
end;
end;
procedure TWordBox.SetWord (index: integer; const value: TWord);
var s_exp: widestring;
begin
s_exp := ReplaceStr(value.exp, #13#10, '\n');
s_exp := ReplaceStr (value.exp, #9, '\t');
FWordList[index] := value.word + #9 + s_exp + #9 + IntToStr(value.Level);
end;
function TWordBox.WordCount (): integer;
begin
result := FWordList.Count;
end;
procedure TWordBox.DeleteWord (index: integer);
begin
end;
procedure TWordBox.Export (o_list: TxlStrList);
var i: integer;
begin
o_list.Clear;
for i := FWordList.Low to FWordList.High do
o_list.Add (FWordList[i]);
end;
end.
|
unit HJYUserInfos;
interface
uses SysUtils;
type
THJYUserInfo = class(TObject)
private
FGuid: string;
FUserCode: string;
FUserName: string;
FUserPass: string;
FPhone: string;
FAddress: string;
FIsStop: Integer;
FRemark: string;
FDeptGuid: string;
FDeptCode: string;
FDeptName: string;
FRoleGuid: string;
FRoleCode: string;
FRoleName: string;
public
function IsAdmin: Boolean;
function IsAdminRole: Boolean;
property Guid: string read FGuid write FGuid;
property UserCode: string read FUserCode write FUserCode;
property UserName: string read FUserName write FUserName;
property UserPass: string read FUserPass write FUserPass;
property Phone: string read FPhone write FPhone;
property Address: string read FAddress write FAddress;
property IsStop: Integer read FIsStop write FIsStop;
property Remark: string read FRemark write FRemark;
property DeptGuid: string read FDeptGuid write FDeptGuid;
property DeptCode: string read FDeptCode write FDeptCode;
property DeptName: string read FDeptName write FDeptName;
property RoleGuid: string read FRoleGuid write FRoleGuid;
property RoleCode: string read FRoleCode write FRoleCode;
property RoleName: string read FRoleName write FRoleName;
end;
THJYRightInfo = class
private
FGuid: string;
FParentGuid: string;
FSerialId: Integer;
FRightName: string;
FFunName: string;
FLibName: string;
FIsModal: Boolean;
FIsHide: Boolean;
FIsAdmin: Boolean;
FImageIndex: Integer;
public
property Guid: string read FGuid write FGuid;
property ParentGuid: string read FParentGuid write FParentGuid;
property SerialId: Integer read FSerialId write FSerialId;
property RightName: string read FRightName write FRightName;
property FunName: string read FFunName write FFunName;
property LibName: string read FLibName write FLibName;
property IsHide: Boolean read FIsHide write FIsHide;
// 是否弹窗显示
property IsModal: Boolean read FIsModal write FIsModal;
// 是否允许 admin 用户操作,业务功能不建议admin操作
property IsAdmin: Boolean read FIsAdmin write FIsAdmin;
property ImageIndex: Integer read FImageIndex write FImageIndex;
end;
implementation
{ THJYUserInfo }
function THJYUserInfo.IsAdmin: Boolean;
begin
Result := SameText(FUserCode, 'admin');
end;
function THJYUserInfo.IsAdminRole: Boolean;
begin
Result := SameText(FRoleCode, 'admin');
end;
end.
|
{ NIM/NAMA : 16518305/QURRATA A'YUNI
TANGGAL : JUMAT, 5 APRIL 2019
DEKSRIPSI : OLAH BILANGAN }
Program barang;
{Program membaca N positif yang divalidasi dulu. Kalo
salah tuliskan 'Masukan salah. Ulangi!'. Kalo N udah
bener, lakukan input bilangan integer. Kemudian minta
nilai X,
- kalo X=0 di urutan pertama ditemukan nol,
tulis indeksnya lalu nilainya. Kalau tidak tuliskan
'Tidak ada 0'.
- kalo X=-1 di urutan pertama ditemukan bilangan
negatif dan tuliskan bilangannya. kalo engga tulis
'Tidak ada negatif'.
- kalo X=-1 di urutan pertama ditemukan bilangan
positif dan tuliskan bilangannya. kalo engga tulis
'Tidak ada positif'.
- selain -1..1 tulis 'Tidak diproses'.}
{Kamus}
var
N, i, X, IX : integer;
tabel : array [1..100] of integer;
found : boolean;
{Algoritma}
function IsXValid (x : integer): boolean ;
{Cek apakah N valid}
begin
if (x>0) and (x<=100) then
IsXValid := true
else
IsXValid := false
end;
begin
{masukkan input}
readln(N);
{input divalidasi}
while IsXValid(N) = false do
begin
writeln ('Masukan salah. Ulangi!'); readln(N);
end;
{isi array}
for i:=1 to N do
begin
readln(tabel[i]);
end;
{minta inputan X}
readln(X);
{cari nilai X di array}
if (X=0) then
begin
found := false;
i := 1;
while (i<=N) and not(found) do
begin
if (tabel[i] = 0) then
found := true
else
i := i+1;
end;
{cetak kondisi}
if (found=true) then
begin
IX := i;
writeln(IX, ' ', tabel[i]);
end else
begin
writeln('Tidak ada 0');
end
end else if (X=-1) then
begin
found := false;
i := 1;
while (i<=N) and not(found) do
begin
if (tabel[i] < 0) then
found := true
else
i := i+1;
end;
{cetak kondisi}
if (found=true) then
begin
IX := i;
writeln(IX, ' ', tabel[i]);
end else
begin
writeln('Tidak ada negatif');
end
end else if (X=1) then
begin
found := false;
i := 1;
while (i<=N) and not(found) do
begin
if (tabel[i] > 0) then
found := true
else
i := i+1;
end;
{cetak kondisi}
if (found=true) then
begin
IX := i;
writeln(IX, ' ', tabel[i]);
end else
begin
writeln('Tidak ada positif')
end
end else
begin
writeln('Tidak diproses');
end
end.
|
unit uAlunoDAO;
interface
uses uDAO, uAluno, system.generics.collections, FireDAC.Comp.Client, DB,
system.sysUtils, uEndereco, uResponsavel, system.DateUtils, uCurso, uAula;
type
TAlunoDAO = class(TConectDAO)
protected
FListaAluno: TobjectList<TAluno>;
procedure preencherlista(Ds: TFDQuery);
public
Constructor Create;
Destructor Destroy; override;
function CadastrarAlunoResponsavel(pAluno: TAluno; pEndereco: TEndereco;
pResponsavel: Tresponsavel): boolean;
function CadastrarAluno(pAluno: TAluno; pEndereco: TEndereco): boolean;
function CadastrarResponsavel(pResponsavel: Tresponsavel): boolean;
function PesquisarAluno(pAluno: TAluno): TobjectList<TAluno>;
function RetornaID(pAluno: TAluno): integer;
function RetornaIDResponsavel(pResponsavel : TResponsavel):integer;
function CadastrarAluno_curso(pAluno: TAluno; pCurso: TCurso): boolean;
function UpdateAluno_curso(pAula: TAula): boolean;
function DeleteAluno_curso(pAula: TAula): boolean;
function RetornaAluno(id: integer): TAluno;
function RetornaResponsavel(id: integer): Tresponsavel;
function UpdateResponsavel(pResponsavel: Tresponsavel): boolean;
function UpdateAlunoResponsavel(pAluno: TAluno): boolean;
function UpdateAluno(pAluno: TAluno): boolean;
function DeleteAluno(pAluno: TAluno): boolean;
function DeleteReponsavel(pAluno: TAluno): boolean;
end;
implementation
{ TAlunoDAO }
function TAlunoDAO.CadastrarAluno(pAluno: TAluno; pEndereco: TEndereco)
: boolean;
var
SQL: string;
begin
SQL := 'select id_endereco from endereco ' +
'where id_endereco not in (select id_endereco from aluno) ' +
'and id_endereco not in (select id_endereco from professor)' +
'and id_endereco not in (select id_endereco from adm)';
FQuery := RetornarDataSet(SQL);
pEndereco.id := FQuery.fieldByName('id_endereco').AsInteger;
SQL := 'INSERT INTO aluno VALUES(default, ' + QuotedSTR(pAluno.Nome) + ', ' +
QuotedSTR(InttoStr(pEndereco.id)) + ', null, ' +
QuotedSTR(FormatDateTime('dd/mm/yyyy', pAluno.DataNasc)) + ', ' +
QuotedSTR(pAluno.Cpf) + ', ' + QuotedSTR(pAluno.rg) + ', ' +
QuotedSTR(pAluno.contatocom) + ', ' + QuotedSTR(pAluno.contato) + ', ' +
QuotedSTR(pAluno.email) + ')';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.CadastrarAlunoResponsavel(pAluno: TAluno;
pEndereco: TEndereco; pResponsavel: Tresponsavel): boolean;
var
SQL: string;
begin
SQL := 'select id_endereco from endereco ' +
'where id_endereco not in (select id_endereco from aluno) ' +
'and id_endereco not in (select id_endereco from professor)' +
'and id_endereco not in (select id_endereco from adm)';
FQuery := RetornarDataSet(SQL);
pEndereco.id := FQuery.fieldByName('id_endereco').AsInteger;
SQL := 'SELECT id_responsavel FROM responsavel WHERE id_responsavel not in ' +
'(Select id_responsavel from aluno where id_responsavel is not null)';
FQuery := RetornarDataSet(SQL);
pResponsavel.id := FQuery.fieldByName('id_responsavel').AsInteger;
SQL := 'INSERT INTO aluno VALUES(default, ' + QuotedSTR(pAluno.Nome) + ', ' +
QuotedSTR(InttoStr(pEndereco.id)) + ', ' +
QuotedSTR(InttoStr(pResponsavel.id)) + ', ' +
QuotedSTR(FormatDateTime('dd/mm/yyyy', pAluno.DataNasc)) + ', ' +
QuotedSTR(pAluno.Cpf) + ', ' + QuotedSTR(pAluno.rg) + ', ' +
QuotedSTR(pAluno.contatocom) + ', ' + QuotedSTR(pAluno.contato) + ', ' +
QuotedSTR(pAluno.email) + ')';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.CadastrarAluno_curso(pAluno: TAluno; pCurso: TCurso)
: boolean;
var
SQL: string;
begin
SQL := 'insert into aluno_curso values(' + QuotedSTR(InttoStr(pAluno.id)) +
', ' + QuotedSTR(InttoStr(pCurso.id)) + ')';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.CadastrarResponsavel(pResponsavel: Tresponsavel): boolean;
Var
SQL: string;
begin
SQL := 'INSERT INTO responsavel VALUES (Default, ' +
QuotedSTR(pResponsavel.Nome) + ', ' + QuotedSTR(pResponsavel.Cpf) + ', ' +
QuotedSTR(pResponsavel.rg) + ', ' + QuotedSTR(pResponsavel.contato) + ', ' +
QuotedSTR(pResponsavel.contatocom) + ', ' +
QuotedSTR(FormatDateTime('dd/mm/yyyy', pResponsavel.DataNasc)) + ')';
result := executarComando(SQL) > 0;
end;
constructor TAlunoDAO.Create;
begin
inherited;
FListaAluno := TobjectList<TAluno>.Create;
end;
function TAlunoDAO.DeleteAluno(pAluno: TAluno): boolean;
var
SQL: string;
begin
SQL := 'delete from aluno_curso where id_aluno = ' +
QuotedSTR(InttoStr(pAluno.id)) + '; ';
result := executarComando(SQL) > 0;
SQL := 'delete from aula where id_aluno = ' +
QuotedSTR(InttoStr(pAluno.id)) + '; ';
result := executarComando(SQL) > 0;
SQL := 'delete from aluno where id_aluno = ' +
QuotedSTR(InttoStr(pAluno.id)) + '; ';
result := executarComando(SQL) > 0;
DeleteReponsavel(pAluno);
SQL := 'delete from endereco where id_endereco = ' +
QuotedSTR(InttoStr(pAluno.IdEndereco)) + '; ';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.DeleteAluno_curso(pAula: TAula): boolean;
var
SQL: string;
begin
SQL := 'delete from aluno_curso where ctid in(select ctid from aluno_curso where id_aluno = ' +
QuotedSTR(InttoStr(pAula.id_aluno)) + ' and id_curso = ' +
QuotedSTR(InttoStr(pAula.id_curso)) + ' limit 1)';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.DeleteReponsavel(pAluno: TAluno): boolean;
var
SQL: string;
begin
SQL := 'delete from responsavel where id_responsavel = ' +
QuotedSTR(InttoStr(pAluno.IDResponsavel)) + '; ';
result := executarComando(SQL) > 0;
end;
destructor TAlunoDAO.Destroy;
begin
try
inherited;
if Assigned(FListaAluno) then
FreeAndNil(FListaAluno);
except
on e: exception do
raise exception.Create(e.Message);
end;
end;
function TAlunoDAO.PesquisarAluno(pAluno: TAluno): TobjectList<TAluno>;
var
SQL: string;
begin
result := nil;
SQL := 'SELECT * FROM aluno WHERE nome LIKE ' +
QuotedSTR('%' + pAluno.Nome + '%') + 'and cpf LIKE ' +
QuotedSTR('%' + pAluno.Cpf + '%') + ' and telefone LIKE ' +
QuotedSTR('%' + pAluno.contato + '%') +
' or id_aluno in (select id_aluno from aluno_curso where id_curso in ' +
'(select id_curso from curso where nome like ' +
QuotedSTR('%' + pAluno.Curso + '%') + ')) order by nome';
FQuery := RetornarDataSet(SQL);
if not(FQuery.IsEmpty) then
begin
preencherlista(FQuery);
result := FListaAluno;
end;
end;
procedure TAlunoDAO.preencherlista(Ds: TFDQuery);
var
I: integer;
SQL: String;
begin
I := 0;
FListaAluno.Clear;
while not Ds.eof do
begin
if Ds.fieldByName('id_responsavel').AsInteger = 0 then
begin
FListaAluno.Add(TAluno.Create);
FListaAluno[I].id := Ds.fieldByName('id_aluno').AsInteger;
FListaAluno[I].Nome := Ds.fieldByName('nome').AsString;
FListaAluno[I].IdEndereco := Ds.fieldByName('id_endereco').AsInteger;
FListaAluno[I].IDResponsavel := Ds.fieldByName('id_responsavel')
.AsInteger;
FListaAluno[I].DataNasc := Ds.fieldByName('data_nasc').AsDateTime;
FListaAluno[I].Cpf := Ds.fieldByName('cpf').AsString;
FListaAluno[I].rg := Ds.fieldByName('rg').AsString;
FListaAluno[I].contatocom := Ds.fieldByName('telefone_comercial')
.AsString;
FListaAluno[I].contato := Ds.fieldByName('telefone').AsString;
FListaAluno[I].email := Ds.fieldByName('email').AsString;
SQL := 'select nome from curso where id_curso in' +
'(select id_curso from aluno_curso where id_aluno ' +
'in (select id_aluno from aluno where id_aluno =' +
QuotedSTR(Ds.fieldByName('id_aluno').AsString) + ' ))';
FQuery2 := RetornarDataSet2(SQL);
while not FQuery2.eof do
begin
FListaAluno[I].Tamanho := FListaAluno[I].Tamanho + 1;
SetLength(FListaAluno[I].Cursos, FListaAluno[I].Tamanho);
FListaAluno[I].Cursos[FListaAluno[I].Tamanho - 1] :=
FQuery2.fieldByName('nome').AsString;
FQuery2.Next;
end;
Ds.Next;
I := I + 1;
end
else
begin
FListaAluno.Add(TAluno.Create);
FListaAluno[I].id := Ds.fieldByName('id_aluno').AsInteger;
FListaAluno[I].Nome := Ds.fieldByName('nome').AsString;
FListaAluno[I].IdEndereco := Ds.fieldByName('id_endereco').AsInteger;
FListaAluno[I].IDResponsavel := Ds.fieldByName('id_responsavel')
.AsInteger;
FListaAluno[I].email := Ds.fieldByName('email').AsString;
SQL := 'select * from responsavel where id_responsavel in ' +
'(select id_responsavel from aluno where id_aluno = ' +
QuotedSTR(Ds.fieldByName('id_aluno').AsString) + ' )';
FQuery2 := RetornarDataSet2(SQL);
FListaAluno[I].DataNasc := FQuery2.fieldByName('data_nasc').AsDateTime;
FListaAluno[I].Cpf := FQuery2.fieldByName('cpf').AsString;
FListaAluno[I].rg := FQuery2.fieldByName('rg').AsString;
FListaAluno[I].contatocom :=
FQuery2.fieldByName('telefone_comercial').AsString;
FListaAluno[I].contato := FQuery2.fieldByName('telefone').AsString;
SQL := 'select nome from curso where id_curso in' +
'(select id_curso from aluno_curso where id_aluno ' +
'in (select id_aluno from aluno where id_aluno =' +
QuotedSTR(Ds.fieldByName('id_aluno').AsString) + ' ))';
FQuery2 := RetornarDataSet2(SQL);
while not FQuery2.eof do
begin
FListaAluno[I].Tamanho := FListaAluno[I].Tamanho + 1;
SetLength(FListaAluno[I].Cursos, FListaAluno[I].Tamanho);
FListaAluno[I].Cursos[FListaAluno[I].Tamanho - 1] :=
FQuery2.fieldByName('nome').AsString;
FQuery2.Next;
end;
Ds.Next;
I := I + 1;
end;
end;
end;
function TAlunoDAO.RetornaAluno(id: integer): TAluno;
var
SQL: string;
aluno: TAluno;
begin
SQL := 'Select * from Aluno where id_aluno = ' + QuotedSTR(InttoStr(id));
FQuery := RetornarDataSet(SQL);
aluno := TAluno.Create;
aluno.id := id;
aluno.Nome := FQuery.fieldByName('nome').AsString;
aluno.Cpf := FQuery.fieldByName('cpf').AsString;
aluno.rg := FQuery.fieldByName('rg').AsString;
aluno.DataNasc := FQuery.fieldByName('data_nasc').AsDateTime;
aluno.contato := FQuery.fieldByName('telefone').AsString;
aluno.email := FQuery.fieldByName('email').AsString;
aluno.IDResponsavel := FQuery.fieldByName('id_responsavel').AsInteger;
aluno.contatocom := FQuery.fieldByName('telefone_comercial').AsString;
aluno.IdEndereco := FQuery.fieldByName('id_endereco').AsInteger;
result := aluno;
end;
function TAlunoDAO.RetornaID(pAluno: TAluno): integer;
var
SQL: string;
begin
SQL := 'select id_aluno from aluno where cpf = ' + QuotedSTR(pAluno.Cpf) +
' and nome = ' + QuotedSTR(pAluno.Nome);
FQuery := RetornarDataSet(SQL);
result := FQuery.fieldByName('id_aluno').AsInteger;
end;
function TAlunoDAO.RetornaIDResponsavel(pResponsavel: TResponsavel): integer;
var SQL : string;
begin
SQL := 'select id_responsavel from responsavel where cpf = ' + QuotedSTR(pResponsavel.Cpf) +
' and nome = ' + QuotedSTR(pResponsavel.Nome);
FQuery := RetornarDataSet(SQL);
result := FQuery.fieldByName('id_responsavel').AsInteger;
end;
function TAlunoDAO.RetornaResponsavel(id: integer): Tresponsavel;
var
SQL: string;
Responsavel: Tresponsavel;
begin
SQL := 'Select * from responsavel where id_responsavel = ' +
QuotedSTR(InttoStr(id));
FQuery := RetornarDataSet(SQL);
Responsavel := Tresponsavel.Create;
Responsavel.id := id;
Responsavel.Nome := FQuery.fieldByName('nome').AsString;
Responsavel.Cpf := FQuery.fieldByName('cpf').AsString;
Responsavel.rg := FQuery.fieldByName('rg').AsString;
Responsavel.DataNasc := FQuery.fieldByName('data_nasc').AsDateTime;
Responsavel.contato := FQuery.fieldByName('telefone').AsString;
Responsavel.contatocom := FQuery.fieldByName('telefone_comercial').AsString;
result := Responsavel;
end;
function TAlunoDAO.UpdateAluno(pAluno: TAluno): boolean;
var
SQL: string;
begin
SQL := 'update aluno set nome = ' + QuotedSTR(pAluno.Nome) +
', id_endereco = ' + QuotedSTR(InttoStr(pAluno.IdEndereco)) +
', id_responsavel = null' + ', cpf = ' + QuotedSTR(pAluno.Cpf) + ', rg = ' +
QuotedSTR(pAluno.rg) + ', telefone = ' + QuotedSTR(pAluno.contato) +
', telefone_comercial = ' + QuotedSTR(pAluno.contatocom) + ', data_nasc = '
+ QuotedSTR(DateToStr(pAluno.DataNasc)) + ', email = ' +
QuotedSTR(pAluno.email) + ' where id_aluno = ' +
QuotedSTR(InttoStr(pAluno.id));
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.UpdateAlunoResponsavel(pAluno: TAluno): boolean;
var
SQL: string;
begin
SQL := 'update aluno set nome = ' + QuotedSTR(pAluno.Nome) +
', id_endereco = ' + QuotedSTR(InttoStr(pAluno.IdEndereco)) +
', id_responsavel = ' + QuotedSTR(InttoStr(pAluno.IDResponsavel)) +
', cpf = ' + QuotedSTR(pAluno.Cpf) + ', rg = ' + QuotedSTR(pAluno.rg) +
', telefone = ' + QuotedSTR(pAluno.contato) + ', telefone_comercial = ' +
QuotedSTR(pAluno.contatocom) + ', data_nasc = ' +
QuotedSTR(DateToStr(pAluno.DataNasc)) + ', email = ' +
QuotedSTR(pAluno.email) + ' where id_aluno = ' +
QuotedSTR(InttoStr(pAluno.id));
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.UpdateAluno_curso(pAula: TAula): boolean;
var
SQL: string;
begin
SQL := 'update aluno_curso set id_aluno = ' +
QuotedSTR(InttoStr(pAula.id_aluno)) + ', id_curso = ' +
QuotedSTR(InttoStr(pAula.id_curso)) + 'where id_aluno = (select id_aluno' +
' from aluno where nome = ' + QuotedSTR(pAula.aluno) +
') and id_curso = (select id_curso ' + 'from curso where nome = ' +
QuotedSTR(pAula.Curso) + ')';
result := executarComando(SQL) > 0;
end;
function TAlunoDAO.UpdateResponsavel(pResponsavel: Tresponsavel): boolean;
var
SQL: string;
begin
SQL := 'update responsavel set nome = ' + QuotedSTR(pResponsavel.Nome) +
', cpf = ' + QuotedSTR(pResponsavel.Cpf) + ', rg = ' +
QuotedSTR(pResponsavel.rg) + ', telefone = ' +
QuotedSTR(pResponsavel.contato) + ', telefone_comercial = ' +
QuotedSTR(pResponsavel.contatocom) + ', data_nasc = ' +
QuotedSTR(DateToStr(pResponsavel.DataNasc)) + ' where id_responsavel =' +
QuotedSTR(InttoStr(pResponsavel.id));
result := executarComando(SQL) > 0;
end;
end.
|
unit Filter;
{ --------------------------------------------------------------
Define filtering criteria for setting record status and type
--------------------------------------------------------------
28/11/00
11/01/01 Updated, can now set record type as well as status
6/3/01 Variable,channel and record type now preserved when form is closed
25/2/02 ... Record type matching criteria added to record selection filter
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ValEdit, ValidatedEdit ;
type
TFilterFrm = class(TForm)
GroupBox3: TGroupBox;
rbAllRecords: TRadioButton;
GroupBox4: TGroupBox;
rbVariable: TRadioButton;
cbVariables: TComboBox;
bApply: TButton;
bCancel: TButton;
cbChannels: TComboBox;
lbChannels: TLabel;
GroupBox5: TGroupBox;
GroupBox2: TGroupBox;
rbAccepted: TRadioButton;
rbRejected: TRadioButton;
ckSetRecordStatus: TCheckBox;
GroupBox1: TGroupBox;
cbRecordType: TComboBox;
ckSetRecordType: TCheckBox;
cbMatchType: TComboBox;
Label3: TLabel;
GroupBox6: TGroupBox;
Label1: TLabel;
Label2: TLabel;
edUpperLimit: TValidatedEdit;
edLowerLimit: TValidatedEdit;
procedure FormShow(Sender: TObject);
procedure bApplyClick(Sender: TObject);
procedure rbAllRecordsClick(Sender: TObject);
procedure rbVariableClick(Sender: TObject);
procedure ckSetRecordStatusClick(Sender: TObject);
procedure ckSetRecordTypeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
LastVariableIndex : Integer ;
LastChannelIndex : Integer ;
LastRecordType : Integer ;
LastMatchType : Integer ;
public
{ Public declarations }
Channel : Integer ; // Channel to which filter is applied (OUT)
Variable : Integer ; // Variable to which filter is applied (OUT)
VarName : string ; // Name of selected variable
SetRecordStatus : Boolean ; // Change record status when match occurs (OUT)
Status : string ; // Change status to this after match (OUT)
SetRecordType : Boolean ; // Change record type when match occurs (OUT)
RecType : string ; // Change Record type to this after match (IN)
VarNames : TStringList ; // Variable name (IN)
LowerLimit : single ; // Lower match criteria (OUT)
UpperLimit : single ; // Upper match criteria (OUT)
AllRecords : Boolean ; // Apply changes to all records (OUT)
MatchType : string ; // Type of record selected for match (OUT)
ShowChannels : Boolean ;
end;
var
FilterFrm: TFilterFrm;
implementation
{$R *.DFM}
uses WCPFIleUnit;
procedure TFilterFrm.FormCreate(Sender: TObject);
//
// Initialisations when form is created
//
begin
LastVariableIndex := -1 ;
LastChannelIndex := -1 ;
LastRecordType := -1 ;
end;
procedure TFilterFrm.FormShow(Sender: TObject);
//
// Initialisations when form is displayed
//
begin
{ Get record type list }
cbRecordType.items := WCPFile.RecordTypes ;
cbRecordType.items.delete(0) ; {Delete first entry 'ALL'}
if LastRecordType < 0 then LastRecordType := 0 ;
cbRecordType.itemIndex := LastRecordType ;
// Selected record type (in matching criteria)
cbMatchType.Items := WCPFile.RecordTypes ;
if LastMatchType < 0 then LastMatchType := 0 ;
cbMatchType.ItemIndex := LastMatchType ;
{ Get names of available variables }
cbVariables.items := VarNames ;
if LastVariableIndex < 0 then LastVariableIndex := 0 ;
cbVariables.ItemIndex := LastVariableIndex ;
{ Ensure option controls are disabled if their check box is clear }
if not ckSetRecordType.Checked then cbRecordType.Enabled := False ;
if not ckSetRecordStatus.Checked then begin
rbAccepted.Enabled := False ;
rbRejected.Enabled := False ;
end ;
{ Make channels combo invisible if only one channel }
if ShowChannels then begin
cbChannels.Visible := True ;
lbChannels.Visible := True ;
cbChannels.items := WCPFile.ChannelNames ;
If LastChannelIndex < 0 then LastChannelIndex := 0 ;
cbChannels.ItemIndex := LastChannelIndex ;
end
else begin
cbChannels.Visible := False ;
lbChannels.Visible := False ;
end ;
end;
procedure TFilterFrm.bApplyClick(Sender: TObject);
{ ---------------------------------------------------
Updated filter criteria and result public variables
--------------------------------------------------- }
begin
Variable := Integer(TObject(cbVariables.Items.Objects[cbVariables.ItemIndex])) ;
VarName := cbVariables.Text ;
Channel := cbChannels.ItemIndex ;
SetRecordStatus := ckSetRecordStatus.Checked ;
if rbAccepted.Checked then Status := 'ACCEPTED'
else Status := 'REJECTED' ;
SetRecordType := ckSetRecordType.Checked ;
RecType := cbRecordType.text ;
// Record type to be selected for matching
MatchType :=cbMatchType.text ;
LowerLimit := edLowerLimit.Value ;
UpperLimit := edUpperLimit.Value ;
AllRecords := rbAllRecords.Checked ;
end;
procedure TFilterFrm.rbAllRecordsClick(Sender: TObject);
begin
rbVariable.Checked := False ;
end;
procedure TFilterFrm.rbVariableClick(Sender: TObject);
begin
rbAllRecords.Checked := False ;
end;
procedure TFilterFrm.ckSetRecordStatusClick(Sender: TObject);
begin
if ckSetRecordStatus.Checked then begin
rbAccepted.Enabled := True ;
rbRejected.Enabled := True ;
end
else begin
rbAccepted.Enabled := False ;
rbRejected.Enabled := False ;
end ;
end;
procedure TFilterFrm.ckSetRecordTypeClick(Sender: TObject);
begin
if ckSetRecordType.Checked then begin
cbRecordType.Enabled := True ;
end
else begin
cbRecordType.Enabled := False ;
end ;
end;
procedure TFilterFrm.FormClose(Sender: TObject; var Action: TCloseAction);
//
// Save settings when form is closed
//
begin
LastVariableIndex := cbVariables.ItemIndex ;
LastChannelIndex := cbChannels.ItemIndex ;
LastRecordType := cbRecordType.ItemIndex ;
LastMatchType := cbMatchType.ItemIndex ;
end;
Initialization
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit UI.Aero.Button.Image;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
System.Classes,
System.Types,
Winapi.Windows,
Winapi.Messages,
Winapi.CommCtrl,
Winapi.UxTheme,
Winapi.DwmApi,
Winapi.GDIPAPI,
Winapi.GDIPOBJ,
Winapi.GDIPUTIL,
Vcl.Controls,
Vcl.Graphics,
Vcl.Themes,
Vcl.Imaging.pngimage,
Vcl.StdCtrls,
{$ELSE}
SysUtils, Windows, Messages, Classes, Controls, Graphics, CommCtrl, Types,
Themes, UxTheme, DwmApi, PNGImage, StdCtrls, Winapi.GDIPAPI, Winapi.GDIPOBJ,
Winapi.GDIPUTIL,
{$ENDIF}
NTS.Code.Common.Types,
UI.Aero.Core.BaseControl,
UI.Aero.Core.CustomControl.Animation,
UI.Aero.Button.Custom,
UI.Aero.Core.Images,
UI.Aero.Globals;
type
TAeroImageButton = Class(TAeroCustomImageButton)
Protected
function GetRenderState: TARenderConfig; override;
function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override;
procedure RenderState(const PaintDC: hDC; var Surface: TGPGraphics; var RConfig: TARenderConfig; const DrawState: Integer); override;
procedure ClassicRender(const ACanvas: TCanvas; const DrawState: Integer); override;
procedure PostRender(const Surface: TCanvas; const RConfig: TARenderConfig; const DrawState: Integer); override;
Published
Property AutoSize;
End;
implementation
{ TAeroImageButton }
function TAeroImageButton.GetRenderState: TARenderConfig;
begin
Result:= [];
end;
procedure TAeroImageButton.PostRender(const Surface: TCanvas; const RConfig: TARenderConfig; const DrawState: Integer);
begin
end;
function TAeroImageButton.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean;
begin
Result:= True;
if Image.DataLoaded then
begin
NewWidth:= Image.PartWidth;
NewHeight:= Image.PartHeight;
end;
end;
procedure TAeroImageButton.ClassicRender(const ACanvas: TCanvas; const DrawState: Integer);
begin
if Image.DataLoaded then
case TAeroButtonState(DrawState) of
bsNormal : AeroPicture.DrawPart(ACanvas.Handle,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartNormal,Image.Orientation);
bsHightLight: AeroPicture.DrawPart(ACanvas.Handle,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartHightLight,Image.Orientation);
bsFocused : AeroPicture.DrawPart(ACanvas.Handle,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartFocused,Image.Orientation);
bsDown : AeroPicture.DrawPart(ACanvas.Handle,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartDown,Image.Orientation);
bsDisabled : AeroPicture.DrawPart(ACanvas.Handle,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartDisabled,Image.Orientation);
end;
end;
procedure TAeroImageButton.RenderState(const PaintDC: hDC; var Surface: TGPGraphics; var RConfig: TARenderConfig; const DrawState: Integer);
begin
if Image.DataLoaded then
case TAeroButtonState(DrawState) of
bsNormal : AeroPicture.DrawPart(PaintDC,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartNormal,Image.Orientation);
bsHightLight: AeroPicture.DrawPart(PaintDC,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartHightLight,Image.Orientation);
bsFocused : AeroPicture.DrawPart(PaintDC,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartFocused,Image.Orientation);
bsDown : AeroPicture.DrawPart(PaintDC,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartDown,Image.Orientation);
bsDisabled : AeroPicture.DrawPart(PaintDC,Image.Data.Canvas.Handle,Point(0,0),Image.PartSize,Image.PartDisabled,Image.Orientation);
end;
end;
end.
|
unit cmpSuDoku;
interface
uses Windows, Messages, Classes, SysUtils, Controls, Graphics, StdCtrls;
type
TSuDokuData = array [0..8, 0..8] of Integer;
TCustomSuDoku = class (TCustomControl)
private
fGridXCoords : array [0..9] of Integer;
fGridYCoords : array [0..9] of Integer;
fGotGridCoords : boolean;
fData : TSuDokuData;
fCellColors : TSuDokuData;
fSelX : Integer;
fSelY : Integer;
fOnSelect: TNotifyEvent;
fUpdateCount : Integer;
fAutoFontSize: boolean;
fOrigFontSize : Integer;
procedure CalcGridCoords (const r : TRect);
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure DoOnSelect;
function GetValue(x, y: Integer): Integer;
procedure SetValue(x, y: Integer; const Value: Integer);
procedure SetAutoFontSize(const Value: boolean);
function GetSquareColor(x, y : Integer): Integer;
procedure SetSquareColor(x, y : Integer; const Value: Integer);
protected
property AutoFontSize : boolean read fAutoFontSize write SetAutoFontSize default True;
procedure Loaded; override;
procedure Paint; override;
procedure ReDisplay;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
property OnSelect : TNotifyEvent read fOnSelect write fOnSelect;
public
constructor Create (AOwner : TComponent); override;
procedure BeginUpdate;
procedure Clear;
procedure EndUpdate;
procedure SelectSquare (x, y : Integer);
procedure UnselectAll;
property SelX : Integer read fSelX;
property SelY : Integer read fSelY;
property Value [x, y : Integer] : Integer read GetValue write SetValue;
property SquareColor [x, y : Integer] : Integer read GetSquareColor write SetSquareColor;
end;
TSuDoku = class (TCustomSuDoku)
published
property Align;
property Anchors;
property BevelEdges;
property BevelInner default bvLowered;
property BevelKind default bkTile;
property BevelOuter default bvLowered;
property BiDiMode;
property Caption;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBiDiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnSelect;
property OnStartDock;
property OnStartDrag;
end;
implementation
{ TCustomSuDoku }
procedure TCustomSuDoku.BeginUpdate;
begin
Inc (fUpdateCount);
end;
procedure TCustomSuDoku.CalcGridCoords (const r : TRect);
var
i, w, h : Integer;
begin
fGotGridCoords := True;
w := r.Right - r.Left;
h := r.Bottom - r.Top;
fGridXCoords [0] := 0;
for i := 1 to 8 do
begin
fGridXCoords [i] := (w * i) div 9;
fGridYCoords [i] := (h * i) div 9;
end;
fGridXCoords [9] := w;
fGridYCoords [9] := h;
Canvas.Pen.Width := 1;
Canvas.Pen.Mode := pmCopy;
Canvas.Pen.Color := clBtnHighlight;
if fAutoFontSize then
Canvas.Font.Height := fGridYCoords [1]
else
Canvas.Font.Height := fOrigFontSize;
end;
procedure TCustomSuDoku.Clear;
var
x, y : Integer;
begin
for x := 0 to 8 do
for y := 0 to 8 do
begin
fData [x, y] := 0;
fCellColors [x, y] := -1
end;
Redisplay
end;
procedure TCustomSuDoku.CMColorChanged(var Message: TMessage);
begin
if Canvas <> nil then
begin
Canvas.Brush.Color := Color;
Invalidate
end
end;
procedure TCustomSuDoku.CMFontChanged(var Message: TMessage);
begin
Canvas.Font := Self.Font;
Invalidate
end;
var
defaultData : TSuDokuData = (
(0, 0, 5, 4, 0, 0, 6, 0, 0),
(0, 0, 0, 0, 0, 2, 0, 0, 0),
(9, 0, 7, 0, 6, 0, 4, 0, 1),
(0, 7, 0, 2, 0, 8, 0, 0, 5),
(0, 0, 8, 0, 0, 0, 1, 0, 0),
(4, 0, 0, 3, 0, 1, 0, 8, 0),
(8, 0, 2, 0, 5, 0, 9, 0, 6),
(0, 0, 0, 8, 0, 0, 0, 0, 0),
(0, 0, 4, 0, 0, 7, 8, 0, 0));
constructor TCustomSuDoku.Create(AOwner: TComponent);
var
x, y : Integer;
begin
inherited;
Width := 300;
Height := 300;
fSelX := -1;
fSelY := -1;
BevelKind := bkTile;
BevelInner := bvLowered;
BevelOuter := bvLowered;
fAutoFontSize := True;
DoubleBuffered := True;
if csDesigning in ComponentState then
for y := 0 to 8 do
for x := 0 to 8 do
fData [x, y] := defaultData [y, x];
for y := 0 to 8 do
for x := 0 to 8 do
fCellColors [x, y] := -1;
end;
procedure TCustomSuDoku.DoOnSelect;
begin
if Assigned (OnSelect) then
OnSelect (self)
end;
procedure TCustomSuDoku.EndUpdate;
begin
Dec (fUpdateCount);
if fUpdateCount = 0 then
Invalidate
end;
function TCustomSuDoku.GetSquareColor(x, y : Integer): Integer;
begin
result := fCellColors [x, y]
end;
function TCustomSuDoku.GetValue(x, y: Integer): Integer;
begin
result := fData [x, y];
end;
procedure TCustomSuDoku.Loaded;
begin
inherited;
fOrigFontSize := Font.Height;
end;
procedure TCustomSuDoku.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
i, sx, sy : Integer;
begin
inherited;
sx := -1;
sy := -1;
for i := 0 to 8 do
begin
if (sx = -1) and (x < fGridXCoords [i+1]) then
sx := i;
if (sy = -1) and (y < fGridYCoords [i+1]) then
sy := i;
end;
if (sx <> -1) and (sy <> -1) then
begin
SelectSquare (sx, sy);
DoOnSelect
end
end;
procedure TCustomSuDoku.Paint;
var
r, r1 : TRect;
i, x, y : Integer;
clr : TColor;
begin
Inherited;
Canvas.FillRect(ClientRect);
r := ClientRect;
if not fGotGridCoords then
CalcGridCoords (r);
for i := 1 to 8 do
begin
if not ((i = 3) or (i = 6)) then
begin
Canvas.MoveTo(fGridXCoords [i], r.Top - 2);
Canvas.LineTo(fGridXCoords [i], r.Bottom + 2);
Canvas.MoveTo(r.Left - 2, fGridYCoords [i]);
Canvas.LineTo(r.Right + 2, fGridYCoords [i]);
end
end;
for i := 1 to 8 do
begin
if (i = 3) or (i = 6) then
begin
r1 := Rect (fGridXCoords [i] - 2, r.Top - 1, fGridXCoords [i] + 2, r.Bottom + 2);
DrawEdge (Canvas.Handle, r1, EDGE_SUNKEN, BF_RECT);
r1 := Rect (r.Left - 2, fGridYCoords [i] - 1, r.Right + 2, fGridYCoords [i] + 2);
DrawEdge (Canvas.Handle, r1, EDGE_SUNKEN, BF_RECT)
end
end;
for x := 0 to 8 do
for y := 0 to 8 do
begin
i := fData [x, y];
if i > 0 then
begin
r.Left := fGridXCoords [x];
r.Top := fGridYCoords [y];
r.Right := r.Left + fGridXCoords [1];
r.Bottom := r.Top + fGridYCoords [1];
SetBkMode (Canvas.Handle, TRANSPARENT);
clr := fCellColors [x, y];
if clr <> -1 then
Canvas.Font.Color := clr;
DrawText (canvas.Handle, PChar (IntToStr (i)), 1, r, DT_CENTER or DT_VCENTER or DT_SINGLELINE);
if clr <> -1 then
Canvas.Font.Color := Font.Color
end;
if (x = fSelX) and (y = fSelY) then
begin
r.Left := fGridXCoords [x];
r.Top := fGridYCoords [y];
r.Right := r.Left + fGridXCoords [1];
r.Bottom := r.Top + fGridYCoords [1];
InflateRect (r, -1, -1);
Inc (r.Bottom);
Inc (r.Right);
DrawEdge (Canvas.Handle, r, EDGE_ETCHED, BF_RECT);
end
end
end;
procedure TCustomSuDoku.ReDisplay;
begin
if fUpdateCount = 0 then
Invalidate
end;
procedure TCustomSuDoku.Resize;
begin
inherited;
fGotGridCoords := False;
end;
procedure TCustomSuDoku.SelectSquare(x, y: Integer);
begin
fSelX := x;
fSelY := y;
ReDisplay
end;
procedure TCustomSuDoku.SetAutoFontSize(const Value: boolean);
begin
if value <> fAutoFontSize then
begin
fAutoFontSize := value;
fGotGridCoords := False;
ReDisplay
end
end;
procedure TCustomSuDoku.SetSquareColor(x, y : Integer; const Value: Integer);
begin
fCellColors [x, y] := Value;
ReDisplay
end;
procedure TCustomSuDoku.SetValue(x, y: Integer; const Value: Integer);
begin
fData [x, y] := Value;
ReDisplay;
end;
procedure TCustomSuDoku.UnselectAll;
begin
fSelX := -1;
fSelY := -1;
ReDisplay
end;
procedure TCustomSuDoku.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.Result := 1;
end;
end. |
object ZeroFrm: TZeroFrm
Left = 623
Top = 156
BorderStyle = bsDialog
Caption = 'Zero Level'
ClientHeight = 226
ClientWidth = 152
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Arial'
Font.Style = []
OldCreateOrder = True
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 15
object TypeGrp: TGroupBox
Left = 8
Top = 35
Width = 137
Height = 160
Caption = 'Zero level modes'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
TabOrder = 0
object Label1: TLabel
Left = 24
Top = 38
Width = 48
Height = 14
Caption = 'At sample'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
end
object Label2: TLabel
Left = 24
Top = 64
Width = 46
Height = 14
Caption = 'No. avgd.'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
end
object Label3: TLabel
Left = 43
Top = 128
Width = 26
Height = 14
Caption = 'Level'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
end
object rbFromRecord: TRadioButton
Left = 8
Top = 20
Width = 97
Height = 17
Hint =
'Calculate signal zero level for each record from a defined regio' +
'n of the record'
Caption = 'From Record'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
ParentShowHint = False
ShowHint = True
TabOrder = 0
OnClick = rbFromRecordClick
end
object rbFixed: TRadioButton
Left = 8
Top = 110
Width = 89
Height = 17
Hint = 'Zero level fixed at a constant level for all records'
Caption = 'Fixed Level'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
ParentShowHint = False
ShowHint = True
TabOrder = 1
OnClick = rbFixedClick
end
object edNumAveraged: TValidatedEdit
Left = 80
Top = 64
Width = 49
Height = 23
Text = ' 1 '
Value = 1.000000000000000000
Scale = 1.000000000000000000
NumberFormat = '%.0f'
LoLimit = 1.000000000000000000
HiLimit = 1.000000015047466E30
end
object edAtSample: TValidatedEdit
Left = 80
Top = 38
Width = 49
Height = 23
Text = ' 1 '
Value = 1.000000000000000000
Scale = 1.000000000000000000
NumberFormat = '%.0f'
LoLimit = 1.000000000000000000
HiLimit = 1.000000015047466E30
end
object edFixedLevel: TValidatedEdit
Left = 80
Top = 128
Width = 49
Height = 23
Text = ' 1 '
Value = 1.000000000000000000
Scale = 1.000000000000000000
NumberFormat = '%.0f'
LoLimit = 1.000000000000000000
HiLimit = 1.000000015047466E30
end
end
object edChannel: TEdit
Left = 8
Top = 8
Width = 137
Height = 23
ReadOnly = True
TabOrder = 1
Text = 'edChannel'
end
object bOK: TButton
Left = 8
Top = 199
Width = 49
Height = 20
Caption = 'OK'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ModalResult = 1
ParentFont = False
TabOrder = 2
OnClick = bOKClick
end
object bCancel: TButton
Left = 64
Top = 200
Width = 57
Height = 17
Caption = 'Cancel'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ModalResult = 2
ParentFont = False
TabOrder = 3
end
end
|
unit DBF;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
Classes,SysUtils,Generics.Collections,ArrayBld;
Type
TDBFField = record
private
FFieldName: String;
FFieldType: Char;
FFieldLength,FDecimalCount: Byte;
FieldValue: Variant;
FieldFormat: String;
Procedure SetFieldName(Value: string);
Procedure SetFieldType(Value: Char);
Procedure SetFieldLength(Value: Byte);
Procedure SetDecimalCount(Value: Byte);
Procedure SetFieldFormat;
Procedure Validate;
public
Constructor Create(const FieldName: String; const FieldType: Char;
const FieldLength,DecimalCount: Byte);
public
Property FieldName: String read FFieldName write SetFieldName;
Property FieldType: Char read FFieldType write SetFieldType;
Property FieldLength: Byte read FFieldLength write SetFieldLength;
Property DecimalCount: Byte read FDecimalCount write SetDecimalCount;
end;
TDBFFile = Class
private
FFileName: string;
FFieldCount,FRecordCount: Integer;
FFields: TArray<TDBFField>;
FileStream: TBufferedFileStream;
FormatSettings: TFormatSettings;
Function GetFieldNames(Field: Integer): String;
Function GetFieldTypes(Field: Integer): Char;
Function GetFieldLength(Field: Integer): Byte;
Function GetDecimalCount(Field: Integer): Byte;
Function GetPairs(Field: Integer): TPair<String,Variant>; overload;
Function GetFieldValues(Field: Integer): Variant;
public
Constructor Create;
Function IndexOf(const FieldName: String; const MustExist: Boolean = false): Integer;
Function GetFields: TArray<TDBFField>;
Function GetPairs: TArray<TPair<String,Variant>>; overload;
public
Property FileName: String read FFileName;
Property FieldCount: Integer read FFieldCount;
Property RecordCount: Integer read FRecordCount;
Property FieldNames[Field: Integer]: String read GetFieldNames;
Property FieldTypes[Field: Integer]: Char read GetFieldTypes;
Property FieldLength[Field: Integer]: Byte read GetFieldLength;
Property DecimalCount[Field: Integer]: Byte read GetDecimalCount;
Property Pairs[Field: Integer]: TPair<String,Variant> read GetPairs;
Property FieldValues[Field: Integer]: Variant read GetFieldValues; default;
end;
TDBFReader = Class(TDBFFile)
private
FRecordIndex: Integer;
FileReader: TBinaryReader;
Version: Byte;
public
Constructor Create(const FileName: String);
Function NextRecord: Boolean;
Destructor Destroy; override;
public
Property RecordIndex: Integer read FRecordIndex;
end;
TDBFWriter = Class(TDBFFile)
private
FileWriter: TBinaryWriter;
Procedure SetFieldValues(Field: Integer; Value: Variant);
public
Constructor Create(const FileName: String; const Fields: array of TDBFField); overload;
Constructor Create(const FileName: String; const DBFFile: TDBFFile); overload;
Procedure AppendRecord; overload;
Procedure AppendRecord(const Values: array of Variant); overload;
Destructor Destroy; override;
public
Property FieldValues[Field: Integer]: Variant read GetFieldValues write SetFieldValues; default;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Constructor TDBFField.Create(const FieldName: String; const FieldType: Char;
const FieldLength,DecimalCount: Byte);
begin
SetFieldName(FieldName);
SetFieldType(FieldType);
SetFieldLength(FieldLength);
SetDecimalCount(DecimalCount);
end;
Procedure TDBFField.SetFieldName(Value: string);
begin
Value := Trim(Uppercase(Value));
if (Value <> '') and (Length(Value) <= 10) then
begin
FFieldName := Value;
for var Chr := 1 to Length(Value) do
if Value[Chr] in ['A'..'Z'] then Continue else
if Value[Chr] in ['0'..'9'] then Continue else
if Value[Chr] <> '_' then raise Exception.Create('Invalid Field Name ' + Value);
end else
raise Exception.Create('Invalid Field Name ' + Value);
end;
Procedure TDBFField.SetFieldType(Value: Char);
begin
if Value <> FFieldType then
begin
FFieldType := Value;
case Value of
'C': begin
FFieldLength := 10;
FDecimalCount := 0;
end;
'D': begin
FFieldLength := 8;
FDecimalCount := 0;
end;
'L': begin
FFieldLength := 1;
FDecimalCount := 0;
end;
'F','N':
begin
FFieldLength := 10;
FDecimalCount := 0;
end;
'I': begin
FFieldLength := 4;
FDecimalCount := 0;
end;
'O': begin
FFieldLength := 8;
FDecimalCount := 0;
end;
else raise Exception.Create('Unsupported Field Type ' + Value);
end;
end;
end;
Procedure TDBFField.SetFieldLength(Value: Byte);
begin
if Value <> FFieldLength then
begin
FFieldLength := Value;
if Value > 0 then
case FFieldType of
'C': if Value > 254 then raise Exception.Create('Invalid Field Length');
'D': if Value <> 8 then raise Exception.Create('Invalid Field Length');
'L': if Value <> 1 then raise Exception.Create('Invalid Field Length');
'F','N':
begin
if Value > 20 then raise Exception.Create('Invalid Field Length') else
if (FDecimalCount > 0) and (Value < FDecimalCount+2) then raise Exception.Create('Invalid Field Length');
SetFieldFormat;
end;
'I': if Value <> 4 then raise Exception.Create('Invalid Field Length');
'O': if Value <> 8 then raise Exception.Create('Invalid Field Length');
end
else
raise Exception.Create('Invalid Field Length');
end;
end;
Procedure TDBFField.SetDecimalCount(Value: Byte);
begin
if Value <> FDecimalCount then
begin
FDecimalCount := Value;
if FFieldType in ['F','N'] then
begin
SetFieldFormat;
if Value > FFieldlength-2 then raise Exception.Create('Field Length too small');
end else
begin
if Value <> 0 then raise Exception.Create('Invalid Decimal Count');
end;
end;
end;
Procedure TDBFField.SetFieldFormat;
begin
if FDecimalCount = 0 then FieldFormat := '0' else
begin
FieldFormat := '0.';
for var Decimal := 1 to FDecimalCount do FieldFormat := FieldFormat + '#';
end;
end;
Procedure TDBFField.Validate;
begin
if (FFieldName = '') or (FFieldType = #0) then raise Exception.Create('Uninitialized DBF Field');
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TDBFFile.Create;
begin
inherited Create;
FormatSettings.DecimalSeparator := '.';
end;
Function TDBFFile.GetFieldNames(Field: Integer): String;
begin
Result := FFields[Field].FFieldName;
end;
Function TDBFFile.GetFieldTypes(Field: Integer): Char;
begin
Result := FFields[Field].FFieldType;
end;
Function TDBFFile.GetFieldLength(Field: Integer): Byte;
begin
Result := FFields[Field].FieldLength;
end;
Function TDBFFile.GetDecimalCount(Field: Integer): Byte;
begin
Result := FFields[Field].DecimalCount;
end;
Function TDBFFile.GetFieldValues(Field: Integer): variant;
begin
Result := FFields[Field].FieldValue;
end;
Function TDBFFile.GetPairs(Field: Integer): TPair<String,Variant>;
begin
Result.Key := FFields[Field].FFieldName;
Result.Value := FFields[Field].FieldValue;
end;
Function TDBFFile.IndexOf(const FieldName: String; const MustExist: Boolean = false): Integer;
begin
Result := -1;
for var Field := 0 to FFieldCount-1 do
if SameText(FFields[Field].FFieldName,FieldName) then Exit(Field);
if MustExist then raise Exception.Create('Field ' + FieldName + ' not found in ' + FFileName);
end;
Function TDBFFile.GetFields: TArray<TDBFField>;
begin
Result := Copy(FFields);
end;
Function TDBFFile.GetPairs: TArray<TPair<String,Variant>>;
begin
SetLength(Result,FFieldCount);
for var Field := 0 to FFieldCount-1 do Result[Field] := GetPairs(Field);
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TDBFReader.Create(const FileName: String);
begin
inherited Create;
FRecordIndex := -1;
FFileName := FileName;
FileStream := TBufferedFileStream.Create(FileName,fmOpenRead or fmShareDenyWrite,4096);
FileReader := TBinaryReader.Create(FileStream,TEncoding.ANSI);
// Read table file header
Version := FileReader.ReadByte and 7;
if Version = 4 then raise Exception.Create('dBase level 7 files not supported');
for var Skip := 1 to 3 do FileReader.ReadByte; // Last update date
FRecordCount := FileReader.ReadInteger;
FFieldCount := (FileReader.ReadInt16 div 32)-1;
for var Skip := 1 to 2 do FileReader.ReadByte; // Nr record bytes
for var Skip := 1 to 2 do FileReader.ReadByte; // Reserved
FileReader.ReadByte; // Incomplete dBase IV transaction
FileReader.ReadByte; // dBase IV encryption flag
for var Skip := 1 to 12 do FileReader.ReadByte; // Reserved
FileReader.ReadByte; // Production MDX flag
FileReader.ReadByte; // Language driver
for var Skip := 1 to 2 do FileReader.ReadByte; // Reserved
// Read field descriptor records
SetLength(FFields,FFieldCount);
for var Field := 0 to FFieldCount-1 do
begin
for var NameChar := 1 to 11 do
begin
var Chr := FileReader.ReadChar;
if Chr <> #0 then FFields[Field].FFieldName := FFields[Field].FFieldName + Chr;
end;
FFields[Field].FFieldType := FileReader.ReadChar;
for var Skip := 1 to 4 do FileReader.ReadByte; // Reserved
FFields[Field].FFieldLength := FileReader.ReadByte;
FFields[Field].FDecimalCount := FileReader.ReadByte;
for var Skip := 1 to 14 do FileReader.ReadByte;
end;
// Read header terminator
FileReader.ReadByte;
end;
Function TDBFReader.NextRecord: Boolean;
Var
DeletedRecord: Boolean;
begin
if FRecordIndex < FRecordCount-1 then
begin
Result := true;
Inc(FRecordIndex);
repeat
DeletedRecord := (FileReader.ReadChar = '*');
for var Field := 0 to FFieldCount-1 do
begin
case FFields[Field].FFieldType of
'I': FFields[Field].FieldValue := FileReader.ReadInt32;
'O': FFields[Field].FieldValue := FileReader.ReadDouble;
else
begin
var FieldValue := '';
for var FieldChar := 1 to FFields[Field].FFieldLength do FieldValue := FieldValue + FileReader.ReadChar;
case FFields[Field].FFieldType of
'C': FFields[Field].FieldValue := Trim(FieldValue);
'D': begin
var Year := Copy(FieldValue,1,4).ToInteger;
var Month := Copy(FieldValue,5,2).ToInteger;
var Day := Copy(FieldValue,7,2).ToInteger;
FFields[Field].FieldValue := EncodeDate(Year,Month,Day);
end;
'L': if (FieldValue='T') or (FieldValue='t') or (FieldValue='Y') or (FieldValue='y') then
begin
FFields[Field].FieldValue := true;
end else
if (FieldValue='F') or (FieldValue='f') or (FieldValue='N') or (FieldValue='n') then
begin
FFields[Field].FieldValue := false;
end else
if FieldValue = '?' then VarClear(FFields[Field].FieldValue) else
raise Exception.Create('Invalid field value (' + FFields[Field].FFieldName +')');
'F','N':
begin
FieldValue := Trim(FieldValue);
if FieldValue = '' then
VarClear(FFields[Field].FieldValue)
else
if FFields[Field].FDecimalCount = 0 then
FFields[Field].FieldValue := StrToInt(FieldValue)
else
FFields[Field].FieldValue := StrToFloat(FieldValue,FormatSettings);
end;
else VarClear(FFields[Field].FieldValue);
end;
end;
end;
end;
until not DeletedRecord;
end else Result := false;
end;
Destructor TDBFReader.Destroy;
begin
FileReader.Free;
FileStream.Free;
inherited Destroy;
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TDBFWriter.Create(const FileName: String; const Fields: array of TDBFField);
Var
B: Byte;
HeaderSize,RecordSize: Word;
Year,Month,Day: Word;
begin
inherited Create;
FFieldCount := Length(Fields);
FFields := TArrayBuilder<TDBFField>.Create(Fields);
// Validate fields
RecordSize := 1; // Deletion marker
for var Field := low(FFields) to high(FFields) do
if IndexOf(Fields[Field].FFieldName) = Field then
begin
Fields[Field].Validate;
Inc(RecordSize,Fields[Field].FFieldLength);
end else
raise Exception.Create('Duplicate Field ' + Fields[field].FFieldName);
// Open File
FileStream := TBufferedFileStream.Create(FileName,fmCreate or fmShareDenyWrite,4096);
FileWriter := TBinaryWriter.Create(FileStream,TEncoding.ANSI);
// Write table file header
FileWriter.Write(#3); // Version
DecodeDate(Now,Year,Month,Day);
B := Year-1900; // Year
FileWriter.Write(B);
B := Month; // Month
FileWriter.Write(B);
B := Day; // Day
FileWriter.Write(B);
FileWriter.Write(RecordCount);
HeaderSize := (FFieldCount+1)*32 + 1;
FileWriter.Write(HeaderSize);
FileWriter.Write(RecordSize);
for var Skip := 1 to 20 do FileWriter.Write(#0);
// Write field descriptor records
for var Field := 0 to FFieldCount-1 do
begin
var Name := FFields[Field].FFieldName;
while Length(Name) < 11 do Name := Name + #0;
FileWriter.Write(Name.ToCharArray);
FileWriter.Write(FFields[Field].FFieldType);
for var Skip := 1 to 4 do FileWriter.Write(#0); // Reserved
FileWriter.Write(FFields[Field].FFieldLength);
FileWriter.Write(FFields[Field].FDecimalCount);
for var Skip := 1 to 14 do FileWriter.Write(#0); // Reserved
end;
// Write header terminator
FileWriter.Write(#13);
end;
Constructor TDBFWriter.Create(const FileName: String; const DBFFile: TDBFFile);
begin
Create(FileName,DBFFile.FFields);
end;
Procedure TDBFWriter.SetFieldValues(Field: Integer; Value: Variant);
begin
FFields[Field].FieldValue := Value;
end;
Procedure TDBFWriter.AppendRecord;
Var
Year,Month,Day: Word;
begin
FileWriter.Write(' '); // Undeleted record
for var Field := 0 to FFieldCount-1 do
begin
case FFields[Field].FFieldType of
'C': begin
var Value: String := FFields[Field].FieldValue;
while Length(Value) < FFields[Field].FieldLength do Value := Value + #0;
FileWriter.Write(Value.ToCharArray);
end;
'D': begin
var Value: TDateTime := FFields[Field].FieldValue;
DecodeDate(Value,Year,Month,Day);
FileWriter.Write(IntToStr(Year).ToCharArray);
if Month < 10 then
FileWriter.Write(('0'+IntToStr(Month)).ToCharArray)
else
FileWriter.Write(IntToStr(Month).ToCharArray);
if Day < 10 then
FileWriter.Write(('0'+IntToStr(Day)).ToCharArray)
else
FileWriter.Write(IntToStr(Day).ToCharArray);
end;
'L': begin
var Value: Boolean := FFields[Field].FieldValue;
if Value then FileWriter.Write('T') else FileWriter.Write('F');
end;
'F','N':
begin
var Value: Float64 := FFields[Field].FieldValue;
var Text := FormatFloat(FFields[Field].FieldFormat,Value,FormatSettings);
while Length(Text) < FFields[Field].FieldLength do Text := ' ' + Text;
if Length(Text) = FFields[Field].FieldLength then
FileWriter.Write(Text.ToCharArray)
else
raise Exception.Create('Numeric value out of range (field=' +
FFields[Field].FFieldName + '; value=' +
Value.ToString + ')');
end;
'I': begin
var Value: Integer := FFields[Field].FieldValue;
FileWriter.Write(Value);
end;
'O': begin
var Value: Float64 := FFields[Field].FieldValue;
FileWriter.Write(Value);
end;
else raise Exception.Create('Unsupported field type');
end;
VarClear(FFields[Field].FieldValue);
end;
Inc(FRecordCount);
end;
Procedure TDBFWriter.AppendRecord(const Values: array of Variant);
begin
if Length(Values) = FFieldCount then
begin
for var Field := 0 to FFieldCount-1 do SetFieldValues(Field,Values[Field]);
AppendRecord;
end else
raise Exception.Create('Invalid number of fields');
end;
Destructor TDBFWriter.Destroy;
begin
// Write eof marker
var EOF: Byte := 26;
if FileWriter <> nil then FileWriter.Write(EOF);
// Update record count
if FileStream <> nil then
begin
FileStream.FlushBuffer;
FileStream.Position := 4;
FileWriter.Write(RecordCount);
end;
// Close file
FileWriter.Free;
FileStream.Free;
inherited Destroy;
end;
end.
|
unit UNetworkEventInfo;
interface
type
// 父类
TNetworkPcEventBase = class
public
PcID : string;
public
constructor Create( _PcID : string );
end;
// 添加
TNetworkPcAddEvent = class( TNetworkPcEventBase )
public
procedure Update;
private
procedure SetToBackup;
procedure SetToCloud;
end;
// 上线
TNetworkPcOnlineEvent = class( TNetworkPcEventBase )
public
procedure Update;
private
procedure SetToBackup;
procedure SetToRestore;
procedure SetToCloud;
end;
// 离线
TNetworkPcOfflineEvent = class( TNetworkPcEventBase )
public
procedure Update;
private
procedure SetToBackup;
procedure SetToRestore;
end;
// 事件调用器
NetworkPcEvent = class
public
class procedure AddPc( PcID : string );
class procedure PcOnline( PcID : string );
class procedure PcOffline( PcID : string );
end;
implementation
uses UMyBackupApiInfo, UMyCloudApiInfo, UMyRestoreApiInfo;
{ NetworkPcEvent }
class procedure NetworkPcEvent.AddPc(PcID: string);
var
NetworkPcAddEvent : TNetworkPcAddEvent;
begin
NetworkPcAddEvent := TNetworkPcAddEvent.Create( PcID );
NetworkPcAddEvent.Update;
NetworkPcAddEvent.Free;
end;
class procedure NetworkPcEvent.PcOffline(PcID: string);
var
NetworkPcOfflineEvent : TNetworkPcOfflineEvent;
begin
NetworkPcOfflineEvent := TNetworkPcOfflineEvent.Create( PcID );
NetworkPcOfflineEvent.Update;
NetworkPcOfflineEvent.Free;
end;
class procedure NetworkPcEvent.PcOnline(PcID: string);
var
NetworkPcOnlineEvent : TNetworkPcOnlineEvent;
begin
NetworkPcOnlineEvent := TNetworkPcOnlineEvent.Create( PcID );
NetworkPcOnlineEvent.Update;
NetworkPcOnlineEvent.Free;
end;
{ TNetworkPcEventBase }
constructor TNetworkPcEventBase.Create(_PcID: string);
begin
PcID := _PcID;
end;
{ TNetworkPcAddEvent }
procedure TNetworkPcAddEvent.SetToBackup;
begin
DesItemAppApi.AddNetworkItem( PcID );
end;
procedure TNetworkPcAddEvent.SetToCloud;
begin
MyCloudAppApi.AddPcItem( PcID );
end;
procedure TNetworkPcAddEvent.Update;
begin
SetToBackup;
SetToCloud;
end;
{ TNetworkPcOnlineEvent }
procedure TNetworkPcOnlineEvent.SetToBackup;
begin
// DesItemAppApi.OnlineDesItem( PcID );
end;
procedure TNetworkPcOnlineEvent.SetToCloud;
begin
MyCloudAppApi.PcOnline( PcID );
end;
procedure TNetworkPcOnlineEvent.SetToRestore;
begin
NetworkRestoreAppApi.AddRestorePc( PcID );
end;
procedure TNetworkPcOnlineEvent.Update;
begin
SetToBackup;
SetToRestore;
SetToCloud;
end;
{ TNetworkPcAOfflineEvent }
procedure TNetworkPcOfflineEvent.SetToBackup;
begin
// NetworkBackupAppApi.OfflineDesItem( PcID );
end;
procedure TNetworkPcOfflineEvent.SetToRestore;
begin
NetworkRestoreAppApi.RemoveRestorePc( PcID );
end;
procedure TNetworkPcOfflineEvent.Update;
begin
SetToBackup;
SetToRestore;
end;
end.
|
unit U_Utilitarios;
interface
uses
System.SysUtils, Data.DB, REST.Response.Adapter, System.JSON;
procedure JsonToDataset(aDataset: TDataSet; aJSON: String);
function DatasetToJson(aDataset: TDataSet): String;
function GetValueBefore(aStr, aSearch: String): String;
function GetValueAfter(aStr, aSearch: String): String;
function GetJsonValue(aJsonObj: TJSONObject; aKey: String): String;
function FloatToSQL(pValue: Double): String;
implementation
procedure JsonToDataset(aDataset: TDataSet; aJSON: String);
var
JObj: TJSONArray;
vConv : TCustomJSONDataSetAdapter;
begin
if (aJSON = EmptyStr) then
Exit;
JObj := TJSONObject.ParseJSONValue(aJSON) as TJSONArray;
vConv := TCustomJSONDataSetAdapter.Create(nil);
try
vConv.Dataset := aDataset;
vConv.UpdateDataSet(JObj);
finally
vConv.Free;
JObj.Free;
end;
end;
function DatasetToJson(aDataset: TDataSet): String;
var
JObj: TJsonObject;
JArray: TJSONArray;
i: Integer;
begin
Result := '{}';
if not aDataset.Active or aDataset.IsEmpty then
Exit;
JArray := TJSONArray.Create;
try
aDataset.DisableControls;
aDataset.First;
while not aDataset.Eof do
begin
JObj := TJSONObject.Create;
for i := 0 to aDataset.FieldCount -1 do
begin
case aDataset.Fields[i].DataType of
ftBoolean:
JObj.AddPair(aDataset.Fields[i].FieldName,
TJSONBool.Create(aDataset.Fields[i].AsBoolean));
ftFloat, ftCurrency, ftBCD, ftFMTBcd, ftExtended, ftSingle, ftAutoInc,
ftLargeint, ftSmallint, ftInteger, ftWord, ftLongWord, ftShortint:
JObj.AddPair(aDataset.Fields[i].FieldName,
TJSONNumber.Create(aDataset.Fields[i].Value));
else
JObj.AddPair(aDataset.Fields[i].FieldName,
TJSONString.Create(aDataset.Fields[i].AsString));
end;
end;
JArray.AddElement(JObj);
aDataset.Next;
end;
Result := JArray.ToString;
finally
aDataset.EnableControls;
JArray.Free;
end;
end;
function GetValueBefore(aStr, aSearch: String): String;
begin
Result := Copy(aStr, 1, Pos(aSearch, aStr) -1);
end;
function GetValueAfter(aStr, aSearch: String): String;
begin
Result := Copy(aStr, Pos(aSearch, aStr) +1, Length(aStr))
end;
function GetJsonValue(aJsonObj: TJSONObject; aKey: String): String;
var
jsValue: TJSONValue;
begin
Result := '';
jsValue := aJsonObj.GetValue(aKey);
if Assigned(jsValue) then
Result := jsValue.Value;
end;
function FloatToSQL(pValue: Double): String;
begin
Result := StringReplace(FloatToStr(pValue), FormatSettings.DecimalSeparator, '.', []);
end;
end.
|
Program Pzim ;
procedure hms(s:integer);
var
hr,min:integer;
begin
hr:= s div 3600;
min:= (s mod 3600)div 60 ;
s:= ((s mod 3600) mod 60);
write(hr,' : ');
write(min,' : ') ;
writeln(s);
end;
{program principal}
var
hr,min,s:integer;
Begin
readln(s);
hms(s);
End. |
unit LayerSlotting;
interface
uses Registrator, BaseObjects, ComCtrls, Classes, RockSample;
type
// слой долбления
TSimpleLayerSlotting = class (TRegisteredIDObject)
private
FRockSamples: TRockSamples;
FBeginingLayer: double;
FEndingLayer: Double;
FCapacity: double;
FDummyLayer: boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
// начало слоя
property BeginingLayer: double read FBeginingLayer write FBeginingLayer;
// окончание слоя
property EndingLayer: double read FEndingLayer write FEndingLayer;
// мощность слоя
property Capacity: double read FCapacity write FCapacity;
// фиктивный слой или настоящий
property DummyLayer: boolean read FDummyLayer write FDummyLayer;
// образцы
property RockSamples: TRockSamples read FRockSamples write FRockSamples;
function List(AListOption: TListOption = loBrief): string; override;
procedure MakeList(AListView: TListItems; NeedsClearing: boolean = false); override;
constructor Create(ACollection: TIDObjects); override;
end;
// слои долбления
TSimpleLayerSlottings = class (TRegisteredIDObjects)
private
function GetItems(Index: integer): TSimpleLayerSlotting;
public
procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override;
property Items [Index: integer] : TSimpleLayerSlotting read GetItems;
procedure Reload; override;
constructor Create; override;
end;
// слой образца
TLayerRockSample = class (TSimpleLayerSlotting)
private
FRockSample: TRockSample;
function GetRockSamples: TRockSamples;
protected
procedure AssignTo(Dest: TPersistent); override;
public
property RockSample: TRockSample read FRockSample write FRockSample;
property RockSamples: TRockSamples read GetRockSamples;
constructor Create(ACollection: TIDObjects); override;
end;
// слои образца
TLayerRockSamples = class (TSimpleLayerSlottings)
private
function GetItems(Index: integer): TLayerRockSample;
public
procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override;
property Items [Index: integer] : TLayerRockSample read GetItems;
procedure Reload; override;
constructor Create; override;
end;
implementation
uses Facade, BaseFacades, LayerSlottingPoster, CoreDescription, SysUtils;
{ TSimpleLayerSlottings }
procedure TSimpleLayerSlottings.Assign(Sourse: TIDObjects; NeedClearing: boolean = true);
begin
inherited;
end;
constructor TSimpleLayerSlottings.Create;
begin
inherited;
FObjectClass := TSimpleLayerSlotting;
end;
function TSimpleLayerSlottings.GetItems(
Index: integer): TSimpleLayerSlotting;
begin
Result := inherited Items[Index] as TSimpleLayerSlotting;
end;
procedure TSimpleLayerSlottings.Reload;
begin
if Assigned(FDataPoster) then
begin
FDataPoster.GetFromDB('', Self);
FDataPoster.SaveState(PosterState);
end;
end;
{ TSimpleLayerSlotting }
procedure TSimpleLayerSlotting.AssignTo(Dest: TPersistent);
var o: TSimpleLayerSlotting;
begin
inherited;
o := Dest as TSimpleLayerSlotting;
o.BeginingLayer := BeginingLayer;
o.EndingLayer := EndingLayer;
o.Capacity := Capacity;
o.FDummyLayer := DummyLayer;
o.RockSamples.Assign(RockSamples);
end;
constructor TSimpleLayerSlotting.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Слой долбления';
CountFields := 9;
FDummyLayer := false;
end;
function TSimpleLayerSlotting.List(AListOption: TListOption): string;
begin
Result := 'Слой ' + trim (Name);
end;
procedure TSimpleLayerSlotting.MakeList(AListView: TListItems;
NeedsClearing: boolean);
var index : integer;
begin
inherited;
Index := AListView.Count - 1 - CountFields;
AListView.Item[Index + 1].Caption := 'Слой';
AListView.Item[Index + 1].Data := nil;
AListView.Item[Index + 1].Data := TObject;
AListView.Item[Index + 2].Caption := 'Номер слоя: ';
AListView.Item[Index + 2].Data := nil;
AListView.Item[Index + 3].Caption := ' ' + FName;
AListView.Item[Index + 4].Caption := 'Начало слоя :';
AListView.Item[Index + 4].Data := nil;
AListView.Item[Index + 5].Caption := ' ' + FloatToStr(FBeginingLayer);
AListView.Item[Index + 6].Caption := 'Окончание слоя :';
AListView.Item[Index + 6].Data := nil;
AListView.Item[Index + 7].Caption := ' ' + FloatToStr(FEndingLayer);
AListView.Item[Index + 8].Caption := 'Мощность :';
AListView.Item[Index + 8].Data := nil;
AListView.Item[Index + 9].Caption := ' ' + FloatToStr(FCapacity);
{
AListView.Item[Index + 10].Caption := 'Наличие описания в базе :';
AListView.Item[Index + 10].Data := nil;
if FTrueDescription then AListView.Item[Index + 11].Caption := ' Да'
else AListView.Item[Index + 11].Caption := ' Нет';
}
end;
{ TLayerRockSamples }
procedure TLayerRockSamples.Assign(Sourse: TIDObjects; NeedClearing: boolean = true);
begin
inherited;
end;
constructor TLayerRockSamples.Create;
begin
inherited;
FObjectClass := TLayerRockSample;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TLayerRockSampleDataPoster]
end;
function TLayerRockSamples.GetItems(Index: integer): TLayerRockSample;
begin
Result := inherited Items[Index] as TLayerRockSample;
end;
procedure TLayerRockSamples.Reload;
begin
if Assigned(FDataPoster) then
begin
FDataPoster.GetFromDB('', Self);
FDataPoster.SaveState(PosterState);
end;
end;
{ TLayerRockSample }
procedure TLayerRockSample.AssignTo(Dest: TPersistent);
begin
inherited;
end;
constructor TLayerRockSample.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Слой образца';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TLayerRockSampleDataPoster];
end;
function TLayerRockSample.GetRockSamples: TRockSamples;
begin
if not Assigned (FRockSamples) then
begin
FRockSamples := TRockSamples.Create;
FRockSamples.Reload('(slotting_uin = ' + IntToStr(Collection.Owner.ID) + ' and rock_sample_uin not in (select rl.rock_sample_uin from tbl_rock_sample_layer rl)) or ' +
'rock_sample_uin in (select rl.rock_sample_uin from tbl_rock_sample_layer rl where rl.layer_slotting_id = ' + IntToStr(ID) + ')');
FRockSamples.Owner := Self;
end;
Result := FRockSamples;
end;
end.
|
unit MBRTUPortThread;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, syncobjs, contnrs,
LoggerItf,
MBRTUMasterDispatcherTypes, MBRTUMasterDispatcherConst,
MBRTURequestBase,
COMCrossTypes;
type
{ TMBRTUPortThread }
TMBRTUPortThread = class(TThreadLogged)
private
FIntervalBetweenPolls : Cardinal;
FIsActive : Boolean;
FCSection : TCriticalSection;
FPortParams : TMBDispPortParam;
FPoolinObjList : TList;
FSingleObjQueue : TObjectQueue;
FComPort : TNPCCustomCOMPort;
FResponceBuff : TMBPacket;
FOwnedSingleRequest : Boolean;
function GetIsActive: Boolean;
procedure SetActive(AIsActive : Boolean);
procedure SetIntervalBetweenPolls(AValue: Cardinal);
protected
procedure Execute; override;
function InitThread : Boolean;
procedure CloseThread;
procedure Lock;
procedure UnLock;
procedure ProcessSingleRequests;
procedure ExecuteRequest(ARequest : TMBRTURequestBase);
public
constructor Create(APortParam : TMBDispPortParam;
ACSection : TCriticalSection;
APool : TList;
AQueue : TObjectQueue;
AOwnedSingleRequest : Boolean = False); virtual;
destructor Destroy; override;
property IsActive : Boolean read GetIsActive;
property IntervalBetweenPolls : Cardinal read FIntervalBetweenPolls write SetIntervalBetweenPolls default DefIntervalBetweenPolls;
end;
implementation
uses MBDefine, MBRTUObjItf,
ExceptionsTypes;
{ TMBRTUPortThread }
constructor TMBRTUPortThread.Create(APortParam: TMBDispPortParam;
ACSection: TCriticalSection; APool: TList; AQueue: TObjectQueue; AOwnedSingleRequest : Boolean);
begin
inherited Create(True,65535);
FIsActive := False;
FCSection := ACSection;
FPortParams := APortParam;
FPoolinObjList := APool;
FSingleObjQueue := AQueue;
FComPort := nil;
FOwnedSingleRequest := AOwnedSingleRequest;
FIntervalBetweenPolls := DefIntervalBetweenPolls;
SetLength(FResponceBuff,DefRSReadBuffSize);
end;
destructor TMBRTUPortThread.Destroy;
begin
SetLength(FResponceBuff,0);
inherited Destroy;
end;
procedure TMBRTUPortThread.SetIntervalBetweenPolls(AValue: Cardinal);
begin
if FIntervalBetweenPolls = AValue then Exit;
if AValue < MinIntervalBetweenPolls then AValue := MinIntervalBetweenPolls;
FIntervalBetweenPolls := AValue;
end;
function TMBRTUPortThread.GetIsActive: Boolean;
begin
Lock;
try
Result := FIsActive;
finally
UnLock;
end;
end;
procedure TMBRTUPortThread.SetActive(AIsActive : Boolean);
begin
Lock;
try
FIsActive := AIsActive;
finally
UnLock;
end;
end;
procedure TMBRTUPortThread.Execute;
var TempReqCount : Integer;
TempRequest : TMBRTURequestBase;
i : Integer;
begin
SetActive(InitThread);
try
while not Terminated do
begin
if not IsActive then
begin
Sleep(FIntervalBetweenPolls);
CloseThread;
SetActive(InitThread);
Continue;
end;
// выполняем запросы из пула
Lock;
try
TempReqCount := FPoolinObjList.Count;
if TempReqCount = 0 then
begin
// выполняем все одиночные запросы
ProcessSingleRequests;
Continue;
end;
for i := 0 to TempReqCount - 1 do
begin
// сначала выполняем все одиночные запросы
ProcessSingleRequests;
TempRequest := TMBRTURequestBase(FPoolinObjList[i]);
if TempRequest = nil then Continue;
// выполняем запрос из пула
ExecuteRequest(TempRequest);
end;
finally
UnLock;
end;
Sleep(10); // нужно для возможности добавления одиночных запросов
end;
finally
CloseThread;
end;
end;
procedure TMBRTUPortThread.ProcessSingleRequests;
var TempRequest : TMBRTURequestBase;
begin
if FSingleObjQueue.Count = 0 then Exit;
while FSingleObjQueue.Count > 0 do
begin
TempRequest := TMBRTURequestBase(FSingleObjQueue.Pop);
if not Assigned(TempRequest) then Continue;
ExecuteRequest(TempRequest);
if FOwnedSingleRequest then FreeAndNil(TempRequest);
end;
end;
procedure TMBRTUPortThread.ExecuteRequest(ARequest: TMBRTURequestBase);
var TempRquest : TMBPacket;
TempLen : Integer;
TempRes : Integer;
TempWaitRes : TWaitResult;
TempTimeOut : QWord;
TempErr : Cardinal;
begin
if (not Assigned(FComPort)) or (not FComPort.Active) then Exit;
TempLen := Length(ARequest.GetRequest);
if TempLen = 0 then ARequest.BuilRequest;
TempRquest := ARequest.GetRequest;
TempRes := FComPort.WriteData(TempRquest[0],TempLen);
if TempLen <> TempRes then
begin
ARequest.LastError := ARequest.CurError;
TempErr := FComPort.LastError;
if ARequest.LastError<>TempErr then
begin
ARequest.CallBackItf.SendEvent(mdeeRSWriteErr,TempErr,1);
end;
ARequest.CurError := TempErr;
Exit;
end;
TempTimeOut := ARequest.ResponceTimeout;
TempWaitRes := FComPort.WaitForData(TempTimeOut);
if TempWaitRes <> wrSignaled then
begin
ARequest.LastError := ARequest.CurError;
if ARequest.LastError<>ERR_RESIVE_DATA_TIMEOUT then
begin
ARequest.CallBackItf.SendEvent(mdeeMBError,ERR_RESIVE_DATA_TIMEOUT,2);
end;
ARequest.CurError := ERR_RESIVE_DATA_TIMEOUT;
Exit;
end;
TempLen := Length(FResponceBuff);
TempRes := FComPort.ReadData(FResponceBuff[0],TempLen);
ARequest.SetResponce(FResponceBuff,TempRes);
FillByte(FResponceBuff[0],TempLen,0);
end;
function TMBRTUPortThread.InitThread: Boolean;
begin
Result := False;
FComPort := TNPCCustomCOMPort.Create(nil);
FComPort.Logger := Logger;
FComPort.PortNumber := FPortParams.PortNum;
FComPort.PortPrefixOther := FPortParams.PortPrefix;
FComPort.BaudRate := FPortParams.BaudRate;
FComPort.ByteSize := FPortParams.DataBits;
FComPort.StopBits := FPortParams.StopBits;
FComPort.Parity := FPortParams.Parity;
FComPort.Open;
if not FComPort.Active then
begin
CloseThread;
Exit;
end;
Result := True;
end;
procedure TMBRTUPortThread.CloseThread;
begin
if not Assigned(FComPort) then Exit;
if FComPort.Active then FComPort.Close;
FreeAndNil(FComPort);
end;
procedure TMBRTUPortThread.Lock;
begin
if Assigned(FCSection) then FCSection.Enter;
end;
procedure TMBRTUPortThread.UnLock;
begin
if Assigned(FCSection) then FCSection.Leave;
end;
end.
|
unit Facade;
interface
uses BaseFacades, Registrator, Classes, DBGate, SDFacade;
type
TMainFacade = class (TSDFacade)
private
FFilter: string;
FRegistrator: TRegistrator;
protected
function GetRegistrator: TRegistrator; override;
public
// фильтр
property Filter: string read FFilter write FFilter;
// в конструкторе создаются и настраиваются всякие
// необходимые в скором времени вещи
constructor Create(AOwner: TComponent); override;
end;
TConcreteRegistrator = class(TRegistrator)
public
constructor Create; override;
end;
implementation
{ TMDFacade }
constructor TMainFacade.Create(AOwner: TComponent);
begin
inherited;
// настройка соединения с бд
//DBGates.ServerClassString := 'RiccServer.CommonServer';
DBGates.AutorizationMethod := amEnum;
DBGates.NewAutorizationMode := false;
// обязательно также тип клиента прям здесь указать
end;
function TMainFacade.GetRegistrator: TRegistrator;
begin
if not Assigned(FRegistrator) then
FRegistrator := TConcreteRegistrator.Create;
Result := FRegistrator;
end;
{ TConcreteRegistrator }
constructor TConcreteRegistrator.Create;
begin
inherited;
AllowedControlClasses.Add(TStringsRegisteredObject);
AllowedControlClasses.Add(TTreeViewRegisteredObject);
end;
end.
|
(*======================================================================*
| unitCharsetMap |
| |
| Set of functions used to interface with the IMultiLanguage interface |
| and provide codepage to codepage mapping etc. |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (the "License"); you may not use this file except in |
| compliance with the License. You may obtain a copy of the License |
| at http://www.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" |
| basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See |
| the License for the specific language governing rights and |
| limitations under the License. |
| |
| Copyright © Colin Wilson 2005 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 10.0 08/03/2006 CPWW BDS 2006 release version |
*======================================================================*)
unit unitCharsetMap;
interface
uses Windows, Classes, SysUtils, Graphics, MultiLanguage_TLB, richedit, ConTnrs;
var
CP_USASCII : Integer = 0;
DefaultCodePage : Integer = 0;
function MIMECharsetNameToCodepage (const MIMECharsetName : string) : Integer;
function CharsetNameToCodepage (const CharsetName : string) : Integer;
function CodepageToMIMECharsetName (codepage : Integer) : string;
function CodepageToCharsetName (codepage : Integer) : string;
function CharsetToCodePage (FontCharset : TFontCharset) : Integer;
function CodePageToCharset (codePage : Integer) : TFontCharset;
function StringToAnsiString (const ws : String; codePage : Integer) : AnsiString;
function AnsiStringToString (const st : AnsiString; codePage : Integer) : String;
function AnsiStringToGDIAnsiString (const s : AnsiString; codePage : Integer) : AnsiString;
function GDIAnsiStringToAnsiString (const s : AnsiString; codePage : Integer) : AnsiString;
function URLSuffixToCodePage (urlSuffix : string) : Integer;
procedure GetCharsetNames (sl : TStrings);
function TrimEx(const S: string): string;
function IsWideCharAlpha (ch : WideChar) : boolean;
function IsWideCharAlnum (ch : WideChar) : boolean;
procedure FontToCharFormat(font: TFont; codePage : Integer; var Format: TCharFormatW);
function StringToUTF8 (const ws : String) : AnsiString;
function UTF8ToString (const st : AnsiString) : String;
var
gIMultiLanguage : IMultiLanguage = Nil;
gMultilanguageLoaded : boolean = False;
gMultiLang : boolean = False;
type
TCountryCodes = class;
TCountryCode = class
private
fCode : Integer;
fName : string;
fOwner : TCountryCodes;
protected
constructor CreateFromReg (AOwner : TCountryCodes; RootKey : HKEY; ACode : Integer);
public
constructor Create (AOwner : TCountryCodes; ACode : Integer; const AName : string);
property Code : Integer read fCode;
property Name : string read fName;
property Owner : TCountryCodes read fOwner;
end;
TCountryCodes = class (TObjectList)
private
fPreferedList : TStrings;
function GetCountryCode(idx: Integer): TCountryCode;
public
constructor Create;
procedure SortByName (const PreferedList : string);
procedure SortByCode;
property CountryCode [idx : Integer] : TCountryCode read GetCountryCode;
end;
implementation
uses ActiveX, Registry;
type
TCharsetRec = record
Name : string;
URLSuffix : string;
CodePage : Integer;
CharSet : TFontCharSet;
MIMECharsetName : string;
CharsetName : string;
end;
var
gCharsetMap : array [0..35] of TCharsetRec = (
(Name:'US ASCII'; URLSuffix:''; CodePage: 0; Charset:0; MIMECharsetName:''; CharsetName:'ANSI_CHARSET' ),
(Name:'US ASCII'; URLSuffix:''; CodePage: 0; Charset:0; MIMECharsetName:'us-ascii'; CharsetName:'ANSI_CHARSET' ),
(Name:'Western Europe (ISO)'; URLSuffix:''; CodePage:28591; Charset:0; MIMECharsetName:'iso-8859-1'; CharsetName:'ANSI_CHARSET' ),
(Name:'Western Europe (Windows)'; URLSuffix:''; CodePage:01252; Charset:0; MIMECharsetName:'windows-1252'; CharsetName:'ANSI_CHARSET' ),
(Name:'Latin (3)'; URLSuffix:''; CodePage:28593; Charset:162; MIMECharsetName:'iso-8859-3'; CharsetName:'TURKISH_CHARSET' ),
(Name:'Latin (9)'; URLSuffix:''; CodePage:28605; Charset:0; MIMECharsetName:'iso-8859-15'; CharsetName:'ANSI_CHARSET' ),
(Name:'Thai'; URLSuffix:'.th'; CodePage:00874; Charset:222; MIMECharsetName:'iso-8859-11'; CharsetName:'ARABIC_CHARSET' ),
(Name:'Japanese (JIS)'; URLSuffix:'.jp'; CodePage:50220; Charset:128; MIMECharsetName:'iso-2022-jp'; CharsetName:'SHIFTJIS_CHARSET' ),
(Name:'Japanese (EUC)'; URLSuffix:''; CodePage:51932; Charset:128; MIMECharsetName:'euc-jp'; CharsetName:'SHIFTJIS_CHARSET' ),
(Name:'Japanese (EUC)'; URLSuffix:''; CodePage:51932; Charset:128; MIMECharsetName:'x-euc-jp'; CharsetName:'SHIFTJIS_CHARSET' ),
(Name:'Japanese (Shift-JIS)'; URLSuffix:''; CodePage:00932; Charset:128; MIMECharsetName:'shift-jis'; CharsetName:'SHIFTJIS_CHARSET' ),
(Name:'Japanese (Shift-JIS)'; URLSuffix:''; CodePage:00932; Charset:128; MIMECharsetName:'x-shift-jis'; CharsetName:'SHIFTJIS_CHARSET' ),
(Name:'Chinese - Simplified (GB2312)'; URLSuffix:''; CodePage:00936; Charset:134; MIMECharsetName:'gb2312'; CharsetName:'GB2312_CHARSET' ),
(Name:'Chinese - Simplified (HZ)'; URLSuffix:''; CodePage:52936; Charset:134; MIMECharsetName:'hz-gb-2312'; CharsetName:'GB2312_CHARSET' ),
(Name:'Chinese - Traditional (Big5)'; URLSuffix:'.cn'; CodePage:00950; Charset:136; MIMECharsetName:'big5'; CharsetName:'CHINESEBIG5_CHARSET'),
(Name:'Chinese - Traditional (Big5)'; URLSuffix:''; CodePage:00950; Charset:136; MIMECharsetName:'x-big5'; CharsetName:'CHINESEBIG5_CHARSET'),
(Name:'Korean'; URLSuffix:'.kr'; CodePage:00949; Charset:129; MIMECharsetName:'iso-2022-kr'; CharsetName:'HANGEUL_CHARSET' ),
(Name:'Korean'; URLSuffix:''; CodePage:00949; Charset:129; MIMECharsetName:'KS_C_5601-1987'; CharsetName:'HANGEUL_CHARSET' ),
(Name:'Korean (EUC)'; URLSuffix:''; CodePage:51949; Charset:129; MIMECharsetName:'euc-kr'; CharsetName:'HANGEUL_CHARSET' ),
(Name:'Korean (EUC)'; URLSuffix:''; CodePage:51949; Charset:129; MIMECharsetName:'x-euc-kr'; CharsetName:'HANGEUL_CHARSET' ),
(Name:'Central European (ISO)'; URLSuffix:''; CodePage:28592; Charset:238; MIMECharsetName:'iso-8859-2'; CharsetName:'EASTEUROPE_CHARSET' ),
(Name:'Central European (Windows)'; URLSuffix:''; CodePage:01250; Charset:238; MIMECharsetName:'windows-1250'; CharsetName:'EASTEUROPE_CHARSET' ),
(Name:'Russian (KOI8-R)'; URLSuffix:'.ru'; CodePage:20878; Charset:204; MIMECharsetName:'koi8-r'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Russian (KOI8-R)'; URLSuffix:''; CodePage:20878; Charset:204; MIMECharsetName:'x-koi8-r'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Russian (KOI8)'; URLSuffix:''; CodePage:20866; Charset:204; MIMECharsetName:'koi8'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Russian (KOI8)'; URLSuffix:''; CodePage:20866; Charset:204; MIMECharsetName:'x-koi8'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Russian (ISO)'; URLSuffix:''; CodePage:28595; Charset:204; MIMECharsetName:'iso-8859-5'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Russian (Windows)'; URLSuffix:''; CodePage:01251; Charset:204; MIMECharsetName:'windows-1251'; CharsetName:'RUSSIAN_CHARSET' ),
(Name:'Greek (ISO)'; URLSuffix:''; CodePage:28597; Charset:161; MIMECharsetName:'iso-8859-7'; CharsetName:'GREEK_CHARSET' ),
(Name:'Greek (Windows)'; URLSuffix:'.gr'; CodePage:01253; Charset:161; MIMECharsetName:'windows-1253'; CharsetName:'GREEK_CHARSET' ),
(Name:'Turkish (ISO)'; URLSuffix:'.tr'; CodePage:28599; Charset:162; MIMECharsetName:'iso-8859-9'; CharsetName:'TURKISH_CHARSET' ),
(Name:'Hebrew (Windows)'; URLSuffix:'.il'; CodePage:01255; Charset:177; MIMECharsetName:'windows-1255'; CharsetName:'HEBREW_CHARSET' ),
(Name:'Hebrew (ISO)'; URLSuffix:''; CodePage:28598; Charset:177; MIMECharsetName:'iso-8859-9'; CharsetName:'HEBREW_CHARSET' ),
(Name:'Arabic (ISO)'; URLSuffix:''; CodePage:28596; Charset:178; MIMECharsetName:'iso-8859-6'; CharsetName:'ARABIC_CHARSET' ),
(Name:'Baltic (ISO)'; URLSuffix:''; CodePage:28594; Charset:186; MIMECharsetName:'iso-8859-4'; CharsetName:'BALTIC_CHARSET' ),
(Name:'Unicode (UTF-8)'; URLSuffix:''; CodePage:65001; Charset:0; MIMECharsetName:'utf-8'; CharsetName:'ANSI_CHARSET' )
);
CharsetMap : array of TCharsetRec;
procedure LoadMultilanguage;
type
PMIMECPInfo = ^tagMIMECPInfo;
var
enum : IEnumCodepage;
p, info : PMIMECPInfo;
i, j, c, ct : DWORD;
found : boolean;
sz : Integer;
begin
if (not gMultilanguageLoaded) or (giMultiLanguage = Nil) then
begin
gMultilanguageLoaded := True;
gIMultiLanguage := CoCMultiLanguage.Create;
gMultiLang := False;
if Assigned (gIMultiLanguage) then
begin
gIMultiLanguage.EnumCodePages(MIMECONTF_MAILNEWS, enum);
info := CoTaskMemAlloc (10* sizeof (tagMIMECPInfo));;
try
c := 2;
while SUCCEEDED (enum.Next (10, info^, ct)) and (ct <> 0) do
begin
SetLength (CharsetMap, c + ct);
if c = 2 then
begin
CharsetMap [0] := gCharsetMap [0];
CharsetMap [1] := gCharsetMap [5]
end;
p := info;
sz := sizeof (info^);
MessageBeep (sz);
for i := 0 to ct - 1 do
begin
CharsetMap [i + c].name := PWideChar (@p^.wszDescription [0]);
CharsetMap [i + c].CodePage := p^.uiCodePage;
CharsetMap [i + c].CharSet := p^.bGDICharset;
CharsetMap [i + c].MIMECharsetName := PWideChar (@p^.wszWebCharset [0]);
CharsetMap [i + c].CharsetName := '';
Inc (p);
end;
Inc (c, ct);
end;
for i := 0 to c - 1 do
for j := Low (gCharsetMap) to High (gCharsetMap) do
if gCharsetMap [j].CodePage = charsetMap [i].CodePage then
begin
if charsetMap [i].URLSuffix = '' then
charsetMap [i].URLSuffix := gCharsetMap [j].URLSuffix;
if charsetMap [i].URLSuffix <> '' then
break
end;
found := False;
for i := 0 to c - 1 do
if charsetMap [i].CodePage = DefaultCodePage then
begin
found := True;
break
end;
if not Found then
for i := Low (gCharsetMap) to High (gCharsetMap) do
if gCharsetMap [i].CodePage = DefaultCodePage then
begin
SetLength (charsetMap, c + 1);
charsetMap [c] := gCharsetMap [i];
break;
end;
finally
CoTaskMemFree (info)
end;
gMultiLang := True
end
else
begin
SetLength (CharsetMap, High (gCharsetMap) + 1);
for i := Low (gCharsetMap) to High (gCharsetMap) do
CharsetMap [i] := gCharsetMap [i]
end
end
end;
function MIMECharsetNameToCodepage (const MIMECharsetName : string) : Integer;
var
i : Integer;
begin
LoadMultiLanguage;
if CompareText (MIMECharsetName, 'us-ascii') = 0 then
result := CP_USASCII
else
begin
result := 0;
i := Pos ('-', MIMECharsetName);
if i > 0 then
if CompareText (Copy (MIMECharsetName, 1, i - 1), 'windows') = 0 then
result := StrToIntDef (Copy (MIMECharsetName, i + 1, MaxInt), 1252);
if result = 0 then
begin
result := CP_USASCII;
for i := Low (CharsetMap) to High (CharsetMap) do
if CompareText (CharsetMap [i].MIMECharsetName, MIMECharsetName) = 0 then
begin
result := CharsetMap [i].codepage;
break
end
end
end
end;
function CharsetNameToCodepage (const CharsetName : string) : Integer;
var
i : Integer;
begin
LoadMultiLanguage;
result := CP_USASCII;
for i := Low (CharsetMap) to High (CharsetMap) do
if CompareText (CharsetMap [i].Name, CharsetName) = 0 then
begin
result := CharsetMap [i].codepage;
break
end
end;
function CodepageToMIMECharsetName (codepage : Integer) : string;
var
i : Integer;
begin
LoadMultiLanguage;
result := '';
for i := Low (CharsetMap) to High (CharsetMap) do
if CharsetMap [i].Codepage = codepage then
begin
result := CharsetMap [i].MIMECharsetName;
break
end
end;
function CodepageToCharsetName (codepage : Integer) : string;
var
i : Integer;
begin
LoadMultiLanguage;
result := '';
for i := Low (CharsetMap) to High (CharsetMap) do
if CharsetMap [i].Codepage = codepage then
begin
result := CharsetMap [i].Name;
break
end
end;
function CharsetToCodePage (FontCharset : TFontCharset) : Integer;
var
i : Integer;
begin
LoadMultiLanguage;
result := CP_USASCII;
for i := Low (CharsetMap) to High (CharsetMap) do
if CharsetMap [i].CharSet = FontCharset then
begin
result := CharsetMap [i].CodePage;
break
end
end;
function CodePageToCharset (codePage : Integer) : TFontCharset;
var
i : Integer;
begin
LoadMultiLanguage;
result := 0;
if codepage <> 65001 then
for i := Low (CharsetMap) to High (CharsetMap) do
if CharsetMap [i].Codepage = codepage then
begin
result := CharsetMap [i].CharSet;
break
end
end;
function StringToAnsiString (const ws : String; codePage : Integer) : AnsiString;
var
dlen, len : DWORD;
mode : DWORD;
begin
LoadMultiLanguage;
len := Length (ws);
dlen := len * 4;
SetLength (result, dlen); // Dest string may be longer than source string if it's UTF-8
if codePage = -1 then
codePage := CP_USASCII;
if gMultiLang and (codePage <> CP_ACP) then
begin
mode := 0;
if not SUCCEEDED (gIMultiLanguage.ConvertStringFromUnicode(mode, codepage, PWord (PWideChar (ws))^, len, PShortInt (PAnsiChar (result))^, dlen)) then
dlen := 0
end
else
dlen := WideCharToMultiByte (codePage, 0, PWideChar (ws), len, PAnsiChar (result), len * 4, nil, nil);
if dlen = 0 then
result := AnsiString (ws)
else
SetLength (result, dlen)
end;
function AnsiStringToString (const st : AnsiString; codePage : Integer) : String;
var
len, dlen, mode : DWORD;
begin
LoadMultiLanguage;
if codePage = -1 then
codePage := CP_USASCII;
if st = '' then
result := ''
else
begin
len := Length (st);
dlen := len * 4;
SetLength (result, dlen);
if gMultiLang and (codePage <> CP_ACP) then
begin
mode := 0;
if not SUCCEEDED (gIMultiLanguage.ConvertStringToUnicode(mode, codepage, PShortInt (PAnsiChar (st))^, len, PWord (PChar (result))^, dlen)) then
dlen := 0;
end
else
dlen := MultiByteToWideChar (codepage, 0, PAnsiChar (st), len, PChar (result), len * 4);
if dlen = 0 then
result := String (st)
else
SetLength (result, dlen)
end
end;
function URLSuffixToCodePage (urlSuffix : string) : Integer;
var
i : Integer;
begin
LoadMultiLanguage;
urlSuffix := LowerCase (urlSuffix);
result := CP_USASCII;
if urlSuffix <> '' then
for i := Low (CharsetMap) to High (CharsetMap) do
if CharsetMap [i].URLSuffix = urlSuffix then
begin
result := CharsetMap [i].CodePage;
break
end
end;
procedure GetCharsetNames (sl : TStrings);
var
i : Integer;
lst : string;
begin
LoadMultiLanguage;
sl.Clear;
lst := '~';
for i := Low (CharsetMap) to High (CharsetMap) do
if lst <> CharsetMap [i].Name then
begin
lst := CharsetMap [i].Name;
sl.Add (lst)
end
end;
function TrimEx(const S: string): string;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and ((S[I] = ' ') or (s [i] = #9)) do Inc(I);
if I > L then Result := '' else
begin
while (S[L] = ' ') or (s [l] = #9) do Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
function LCIDToCodePage(ALcid: LCID): Integer;
var
Buffer: array [0..6] of Char;
begin
GetLocaleInfo(ALcid, LOCALE_IDEFAULTANSICODEPAGE, Buffer, SizeOf(Buffer));
Result:= StrToIntDef(Buffer, GetACP);
end;
function AnsiStringToGDIAnsiString (const s : AnsiString; codePage : Integer) : AnsiString;
var
cs : TFontCharset;
i : Integer;
destCP : Integer;
mode : DWORD;
len, dlen : DWORD;
begin
LoadMultiLanguage;
cs := CodePageToCharset (codePage);
destCP := -1;
for i := Low (CharsetMap) to High (CharsetMap) do
if (CharsetMap [i].CharSet = cs) and (CharsetMap [i].CodePage < 2000) then
begin
destCP := CharsetMap [i].codePage;
break
end;
if (destCP = -1) or (destCP = codePage) or (gIMultiLanguage.IsConvertible (codePage, destCP) <> S_OK) then
result := s
else
begin
mode := 0;
len := Length (s);
dlen := len * 4;
SetLength (result, dlen);
if not SUCCEEDED (gIMultiLanguage.ConvertString (mode, codepage, destCP, PByte (PAnsiChar (s))^, len, PByte (PAnsiChar (result))^, dlen)) then
dlen := 0;
if dlen = 0 then
result := s
else
SetLength (result, dlen)
end
end;
function GDIAnsiStringToAnsiString (const s : AnsiString; codePage : Integer) : AnsiString;
var
cs : TFontCharset;
i : Integer;
srcCP : Integer;
mode : DWORD;
len, dlen : DWORD;
begin
LoadMultiLanguage;
cs := CodePageToCharset (codePage);
srcCP := -1;
for i := Low (CharsetMap) to High (CharsetMap) do
if (CharsetMap [i].CharSet = cs) and (CharsetMap [i].CodePage < 2000) then
begin
srcCP := CharsetMap [i].codePage;
break
end;
if (srcCP = -1) or (srcCP = codePage) or (gIMultiLanguage.IsConvertible (srcCP, codePage) <> S_OK) then
result := s
else
begin
mode := 0;
len := Length (s);
dlen := len * 4;
SetLength (result, dlen);
if not SUCCEEDED (gIMultiLanguage.ConvertString (mode, srcCP, codepage, PByte (PAnsiChar (s))^, len, PByte (PAnsiChar (result))^, dlen)) then
dlen := 0;
if dlen = 0 then
result := s
else
SetLength (result, dlen)
end
end;
function IsWideCharAlpha (ch : WideChar) : boolean;
var
w : word;
begin
w := Word (ch);
if w < $80 then // Ascii range
result := (w >= $41) and (w <= $5a) or
(w >= $61) and (w <= $7a)
else
if w < $250 then // Latin & extensions
result := (w >= $c0) and (w <= $d6) or
(w >= $d8) and (w <= $f6) or
(w >= $f7) and (w <= $ff) or
(w >= $100) and (w <= $17f) or
(w >= $180) and (w <= $1bf) or
(w >= $1c4) and (w <= $233)
else
if w < $370 then // IPA Extensions
result := (w >= $250) and (w <= $2ad)
else
if w < $400 then // Greek & Coptic
result := (w >= $386) and (w < $3ff)
else
if w < $530 then // Cryllic
result := (w >= $400) and (w <= $47f) or
(w >= $500) and (w <= $52f)
else
if w < $590 then // Armenian
result := (w >= $531) and (w <= $556) or
(w >= $561) and (w <= $587)
else
result := True; // Can't be bothered to do any more - for the moment!
end;
function IsWideCharAlnum (ch : WideChar) : boolean;
var
w : word;
begin
w := Word (ch);
if (w >= $30) and (w <= $39) then
result := True
else
result := IsWideCharAlpha (ch)
end;
procedure FontToCharFormat(font: TFont; codePage : Integer; var Format: TCharFormatW);
var
wFontName : WideString;
begin
FillChar (Format, SizeOf (Format), 0);
Format.cbSize := sizeof (Format);
Format.dwMask := Integer (CFM_SIZE or CFM_COLOR or CFM_FACE or CFM_CHARSET or CFM_BOLD or CFM_ITALIC or CFM_UNDERLINE or CFM_STRIKEOUT);
if Font.Color = clWindowText then
Format.dwEffects := CFE_AUTOCOLOR
else
Format.crTextColor := ColorToRGB (Font.Color);
if fsBold in Font.Style then
Format.dwEffects := Format.dwEffects or CFE_BOLD;
if fsItalic in Font.Style then
Format.dwEffects := Format.dwEffects or CFE_ITALIC;
if fsUnderline in Font.Style then
Format.dwEffects := Format.dwEffects or CFE_UNDERLINE;
if fsStrikeOut in Font.Style then
Format.dwEffects := Format.dwEffects or CFE_STRIKEOUT;
Format.yHeight := Abs (Font.Size) * 20;
Format.yOffset := 0;
Format.bCharSet := CodePageToCharset (codePage);
case Font.Pitch of
fpVariable: Format.bPitchAndFamily := VARIABLE_PITCH;
fpFixed: Format.bPitchAndFamily := FIXED_PITCH;
else Format.bPitchAndFamily := DEFAULT_PITCH;
end;
wFontName := font.Name;
lstrcpynw (Format.szFaceName, PWideChar (wFontName),LF_FACESIZE - 1) ;
end;
function StringToUTF8 (const ws : String) : AnsiString;
begin
result := StringToAnsiString (ws, CP_UTF8);
end;
function UTF8TOString (const st : AnsiString) : String;
begin
result := AnsiStringToString (st, CP_UTF8);
end;
{ TCountryCodes }
constructor TCountryCodes.Create;
var
reg : TRegistry;
sl : TStrings;
i : Integer;
begin
inherited Create (true);
sl := Nil;
reg := TRegistry.Create (KEY_READ);
try
reg.RootKey := HKEY_LOCAL_MACHINE;
if reg.OpenKey ('\Software\Microsoft\Windows\CurrentVersion\Telephony\Country List', false) then
begin
sl := TStringList.Create;
reg.GetKeyNames(sl);
for i := 0 to sl.Count - 1 do
Add (TCountryCode.CreateFromReg (self, reg.CurrentKey, StrToInt (sl [i])));
end
finally
reg.Free;
sl.Free
end
end;
function TCountryCodes.GetCountryCode(idx: Integer): TCountryCode;
begin
result := TCountryCode (Items [idx]);
end;
function CompareItems (item1, item2 : pointer) : Integer;
var
c1, c2 : TCountryCode;
p1, p2 : Integer;
begin
c1 := TCountryCode (item1);
c2 := TCountryCode (item2);
if Assigned (c1.Owner.fPreferedList) then
begin
p1 := c1.Owner.fPreferedList.IndexOf(IntToStr (c1.Code));
p2 := c1.Owner.fPreferedList.IndexOf(IntToStr (c2.Code));
if p1 = -1 then
if p2 = -1 then
result := CompareText (c1.Name, c2.Name)
else
result := 1
else
if p2 = -1 then
result := -1
else
result := p1 - p2
end
else
result := CompareText (c1.Name, c2.Name);
end;
function CompareCodes (item1, item2 : pointer) : Integer;
var
c1, c2 : TCountryCode;
begin
c1 := TCountryCode (item1);
c2 := TCountryCode (item2);
result := c2.Code - c1.Code
end;
procedure TCountryCodes.SortByCode;
begin
Sort (CompareCodes);
end;
procedure TCountryCodes.SortByName(const PreferedList: string);
begin
try
if PreferedList <> '' then
begin
fPreferedList := TStringList.Create;
fPreferedList.CommaText := PreferedList;
end;
inherited Sort (CompareItems);
finally
FreeAndNil (fPreferedList);
end
end;
{ TCountryCode }
constructor TCountryCode.Create(AOwner : TCountryCodes; ACode: Integer; const AName: string);
begin
fOwner := AOwner;
fCode := ACode;
fName := AName;
end;
constructor TCountryCode.CreateFromReg(AOwner : TCountryCodes; RootKey: HKEY; ACode: Integer);
var
reg : TRegistry;
st : string;
ok : boolean;
begin
reg := TRegistry.Create (KEY_READ);
try
reg.RootKey := RootKey;
ok := reg.OpenKey (IntToStr (ACode), false);
if ok then
begin
st := reg.ReadString ('Name');
ok := st <> '';
if ok then
Create (AOwner, ACode, st);
end;
if not ok then
raise Exception.CreateFmt('Can''t get country details for %d', [ACode]);
finally
reg.Free
end
end;
initialization
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then
CP_USASCII := 20127
else
CP_USASCII := CP_ACP;
gCharsetMap [0].CodePage := CP_USASCII;
gCharsetMap [1].CodePage := CP_USASCII;
DefaultCodePage := LCIDToCodePage (SysLocale.DefaultLCID);
end.
|
unit TextEditor.Highlighter.Info;
interface
type
TTextEditorAuthorInfo = record
Name: string;
Email: string;
Comments: string;
end;
TTextEditorGeneralInfo = record
Version: string;
Date: string;
Sample: string;
end;
TTextEditorHighlighterInfo = class
public
Author: TTextEditorAuthorInfo;
General: TTextEditorGeneralInfo;
procedure Clear;
end;
implementation
procedure TTextEditorHighlighterInfo.Clear;
begin
General.Version := '';
General.Date := '';
General.Sample := '';
Author.Name := '';
Author.Email := '';
Author.Comments := '';
end;
end. |
unit uModel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uView, uCommonLib, Dialogs;
procedure Add(Chip : TChip);
procedure Remove(Chip : TChip);
implementation
resourcestring
fileDB = './Data/db.dat';
const
CHIPS_COST : array[TChip] of Integer = (1, 5, 25, 100, 500, 2000, 5000);
var
Sum : Integer;
function SplitOnChips(Sum : Integer) : TChipsAmount;
var
Chip : TChip;
begin
for Chip := High(TChip) downto Low(TChip) do
begin
Result[Chip] := Sum div CHIPS_COST[Chip];
Sum := Sum mod CHIPS_COST[Chip];
end;
end;
procedure Add(Chip : TChip);
begin
Inc(Sum, CHIPS_COST[Chip]);
ViewChips(SplitOnChips(Sum));
end;
procedure Remove(Chip : TChip);
begin
Dec(Sum, CHIPS_COST[Chip]);
ViewChips(SplitOnChips(Sum));
end;
procedure SaveData;
var
SaveFile : file of Integer;
begin
Assign(SaveFile, fileDB);
Rewrite(SaveFile);
Write(SaveFile, Sum);
CloseFile(SaveFile);
end;
procedure LoadData;
var
LoadFile : file of Integer;
begin
if (FileExists(fileDB)) then
begin
Assign(LoadFile, fileDB);
Reset(LoadFile);
Read(LoadFile, Sum);
CloseFile(LoadFile);
end
else
Sum := 0;
end;
initialization
LoadData;
ViewChips(SplitOnChips(Sum));
finalization
SaveData;
end.
|
{-----------------------------------------------------------}
{----Purpose : VT With Groupheader and Footer. }
{ By : Ir. G.W. van der Vegt }
{ For : Fun }
{ Module : VirtualGHFStringTree.pas }
{ Depends : VT 3.2.1 }
{-----------------------------------------------------------}
{ ddmmyyyy comment }
{ -------- -------------------------------------------------}
{ 05062002-Initial version. }
{ -Footer Min/Maxwidth linked to VT Header. }
{ 06062002-Implemented Min/MaxWdith width for groupheader. }
{ -Set Fulldrag of THeadControls to False to prevent}
{ strange width problems when dragging exceeds }
{ MaxWidth. }
{ -Corrected some bugs. }
{ -Started on documentation. }
{-----------------------------------------------------------}
{ nr. todo }
{ ------ -------------------------------------------------- }
{ 1. Scan for missing 3.2.1 properties. }
{-----------------------------------------------------------}
{$A+,B-,C+,D+,E-,F-,G+,H+,I+,J+,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{
@abstract(Extends a TVirtualStringTree with a GroupHeader and Footer Control. )
@author(G.W. van der Vegt <wvd_vegt@knoware.nl>)
@created(Juli 05, 2002)
@lastmod(Juli 06, 2002)
This unit contains a TVirtualStringTree Descendant that can
be linked to two THeaderControls that will act as a
GroupHeader and a Footer. The Component takes care of the
synchronized resizing of the columns, sections and controls.
<P>
Just drop a TVirtualGHFDBTreeEx and up to two
THeaderControls and link them to the TVirtualGHFDBTreeEx.
Then add columns to both THeaderControls and Columns to
the TVirtualGHFDBTreeEx's Header.
<P>
The Tag Value of the TVirtualGHFDBTreeEx Header Columns is
used to group the columns and link them to a GroupHeader's
Section.
}
{$IFDEF FPC}
{$mode delphi}{$H+}
{$ENDIF}
unit virtualghfdbtreeex;
interface
uses
{$IFDEF LCL}
LCLProc, LCLType, LMessages,
{$ELSE}
Windows,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
VirtualDBTreeEx, Laz.VirtualTrees, StdCtrls, Comctrls;
type
{ This TVirtualStringTree Descendant allows one to
attach a GroupHeader and or Footer to a
TVirtualStringTree.
<P>
Both GroupHeader and Footer are THeaderControl's.
TVirtualGHFDBTreeEx takes care of the synchronized
resizing of all three components.
}
TVirtualGHFDBTreeEx = class(TVirtualDBTreeEx)
private
FGroupHeader: THeaderControl;
FFooter: THeaderControl;
function GetFooter: THeaderControl;
function GetGroupHeader: THeaderControl;
procedure SetFooter(const Value: THeaderControl);
procedure SetGroupHeader(const Value: THeaderControl);
protected
{ Description<P>
Used for TreeOption in VirtualTreeView. }
function GetOptionsClass: TTreeOptionsClass; override;
{ Description<P>
Sets the name of the Component and renames the GroupHeader
and Footer controls accordingly. Do not call it directly
but use the name property instead.
<P>
Parameters<P>
NewName : The new name of the Component. }
procedure SetName(const NewName: TComponentName); override;
{ Description<P>
Responds to Resizing the component by re-aligning
the GroupHeader and Footer controls accordingly. Do
not call directly.
<P>
Parameters<P>
Message : The WM_SIZE Message. }
procedure WMSize(var Message: TWMSize); message WM_SIZE;
{ Description<P>
Responds to Moving the component by re-aligning
the GroupHeader and Footer controls accordingly. Do
not call directly.
<P>
Parameters<P>
Message : The WM_MOVE Message. }
procedure WMMove(var Message: {$IFDEF FPC}TLMMove{$ELSE}TWMMove{$ENDIF}); message {$IFDEF FPC}LM_MOVE{$ELSE}WM_MOVE{$ENDIF};
{ Description<P>
Called when the component's loading is finished. It
will re-align the GroupHeader and Footer controls.
Do not call directly. }
procedure Loaded; override;
{ Description<P>
Internally used to Resize the GroupHeader and Footer controls and
update the MinWidth and Maxwith properties of both GroupHeader and Footer's
Sections. Do not call directly. }
procedure MyResize;
{ Description<P>
Internally used to Resize the Columns and Sections.
Do not call directly. }
procedure ReAlignAll;
{ Description<P>
Internally used to trap Column Resizing. Attached to
the TVirtualStringTree's OnColumnResize Event.}
procedure MyOnColumnResize(Sender: TVTHeader;
Column: TColumnIndex);
{ Description<P>
Internally used to trap Footer Section Resizing. Attached to
the Footer's OnSectionTrack Event.}
procedure MyOnFooterSectionTrack(HeaderControl: TCustomHeaderControl;
Section: THeaderSection; AWidth: Integer; State: TSectionTrackState);
{ Description<P>
Internally used to trap Group Header Section Resizing. Attached to
the GroupHeader's OnSectionTrack Event.}
procedure MyOnGroupHeaderSectionTrack(HeaderControl: TCustomHeaderControl;
Section: THeaderSection; AWidth: Integer; State: TSectionTrackState);
public
{ Description<P>
Standard Constructor.
<P>
Parameters<P>
AOwner : The owning Component. }
constructor Create(AOwner: TComponent); override;
{ Description<P>
Standard Destructor. }
destructor Destroy; override;
published
{ Get/Sets the Footer value of the TVirtualGHFDBTreeEx.
The number of sections must be equal to the number of
columns in the TVirtualGHFDBTreeEx. MinWidth and MaxWidth
are derived from the Header Columns.
<P>
Note<P>
The Footer is renamed on basis of the TVirtualGHFDBTreeEx's
name to prevent problems with determining which THeaderControl belongs
to which TVirtualGHFDBTreeEx.}
property Footer: THeaderControl read GetFooter write SetFooter;
{ Get/Sets the GroupHeader value of the TVirtualGHFDBTreeEx.
The Tag property of the HeaderColumn is used to determine
which Header Columns belong to which GroupHeader Section.
A group consists of adjacent Header Columns. The rightmost
group(s) may be empty if their Indexes aren't used as the Tag Value
in any Header Column. MinWidth and MaxWidth are derived from
the Header Columns.
<P>
Note<P>
The GroupHeader is renamed on basis of the TVirtualGHFDBTreeEx's
name to prevent problems with determining which THeaderControl belongs
to which TVirtualGHFDBTreeEx.}
property GroupHeader: THeaderControl read GetGroupHeader write SetGroupHeader;
//Default Properties:
end;
implementation
function LineHeight(Canvas: TCanvas): Integer;
var
tm : {$IFDEF FPC}TLCLTextMetric{$ELSE}TEXTMETRIC{$ENDIF};
begin
with Canvas do
begin
GetTextmetrics({$IFNDEF FPC}handle, {$ENDIF}tm);
Result := {$IFDEF FPC}tm.Height + tm.Ascender{$ELSE}tm.tmHeight + tm.tmExternalLeading{$ENDIF};
end;
end;
{ TVirtualGHFDBTreeEx }
constructor TVirtualGHFDBTreeEx.Create(AOwner: TComponent);
begin
inherited;
//Preset some settings so it looks like a R/O Memo
DefaultNodeHeight := 13; //Measured against a plain TMemo so it looks equal to it.
Header.Height := 17; //Measured against a TListView;
with TStringTreeOptions(TreeOptions) do
begin
PaintOptions := PaintOptions + [toShowRoot, toShowTreeLines, toShowButtons, toHideFocusRect];
SelectionOptions := SelectionOptions + [toFullRowSelect];
end;
Parent := TWinControl(AOwner);
Header.Options := Header.Options + [hoVisible] - [hoRestrictDrag, hoDrag];
BorderWidth := 0;
{$IFNDEF FPC}
BevelKind := bkNone;
{$ENDIF}
BorderStyle := bsNone;
FGroupHeader := nil;
FFooter := nil;
OnColumnResize := MyOnColumnResize;
Header.Height := Round(2.6 * lineHeight(Canvas)); //34
Hint := '';
end;
destructor TVirtualGHFDBTreeEx.Destroy;
begin
{
If Assigned(FGroupHeader) then
begin
FGroupHeader.Parent:=nil;
FGroupHeader.Free;
end;
If Assigned(FFooter) then
begin
FFooter.Parent:=nil;
FFooter.Free;
end;
}
inherited;
end;
function TVirtualGHFDBTreeEx.GetOptionsClass: TTreeOptionsClass;
begin
Result := TStringTreeOptions;
end;
procedure TVirtualGHFDBTreeEx.MyResize;
begin
if Assigned(FGroupHeader) then
begin
FGroupHeader.Left := Left;
FGroupHeader.Width := Width;
FGroupHeader.Height := Round(1.6 * lineHeight(FGroupHeader.Canvas)); //1.9 = 25, 1.8 = 23, was 1.6 = 21
FGroupHeader.Top := Top - Round(1.6 * lineHeight(FGroupHeader.Canvas));
end;
if Assigned(FFooter) then
begin
FFooter.Left := Left;
FFooter.Width := Width;
FFooter.Top := Self.Top + Self.Height;
FFooter.Height := Round(2.6 * lineHeight(FFooter.Canvas)); //34
end;
end;
procedure TVirtualGHFDBTreeEx.MyOnColumnResize(Sender: TVTHeader;
Column: TColumnIndex);
var
ndx,
w,
i : Integer;
begin
ndx := Sender.Columns[Column].Tag;
if not (assigned(GroupHeader)) or (ndx >= GroupHeader.Sections.Count) then Exit;
//Get Width of Group Header's columns
w := 0;
for i := 0 to Pred(Header.Columns.Count) do
if (Sender.Columns[i].Tag = ndx) then Inc(w, Header.Columns[i].Width);
GroupHeader.Sections[ndx].Width := w;
GroupHeader.Update;
if not (assigned(Footer)) or (Header.Columns.Count <> Footer.Sections.Count) then Exit;
for i := 0 to Pred(Header.Columns.Count) do
begin
Footer.Sections[i].MinWidth := Header.Columns[i].MinWidth;
Footer.Sections[i].MaxWidth := Header.Columns[i].MaxWidth;
Footer.Sections[i].Width := Header.Columns[i].Width;
end;
Footer.Update;
end;
procedure TVirtualGHFDBTreeEx.ReAlignAll;
var
i, j : TColumnIndex;
MinW, MaxW : Integer;
begin
if assigned(GroupHeader) then
begin
//Loop through the Groupheaders Columns to calculated the Total MinWidth and MaxWidth
for i := 0 to Pred(GroupHeader.Sections.Count) do
begin
MinW := -1;
MaxW := -1;
for j := 0 to Pred(Header.Columns.Count) do
if (i = Header.Columns[j].Tag) then
begin
Inc(MinW, Header.Columns[j].MinWidth);
Inc(MaxW, Header.Columns[j].MaxWidth);
end;
if (MinW <> -1) and (MaxW <> -1) then
begin
GroupHeader.Sections[i].MinWidth := MinW + 1;
GroupHeader.Sections[i].MaxWidth := MaxW + 1;
end;
end;
end;
//Loop through the Header Columns to copy their MinWidth and MaxWidth to the Footer
if Assigned(Footer) then
begin
Footer.Sections.BeginUpdate;
for i := 0 to Pred(Header.Columns.Count) do
begin
Footer.Sections[i].MinWidth := Header.Columns[i].MinWidth;
Footer.Sections[i].MaxWidth := Header.Columns[i].MaxWidth;
end;
Footer.Sections.EndUpdate;
end;
//Resize Every Column.
for i := 0 to Pred(Header.Columns.Count) do
MyOnColumnResize(Header, i);
end;
procedure TVirtualGHFDBTreeEx.MyOnFooterSectionTrack(HeaderControl: TCustomHeaderControl;
Section: THeaderSection; AWidth: Integer; State: TSectionTrackState);
begin
//Strange Effects when MaxWidth is Exceeded during Drag. Width seem to be Starting at zero again.
// OutputDebugString(PChar(IntToStr(Width)));
Header.Columns[Section.Index].Width := Width;
HeaderControl.Repaint;
MyOnColumnResize(Header, Section.Index);
end;
procedure TVirtualGHFDBTreeEx.MyOnGroupHeaderSectionTrack(HeaderControl: TCustomHeaderControl;
Section: THeaderSection; AWidth: Integer; State: TSectionTrackState);
var
d, i, gr, grw, sw: Integer;
found : Boolean;
v, mid, sid : Integer;
begin
//Strange Effects when MaxWidth is Exceeded during Drag. Width seem to be Starting at zero again.
gr := Section.Index;
found := False;
grw := 0;
for i := 0 to Pred(Header.Columns.Count) do
if (Header.Columns[i].Tag = gr) then
begin
Inc(grw, Header.Columns[i].Width);
Found := True;
end;
Section.Width := Width;
//Prevent Resizing when there are no columns for this GroupHeader Section.
if not Found then exit;
// OutputDebugString(PChar(IntToStr(Width) + '+' + IntToStr(grw) + '+' + IntToStr(gr)));
sw := Width;
d := Abs(grw - sw);
//Now loop and Increment either the smallest or Decrement the largest column
//until the sizes match.
Header.Columns.BeginUpdate;
repeat
found := false;
if (d > 0) then
begin
if (grw - sw) > 0 then
begin
//Find largest
v := -1;
mid := 0;
for i := 0 to Pred(Header.Columns.Count) do
if (Header.Columns[i].Tag = gr) and (v < Header.Columns[i].Width) then
begin
v := Header.Columns[i].Width;
mid := i;
end;
if (Header.Columns[mid].Width > Header.Columns[mid].MinWidth) then
begin
Header.Columns[mid].Width := Header.Columns[mid].Width - 1;
Dec(d);
Dec(grw);
found := True;
end;
end
else
begin
//Find smallest
v := maxint;
sid := 0;
for i := 0 to Pred(Header.Columns.Count) do
if (Header.Columns[i].Tag = gr) and (v > Header.Columns[i].Width) then
begin
v := Header.Columns[i].Width;
sid := i;
end;
if (Header.Columns[sid].Width < Header.Columns[sid].MaxWidth) then
begin
Header.Columns[sid].Width := Header.Columns[sid].Width + 1;
Dec(d);
Inc(grw);
found := True;
end;
end;
end
until (d = 0) or not found;
Header.Columns.EndUpdate;
Update;
//Prevent Resizing when there's no Footer
if not (assigned(Footer)) or (Header.Columns.Count <> Footer.Sections.Count) then Exit;
Footer.Sections.BeginUpdate;
for i := 0 to Pred(Header.Columns.Count) do
Footer.Sections[i].Width := Header.Columns[i].Width;
Footer.Sections.EndUpdate;
Footer.Update;
end;
procedure TVirtualGHFDBTreeEx.SetName(const NewName: TComponentName);
begin
inherited;
//Rename the headercontrols so we can see to who they belong.
//Makes it ieasier to find the newly dropped ones with their default names.
if Assigned(FGroupHeader) then FGroupHeader.Name := NewName + '_GroupHeader';
if Assigned(FFooter) then FFooter.Name := NewName + '_Footer';
//Update after the components name is changed won't hurt.
MyResize;
ReAlignAll;
end;
procedure TVirtualGHFDBTreeEx.Loaded;
begin
inherited;
//We need an update after the component is loaded to align everything.
MyResize;
ReAlignAll;
end;
function TVirtualGHFDBTreeEx.GetGroupHeader: THeaderControl;
begin
Result := FGroupHeader;
end;
procedure TVirtualGHFDBTreeEx.SetGroupHeader(
const Value: THeaderControl);
begin
if Assigned(Value) then
begin
//Make sure to change some properties so we don't get problems.
FGroupHeader := Value;
FGroupHeader.Align := alNone;
FGroupHeader.DoubleBuffered := True;
//Prevent Strange Effects when MaxWidth is Exceeded during Drag. Width seem to be Starting at zero again.
{$IFNDEF FPC}
FGroupHeader.FullDrag := False;
{$ENDIF}
FGroupHeader.OnSectionTrack := MyOnGroupHeaderSectionTrack;
//Rename the headercontrol so we can see to who they belong.
//Makes it easier to find the newly dropped ones with their default names.
FGroupHeader.Name := Name + '_GroupHeader';
//Re-arrange all when adding or removing a header
MyResize;
ReAlignAll;
end
else
begin
FGroupHeader.OnSectionTrack := nil;
FGroupHeader := Value;
end;
end;
function TVirtualGHFDBTreeEx.GetFooter: THeaderControl;
begin
Result := FFooter;
end;
procedure TVirtualGHFDBTreeEx.SetFooter(const Value: THeaderControl);
begin
if Assigned(Value) then
begin
//Make sure to change some properties so we don't get problems.
FFooter := Value;
FFooter.Align := alNone;
FFooter.DoubleBuffered := True;
//Strange Effects when MaxWidth is Exceeded during Drag. Width seem to be Starting at zero again.
{$IFNDEF FPC}
FGroupHeader.FullDrag := False;
{$ENDIF}
FFooter.OnSectionTrack := MyOnFooterSectionTrack;
//Rename the headercontrols so we can see to who they belong.
//Makes it easier to find the newly dropped ones with their default names.
FFooter.Name := Name + '_Footer';
//Re-arrange all when adding or removing a footer
MyResize;
ReAlignAll;
end
else
begin
FFooter.OnSectionTrack := nil;
FFooter := Value;
end;
end;
procedure TVirtualGHFDBTreeEx.WMMove(var Message: {$IFDEF FPC}TLMMove{$ELSE}TWMMove{$ENDIF});
begin
inherited;
//Re-arrange all when moving the component.
MyResize;
ReAlignAll;
end;
procedure TVirtualGHFDBTreeEx.WMSize(var Message: TWMSize);
begin
inherited;
//Re-arrange all when sizing the component.
MyResize;
ReAlignAll;
end;
end.
|
unit long;
{--------}
interface
{--------}
const
max=255;
type
tlong=record
sign:char;
len:byte;
number:array[1..maxlen]of byte;
end;
procedure input(s:string;var a:tlong);
procedure output(var s:string;a:tlong);
function compare(a,b:tlong):shortint;
function compareabs(a,b:tlong):boolean;
procedure summaabs(a,b:tlong;var result:tlong);
procedure minusabs(a,b:tlong;var result:tlong);
procedure suma(operand1,operand2:tlong;var result:tlong);
procedure minus(operand1,operand2;tlong;var result:tlong);
procedure multiplay(a,b:tlong;var res:tlong);
procedure divmod(a,b:tlong;var res,ost:tlong);
{------------}
implementation
{------------}
procedure input;
var
i,k:byte;
begin
if(s[1]='-')or(s[1]='+')then
begin
a.sign:=s[1];
a.len:=length(s)-1;
k:=2;
end
else
begin
a.sign:='+';
a.len:=length(s);
k:=1;
end;
for i:=length(s) downto k do
a.digit[i+max-length(s)]:=ord(s[i])-ord('0');
end;
procedure output;
begin
end;
function compare;
var
i:byte;
begin
if (a.sign='-')and(b.sign='+') then
compare:=-1;
if (a.sign='+')and(b.sign='-') then
compare:=1;
if (a.sign='-')and(b.sign='-') then
begin
if a.len<b.len then
compare:=1;
if a.len>b.len then
compare:=-1;
end;
if (a.sign='+')and(b.sign='+') then
begin
if a.len<b.len then
compare:=-1;
if a.len>b.len then
compare:=1;
end;
if (a.sign=b.sign)and(a.len=b.len) then
begin
compare:=1;
i:=max-a.len+1;
while (a.number[i]=b.number[i])and(i<=max) do
inc(i);
if i>max then
compare:=0
else
begin
if (a.sign='-')and(a.number[i]>b.number) then
compare:=-1;
if (a.sign='+')and(a.number[i]<b.number) then
compare:=-1;
end;
end;
end;
function compareabs;
var
i:byte;
begin
compareabs:=true;
if a.len<b.len then
compareabs:=false;
if a.len=b.len then
begin
i:=max-a.len+1;
while (a.number[i]=b.number[i])and(i<=max) do
inc(i);
if a.number[i]<b.number[i] then
compareabs:=false;
end;
end;
procedure summaabs;
var
i,p,len:byte;
begin
p:=0;
if a.len>b.len then
len:=a.len+1
else
len:=b.len+1;
for i:=max downto max-len do
begin
result.number[i]:=(a.number[i]+b.number[i]+p) mod 10;
p:=(a.number[i]+b.number[i]+p) div 10;
end;
i:=1;
while (result.number[i]=0)and(i<max) do
inc(i);
result.len:=max-i+1;
end;
procedure minusabs;
var
i,z,len:byte;
begin
z:=0;
if a.len>b.len then
len:=a.len
else
len:=b.len;
for i:=max downto max-len do
begin
result.number[i]:=a.number[i]-b.number[i]-z;
if result.number[i]<0 then
begin
result.number[i]:=result.number[i]+10;
z:=1;
end
else
z:=0;
end;
i:=1;
while (result.number[i]=0)and(i<max)do
inc(i);
result.len:=max-i+1;
end;
procedure suma;
begin
if (operand1.sign=operand2.sign) then
begin
sumaabs(operand1,operand2,result);
result.sign:=operand1.sign;
end
else
begin
if compareabs(operand1,operand2)=true then
begin
minusabs(operand1,operand2,result);
result.sign:=operand1.sign;
end
else
begin
minusabs(operand2,operand1,result)
result.sign:=operand2.sign;
end;
end;
end;
procedure minus;
begin
if operand2.sign='-' then
operand2.sign:='+'
else
operand2.sign:='-';
suma(operand1,operand2,result);
end;
procedure multiplay;
var
i,j,p,mulcifra:byte;
begin
for i:=1 to max do
res.number[i]:=0;
p:=0;
for j:=max downto max-b.len+1 do
begin
for i:=max downto max-a.len+1 do
begin
mulcifra:=res.number[i-p]+a.number[i]*b.number[j];
res.number[i-p]:=mulcifra mod 10;
res.number[i-p-1]:=res.number[i-p-1]+mulcifra div 10;
end;
p:=p+1;
end;
i:=1;
while (result.number[i]=0)and(i<max) do
inc(i);
result.len:=max-i+1;
if a.sign=b.sign then
res.sign:='+'
else
res.sign:='-'
end;
procedure divmod;
var
i,p,s:byte;
procedure sdvig(var a:tlong;k:byte);
var
i:byte;
begin
for i:=1 to max-k do
a.number[i]:=a.number[i+k];
for i:=max-k+1 to max do
a.nuber[i]:=0;
end;
function dlina(a:tlong):byte;
var
i:byte;
begin
i:=1;
while (a.number[i]=0)and(i<max) do
i:=i+1;
dlina:=max-i+1;
end;
function comp0(x:tlong):boolean;
var
i:byte;
begin
comp0:=true;
i:=1;
while (x.number[i]=0)and(i<=max) do
i:=i+1;
if i<=max then
comp0:=false;
end;
begin
for i:=1 to max do
begin
res.number[i]:=0;
ost.number[i]:=0;
end;
end. |
unit sGlyphUtils;
{$I sDefs.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
sConst, buttons, acntUtils, sGraphUtils, sDefaults, ImgList, acAlphaImageList, sSpeedButton;
type
TsGlyphMode = class(TPersistent)
private
FOwner : TWinControl;
FImages: TCustomImageList;
FImageIndex: integer;
FImageIndexHot: integer;
FImageIndexPressed: integer;
procedure SetBlend(const Value: integer);
function GetHint: string;
procedure SetHint(const Value: string);
procedure SetGrayed(const Value: boolean);
procedure SetImages(const Value: TCustomImageList);
procedure SetImageIndex(const Value: integer);
procedure SetImageIndexHot(const Value: integer);
procedure SetImageIndexPressed(const Value: integer);
function ReadBlend: integer;
function ReadGrayed: boolean;
function BtnIsReady : boolean;
public
Btn : TsSpeedButton;
constructor Create(AOwner: TWinControl);
procedure Invalidate;
function ImageCount : integer;
function Width: Integer;
function Height: Integer;
published
property Blend : integer read ReadBlend write SetBlend;
property Grayed: boolean read ReadGrayed write SetGrayed;
property Hint: string read GetHint write SetHint;
property Images : TCustomImageList read FImages write SetImages;
property ImageIndex : integer read FImageIndex write SetImageIndex default -1;
property ImageIndexHot : integer read FImageIndexHot write SetImageIndexHot default -1;
property ImageIndexPressed : integer read FImageIndexPressed write SetImageIndexPressed default -1;
end;
const
iBTN_OPENFILE = 0;
iBTN_OPENFOLDER = 1;
iBTN_DATE = 2;
iBTN_ELLIPSIS = 3;
iBTN_CALC = 4;
acGlyphsResNames : array [0..4] of string = ('SF', 'SR', 'SD', 'SE', 'SC');
var
acResImgList : TsAlphaImageList;
implementation
uses sCustomComboEdit, sComboBox,
{$IFNDEF ALITE}
sCurrencyEdit,
{$ENDIF}
sMessages, acPNG, CommCtrl {$IFDEF UNICODE}, PngImage{$ENDIF};
{ TsGlyphMode }
constructor TsGlyphMode.Create(AOwner: TWinControl);
begin
Btn := nil;
FOwner := AOwner;
FImageIndex := -1;
FImageIndexHot := -1;
FImageIndexPressed := -1;
end;
function TsGlyphMode.GetHint: string;
begin
if (FOwner is TsCustomComboEdit) and (TsCustomComboEdit(FOwner).Button <> nil) then begin
Result := TsCustomComboEdit(FOwner).Button.Hint;
end
else Result := TsComboBox(FOwner).Hint;
end;
procedure TsGlyphMode.SetBlend(const Value: integer);
begin
if BtnIsReady then Btn.Blend := Value;
end;
procedure TsGlyphMode.SetHint(const Value: string);
begin
if (FOwner is TsCustomComboEdit) and (TsCustomComboEdit(FOwner).Button <> nil) then begin
TsCustomComboEdit(FOwner).Button.Hint := Value;
end;
end;
procedure TsGlyphMode.SetGrayed(const Value: boolean);
begin
if BtnIsReady then Btn.Grayed := Value;
end;
procedure TsGlyphMode.Invalidate;
begin
if FOwner is TsCustomComboEdit then begin
TsCustomComboEdit(FOwner).Button.Width := Width + 2;
TsCustomComboEdit(FOwner).Button.NumGlyphs := ImageCount;
TsCustomComboEdit(FOwner).Button.Invalidate;
end;
end;
function TsGlyphMode.Width: Integer;
begin
if FOwner is TsCurrencyEdit then begin
Result := 0;
Exit;
end;
if Assigned(FImages) and (ImageIndex > -1) and (ImageIndex < FImages.Count) then begin
Result := FImages.Width div ImageCount;
end
else begin
Result := acResImgList.Width div ImageCount;
end;
end;
function TsGlyphMode.Height: Integer;
begin
if Assigned(FImages) and (ImageIndex > -1) and (ImageIndex < FImages.Count) then begin
Result := FImages.Height
end
else begin
Result := acResImgList.Height
end;
end;
function TsGlyphMode.ImageCount: integer;
var
w, h : integer;
begin
if Assigned(FImages) and (ImageIndex > -1) and (ImageIndex < FImages.Count) then begin
w := FImages.Width;
h := FImages.Height
end
else begin
w := acResImgList.Width;
h := acResImgList.Height
end;
if w mod h = 0 then Result := w div h else Result := 1;
end;
procedure TsGlyphMode.SetImages(const Value: TCustomImageList);
begin
if FImages <> Value then begin
FImages := Value;
Invalidate;
end;
end;
procedure TsGlyphMode.SetImageIndex(const Value: integer);
begin
if FImageIndex <> Value then begin
FImageIndex := Value;
Invalidate;
end;
end;
procedure TsGlyphMode.SetImageIndexHot(const Value: integer);
begin
if FImageIndexHot <> Value then begin
FImageIndexHot := Value;
Invalidate;
end;
end;
procedure TsGlyphMode.SetImageIndexPressed(const Value: integer);
begin
if FImageIndexPressed <> Value then begin
FImageIndexPressed := Value;
Invalidate;
end;
end;
function TsGlyphMode.ReadBlend: integer;
begin
if BtnIsReady then Result := Btn.Blend else Result := 0;
end;
function TsGlyphMode.ReadGrayed: boolean;
begin
if BtnIsReady then Result := Btn.Grayed else Result := False;
end;
function TsGlyphMode.BtnIsReady: boolean;
begin
Result := (Btn <> nil) and not (csLoading in Btn.ComponentState) and not (csDestroying in Btn.ComponentState)
end;
{
procedure Ico2Bmp(Icon : HIcon; Bmp : TBitmap);
var
SDC, DDC: HDC;
hBMP: HBitmap;
TheBitmap:Pbitmap;
iINFO: TICONINFO;
begin
GetIconInfo(Icon, iinfo);
SDC := CreateCompatibleDC(0);
DDC := CreateCompatibleDC(0);
SelectObject(DDC, iinfo.hbmColor);
hBMP := SelectObject(SDC, iinfo.hbmMask);
BitBlt(DDC, 0, 0, 32, 32, SDC, 0, 0, SRCPAINT);
Bmp.handle := SelectObject(DDC, hBMP);
DeleteDC(DDC);
DeleteDC(SDC);
end;
}
{$IFDEF UNICODE}
function MakeIconFromPng(Png: TPngImage): HICON;
var
IconInfo: TIconInfo;
MaskBitmap: TBitmap;
ImgBitmap : TBitmap;
begin
MaskBitmap := TBitmap.Create;
ImgBitmap := TBitmap.Create;
try
MaskBitmap.Width := Png.Width;
MaskBitmap.Height := Png.Height;
MaskBitmap.PixelFormat := pf1bit;
MaskBitmap.Canvas.Brush.Color := clBlack;
MaskBitmap.Canvas.FillRect(Rect(0, 0, MaskBitmap.Width, MaskBitmap.Height));
IconInfo.fIcon := True;
Png.AssignTo(ImgBitmap);
IconInfo.hbmColor := ImgBitmap.Handle;
IconInfo.hbmMask := MaskBitmap.Handle;
Result := CreateIconIndirect(IconInfo);
finally
ImgBitmap.Free;
MaskBitmap.Free;
end;
end;
{$ENDIF}
var
s : TResourceStream;
it : integer;
// Ico : hIcon;
// pg : {$IFDEF UNICODE}TPngImage{$ELSE}TPNGGraphic{$ENDIF};
initialization
acResImgList := TsAlphaImageList.Create(nil);
acResImgList.Width := 48;
acResImgList.Height := 16;
for it := 0 to 4 do begin
s := TResourceStream.Create(hInstance, acGlyphsResNames[it], RT_RCDATA);
{.$IFDEF UNICODE
pg := TPngImage.Create;
pg.LoadFromStream(s);
Ico := MakeIconFromPng(pg);
.$ELSE}
{ pg := TPNGGraphic.Create;
pg.LoadFromStream(s);
Ico := MakeIcon32(pg);}
{.$ENDIF}
with TsImgListItem(acResImgList.Items.Add) do begin
ImgData.LoadFromStream(s);
ImageFormat := ifPNG;
PixelFormat := pf32bit;
end;
{
if Ico <> 0 then begin
ImageList_AddIcon(acResImgList.Handle, Ico);
DestroyIcon(Ico);
end;
}
// pg.Free;
s.Free;
end;
acResImgList.GenerateStdList;
finalization
FreeAndNil(acResImgList);
end.
|
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
//
// Unidad: HiloDescarga.pas
//
// Propósito:
// Implementa un descendiente de TThread que permite descargar un recurso de internet,
// utilizando el método directo de Wininet.
//
// Autor: José Manuel Navarro - http://www.lawebdejm.com
// Observaciones: Unidad creada en Delphi 5
// Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre que
// SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos comentarios
// o de cualquier otro modo.
//
// Modificaciones:
// JM 01/06/2003 Versión inicial
// JM 11/07/2003 Corregido un error al acceder a un host o recurso inexistente.
//
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
unit HiloDescargaHTTP;
interface
uses classes, windows;
type
//
// tipos de estado para el evento OnEstado.
//
TTipoEstado = (tsErrorInternetOpen, tsInternetOpen,
tsErrorInternetOpenUrl, tsInternetOpenUrl,
tsErrorInternetReadFile, tsInternetReadFile,
tsErrorHttpQueryInfo, tsErrorNoMoreFiles, tsContentLength,
tsErrorCreateFile, tsErrorCreateFileMapping, tsErrorMapViewOfFile,
tsErrorConnectionAborted);
//
// Eventos que genera el hilo
//
TOnEstado = procedure (tipo: TTipoEstado; msg: string; data: DWORD; var cancel: boolean) of object;
TOnProgreso = procedure (BytesActual, BytesTotal: DWORD; var cancel: boolean) of object;
//
// Clase THiloDescarga
//
// Su uso es sencillo, se crea como cualquier otro descendiente de TThread, y se asignan
// los eventos que queramos recibir:
// OnEstado: se envían mensajes por cada operación realizada, y cada error producido
// OnProgreso: se lanza cada vez que se descarga del servidor.
// Después se utiliza como cualquier otro TThread, llamando al método Resume para comenzar
// la ejecución
THiloDescarga = class(TThread)
private
FURL: string;
FDestino: string;
// situación actual de la descarga
FBytesTotal: DWORD;
FBytesActual: DWORD;
// eventos que soporta el hilo
FOnEstado: TOnEstado;
FOnProgreso: TOnProgreso;
// variable auxiliares para pasar parámetros a las funciones CallXXX
TmpTipo : TTipoEstado;
TmpData : DWORD;
TmpMsg : string;
TmpCancel : boolean;
// funciones para llamar a los eventos con Synchronize
procedure CallOnEstado;
procedure CallOnProgreso;
protected
function SendEstado(tipo: TTipoEstado; data: DWORD): boolean;
function SendProgreso: boolean;
function Descargar(var data: Pointer): integer;
function Guardar(const data: Pointer; len: DWORD): integer; virtual;
procedure Execute; override;
public
constructor Create(AURL, ADestino: string);
property URL: string read FURL write FUrl;
property Destino: string read FDestino write FDestino;
property OnEstado: TOnEstado read FOnEstado write FOnEstado;
property OnProgreso: TOnProgreso read FOnProgreso write FOnProgreso;
property ReturnValue; // publicar propiedad
end;
implementation
uses wininet, SysUtils,
forms;
constructor THiloDescarga.Create(AURL, ADestino: string);
begin
inherited Create(true);
FURL := AURL;
FDestino := ADestino;
end;
//
// Método principal del hilo.
// Descarga el recurso y lo guarda en disco
//
procedure THiloDescarga.Execute;
var
data: Pointer;
len_data: integer;
begin
len_data := Descargar(data);
if len_data <= 0 then
ReturnValue := len_data
else
begin
ReturnValue := self.Guardar(data, len_data);
if (data <> nil) then
FreeMem(data, len_data);
end;
end;
//
// Descarga de internet y lo almacena el buffer de parámetro, reservando espacio para él.
// Pasos:
// 1.- Abrir el API Wininet con InternetOpen
// 2.- Abrir el recurso con InternetOpenUrl
// 3.- Consultar la cabecera ContentLength para averiguar el tamaño del recurso
// 4.- Ir leyendo el recurso con InternetReadFile y almacenarlo en memoria
// Retorna
// 0 cancelado,
// < 0 error
// > 0 número de bytes del buffer (a liberar por el que llame a esta función)
//
function THiloDescarga.Descargar(var data: Pointer): integer;
var
hInet: HINTERNET;
hUrl: HINTERNET;
len: DWORD;
indice: DWORD;
dummy: DWORD;
buff_lectura: Pointer;
disponible: DWORD;
data_tmp: Pointer;
len_data: DWORD;
size_data: DWORD;
function SalirConError(code: integer): integer;
begin
if (hInet <> nil) then InternetCloseHandle(hInet);
if (hUrl <> nil) then InternetCloseHandle(hUrl);
if data <> nil then
begin
FreeMem(data, size_data);
data := nil;
end;
result := code;
end;
function AmpliarBuffer(var buffer: Pointer; LenActual, LenMinima, LenDatos: DWORD): DWORD;
var
new_len: DWORD;
buff_tmp: Pointer;
begin
// Esta función amplía el buffer hasta que quepan "LenMinima" bytes.
// Además copia "LenDatos" bytes del buffer original al nuevo buffer.
// Para ello se va duplicando el tamaño del buffer hasta llegar a "LenMinima"
// La razón por la que se duplica el tamaño del buffer, en vez de ampliar
// hasta el tamaño exacto, la expliqué durante el artículo
// sobre los montones, que podéis consultar en http://www.lawebdejm.com/?id=21130
// La función retorna el nuevo tamaño del buffer.
new_len := LenActual;
while ( new_len < LenMinima ) do
new_len := new_len * 2;
// Una vez que sabemos el tamaño al que tenemos que ampliar, creamos un nuevo
// buffer de ese tamaño y traspasamos los datos.
if new_len <> LenActual then
begin
// creo un buffer auxiliar donde copio el contenido
GetMem(buff_tmp, new_len);
if ( LenDatos > 0 ) then
CopyMemory(buff_tmp, buffer, LenDatos);
FreeMem(buffer, LenActual); // elimino el buffer actual (que se ha quedado demasiado pequeño)
buffer := buff_tmp; // paso a utilizar el nuevo buffer, que es el doble que el anterior
end;
result := new_len;
end;
begin
hUrl := nil;
data := nil;
// Paso 1
hInet := InternetOpen('Descarga - Delphi', // el user-agent
INTERNET_OPEN_TYPE_PRECONFIG, // configuración por defecto
nil, nil, // sin proxy
0 ); // sin opciones
if ( hInet = nil ) then
begin
SendEstado(tsErrorInternetOpen, GetLastError());
result := SalirConError(-1);
exit;
end
else
SendEstado(tsInternetOpen, DWORD(hInet));
// Paso 2
hURL := InternetOpenUrl(hInet, // el descriptor del api
PChar(FUrl), nil, 0,
INTERNET_FLAG_RELOAD, // opciones configuradas
0 );
if self.Terminated then
begin
result := SalirConError(0);
exit;
end
else if ( hURL = nil ) then
begin
SendEstado(tsErrorInternetOpenUrl, GetLastError());
result := SalirConError(-2);
exit;
end
else
begin
len := sizeof(indice);
indice := 0;
dummy := 0;
HttpQueryInfo(hUrl, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @indice, len, dummy);
case indice of
HTTP_STATUS_OK:
SendEstado(tsInternetOpenUrl, DWORD(hUrl));
HTTP_STATUS_NOT_FOUND:
begin
SendEstado(tsErrorNoMoreFiles, DWORD(hUrl));
result := SalirConError(-3);
exit;
end;
else
begin
SendEstado(tsErrorInternetOpenUrl, indice);
result := SalirConError(-3);
exit;
end;
end;
end;
// Paso 3
indice := 0;
len := sizeof(DWORD);
FBytesActual := 0;
if ( not HttpQueryInfo(hUrl, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,
@FBytesTotal, len, indice) ) then
begin
SendEstado(tsErrorHttpQueryInfo, GetLastError());
FBytesTotal := 0;
size_data := 512; // comenzamos con un buffer de 512 bytes que irá creciendo
end
else
begin
if ( not SendEstado(tsContentLength, FBytesTotal) ) then
begin
result := SalirConError(0);
exit;
end;
// si conocemos el tamaño total, reservamos los bufferes directamente
size_data := FBytesTotal;
end;
// Paso 4
buff_lectura := nil;
disponible := 0;
GetMem(data, size_data);
len_data := 0;
len := 0;
repeat
if self.Terminated then
begin
result := SalirConError(0);
exit;
end;
//
// Consultar los datos que están disponibles en el servidor
//
if ( not InternetQueryDataAvailable( hUrl, disponible, 0, 0) ) then
begin
case GetLastError() of
ERROR_NO_MORE_FILES:
begin
if not SendEstado(tsErrorNoMoreFiles, ERROR_NO_MORE_FILES) then
result := SalirConError(0)
else
result := SalirConError(-4);
end;
ERROR_INTERNET_CONNECTION_RESET,
ERROR_INTERNET_CONNECTION_ABORTED:
begin
if not SendEstado(tsErrorConnectionAborted, GetLastError()) then
result := SalirConError(0)
else
result := SalirConError(-5);
end;
else
result := SalirConError(-6);
end;
exit;
end;
if ( 0 = disponible ) then
begin
len := 0;
continue;
end
else
GetMem(buff_lectura, disponible);
//
// Leer el número de bytes disponibles
//
if ( not InternetReadFile( hUrl, buff_lectura, disponible, len) ) then
begin
if not SendEstado(tsErrorInternetReadFile, 0) then
result := SalirConError(0)
else
result := SalirConError(-7);
FreeMem(buff_lectura, disponible);
exit;
end
else if ( len > 0 ) then
begin
// ampliar el buffer con la función auxiliar
size_data := AmpliarBuffer(data, size_data, len_data + len, len_data);
// copiar los datos leídos al nuevo buffer general
data_tmp := data;
Inc(PByte(data_tmp), len_data);
CopyMemory(data_tmp, buff_lectura, len);
Inc(len_data, len);
// se notifica del tamaño descargado
FBytesActual := len_data;
if ( not SendProgreso() ) then
begin
result := SalirConError(0);
exit;
end;
end;
until ( len = 0 );
if ( buff_lectura <> nil ) then
FreeMem(buff_lectura, disponible);
result := size_data;
end;
//
// Guarda una zona de memoria en el disco, utilizando la técnica de archivos proyectados en
// memoria. Para más información sobre cómo utilizar esta técnica podéis consultar el artículo
// publicado en http://www.lawebdejm.com/?id=21140
//
function THiloDescarga.Guardar(const data: Pointer; len: DWORD): integer;
var
hFile: THandle;
hFileMap: THandle;
vista: Pointer;
begin
hFile := CreateFile(PChar(Destino), // los datos los guardamos en el destino
GENERIC_READ or GENERIC_WRITE, 0, nil, // abrimos de lectura/escritura
CREATE_ALWAYS, // creamos un archivo si no existe
FILE_ATTRIBUTE_NORMAL, 0);
if ( INVALID_HANDLE_VALUE = hFile ) then
begin
SendEstado(tsErrorCreateFile, 0);
result := -100;
end
else
begin
hFileMap := CreateFileMapping(hFile, // creamos la proyección
nil, PAGE_READWRITE, // de lectura/escritura
0, len, // del tamaño del buffer
nil); // sin nombre
if ( hFileMap = 0 ) then
begin
SendEstado(tsErrorCreateFileMapping, 0);
result := -200;
end
else
begin
vista := MapViewOfFile(hFileMap, // creamos la vista sobre la proyección
FILE_MAP_WRITE, // de lectura/escritura
0, 0, 0);
if ( vista = nil ) then
begin
SendEstado(tsErrorMapViewOfFile, 0);
result := -300;
end
else
begin
// como ya podemos acceder al archivo como si fuera un bloque de memoria,
// copiamos los caracteres en él,utilizando la función del API Win32 CopyMemory
CopyMemory(vista, data, len);
FlushViewOfFile(vista, len); // nos aseguramos que todo queda bien guardado
UnmapViewOfFile(vista); // y cerramos todos los descriptores abiertos
result := 0;
end;
CloseHandle(hFileMap);
end;
CloseHandle(hFile);
end;
end;
//
// Métodos para simplificar las llamadas a los eventos
//
function THiloDescarga.SendEstado(tipo: TTipoEstado; data: DWORD): boolean;
const
MENSAJES_ESTADO: array[TTipoEstado] of PChar =
(
'Error InternetOpen - %d', // tsErrorInternetOpen
'Instancia a internet abierta con éxito.', // tsInternetOpen
'Error InternetOpenUrl - %d', // tsErrorInternetOpenUrl
'Recurso remoto abierto con éxito.', // tsInternetOpenUrl
'Error InternetReadFile - %d', // tsErrorInternetReadFile
'Leídos %u bytes del servidor.', // tsInternetReadFile
'No es posible recuperar el tamaño del archivo.', // tsErrorHttpQueryInfo
'El recurso no existe', // tsErrorNoMoreFiles
'El archivo ocupa %u bytes.', // tsContentLength
'No se ha podido crear el archivo destino.', // tsErrorCreateFile
'No se ha podido crear la proyección de archivo.', // tsErrorCreateFileMapping,
'No se ha podido crear la vista sobre la proyección de archivo.', //tsErrorMapViewOfFile
'Se ha perdido la conexión con el servidor.' //tsErrorConnectionAborted
);
begin
result := true;
if Assigned(FOnEstado) then
begin
case tipo of
tsInternetReadFile, tsContentLength:
SendProgreso();
end;
TmpMsg := Format(MENSAJES_ESTADO[tipo], [data]);
TmpTipo := tipo;
TmpData := data;
TmpCancel := false;
Synchronize(CallOnEstado);
result := not TmpCancel;
end;
end;
function THiloDescarga.SendProgreso: boolean;
begin
TmpData := FBytesActual;
TmpCancel := false;
Synchronize(CallOnProgreso);
result := not TmpCancel;
end;
//
// Métodos auxiliares para llamar a los eventos con Synchronize
//
procedure THiloDescarga.CallOnEstado;
begin
if Assigned(FOnEstado) then
FOnEstado(TmpTipo, TmpMsg, TmpData, TmpCancel);
end;
procedure THiloDescarga.CallOnProgreso;
begin
if Assigned(FOnProgreso) then
FOnProgreso(TmpData, FBytesTotal, TmpCancel);
end;
end.
|
unit sdlticks;
{
$Id: sdlticks.pas,v 1.1 2005/05/25 23:15:42 savage Exp $
}
{******************************************************************************}
{ }
{ JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer }
{ SDL GetTicks Class Wrapper }
{ }
{ }
{ The initial developer of this Pascal code was : }
{ Dominique Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Portions created by Dominique Louis are }
{ Copyright (C) 2004 - 2100 Dominique Louis. }
{ }
{ }
{ Contributor(s) }
{ -------------- }
{ Dominique Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Obtained through: }
{ Joint Endeavour of Delphi Innovators ( Project JEDI ) }
{ }
{ You may retrieve the latest version of this file at the Project }
{ JEDI home page, located at http://delphi-jedi.org }
{ }
{ The contents of this file are used with permission, subject to }
{ the Mozilla Public License Version 1.1 (the "License"); you may }
{ not use this file except in compliance with the License. You may }
{ obtain a copy of the License at }
{ http://www.mozilla.org/MPL/MPL-1.1.html }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or }
{ implied. See the License for the specific language governing }
{ rights and limitations under the License. }
{ }
{ Description }
{ ----------- }
{ SDL Window Wrapper }
{ }
{ }
{ Requires }
{ -------- }
{ SDL.dll on Windows platforms }
{ libSDL-1.1.so.0 on Linux platform }
{ }
{ Programming Notes }
{ ----------------- }
{ }
{ }
{ }
{ }
{ Revision History }
{ ---------------- }
{ }
{ September 23 2004 - DL : Initial Creation }
{
$Log: sdlticks.pas,v $
Revision 1.1 2005/05/25 23:15:42 savage
Latest Changes
Revision 1.1 2004/09/30 22:35:47 savage
Changes, enhancements and additions as required to get SoAoS working.
}
{******************************************************************************}
interface
uses
sdl;
type
TSDLTicks = class
private
m_startTime : Int64;
m_ticksPerSecond : Int64;
s_lastTime : Int64;
public
constructor Create;
destructor Destroy; override; // destructor
{*****************************************************************************
Init
If the hi-res timer is present, the tick rate is stored and the function
returns true. Otherwise, the function returns false, and the timer should
not be used.
*****************************************************************************}
function Init : boolean;
function GetElapsedSeconds( elapsedFrames : Cardinal = 1 ) : single;
{***************************************************************************
GetFPS
Returns the average frames per second over elapsedFrames, which defaults to
one. If this is not called every frame, the client should track the number
of frames itself, and reset the value after this is called.
***************************************************************************}
function GetFPS( elapsedFrames : Cardinal = 1 ) : single;
{***************************************************************************
LockFPS
Used to lock the frame rate to a set amount. This will block until enough
time has passed to ensure that the fps won't go over the requested amount.
Note that this can only keep the fps from going above the specified level;
it can still drop below it. It is assumed that if used, this function will
be called every frame. The value returned is the instantaneous fps, which
will be <= targetFPS.
***************************************************************************}
function LockFPS( targetFPS : Byte ) : single;
end;
implementation
{ TSDLTicks }
constructor TSDLTicks.Create;
begin
end;
destructor TSDLTicks.Destroy;
begin
inherited;
end;
function TSDLTicks.GetElapsedSeconds( elapsedFrames: Cardinal ): single;
var
currentTime : Int64;
begin
// s_lastTime := m_startTime;
currentTime := SDL_GetTicks;
//QueryPerformanceCounter( currentTime );
result := (currentTime - s_lastTime) / m_ticksPerSecond;
// reset the timer
s_lastTime := currentTime;
end;
function TSDLTicks.GetFPS( elapsedFrames: Cardinal ): single;
var
currentTime : integer;
fps : single;
begin
// s_lastTime := m_startTime;
currentTime := SDL_GetTicks;
fps := elapsedFrames * m_ticksPerSecond / ( currentTime - s_lastTime);
// reset the timer
s_lastTime := currentTime;
result := fps;
end;
function TSDLTicks.Init: boolean;
begin
m_startTime := SDL_GetTicks;
s_lastTime := m_startTime;
m_ticksPerSecond := 1000;
result := true;
end;
function TSDLTicks.LockFPS(targetFPS: Byte): single;
var
currentTime : integer;
fps : single;
begin
if (targetFPS = 0) then
targetFPS := 1;
s_lastTime := m_startTime;
// delay to maintain a constant frame rate
repeat
currentTime := SDL_GetTicks;
fps := m_ticksPerSecond / (currentTime - s_lastTime);
until (fps > targetFPS);
// reset the timer
s_lastTime := m_startTime;
result := fps;
end;
end.
|
unit UnitTest;
interface
uses
System.SysUtils,
System.Messaging,
System.Math.Vectors;
type
TTestFailedMessage = class(TMessage)
{$REGION 'Internal Declarations'}
private
FTestClassName: String;
FTestMethodName: String;
FMessage: String;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const ATestClassName, ATestMethodName, AMessage: String);
property TestClassName: String read FTestClassName;
property TestMethodName: String read FTestMethodName;
property Message: String read FMessage;
end;
type
{$M+}
TUnitTest = class
{$REGION 'Internal Declarations'}
private
FCurrentTestMethodName: String;
FChecksPassed: Integer;
FChecksFailed: Integer;
FChecksTotal: Integer;
{$ENDREGION 'Internal Declarations'}
protected
procedure Fail(const AMsg: String); overload;
procedure Fail(const AMsg: String; const AArgs: array of const); overload;
procedure CheckEquals(const AExpected, AActual: String;
const AMsg: String = ''); overload;
procedure CheckEquals(const AExpected, AActual, AEpsilon: Double;
const AMsg: String = ''); overload;
procedure CheckTrue(const ACondition: Boolean);
procedure CheckFalse(const ACondition: Boolean);
procedure ShouldRaise(const AExceptionClass: ExceptClass;
const AProc: TProc);
public
constructor Create; virtual;
procedure Run;
property ChecksPassed: Integer read FChecksPassed;
property ChecksFailed: Integer read FChecksFailed;
end;
TUnitTestClass = class of TUnitTest;
{$M-}
var
USFormatSettings: TFormatSettings;
implementation
uses
System.Math,
System.Rtti,
System.TypInfo;
{ TTestFailedMessage }
constructor TTestFailedMessage.Create(const ATestClassName, ATestMethodName,
AMessage: String);
begin
inherited Create;
FTestClassName := ATestClassName;
FTestMethodName := ATestMethodName;
FMessage := AMessage;
end;
{ TUnitTest }
procedure TUnitTest.CheckEquals(const AExpected, AActual, AMsg: String);
begin
Inc(FChecksTotal);
if (AExpected <> AActual) then
Fail('%s: Expected: %s, Actual: %s', [AMsg, AExpected, AActual]);
end;
procedure TUnitTest.CheckEquals(const AExpected, AActual, AEpsilon: Double;
const AMsg: String);
var
ExpectedIsExtreme, ActualIsExtreme, OK: Boolean;
begin
Inc(FChecksTotal);
{ FastMath treats all extreme values (Infinite and Nan) the same. }
ExpectedIsExtreme := IsInfinite(AExpected) or IsNan(AExpected);
ActualIsExtreme := IsInfinite(AActual) or IsNan(AActual);
if (ExpectedIsExtreme) then
OK := ActualIsExtreme
else if (ActualIsExtreme) then
OK := ExpectedIsExtreme
else if (AEpsilon = 0) then
OK := SameValue(AExpected, AActual)
else
OK := (Abs(AExpected - AActual) <= AEpsilon);
if (not OK) then
Fail('%s: Expected: %.6f, Actual: %.6f', [AMsg, AExpected, AActual]);
end;
procedure TUnitTest.CheckFalse(const ACondition: Boolean);
begin
Inc(FChecksTotal);
if (ACondition) then
Fail('Expected False but was True');
end;
procedure TUnitTest.CheckTrue(const ACondition: Boolean);
begin
Inc(FChecksTotal);
if (not ACondition) then
Fail('Expected True but was False');
end;
constructor TUnitTest.Create;
begin
inherited;
end;
procedure TUnitTest.Fail(const AMsg: String; const AArgs: array of const);
begin
Fail(Format(AMsg, AArgs));
end;
procedure TUnitTest.Fail(const AMsg: String);
begin
Inc(FChecksFailed);
TMessageManager.DefaultManager.SendMessage(Self,
TTestFailedMessage.Create(ClassName, FCurrentTestMethodName, AMsg));
end;
procedure TUnitTest.Run;
var
Context: TRttiContext;
TestType: TRttiType;
Method: TRttiMethod;
begin
FChecksPassed := 0;
FChecksFailed := 0;
FChecksTotal := 0;
FCurrentTestMethodName := '';
Context := TRttiContext.Create;
TestType := Context.GetType(ClassType);
if (TestType = nil) then
Fail('Internal test error: cannot get test class type');
for Method in TestType.GetMethods do
begin
if (Method.Visibility = TMemberVisibility.mvPublished)
and (Method.ReturnType = nil) and (Method.GetParameters = nil)
and (not Method.IsConstructor) and (not Method.IsDestructor)
and (not Method.IsClassMethod) and (not Method.IsStatic) then
begin
FCurrentTestMethodName := Method.Name;
try
Method.Invoke(Self, []);
except
on E: Exception do
Fail('Unexpected exception of type "%s"', [E.ClassName]);
end;
end;
end;
FChecksPassed := FChecksTotal - FChecksFailed;
end;
procedure TUnitTest.ShouldRaise(const AExceptionClass: ExceptClass;
const AProc: TProc);
begin
try
AProc();
except
on E: Exception do
begin
if (E.ClassType = AExceptionClass) then
Exit
else
Fail('Expected exception of type "%s", but got exception of type "%s"',
[AExceptionClass.ClassName, E.ClassName]);
end;
end;
Fail('Expected exception of type "%s"', [AExceptionClass.ClassName]);
end;
initialization
USFormatSettings := TFormatSettings.Create('en-US');
USFormatSettings.ThousandSeparator := ',';
USFormatSettings.DecimalSeparator := '.';
end.
|
unit TextEditor.Caret.MultiEdit;
interface
uses
System.Classes, TextEditor.Caret.MultiEdit.Colors, TextEditor.Types;
const
TEXTEDITOR_MULTIEDIT_DEFAULT_OPTIONS = [meoShowActiveLine, meoShowGhost];
type
TTextEditorCaretMultiEdit = class(TPersistent)
strict private
FActive: Boolean;
FColors: TTextEditorCaretMultiEditColors;
FOnChange: TNotifyEvent;
FOptions: TTextEditorCaretMultiEditOptions;
FStyle: TTextEditorCaretStyle;
procedure DoChange;
procedure SetActive(const AValue: Boolean);
procedure SetColors(const AValue: TTextEditorCaretMultiEditColors);
procedure SetOptions(const AValue: TTextEditorCaretMultiEditOptions);
procedure SetStyle(const AValue: TTextEditorCaretStyle);
public
constructor Create;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
procedure SetOption(const AOption: TTextEditorCaretMultiEditOption; const AEnabled: Boolean);
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Active: Boolean read FActive write SetActive default True;
property Colors: TTextEditorCaretMultiEditColors read FColors write SetColors;
property Options: TTextEditorCaretMultiEditOptions read FOptions write SetOptions default TEXTEDITOR_MULTIEDIT_DEFAULT_OPTIONS;
property Style: TTextEditorCaretStyle read FStyle write SetStyle default csThinVerticalLine;
end;
implementation
constructor TTextEditorCaretMultiEdit.Create;
begin
inherited;
FColors := TTextEditorCaretMultiEditColors.Create;
FActive := True;
FStyle := csThinVerticalLine;
FOptions := TEXTEDITOR_MULTIEDIT_DEFAULT_OPTIONS;
end;
destructor TTextEditorCaretMultiEdit.Destroy;
begin
FColors.Free;
inherited;
end;
procedure TTextEditorCaretMultiEdit.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorCaretMultiEdit) then
with ASource as TTextEditorCaretMultiEdit do
begin
Self.FColors.Assign(FColors);
Self.FActive := FActive;
Self.FOptions := FOptions;
Self.FStyle := FStyle;
Self.DoChange;
end
else
inherited Assign(ASource);
end;
procedure TTextEditorCaretMultiEdit.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TTextEditorCaretMultiEdit.SetActive(const AValue: Boolean);
begin
if FActive <> AValue then
begin
FActive := AValue;
DoChange;
end;
end;
procedure TTextEditorCaretMultiEdit.SetStyle(const AValue: TTextEditorCaretStyle);
begin
if FStyle <> AValue then
begin
FStyle := AValue;
DoChange;
end;
end;
procedure TTextEditorCaretMultiEdit.SetColors(const AValue: TTextEditorCaretMultiEditColors);
begin
FColors.Assign(AValue);
end;
procedure TTextEditorCaretMultiEdit.SetOptions(const AValue: TTextEditorCaretMultiEditOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
DoChange;
end;
end;
procedure TTextEditorCaretMultiEdit.SetOption(const AOption: TTextEditorCaretMultiEditOption; const AEnabled: Boolean);
begin
if AEnabled then
Include(FOptions, AOption)
else
Exclude(FOptions, AOption);
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela para Mesclar Lançamentos
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 UFinMesclaPagamento;
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, 'Mescla Pagamento')]
TFFinMesclaPagamento = class(TFTelaCadastro)
BevelEdits: TBevel;
PanelMestre: TPanel;
EditIdFornecedor: TLabeledCalcEdit;
EditFornecedor: TLabeledEdit;
EditIdDocumentoOrigem: TLabeledCalcEdit;
EditDocumentoOrigem: TLabeledEdit;
ComboBoxPagamentoCompartilhado: TLabeledComboBox;
EditImagemDocumento: TLabeledEdit;
EditPrimeiroVencimento: TLabeledDateEdit;
EditQuantidadeParcelas: TLabeledCalcEdit;
EditValorAPagar: TLabeledCalcEdit;
EditValorTotal: TLabeledCalcEdit;
EditDataLancamento: TLabeledDateEdit;
EditNumeroDocumento: TLabeledEdit;
EditIntervalorEntreParcelas: TLabeledCalcEdit;
PageControlItensLancamento: TPageControl;
tsLancamentos: TTabSheet;
PanelItensLancamento: TPanel;
GridItens: TJvDBUltimGrid;
PanelTotais: TPanel;
DSLancamentoSelecionado: TDataSource;
CDSLancamentoSelecionado: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure CalcularTotais;
procedure GridCellClick(Column: TColumn);
procedure GridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure EditIdFornecedorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditIdDocumentoOrigemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
procedure ControlaBotoes; override;
procedure ControlaPopupMenu; override;
// Controles CRUD
function DoEditar: Boolean; override;
end;
var
FFinMesclaPagamento: TFFinMesclaPagamento;
ChequeEmitido: TFinChequeEmitidoVO;
SomaCheque: Extended;
AdmParametroVO: TAdmParametroVO;
implementation
uses
FinLancamentoPagarVO, FinLancamentoPagarController, FinParcelaPagarVO,
FinParcelaPagarController, FinTipoPagamentoVO, FinTipoPagamentoController,
ContaCaixaVO, ContaCaixaController, UTela, USelecionaCheque, UDataModule,
AdmParametroController, FinDocumentoOrigemVO, FinDocumentoOrigemController,
ViewPessoaFornecedorVO, ViewPessoaFornecedorController;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFFinMesclaPagamento.FormCreate(Sender: TObject);
var
Filtro: String;
begin
ClasseObjetoGridVO := TFinLancamentoPagarVO;
ObjetoController := TFinLancamentoPagarController.Create;
inherited;
// Configura a Grid dos itens
ConfiguraCDSFromVO(CDSLancamentoSelecionado, TViewFinLancamentoPagarVO);
ConfiguraGridFromVO(GridItens, TViewFinLancamentoPagarVO);
end;
procedure TFFinMesclaPagamento.ControlaBotoes;
begin
inherited;
BotaoInserir.Visible := False;
BotaoExcluir.Visible := False;
BotaoAlterar.Caption := 'Mesclar [F3]';
end;
procedure TFFinMesclaPagamento.ControlaPopupMenu;
begin
inherited;
MenuInserir.Visible := False;
MenuExcluir.Visible := False;
MenuAlterar.Caption := 'Mesclar [F3]';
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFFinMesclaPagamento.DoEditar: Boolean;
var
Contador: Integer;
Filtro, FiltroIN: String;
begin
Contador := 0;
if not CDSGrid.IsEmpty then
begin
CDSGrid.DisableControls;
CDSGrid.First;
while not CDSGrid.Eof do
begin
if CDSGrid.FieldByName('MesclarPagamento').AsString = 'S' then
begin
Inc(Contador);
if Contador = 1 then
FiltroIN := '(' + CDSGrid.FieldByName('ID').AsString
else
FiltroIN := FiltroIN + ',' + CDSGrid.FieldByName('ID').AsString;
end;
CDSGrid.Next;
end;
CDSGrid.First;
CDSGrid.EnableControls;
if Contador <= 1 then
begin
Application.MessageBox('É preciso selecionar mais do que UM lançamento para realizar a mesclagem.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
FiltroIN := FiltroIN + ')';
TViewFinLancamentoPagarController.SetDataSet(CDSLancamentoSelecionado);
Filtro := 'ID_LANCAMENTO_PAGAR in ' + FiltroIN;
TController.ExecutarMetodo('ViewFinLancamentoPagarController.TViewFinLancamentoPagarController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista');
CalcularTotais;
Result := inherited DoEditar;
if Result then
begin
EditIdFornecedor.SetFocus;
end;
end;
end;
{$ENDREGION}
{$REGION 'Campos Transientes'}
procedure TFFinMesclaPagamento.EditIdFornecedorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdFornecedor.Value <> 0 then
Filtro := 'ID = ' + EditIdFornecedor.Text
else
Filtro := 'ID=0';
try
EditIdFornecedor.Clear;
EditFornecedor.Clear;
if not PopulaCamposTransientes(Filtro, TViewPessoaFornecedorVO, TViewPessoaFornecedorController) then
PopulaCamposTransientesLookup(TViewPessoaFornecedorVO, TViewPessoaFornecedorController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdFornecedor.Text := CDSTransiente.FieldByName('ID').AsString;
EditFornecedor.Text := CDSTransiente.FieldByName('NOME').AsString;
end
else
begin
Exit;
EditIdDocumentoOrigem.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
procedure TFFinMesclaPagamento.EditIdDocumentoOrigemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdDocumentoOrigem.Value <> 0 then
Filtro := 'ID = ' + EditIdDocumentoOrigem.Text
else
Filtro := 'ID=0';
try
EditIdDocumentoOrigem.Clear;
EditDocumentoOrigem.Clear;
if not PopulaCamposTransientes(Filtro, TFinDocumentoOrigemVO, TFinDocumentoOrigemController) then
PopulaCamposTransientesLookup(TFinDocumentoOrigemVO, TFinDocumentoOrigemController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdDocumentoOrigem.Text := CDSTransiente.FieldByName('ID').AsString;
EditDocumentoOrigem.Text := CDSTransiente.FieldByName('SIGLA_DOCUMENTO').AsString;
end
else
begin
Exit;
EditNumeroDocumento.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFFinMesclaPagamento.GridCellClick(Column: TColumn);
begin
if Column.Index = 0 then
begin
if CDSGrid.FieldByName('MESCLADO_PARA').AsInteger > 0 then
begin
Application.MessageBox('Procedimento não permitido. Lançamento já mesclado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
CDSGrid.Edit;
if CDSGrid.FieldByName('MesclarPagamento').AsString = '' then
CDSGrid.FieldByName('MesclarPagamento').AsString := 'S'
else
CDSGrid.FieldByName('MesclarPagamento').AsString := '';
CDSGrid.Post;
end;
end;
procedure TFFinMesclaPagamento.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;
{$ENDREGION}
{$REGION 'Actions'}
procedure TFFinMesclaPagamento.CalcularTotais;
var
Juro, Multa, Desconto, Total, Saldo: Extended;
begin
/// EXERCICIO: VERIFIQUE SE HÁ A NECESSIDADE DE EXIBIR OS TOTAIS. CORRIJA O QUE FOR NECESSÁRIO NO PROCEDIMENTO E/OU NA VIEW.
/// EXERCICIO: LEVE EM CONTA NO CALCULO AS PARCELAS JA QUITADAS.
Juro := 0;
Multa := 0;
Desconto := 0;
Total := 0;
Saldo := 0;
//
CDSLancamentoSelecionado.DisableControls;
CDSLancamentoSelecionado.First;
while not CDSLancamentoSelecionado.Eof do
begin
Juro := Juro + CDSLancamentoSelecionado.FieldByName('VALOR_JURO').AsExtended;
Multa := Multa + CDSLancamentoSelecionado.FieldByName('VALOR_MULTA').AsExtended;
Desconto := Desconto + CDSLancamentoSelecionado.FieldByName('VALOR_DESCONTO').AsExtended;
Total := Total + CDSLancamentoSelecionado.FieldByName('VALOR_PARCELA').AsExtended;
CDSLancamentoSelecionado.Next;
end;
CDSLancamentoSelecionado.First;
CDSLancamentoSelecionado.EnableControls;
//
PanelTotais.Caption := '| Juros: ' + FloatToStrF(Juro, ffCurrency, 15, 2) +
' | Multa: ' + FloatToStrF(Multa, ffCurrency, 15, 2) +
' | Desconto: ' + FloatToStrF(Desconto, ffCurrency, 15, 2) +
' | Total Parcelas: ' + FloatToStrF(Total, ffCurrency, 15, 2) +
' | Saldo: ' + FloatToStrF(Total - EditValorAPagar.Value, ffCurrency, 15, 2) + ' |';
end;
{$ENDREGION}
/// EXERCICIO: IMPLEMENTE A PERSISTENCIA DA NOVA PARCELA MESCLADA
/// EXERCICIO: ARMAZENE NO CAMPO MESCLADO_PARA O ID DO NOVO LANÇAMENTO GERADO PARA VINCULAR O HISTORICO DOS LANÇAMENTOS
/// EXERCICIO: DESENHE A JANELA DA MELHOR FORMA POSSÍVEL PARA O USUÁRIO
end.
|
unit uVendasController;
interface
uses
uVendasModel, uVendasDao,System.Generics.Collections, System.SysUtils;
type
TVendasController = class
private
FVendasList: TVendaList;
FVendas : TvendasModel;
FVendasDao : TvendasDao;
procedure SetVendas(const Value: TvendasModel);
procedure SetVendasList(const Value: TVendaList);
procedure SetVendasDao(const Value: TvendasDao);
public
constructor Create;
destructor Destroy; override;
property VendasDao: TvendasDao read FVendasDao write SetVendasDao;
property Vendas: TvendasModel read FVendas write SetVendas;
property VendasList: TVendaList read FVendasList write SetVendasList;
function VerificaPedido: Boolean;
function SomaTotalVendas:Currency;
function Inserir(out sErro: String):Boolean;
function FinalizaVendaCtr(out sErro: String):Boolean;
procedure CarregaPedido(Pedido: Integer);
end;
implementation
{ TVendasController }
procedure TVendasController.CarregaPedido(Pedido: Integer);
begin
FVendasDao.CarregaPedido(FVendasList, Pedido);
end;
constructor TVendasController.Create;
begin
FVendasDao := TvendasDao.Create;
FVendas := TvendasModel.Create;
FVendasList := TVendaList.Create;
end;
destructor TVendasController.Destroy;
begin
FreeAndNil(FVendasList);
FreeAndNil(FVendas);
FreeAndNil(FVendasDao);
inherited;
end;
function TVendasController.FinalizaVendaCtr(out sErro: String): Boolean;
begin
Result:= DaoVendas.FinalizaPedido(FVendasList, sErro);
end;
function TVendasController.Inserir(out sErro: String): Boolean;
begin
Result:= DaoVendas.Inserir(FVendas, sErro);
end;
procedure TVendasController.SetVendas(const Value: TvendasModel);
begin
FVendas := Value;
end;
procedure TVendasController.SetVendasDao(const Value: TvendasDao);
begin
FVendasDao := Value;
end;
procedure TVendasController.SetVendasList(const Value: TVendaList);
begin
FVendasList := Value;
end;
function TVendasController.SomaTotalVendas: Currency;
var i: Integer;
var O: TObject;
begin
Result:=0;
for i := 0 to FVendasList.Count - 1 do
begin
o := FVendasList.Items[i];
if Assigned(O) then
begin
Result:=Result + FVendasList.Items[i].car_valorTotal
end;
end;
end;
function TVendasController.VerificaPedido: Boolean;
begin
Result := FVendasDao.VerificaPedido;
end;
end.
|
unit uParserPL0;
interface
uses
uParser;
type
{TParserPL0}
TParserPL0 = class(TBaseParser)
private
procedure Factor;
procedure Term;
procedure Expression;
procedure Condition;
procedure Statement;
procedure Block;
protected
procedure RegisterKeywordTokens; override;
procedure ParseInput; override;
public
end;
implementation
var
Token_odd : Integer;
Token_call : Integer;
procedure TParserPL0.Factor;
begin
if Accept(Token_ident) then
begin
end
else
if Accept(Token_number) then
begin
end
else
if Accept(Token_lparen) then
begin
Expression;
Expect(Token_rparen);
end
else
begin
Error('factor: syntax error');
GetToken;
end;
end;
procedure TParserPL0.Term;
begin
Factor;
while Token.TokenType in [Token_times,Token_slash] do
begin
GetToken;
Factor;
end;
end;
procedure TParserPL0.Expression;
begin
if Token.TokenType in [Token_plus,Token_minus] then
GetToken;
Term;
while Token.TokenType in [Token_plus,Token_minus] do
begin
GetToken;
Term;
end;
end;
procedure TParserPL0.Condition;
begin
if Accept(Token_odd) then
begin
Expression;
end
else
begin
Expression;
if Token.TokenType in [Token_eql,Token_neq,Token_lss,Token_leq,Token_gtr,Token_geq] then
begin
GetToken;
Expression;
end
else
begin
Error('Condition: invalid operator');
GetToken;
end;
end;
end;
procedure TParserPL0.Statement;
begin
if Accept(Token_ident) then
begin
Expect(Token_becomes);
Expression;
end
else
if Accept(Token_call) then
begin
Expect(Token_ident);
end
else
if Accept(Token_begin) then
begin
repeat
Statement;
until not Accept(Token_semicolon);
Expect(Token_end);
end
else
if Accept(Token_if) then
begin
Condition;
Expect(Token_then);
Statement;
end
else
if Accept(Token_while) then
begin
Condition;
Expect(Token_do);
statement;
end;
end;
procedure TParserPL0.Block;
begin
if Accept(Token_const) then
begin
repeat
Expect(Token_ident);
Expect(Token_eql);
Expect(Token_number);
until not Accept(Token_comma);
Expect(Token_semicolon);
end;
if Accept(Token_var) then
begin
repeat
Expect(Token_ident);
until not Accept(Token_comma);
Expect(Token_semicolon);
end;
while Accept(Token_proc) do
begin
Expect(Token_ident);
Expect(Token_semicolon);
Block;
Expect(Token_semicolon);
end;
Statement;
end;
procedure TParserPL0.ParseInput;
begin
Block;
Expect(Token_period);
end;
procedure TParserPL0.RegisterKeywordTokens;
begin
inherited RegisterKeywordTokens;
Token_odd := RegisterKeywordToken('odd');
Token_call := RegisterKeywordToken('call');
end;
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.Scene3D.Renderer.OrderIndependentTransparencyBuffer;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application;
type { TpvScene3DRendererOrderIndependentTransparencyBuffer }
TpvScene3DRendererOrderIndependentTransparencyBuffer=class
private
fVulkanBuffer:TpvVulkanBuffer;
fVulkanBufferView:TpvVulkanBufferView;
public
constructor Create(const aSize:TpvInt32;const aFormat:TVkFormat;const aBufferUsage:TVkBufferUsageFlags=TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT));
destructor Destroy; override;
published
property VulkanBuffer:TpvVulkanBuffer read fVulkanBuffer;
property VulkanBufferView:TpvVulkanBufferView read fVulkanBufferView;
end;
implementation
{ TpvScene3DRendererOrderIndependentTransparencyBuffer }
constructor TpvScene3DRendererOrderIndependentTransparencyBuffer.Create(const aSize:TpvInt32;const aFormat:TVkFormat;const aBufferUsage:TVkBufferUsageFlags);
begin
inherited Create;
fVulkanBuffer:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
aSize,
aBufferUsage,
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
0,
0,
0,
0,
0,
[]);
if (aBufferUsage and (TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) or
TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)))<>0 then begin
fVulkanBufferView:=TpvVulkanBufferView.Create(pvApplication.VulkanDevice,
fVulkanBuffer,aFormat,
0,
TVkDeviceSize(VK_WHOLE_SIZE));
end else begin
fVulkanBufferView:=nil;
end;
end;
destructor TpvScene3DRendererOrderIndependentTransparencyBuffer.Destroy;
begin
FreeAndNil(fVulkanBufferView);
FreeAndNil(fVulkanBuffer);
inherited Destroy;
end;
end.
|
unit thDataHora;
interface
uses
Windows, Messages, SysUtils, Classes, data_datahora, principal, ActiveX;
type
TOnGetDataHora = procedure(var datahora: TDateTime) of object;
ThreadDataHora = class(TThread)
private
dmoDataHora: TdmoDataHora;
outDataHora: TDateTime;
FOnGetDataHora: TOnGetDataHora;
procedure DisplayResults;
protected
procedure Execute; override;
property OnGetDataHora: TOnGetDataHora read FOnGetDataHora
write FOnGetDataHora;
public
constructor Create(proc: TOnGetDataHora);
destructor Destroy; override;
end;
implementation
constructor ThreadDataHora.Create(proc: TOnGetDataHora);
begin
inherited Create(true);
FreeOnTerminate := true;
Priority := tpNormal;
OnGetDataHora := proc;
Resume;
end;
procedure ThreadDataHora.Execute;
begin
CoInitialize(nil);
dmoDataHora := TdmoDataHora.Create(nil);
with dmoDataHora.cdsDataHora do
begin
if active then close;
open;
outDataHora := fieldByName('DATAHORA').AsDateTime;
close;
end;
CS.Enter;
Synchronize(DisplayResults);
CS.Leave;
CoUnInitialize;
end;
procedure ThreadDataHora.DisplayResults;
begin
if Assigned(OnGetDataHora) then
OnGetDataHora(outDataHora);
end;
destructor ThreadDataHora.Destroy;
begin
dmoDataHora.Free;
inherited destroy;
end;
end.
|
unit Right;
interface
uses
DBTables,Classes,tSqlCls;
type
TRight=class(TObject)
private
DisplayLabel : String;
BitMask : LongInt;
Parent : TRight;
List : TList;
function ReadRight(Index:integer):TRight;
function ReadRightsCount:integer;
procedure SubTree(q:TQuery;Parent:LongInt);
public
ID : LongInt;
GroupName : String;
Level : Word;
Checked : Boolean;
Constructor Create(aParent:TRight);
Destructor Destroy; override;
Procedure BuildTree(st:longint);
Property Childs[index:INTEGER]:TRight read ReadRight;
Property ChildsCount:integer read ReadRightsCount;
Function RightByID(aID:LongInt):TRight;
Function RightByBitMask(aBitMask:LongInt):TRight;
Function isChecked(aBitMask:LongInt):Boolean;
Function ToggleCheck:Boolean;
Procedure SetCheck(aChecked:Boolean);
Function GetDisplayLabel:String;
Procedure Clear;
end;
implementation
uses DB;
Function TRight.GetDisplayLabel:String;
begin
GetDisplayLabel:=DisplayLabel
end;
function TRight.ReadRight(Index:integer):TRight;
begin
ReadRight:=TRight(List.Items[index])
end;
function TRight.ReadRightsCount:integer;
begin
ReadRightsCount:=List.Count
end;
destructor TRight.Destroy;
var
i:Integer;
begin
for i:=0 to ChildsCount-1 do
Childs[i].Free;
List.Free;
inherited Destroy
end;
constructor TRight.Create(aParent:TRight);
begin
inherited Create;
List:=TList.Create;
Parent:=aParent;
Level:=0;
end;
procedure TRight.BuildTree(st:longint);
var
q: TQuery;
begin
q:=sql.Select('FunRight','','','ID');
subTree(q,st);
q.Free;
end;
procedure TRight.SubTree(q:TQuery;Parent:LongInt);
var r:TRight;
i:integer;
fldParentID,fldID,fldDisplayLabel,fldGroupName,fldBitMask:TField;
begin
fldParentID:=q.FieldByName('ParentID');
fldID:=q.FieldByName('ID');
fldDisplayLabel:=q.FieldByName('DisplayLabel');
fldGroupName:=q.FieldByName('GroupName');
fldBitMask:=q.FieldByName('BitMask');
q.First;
While Not q.Eof do
begin
if (fldParentID.AsInteger=Parent) or (fldParentID.IsNull) and (Parent=0) then
begin
r:=TRight.Create(Self);
List.Add(r);
r.Level:=Level+1;
r.ID:=fldID.AsInteger;
r.DisplayLabel:=fldDisplayLabel.AsString;
r.GroupName:=fldGroupName.AsString;
r.BitMask:=fldBitMask.AsInteger;
end;
q.Next
end;
for i:=0 to ChildsCount-1 do
Childs[i].SubTree(q,Childs[i].ID);
end;
Function TRight.RightByID(aID:LongInt):TRight;
var
i : Integer;
p : Pointer;
begin
if ID=aID then
p:=self
else
begin
p:=Nil;
for i:=0 to ChildsCount-1 do
begin
p:=Childs[i].RightByID(aID);
if p<>nil then
break
end
end;
RightByID:=p
end;
Function TRight.RightByBitMask(aBitMask:LongInt):TRight;
var
i : Integer;
p : Pointer;
begin
if BitMask=aBitMask then
p:=self
else
begin
p:=Nil;
for i:=0 to ChildsCount-1 do
begin
p:=Childs[i].RightByBitMask(aBitMask);
if p<>nil then
break
end
end;
RightByBitMask:=p
end;
Function TRight.isChecked(aBitMask:LongInt):Boolean;
var
p : TRight;
begin
p:=RightByBitMask(aBitMask);
if p=Nil then
isChecked:=False
else
isChecked:=p.Checked
end;
Procedure TRight.SetCheck(aChecked:Boolean);
var
i : Integer;
begin
Checked:=aChecked;
for i:=0 to ChildsCount-1 do
Childs[i].SetCheck(aChecked)
end;
Procedure TRight.Clear;
begin
SetCheck(False)
end;
Function TRight.ToggleCheck:Boolean;
var { Toggle children to}
b : Boolean;
begin
b:=not IsChecked(BitMask);
SetCheck(b);
ToggleCheck:=b
end;
end.
|
unit UOptParams;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Spin, tc;
type
TFOptParams = class(TForm)
Button1: TButton;
Button2: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
GroupBox1: TGroupBox;
CheckBox1: TCheckBox;
Label1: TLabel;
TrackBar1: TTrackBar;
SpinEdit1: TSpinEdit;
procedure TrackBar1Change(Sender: TObject);
procedure SpinEdit1Change(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
M : TModel;
procedure SetShowProgress(value : boolean);
function GetShowProgress : boolean;
property ShowProgress : boolean read GetShowProgress write SetShowProgress;
procedure SetPointCount(value : integer);
function GetPointCount : integer;
property PointCount : integer read GetPointCount write SetPointCount;
procedure Load;
procedure Save;
end;
var
FOptParams: TFOptParams;
implementation
{$R *.DFM}
procedure TFOptParams.TrackBar1Change(Sender: TObject);
begin
SpinEdit1.Value := TrackBar1.Position ;
end;
procedure TFOptParams.SpinEdit1Change(Sender: TObject);
begin
TrackBar1.Position := SpinEdit1.Value;
end;
function TFOptParams.GetPointCount: integer;
begin
result := TrackBar1.Position;
end;
function TFOptParams.GetShowProgress: boolean;
begin
result := CheckBox1.Checked;
end;
procedure TFOptParams.SetPointCount(value: integer);
begin
TrackBar1.Position := value;
end;
procedure TFOptParams.SetShowProgress(value: boolean);
begin
CheckBox1.Checked := value;
end;
procedure TFOptParams.Load;
begin
ShowProgress := m.FShowProgress;
PointCount := m.point_count;
end;
procedure TFOptParams.Save;
begin
m.point_count := PointCount;
m.FShowProgress := ShowProgress;
end;
procedure TFOptParams.Button2Click(Sender: TObject);
begin
close;
end;
procedure TFOptParams.Button1Click(Sender: TObject);
begin
Save;
close;
end;
procedure TFOptParams.FormActivate(Sender: TObject);
begin
Load;
end;
end.
|
{
ID: ndchiph1
PROG: nuggets
LANG: PASCAL
}
uses math;
const
inputfile = 'nuggets.in';
outputfile = 'nuggets.out';
LM = 700000;
maxN = 11;
//type
var
fi,fo: text;
n: longint;
a: array[1..maxN] of longint;
f: array[0..LM] of boolean;
procedure openfile;
begin
assign(fi,inputfile); reset(fi);
assign(fo,outputfile); rewrite(fo);
end;
procedure closefile;
begin
close(fi);
close(fo);
end;
function gcd(x,y: longint): longint;
var
t: longint;
begin
while (y > 0) do
begin
t:= x mod y;
x:= y;
y:= t;
end;
exit(x);
end;
function lcm(x,y: longint): longint;
begin
exit(x * y div gcd(x,y));
end;
procedure output(res: longint);
begin
writeln(fo,res);
closefile;
halt;
end;
procedure input;
var
i,j,t: longint;
begin
readln(fi,n);
for i:= 1 to n do
readln(fi,a[i]);
//sort;
for i:= 1 to n-1 do
for j:= i+1 to n do
if (a[i] > a[j]) then
begin
t:= a[i];
a[i]:= a[j];
a[j]:= t;
end;
//check;
if (n = 1) or (a[i] = 1) then output(0);
t:= a[1];
for i:= 2 to n do
t:= gcd(t,a[i]);
if (t <> 1) then output(0);
end;
procedure process;
var
i,j,num,maxval: longint;
begin
maxval:= lcm(a[n],a[n-1]);
f[0]:= true;
for i:= 1 to n do
begin
for j:= a[i] to maxval do
if f[j-a[i]] then f[j]:= true;
end;
for i:= maxval downto 1 do
if not f[i] then output(i);
end;
BEGIN
openfile;
input;
process;
closefile;
END.
|
unit CPL.View.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Sensors,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Layouts,
FMX.Memo.Types,
{$IF Defined(ANDROID)}
Androidapi.JNI.GraphicsContentViewText,
DW.MultiReceiver.Android,
{$ENDIF}
DW.Location;
type
TMessageReceivedEvent = procedure(Sender: TObject; const Msg: string) of object;
{$IF Defined(ANDROID)}
TLocalReceiver = class(TMultiReceiver)
private
FOnMessageReceived: TMessageReceivedEvent;
procedure DoMessageReceived(const AMsg: string);
protected
procedure Receive(context: JContext; intent: JIntent); override;
procedure ConfigureActions; override;
public
property OnMessageReceived: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
end;
{$ENDIF}
TMainView = class(TForm)
Memo: TMemo;
ClearButton: TButton;
ContentLayout: TLayout;
procedure ClearButtonClick(Sender: TObject);
private
FLocation: TLocation;
{$IF Defined(ANDROID)}
FReceiver: TLocalReceiver;
{$ENDIF}
procedure LocationChangedHandler(Sender: TObject; const ALocation: TLocationCoord2D);
procedure ReceiverMessageReceivedHandler(Sender: TObject; const AMsg: string);
procedure RequestLocationPermissions;
procedure StartLocation;
protected
procedure DoShow; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
MainView: TMainView;
implementation
{$R *.fmx}
uses
System.Permissions,
{$IF Defined(CLOUDLOGGING)}
Grijjy.CloudLogging,
{$ENDIF}
DW.OSLog, DW.OSDevice,
{$IF Defined(ANDROID)}
Androidapi.Helpers,
DW.ServiceCommander.Android,
{$ENDIF}
DW.Sensors, DW.Consts.Android, DW.UIHelper,
CPL.Consts;
type
TPermissionStatuses = TArray<TPermissionStatus>;
TPermissionStatusesHelper = record helper for TPermissionStatuses
public
function AreAllGranted: Boolean;
end;
{ TPermissionStatusesHelper }
function TPermissionStatusesHelper.AreAllGranted: Boolean;
var
LStatus: TPermissionStatus;
begin
for LStatus in Self do
begin
if LStatus <> TPermissionStatus.Granted then
Exit(False);
end;
Result := True;
end;
{$IF Defined(ANDROID)}
{ TLocalReceiver }
procedure TLocalReceiver.ConfigureActions;
begin
IntentFilter.addAction(StringToJString(cServiceMessageAction));
end;
procedure TLocalReceiver.DoMessageReceived(const AMsg: string);
begin
if Assigned(FOnMessageReceived) then
FOnMessageReceived(Self, AMsg);
end;
procedure TLocalReceiver.Receive(context: JContext; intent: JIntent);
begin
if intent.getAction.equals(StringToJString(cServiceMessageAction)) then
DoMessageReceived(JStringToString(intent.getStringExtra(StringToJString(cServiceBroadcastParamMessage))));
end;
{$ENDIF}
{ TMainView }
constructor TMainView.Create(AOwner: TComponent);
begin
inherited;
{$IF Defined(CLOUDLOGGING)}
GrijjyLog.SetLogLevel(TgoLogLevel.Info);
GrijjyLog.Connect(cCloudLoggingHost, cCloudLoggingName);
{$ENDIF}
{$IF Defined(ANDROID)}
FReceiver := TLocalReceiver.Create(True);
FReceiver.OnMessageReceived := ReceiverMessageReceivedHandler;
{$ENDIF}
FLocation := TLocation.Create;
FLocation.Usage := TLocationUsage.Always;
FLocation.Activity := TLocationActivity.Navigation;
// FLocation.UsesService := True;
FLocation.OnLocationChanged := LocationChangedHandler;
end;
destructor TMainView.Destroy;
begin
{$IF Defined(ANDROID)}
FReceiver.Free;
{$ENDIF}
FLocation.Free;
inherited;
end;
procedure TMainView.DoShow;
begin
inherited;
{$IF Defined(ANDROID)}
RequestLocationPermissions;
{$ELSE}
StartLocation;
{$ENDIF}
end;
procedure TMainView.Resize;
begin
inherited;
ContentLayout.Padding.Rect := TUIHelper.GetOffsetRect;
end;
procedure TMainView.ReceiverMessageReceivedHandler(Sender: TObject; const AMsg: string);
begin
Memo.Lines.Add('Message from service: ' + AMsg);
end;
procedure TMainView.RequestLocationPermissions;
var
LPermissions: TArray<string>;
begin
LPermissions := [cPermissionAccessCoarseLocation, cPermissionAccessFineLocation];
if TOSVersion.Check(10) then
LPermissions := LPermissions + [cPermissionAccessBackgroundLocation];
PermissionsService.RequestPermissions(LPermissions,
procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>)
begin
if AGrantResults.AreAllGranted then
StartLocation;
end
);
end;
procedure TMainView.StartLocation;
begin
{$IF Defined(ANDROID)}
TServiceCommander.StartService(cServiceName);
{$ENDIF}
FLocation.IsActive := True;
end;
procedure TMainView.LocationChangedHandler(Sender: TObject; const ALocation: TLocationCoord2D);
var
LTimestamp: string;
begin
LTimestamp := FormatDateTime('yyyy/mm/dd hh:nn:ss.zzz', Now);
Memo.Lines.Add(Format('%s - Location: %2.6f, %2.6f', [LTimestamp, ALocation.Latitude, ALocation.Longitude]));
end;
procedure TMainView.ClearButtonClick(Sender: TObject);
begin
Memo.Lines.Clear;
end;
end.
|
unit Master;
interface
uses BaseObjects, ComCtrls;
type
TMasterCreate = class (TIDObject)
private
FStepCount: integer;
FSteps: TPageControl;
FNewObject: TIDObject;
public
// количество шагов
property StepCount: integer read FStepCount write FStepCount;
property Steps: TPageControl read FSteps write FSteps;
property NewObject: TIDObject read FNewObject write FNewObject;
function SetOptions (N: integer): integer;
constructor Create (ACollection: TIDObjects); override;
destructor Destroy; override;
end;
TMasterCreates = class(TIdObjects)
private
function GetItems(Index: Integer): TMasterCreate;
public
property Items[Index: Integer]: TMasterCreate read GetItems;
constructor Create; override;
end;
implementation
{ TMasterCreate }
constructor TMasterCreate.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Мастер добавления новых обектов';
FNewObject := TIDObject.Create(nil);
end;
destructor TMasterCreate.Destroy;
begin
inherited;
end;
function TMasterCreate.SetOptions(N: integer): integer;
var i: integer;
begin
for i := 0 to Steps.PageCount - 1 do
Steps.Pages[i].TabVisible := false;
Steps.Pages[N - 1].TabVisible := true;
Result := N - 1;
end;
{ TMasterCreates }
constructor TMasterCreates.Create;
begin
inherited;
FObjectClass := TMasterCreate;
end;
function TMasterCreates.GetItems(Index: Integer): TMasterCreate;
begin
Result := INHERITED Items[Index] as TMasterCreate;
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)
@abstract(Website : http://www.ormbr.com.br)
@abstract(Telagram : https://t.me/ormbr)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit dbcbr.types.mapping;
interface
type
TRuleAction = (None, Cascade, SetNull, SetDefault);
TSortingOrder = (NoSort, Ascending, Descending);
TMultiplicity = (OneToOne, OneToMany, ManyToOne, ManyToMany);
TGenerated = (Never, Insert, Always);
TJoin = (InnerJoin, LeftJoin, RightJoin, FullJoin);
TSequenceType = (NotInc, AutoInc, TableInc, GuidInc);
TRestriction = (NotNull, NoInsert, NoUpdate, NoValidate, Unique, Hidden, VirtualData);
TRestrictions = set of TRestriction;
TCascadeAction = (CascadeNone, CascadeAutoInc, CascadeInsert, CascadeUpdate, CascadeDelete);
TCascadeActions = set of TCascadeAction;
TMasterEvent = (AutoPost, AutoEdit, AutoInsert);
TMasterEvents = set of TMasterEvent;
TEnumType = (etChar, etString, etInteger, etBoolean);
TFieldEvent = (onChange, onGetText, onSetText, onValidate);
TFieldEvents = set of TFieldEvent;
implementation
end.
|
program MaxInArray;
{ shows several statements that use the function MAX and we shall
decedide which could get the index out of bounds in the FELD array }
const
GRENZE = 10;
type
tIndex = 1..GRENZE;
tFeld = array [tIndex] of integer;
var
Feld : tFeld;
w,
w1,
w2 : integer;
function max (
ParFeld: tFeld;
von, bis: tIndex): integer;
{ bestimmt das Maximum im Teilfeld von ParFeld[von]
bis ParFeld[bis] }
var
Wert : integer;
i : tIndex;
begin
Wert := ParFeld[von];
for i := von + 1 to bis do
if ParFeld[i] > Wert then
Wert := ParFeld[i];
max := Wert
end; { max }
begin
Feld[1] := 1; Feld[2] := 2; Feld[3] := 3; Feld[4] := 4; Feld[5] := 5;
Feld[6] := 6; Feld[7] := 7; Feld[8] := 88; Feld[9] := 9; Feld[10] := 10;
{ A }
w := max (Feld, Feld[1], Feld[GRENZE]);
writeln(w);
{ B }
w := max (Feld, (GRENZE-1) div 2,
(GRENZE-1) div 2);
writeln(w);
{ C }
if max (Feld, 1, (GRENZE-1) div 2) >
max (Feld, (GRENZE+1) div 2, GRENZE)
then
w := max (Feld, 1, (GRENZE-1) div 2)
else
w := max (Feld, (GRENZE+1) div 2, GRENZE);
writeln(w);
{ D - out of bounds}
w := max (Feld, 1, GRENZE);
if w <= GRENZE then { would fail if w <= 0}
write (max (Feld, w, w));
{ E - out of bounds }
w1 := max (Feld, 1, GRENZE);
w2 := max (Feld, 4, GRENZE-1);
if (0 < w2) and (w1 <= GRENZE) then
begin { e.g. when w assumes a negative value }
w := max (Feld, 2, GRENZE);
w := max (Feld, 1, w)
end;
end. { MaxInArray }
|
unit ArticlesPlugin;
interface
uses PluginManagerIntf, PluginIntf, ControlPanelElementIntf, Graphics,
DataModuleIntf;
type
TArticlesPlugin = class (TPlugin, IPlugin, IControlPanelElement, IDataModule)
private
FDisplayName: string;
FBitmap: TBitmap;
FDataPath: String;
public
constructor Create(Module: HMODULE; PluginManager: IPluginManager);
destructor Destroy; override;
function Execute: Boolean;
function GetDescription: string;
function GetDisplayName: string;
function GetBitmap: TBitmap;
function GetName: string;
function Load: Boolean;
procedure SetDisplayName(const Value: string);
function UnLoad: Boolean;
{ IDataModule }
function GetDataPath: String;
procedure SetDataPath(const Value: String);
end;
function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean;
exports RegisterPlugin;
implementation
uses Windows, artMainFrm;
function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean;
var
Plugin: IInterface;
begin
Plugin := TArticlesPlugin.Create(Module, PluginManager);
Result := PluginManager.RegisterPlugin(Plugin);
end;
{ TArticlesPlugin }
constructor TArticlesPlugin.Create(Module: HMODULE;
PluginManager: IPluginManager);
begin
inherited;
FBitmap := Graphics.TBitmap.Create;
FDisplayName := 'Статьи';
FBitmap.Handle := LoadBitmap(Module, 'PLUGIN_ICON');
end;
destructor TArticlesPlugin.Destroy;
begin
FBitmap.Free;
inherited;
end;
function TArticlesPlugin.Execute: Boolean;
begin
Result := GetMainForm(FPluginManager, FDataPath) = IDOK;
end;
function TArticlesPlugin.GetBitmap: Graphics.TBitmap;
begin
Result := FBitmap;
end;
function TArticlesPlugin.GetDataPath: String;
begin
Result := FDataPath;
end;
function TArticlesPlugin.GetDescription: string;
begin
Result := 'Редактирование статей';
end;
function TArticlesPlugin.GetDisplayName: string;
begin
Result := FDisplayName;
end;
function TArticlesPlugin.GetName: string;
begin
Result := 'ArticlesPlugin';
end;
function TArticlesPlugin.Load: Boolean;
begin
Result := True;
end;
procedure TArticlesPlugin.SetDataPath(const Value: String);
begin
FDataPath := Value;
end;
procedure TArticlesPlugin.SetDisplayName(const Value: string);
begin
FDisplayName := Value;
end;
function TArticlesPlugin.UnLoad: Boolean;
begin
Result := True;
end;
end.
|
(*======================================================================*
| unitSecurityDescriptor unit for NSIHHTController |
| |
| Class to initialize a security descriptor from a thread token. Used |
| to set server's DCOM security model. |
| |
| Copyright © Marks & Spencer PLC 2002. All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 12/02/2002 CPWW Original |
*======================================================================*)
unit unitSecurityDescriptor;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses Windows, Classes, SysUtils;
const
RPC_C_AUTHN_LEVEL_DEFAULT = 0;
RPC_C_AUTHN_LEVEL_NONE = 1;
RPC_C_AUTHN_LEVEL_CONNECT = 2;
RPC_C_AUTHN_LEVEL_CALL = 3;
RPC_C_AUTHN_LEVEL_PKT = 4;
RPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5;
RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6;
RPC_C_IMP_LEVEL_DEFAULT = 0;
RPC_C_IMP_LEVEL_ANONYMOUS = 1;
RPC_C_IMP_LEVEL_IDENTIFY = 2;
RPC_C_IMP_LEVEL_IMPERSONATE = 3;
RPC_C_IMP_LEVEL_DELEGATE = 4;
type
EOLE_AUTHENTICATION_CAPABILITIES = (
EOAC_NONE = 0,
EOAC_MUTUAL_AUTH = $1,
EOAC_STATIC_CLOAKING = $20,
EOAC_DYNAMIC_CLOAKING = $40,
EOAC_ANY_AUTHORITY = $80,
EOAC_MAKE_FULLSIC = $100,
EOAC_DEFAULT = $800,
EOAC_SECURE_REFS = $2,
EOAC_ACCESS_CONTROL = $4,
EOAC_APPID = $8,
EOAC_DYNAMIC = $10,
EOAC_REQUIRE_FULLSIC = $200,
EOAC_AUTO_IMPERSONATE = $400,
EOAC_NO_CUSTOM_MARSHAL= $2000,
EOAC_DISABLE_AAA = $1000);
procedure InitializeSDFromThreadToken (var sd : TSecurityDescriptor; bDefaulted : Boolean = False; bRevertToProcessToken : boolean = TRUE);
implementation
type
TTokenUser = record
User : SID_AND_ATTRIBUTES;
end;
PTokenUser = ^TTokenUser;
TTokenGroups = record
dwGroupCount : DWORD;
Groups : array [0..0] of SID_AND_ATTRIBUTES;
end;
PTokenGroups = ^TTokenGroups;
TTokenPrimaryGroup = record
PrimaryGroup : PSID;
end;
PTokenPrimaryGroup = ^TTokenPrimaryGroup;
(*----------------------------------------------------------------------*
| GetTokenSids |
| |
| Get the user and primary group SID for a token's hande. |
| |
| Parameters: |
| hToken : THandle; The token to query |
| var pUserSid : PSID Returns the user SID |
| var pGroupSid : PSID Returns the primary group's SID |
*----------------------------------------------------------------------*)
procedure GetTokenSids (hToken : THandle; var pUserSid, pGroupSid : PSID);
var
ptkUser : PTokenUser;
ptkGroup : PTokenPrimaryGroup;
ps : PSID;
dwSize : DWORD;
begin
pUserSid := Nil;
pGroupSid := Nil;
try
if not GetTokenInformation (hToken, TokenUser, Nil, 0, dwSize) then
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
RaiseLastOSError;
GetMem (ptkUser, dwSize); // Get the token's user
Win32Check (GetTokenInformation (hToken, TokenUser, ptkUser, dwSize, dwSize));
dwSize := GetLengthSid (ptkUser^.User.Sid);
GetMem (ps, dwSize);
try
Win32Check (CopySid (dwSize, ps, ptkUser^.User.Sid));
Win32Check (IsValidSID (ps));
except
FreeMem (ps);
raise
end;
pUserSid := ps; // Allocate & save pUserSid
// Get the token's primary group
if not GetTokenInformation (hToken, TokenPrimaryGroup, Nil, 0, dwSize) then
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
RaiseLastOSError;
GetMem (ptkGroup, dwSize);
Win32Check (GetTokenInformation (hToken, TokenPrimaryGroup, ptkGroup, dwSize, dwSize));
dwSize := GetLengthSid (ptkGroup^.PrimaryGroup);
GetMem (ps, dwSize);
try
Win32Check (CopySid (dwSize, ps, ptkGroup^.PrimaryGroup));
Win32Check (IsValidSID (ps));
except
FreeMem (ps);
raise
end;
pGroupSid := ps; // Allocate & save primary group
except // If there were errors, clear up by
ReallocMem (pUserSid, 0); // deleting the allocated SIDs
ReallocMem (pGroupSid, 0);
raise
end
end;
(*----------------------------------------------------------------------*
| GetThreadSids |
| |
| Get the user & primary group SID for the current thread |
| |
| Parameters: |
| var pUserSid, pGroupSid : PSID |
| |
| The function returns boolean |
*----------------------------------------------------------------------*)
function GetThreadSids (var pUserSid, pGroupSid : PSID) : boolean;
var
hToken : THandle;
begin
result := False;
if OpenThreadToken (GetCurrentThread, TOKEN_QUERY, False, hToken) then
begin
GetTokenSids (hToken, pUserSid, pGroupSid);
Result := True
end
else
if GetLastError <> ERROR_NO_TOKEN then
RaiseLastOSError
end;
(*----------------------------------------------------------------------*
| GetProcessSids |
| |
| Get the user & primary group SID for the current process |
| |
| Parameters: |
| var pUserSid, pGroupSid : PSID |
| |
| The function returns boolean |
*----------------------------------------------------------------------*)
function GetProcessSids (var pUserSid, pGroupSid : PSID) : boolean;
var
hToken : THandle;
begin
Result := False;
if OpenProcessToken (GetCurrentProcess, TOKEN_QUERY, hToken) then
begin
GetTokenSids (hToken, pUserSid, pGroupSid);
Result := True
end
else
if GetLastError <> ERROR_NO_TOKEN then
RaiseLastOSError
end;
(*
function CreateSelfRelativeSD (sd : TSecurityDescriptor) : PSECURITY_DESCRIPTOR;
var
sdLen : DWORD;
begin
sdLen := 1024;
Result := nil;
try
repeat
ReallocMem (result, sdLen);
if MakeSelfRelativeSD (@sd, result, sdLen) then
SetLastError (0)
until GetLastError <> ERROR_INSUFFICIENT_BUFFER;
if GetLastError <> 0 then
RaiseLastOSError;
sdLen := GetSecurityDescriptorLength (result);
ReallocMem (result, sdLen);
except
FreeMem (result);
raise
end
end;
*)
(*----------------------------------------------------------------------*
| InitializeSDFromThreadToken |
| |
| Initialize an SD, and fill in it's DACL (a clear one!) and it's |
| owner and group (from this process or thread). |
| |
| Remember to Free sd.owner & sd.group afterwards. |
| |
| Parameters: |
| var sd : TSecurityDescriptor; The SD to initialize |
| bDefaulted : Boolean = False; |
| bRevertToProcessToken : boolean = TRUE Use process roken if |
| thread token not there! |
*----------------------------------------------------------------------*)
procedure InitializeSDFromThreadToken (var sd : TSecurityDescriptor; bDefaulted : Boolean = False; bRevertToProcessToken : boolean = TRUE);
var
pUserSid : PSID;
pGroupSid : PSID;
begin
pUserSid := nil;
pGroupSid := nil;
Win32Check (InitializeSecurityDescriptor (@sd, SECURITY_DESCRIPTOR_REVISION));
SetSecurityDescriptorDacl (@sd, True, nil, False);
if GetThreadSids (pUserSid, pGroupSid) or (bRevertToProcessToken and GetProcessSids (pUserSid, pGroupSid)) then
try
if SetSecurityDescriptorOwner (@sd, pUserSid, bDefaulted) then
Win32Check (SetSecurityDescriptorGroup (@sd, pGroupSid, bDefaulted))
else
RaiseLastOSError;
finally
//---------------------------------------------------------
// CoInitializeSecurity seems to need an absolute SD (not a
// self-relative one) - so we can't free the sids 'til after
// we've called it.
//
// ReallocMem (pUserSid, 0);
// ReallocMem (pGroupSid, 0)
end
end;
end.
|
(*
* Библиотека Modbus
* Реализует взаимодействие с устройством по протоколу Modbus
*
* Фабрика запросов modbus создает ReadInput, ReadHolding, WriteMultiple и т.д.
* Запрос помещается в очередь контроллера.
* Результат выполнения можно узнать с помощью функции 'Responded'.
* Строитель создает определенный стек modbus (TCP, RTU) и настраивает его
* должным образом.
*)
library modbus;
{$mode objfpc}{$H+}
uses
Classes, WinSock2, Windows,
ubase, // Модуль с базовыми классами
userver, // Сервер
ucontrollerpool, // Пул контроллеров (используется для серверного сокета)
ucontroller, // Уровни стека - контроллер
utransaction, // Уровни стека - транзакция
ucommunication, // Уровни стека - коммуникация
uconnection, // Уровни стека - соединение
ustackbuilder, // Строитель стека
uframe, // Фреймы modbus запросов
uframefactory, // Фабрика фреймов
ulogger, // Логгирование ошибок транзакций
umodbus; // Экспортный интерфейсный модуль
{$R *.res}
var
WSAData: TWSAData;
{%H-}DLLProc: Pointer;
// Глобальные объектные переменные
StackBuilder: IStackBuilder;
ControllerPool: IControllerPool;
// Определение экспортируемых функций и процедур
function GetControllerPool: IControllerPool; export;
begin
if ControllerPool = nil then
ControllerPool := TControllerPool.Create;
Result := ControllerPool;
end;
function GetStackBuilder: IStackBuilder; export;
begin
if StackBuilder = nil then
StackBuilder := TStackBuilder.Create;
Result := StackBuilder;
end;
function GetRtuBuilder: IRtuBuilder;
begin
Result := GetStackBuilder.RtuBuilder;
end;
function GetTcpBuilder: ICnTcpBuilder;
begin
Result := GetStackBuilder.CnTcpBuilder;
end;
function GetServer(const aPort: word): IServer; export;
begin
Result := TServer.Create(GetStackBuilder.GetAcTcpBuilder, GetControllerPool);
Result.TcpConnection := TSvTcpConnection.Create(aPort);
end;
function ReadInput(const aSlaveId: Byte; const aStart,
aRegCount: Word; const aTimeout: dword): IFrame; export;
begin
Result := TFrameFactory.ReadInput(aSlaveId, aStart, aRegCount, aTimeout);
end;
function ReadHolding(const aSlaveId: Byte; const aStart,
aRegCount: Word; const aTimeout: dword): IFrame; export;
begin
Result := TFrameFactory.ReadHolding(aSlaveId, aStart, aRegCount, aTimeout);
end;
function WriteMultiple(const aSlaveId: Byte; const aStart,
aRegCount: Word; const aValue, aTimeout: dword): IFrame; export;
begin
Result := TFrameFactory.WriteMultiple(aSlaveId, aStart, aRegCount, aValue, aTimeout);
end;
// Список экспортируемых функций процедур
exports
GetControllerPool,
GetServer,
GetRtuBuilder,
GetTcpBuilder,
ReadInput,
ReadHolding,
WriteMultiple;
// Инициализация библиотеки WinSock
procedure DLLEntryPoint(Reason: Word);
begin
case Reason of
DLL_PROCESS_ATTACH: WSAStartup($101, WSAData);
DLL_PROCESS_DETACH: WSACleanup;
end;
end;
begin
DLLProc := @DLLEntryPoint;
DLLEntryPoint(DLL_PROCESS_ATTACH);
end.
|
PROGRAM Part10;
VAR
number : INTEGER;
a, b, c, x : INTEGER;
y : REAL;
PROCEDURE P1(a : REAL);
VAR
k : INTEGER;
BEGIN {P1}
a := 10;
k := 1;
number := 3;
END; {P1}
BEGIN {Part10}
BEGIN
b := 10 * a + 3 * number DIV 4;
c := a - - b
END;
x := 11;
y := 10 / 3 + 3.14;
{ writeln('a = ', a); }
{ writeln('b = ', b); }
{ writeln('c = ', c); }
{ writeln('number = ', number); }
{ writeln('x = ', x); }
{ writeln('y = ', y); }
END. {Part10}
|
unit ssl_util;
interface
uses ssl_types, ssl_asn;
var
CRYPTO_malloc : function(num: TC_INT; const _file: PAnsiChar; line: TC_INT): Pointer cdecl = nil;
CRYPTO_realloc: function(addr: Pointer; num: TC_INT; _file: PAnsiChar; line: TC_INT): Pointer; cdecl = nil;
CRYPTO_free : procedure(ptr : Pointer) cdecl = nil;
CRYPTO_malloc_init: procedure; cdecl = nil;
CRYPTO_set_mem_functions:function (_malloc: CRYPTO_mem_alloc_func; _realloc: CRYPTO_mem_realloc_func; _free: CRYPTO_mem_free_func): TC_INT; cdecl = nil;
fCRYPTO_lock: procedure(_mode: TC_INT; _type: TC_INT; _file: PAnsiChar; line: TC_INT); cdecl = nil;
OPENSSL_gmtime: function(var timer: TC_time_t; var time: tm): tm; cdecl = nil;
function OpenSSL_malloc(iSize: TC_INT): Pointer;
procedure OpenSSL_free(ptr: Pointer);
function Asn1ToString(str: PASN1_STRING): String;
function StringToASN1(s: String; nid: Integer): PASN1_STRING;
function OBJ_ln2sn(ln: PAnsiChar): PAnsiChar;
function OBJ_sn2ln(ln: PAnsiChar): PAnsiChar;
function OBJ_obj2sn(a: PASN1_OBJECT): PAnsiChar;
function OBJ_obj2String(a: PASN1_OBJECT; no_name: Integer = 0): String;
procedure SSL_InitUtil;
function DateTimeToUnixTime(ADateTime: TDateTime): TC_time_t;
function UnixTimeToDateTime(const AUnixTime: TC_time_t): TDateTime;
function ASN1ToDateTime(a: PASN1_TIME): TDateTime;
function DateTimeToASN1(ADateTime: TDateTime): PASN1_TIME;
implementation
uses ssl_lib, ssl_const, Winapi.WinSock, SysUtils, ssl_err, ssl_objects, Math;
function _CR_alloc(_size: TC_SIZE_T): Pointer; cdecl;
begin
Result := AllocMem(_size);
end;
function _CR_realloc(_mem: Pointer; _size: TC_SIZE_T): Pointer; cdecl;
begin
Result := ReallocMemory(_mem, _size);
end;
procedure _CR_free(_mem: Pointer); cdecl;
begin
FreeMem(_mem);
end;
procedure SSL_InitUtil;
begin
if @CRYPTO_malloc = nil then
begin
@CRYPTO_malloc := LoadFunctionCLib('CRYPTO_malloc');
@CRYPTO_free := LoadFunctionCLib('CRYPTO_free');
@CRYPTO_realloc := LoadFunctionCLib('CRYPTO_realloc', false);
@CRYPTO_set_mem_functions := LoadFunctionCLib('CRYPTO_set_mem_functions');
@fCRYPTO_lock := LoadFunctionCLib('CRYPTO_lock');
CRYPTO_set_mem_functions(_CR_alloc, _CR_realloc, _CR_free);
@OPENSSL_gmtime := LoadFunctionCLib('OPENSSL_gmtime', False);
end;
end;
function OpenSSL_malloc(iSize: TC_INT): Pointer;
begin
if @CRYPTO_malloc <> nil then
Result := CRYPTO_malloc(iSize, '', 0)
else
Result := nil;
end;
procedure OpenSSL_free(ptr: Pointer);
begin
if @CRYPTO_Free <> nil then
CRYPTO_free(ptr);
end;
function Asn1ToString(str: PASN1_STRING): String;
var
P: PWideChar;
begin
case Str._type of
V_ASN1_BMPSTRING: begin
P := GetMemory(Str.length div 2);
UnicodeToUtf8(str.data, p, str.length div 2);
Result := P;
FreeMem(P);
end;
V_ASN1_UTF8STRING: begin
Result := Str.data;
end;
V_ASN1_T61STRING: begin
Result := Str.data;
end;
else
Result := Str.data;
end;
end;
function StringToASN1(s: String; nid: Integer): PASN1_STRING;
var
B: TBytes;
gmask: TC_ULONG;
mask: TC_ULONG;
tbl: PASN1_STRING_TABLE;
_in: PAnsiChar;
_ins: AnsiString;
begin
B := TEncoding.Convert(TEncoding.Default, TEncoding.UTF8, BytesOf(s));
_ins := StringOf(B);
gmask := ASN1_STRING_get_default_mask();
mask := DIRSTRING_TYPE and gmask;
Result := nil;
tbl := ASN1_STRING_TABLE_get(nid);
SSL_CheckError;
if tbl <> nil then
begin
mask := tbl.mask;
if (tbl.flags and STABLE_NO_MASK) = 0 then
mask := mask and gmask;
end;
ASN1_mbstring_copy(@Result, @_ins[1], -1, MBSTRING_UTF8, mask);
SSL_CheckError;
end;
function OBJ_ln2sn(ln: PAnsiChar): PAnsiChar;
begin
Result := OBJ_nid2sn(OBJ_ln2nid(ln))
end;
function OBJ_sn2ln(ln: PAnsiChar): PAnsiChar;
begin
Result := OBJ_nid2ln(OBJ_sn2nid(ln))
end;
function OBJ_obj2sn(a: PASN1_OBJECT): PAnsiChar;
begin
OBJ_obj2nid(a);
SSL_CheckError;
Result := OBJ_nid2sn(OBJ_obj2nid(a));
end;
function OBJ_obj2String(a: PASN1_OBJECT; no_name: Integer = 0): String;
var len: Integer;
buf: PAnsiChar;
begin
Len := OBJ_obj2txt(buf, 256, a, no_name);
SSL_CheckError;
Result := buf;
end;
function DateTimeToUnixTime(ADateTime: TDateTime): TC_time_t;
begin
Result := Round((ADateTime - UnixDateDelta) * SecsPerDay);
end;
function UnixTimeToDateTime(const AUnixTime: TC_time_t): TDateTime;
begin
Result:= UnixDateDelta + (AUnixTime / SecsPerDay);
end;
function GeneralizedTimeToDateTime(AGenTime: String): TDateTime;
var FS: TFormatSettings;
y, m, d, h, mm, s: Word;
begin
y := StrToInt(Copy(AGenTime, 1, 4));
m := StrToInt(Copy(AGenTime, 5, 2));
d := StrToInt(Copy(AGenTime, 7, 2));
h := StrToInt(Copy(AGenTime, 9, 2));
mm := StrToInt(Copy(AGenTime, 11, 2));
s := StrToInt(Copy(AGenTime, 13, 2));
Result := EncodeDate(y, m, d)+EncodeTime(h, mm, s, 0);
end;
function ASN1ToDateTime(a: PASN1_TIME): TDateTime;
var gt: PASN1_GENERALIZEDTIME;
begin
gt := ASN1_TIME_to_generalizedtime(a, nil);
Result := GeneralizedTimeToDateTime(gt.data);
end;
function DateTimeToASN1(ADateTime: TDateTime): PASN1_TIME;
begin
Result := ASN1_TIME_new;
ASN1_TIME_set(Result, DateTimeToUnixTime(ADateTime));
end;
end.
|
unit uAlarmTemplateEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids,
StdCtrls, Menus, uCustomTypes, Math, uEditAlarmTemplate, uStrUtils;
type
{ TfAlarmTemplateEditor }
TfAlarmTemplateEditor = class(TForm)
bCancel: TButton;
bOK: TButton;
pmiCopyTemplate: TMenuItem;
miCopyTemplate: TMenuItem;
miActions: TMenuItem;
miAddTemplate: TMenuItem;
miDeleteTemplate: TMenuItem;
miEditTemplate: TMenuItem;
mmAlarmTemplateEditor: TMainMenu;
pmAlarmTemplateEditor: TPopupMenu;
pmiAddTemplate: TMenuItem;
pmiDelTemplate: TMenuItem;
pmiEditTemplate: TMenuItem;
sgAlarms: TStringGrid;
procedure bCancelClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure miAddTemplateClick(Sender: TObject);
procedure miCopyTemplateClick(Sender: TObject);
procedure miDeleteTemplateClick(Sender: TObject);
procedure miEditTemplateClick(Sender: TObject);
procedure pmiAddTemplateClick(Sender: TObject);
procedure pmiCopyTemplateClick(Sender: TObject);
procedure pmiDelTemplateClick(Sender: TObject);
procedure pmiEditTemplateClick(Sender: TObject);
procedure sgAlarmsDblClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
fAlarmTemplateEditor: TfAlarmTemplateEditor;
COPYarrServerAlarmList:array of uCustomTypes.TAlarmTemplate;
res:string;
isSelectMode:boolean;
function SelectAlarmTemplate(alarm_template_name:string):string;
procedure StartAlarmTemplateEdit;
procedure RefreshList;
procedure AddA;
procedure EditA;
procedure CopyA;
procedure DelA;
function AlarmUsedInEvent(alarm:TAlarmTemplate):boolean;
function AlarmNameUsed(alarm_name,initial_alarm_name:string):boolean;
implementation
uses uMain, uSchEditor;
{$R *.lfm}
{ TfAlarmTemplateEditor }
function SelectAlarmTemplate(alarm_template_name:string):string;
var
x:integer;
begin
isSelectMode:=true;
Setlength(COPYarrServerAlarmList,length(uMain.arrServerAlarmList));
for x:=1 to length(uMain.arrServerAlarmList) do
begin
COPYarrServerAlarmList[x-1]:=uMain.arrServerAlarmList[x-1];
end;
Application.CreateForm(TfAlarmTemplateEditor, fAlarmTemplateEditor);
RefreshList;
// find alarm template name
for x:=1 to length(COPYarrServerAlarmList) do
begin
if UpperCase(alarm_template_name)=UpperCase(COPYarrServerAlarmList[x-1].alarm_template_name) then
begin
fAlarmTemplateEditor.sgAlarms.Row:=x;
end;
end;
fAlarmTemplateEditor.bOK.Caption:='Select';
fAlarmTemplateEditor.ShowModal;
Result:=res;
end;
procedure StartAlarmTemplateEdit;
var
x:integer;
begin
isSelectMode:=false;
Setlength(COPYarrServerAlarmList,length(uMain.arrServerAlarmList));
for x:=1 to length(uMain.arrServerAlarmList) do
begin
COPYarrServerAlarmList[x-1]:=uMain.arrServerAlarmList[x-1];
end;
Application.CreateForm(TfAlarmTemplateEditor, fAlarmTemplateEditor);
RefreshList;
fAlarmTemplateEditor.ShowModal;
end;
procedure RefreshList;
var
x,l,r:integer;
begin
r:=fAlarmTemplateEditor.sgAlarms.Row;
l:=length(COPYarrServerAlarmList);
fAlarmTemplateEditor.sgAlarms.RowCount:=max(l+1,2);
if l=0 then
begin
fAlarmTemplateEditor.sgAlarms.Cells[0,1]:='';
end;
for x:=1 to l do
begin
fAlarmTemplateEditor.sgAlarms.Cells[0,x]:=COPYarrServerAlarmList[x-1].alarm_template_name;
end;
fAlarmTemplateEditor.sgAlarms.Row:=r;
end;
procedure TfAlarmTemplateEditor.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
CloseAction:=caFree;
end;
procedure TfAlarmTemplateEditor.miAddTemplateClick(Sender: TObject);
begin
AddA;
end;
procedure TfAlarmTemplateEditor.miCopyTemplateClick(Sender: TObject);
begin
CopyA;
end;
procedure TfAlarmTemplateEditor.miDeleteTemplateClick(Sender: TObject);
begin
DelA;
end;
procedure TfAlarmTemplateEditor.bOKClick(Sender: TObject);
var
x,r:integer;
begin
if isSelectMode then
begin
r:=fAlarmTemplateEditor.sgAlarms.Row;
if r<1 then
begin
ShowMessage('Select alarm template first!');
exit;
end;
if r>Length(COPYarrServerAlarmList) then
begin
ShowMessage('Select alarm template first!');
exit;
end;
Setlength(uMain.arrServerAlarmList,length(COPYarrServerAlarmList));
for x:=1 to length(COPYarrServerAlarmList) do
begin
uMain.arrServerAlarmList[x-1]:=COPYarrServerAlarmList[x-1];
end;
res:=COPYarrServerAlarmList[r-1].alarm_template_name;
close;
end
else
begin
Setlength(uMain.arrServerAlarmList,length(COPYarrServerAlarmList));
for x:=1 to length(COPYarrServerAlarmList) do
begin
uMain.arrServerAlarmList[x-1]:=COPYarrServerAlarmList[x-1];
end;
WaitSocketForOp(7); // save alarm list to server
close;
end;
end;
procedure TfAlarmTemplateEditor.bCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfAlarmTemplateEditor.miEditTemplateClick(Sender: TObject);
begin
EditA;
end;
procedure TfAlarmTemplateEditor.pmiAddTemplateClick(Sender: TObject);
begin
AddA;
end;
procedure TfAlarmTemplateEditor.pmiCopyTemplateClick(Sender: TObject);
begin
CopyA;
end;
procedure TfAlarmTemplateEditor.pmiDelTemplateClick(Sender: TObject);
begin
DelA;
end;
procedure TfAlarmTemplateEditor.pmiEditTemplateClick(Sender: TObject);
begin
EditA;
end;
procedure TfAlarmTemplateEditor.sgAlarmsDblClick(Sender: TObject);
begin
if isSelectMode then
begin
bOK.Click;
end
else
begin
EditA;
end;
end;
procedure EditA;
var
r:integer;
atr:uCustomTypes.TAlarmTemplateResult;
begin
r:=fAlarmTemplateEditor.sgAlarms.Row;
if r<1 then
begin
ShowMessage('Select alarm template first!');
exit;
end;
if r>Length(COPYarrServerAlarmList) then
begin
ShowMessage('Select alarm template first!');
exit;
end;
atr:=uEditAlarmTemplate.EditAlarmTemplate(COPYarrServerAlarmList[r-1],AlarmUsedInEvent(COPYarrServerAlarmList[r-1]));
if atr.res then
begin
COPYarrServerAlarmList[r-1]:=atr.atr_alarm_template;
RefreshList;
end;
end;
procedure CopyA;
var
r:integer;
atr:uCustomTypes.TAlarmTemplateResult;
a:uCustomTypes.TAlarmTemplate;
begin
r:=fAlarmTemplateEditor.sgAlarms.Row;
if r<1 then
begin
ShowMessage('Select alarm template first!');
exit;
end;
if r>Length(COPYarrServerAlarmList) then
begin
ShowMessage('Select alarm template first!');
exit;
end;
a:=COPYarrServerAlarmList[r-1];
a.alarm_template_name:='';
atr:=uEditAlarmTemplate.EditAlarmTemplate(a,false);
if atr.res then
begin
SetLength(COPYarrServerAlarmList,Length(COPYarrServerAlarmList)+1);
COPYarrServerAlarmList[Length(COPYarrServerAlarmList)-1]:=atr.atr_alarm_template;
RefreshList;
end;
end;
function AlarmUsedInEvent(alarm:TAlarmTemplate):boolean;
var
x,l:integer;
tmp_bn:string;
begin
result:=false;
if isSelectMode then
begin
l:=length(uSchEditor.COPYarrServerSch);
for x:=1 to l do
begin
tmp_bn:=uStrUtils.GetFieldFromString(uSchEditor.COPYarrServerSch[x-1].event_alarm_str,ParamLimiter,4);
if UpperCase(tmp_bn)=UpperCase(alarm.alarm_template_name) then
begin
result:=true;
exit;
end;
end;
end
else
begin
l:=length(arrServerSch);
for x:=1 to l do
begin
tmp_bn:=uStrUtils.GetFieldFromString(arrServerSch[x-1].event_alarm_str,ParamLimiter,4);
if UpperCase(tmp_bn)=UpperCase(alarm.alarm_template_name) then
begin
result:=true;
exit;
end;
end;
end;
end;
function AlarmNameUsed(alarm_name,initial_alarm_name:string):boolean;
var
x:integer;
begin
result:=false;
if UPPERCASE(alarm_name)=UPPERCASE(initial_alarm_name) then
begin
exit;
end;
for x:=1 to length(COPYarrServerAlarmList) do
begin
if UPPERCASE(alarm_name)=UPPERCASE(COPYarrServerAlarmList[x-1].alarm_template_name) then
begin
result:=true;
exit;
end;
end;
end;
procedure AddA;
var
atl:uCustomTypes.TAlarmTemplate;
atr:uCustomTypes.TAlarmTemplateResult;
begin
atl.alarm_template_name:='';
atl.alarm_template_str:='0';
atl.alarm_template_params:='';
atr:=uEditAlarmTemplate.EditAlarmTemplate(atl,false);
if atr.res then
begin
SetLength(COPYarrServerAlarmList,Length(COPYarrServerAlarmList)+1);
COPYarrServerAlarmList[Length(COPYarrServerAlarmList)-1]:=atr.atr_alarm_template;
RefreshList;
end;
end;
procedure DelA;
var
r:integer;
x:integer;
begin
r:=fAlarmTemplateEditor.sgAlarms.Row;
if r<1 then
begin
ShowMessage('Select alarm template first!');
exit;
end;
if r>Length(COPYarrServerAlarmList) then
begin
ShowMessage('Select alarm template first!');
exit;
end;
if AlarmUsedInEvent(COPYarrServerAlarmList[r-1]) then
begin
ShowMessage('Selected alarm template used in tasks!');
exit;
end;
if MessageDlg('Are you sure?','Delete alarm template '+COPYarrServerAlarmList[r-1].alarm_template_name+'?',mtConfirmation,[mbYes, mbNo],0)=mrYes then
begin
for x:=r to Length(COPYarrServerAlarmList)-1 do
begin
COPYarrServerAlarmList[x-1]:=COPYarrServerAlarmList[x];
end;
SetLength(COPYarrServerAlarmList,Length(COPYarrServerAlarmList)-1);
RefreshList;
end;
end;
end.
|
unit PessoaTelefone;
interface
uses
MVCFramework.Serializer.Commons, ModelBase;
type
[MVCNameCase(ncLowerCase)]
TPessoaTelefone = class(TModelBase)
private
FID: Integer;
FID_PESSOA: Integer;
FTIPO: string;
FNUMERO: string;
public
procedure ValidarInsercao; override;
procedure ValidarAlteracao; override;
procedure ValidarExclusao; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FID write FID;
[MVCColumnAttribute('ID_PESSOA')]
[MVCNameAsAttribute('idPessoa')]
property IdPessoa: Integer read FID_PESSOA write FID_PESSOA;
[MVCColumnAttribute('TIPO')]
[MVCNameAsAttribute('tipo')]
property Tipo: string read FTIPO write FTIPO;
[MVCColumnAttribute('NUMERO')]
[MVCNameAsAttribute('numero')]
property Numero: string read FNUMERO write FNUMERO;
end;
implementation
{ TPessoaTelefone }
procedure TPessoaTelefone.ValidarInsercao;
begin
inherited;
end;
procedure TPessoaTelefone.ValidarAlteracao;
begin
inherited;
end;
procedure TPessoaTelefone.ValidarExclusao;
begin
inherited;
end;
end.
|
unit uOriginalDrinks;
interface
type
TCoffee = class
public
procedure PrepareCoffee;
procedure BoilWater;
procedure BrewCoffeeGrinds;
procedure PourInCup;
procedure AddSugarAndMilk;
end;
TTea = class
public
procedure PrepareRecipe;
procedure BoilWater;
procedure SteepTeaBag;
procedure AddLemon;
procedure PourInCup;
end;
implementation
{ TOriginalCoffee }
procedure TCoffee.AddSugarAndMilk;
begin
WriteLn('Adding sugar and milk...');
end;
procedure TCoffee.BoilWater;
begin
WriteLn('Boiling water...');
end;
procedure TCoffee.BrewCoffeeGrinds;
begin
WriteLn('Brewing coffee grinds...');
end;
procedure TCoffee.PourInCup;
begin
WriteLn('Pouring in Cup...');
end;
procedure TCoffee.PrepareCoffee;
begin
BoilWater;
BrewCoffeeGrinds;
PourInCup;
AddSugarAndMilk;
end;
{ TTea }
procedure TTea.AddLemon;
begin
WriteLn('Adding Lemon...');
end;
procedure TTea.BoilWater;
begin
WriteLn('Boiling water...');
end;
procedure TTea.PourInCup;
begin
WriteLn('Pouring in cup...');
end;
procedure TTea.PrepareRecipe;
begin
BoilWater;
SteepTeaBag;
PourInCup;
AddLemon;
end;
procedure TTea.SteepTeaBag;
begin
WriteLn('Steeping tea bag...');
end;
end.
|
unit frmTracerConfigUnit;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
StdCtrls, ExtCtrls, debuggertypedefinitions, betterControls;
type
{ TfrmTracerConfig }
TfrmTracerConfig = class(TForm)
btnCancel: TButton;
btnOK: TButton;
cbDereferenceAddresses: TCheckBox;
cbSaveStack: TCheckBox;
cbStepOver: TCheckBox;
cbSkipSystemModules: TCheckBox;
cbDBVMBreakAndTrace: TCheckBox;
cbDBVMTriggerCOW: TCheckBox;
cbStayInsideInitialModule: TCheckBox;
cbStepOverRep: TCheckBox;
edtStartCondition: TEdit;
edtMaxTrace: TEdit;
edtStopCondition: TEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Panel1: TPanel;
rbBPHardware: TRadioButton;
rbBPSoftware: TRadioButton;
rbBPException: TRadioButton;
rbBPDBVM: TRadioButton;
rbBreakOnAccess: TRadioButton;
rbBreakOnWrite: TRadioButton;
procedure cbDBVMBreakAndTraceChange(Sender: TObject);
procedure cbStepOverChange(Sender: TObject);
procedure FormConstrainedResize(Sender: TObject; var MinWidth, MinHeight,
MaxWidth, MaxHeight: TConstraintSize);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ private declarations }
fDataTrace: boolean;
procedure setDataTrace(state: boolean);
function getBreakpointmethod: TBreakpointmethod;
procedure setBreakPointMethod(m: TBreakpointmethod);
public
{ public declarations }
property DataTrace: boolean read fDataTrace write setDataTrace;
property breakpointmethod: TBreakpointMethod read getBreakpointMethod write setBreakpointMethod;
end;
var frmTracerConfig:TfrmTracerConfig;
implementation
{ TfrmTracerConfig }
uses NewKernelHandler, DebugHelper, debuggerinterface, DebuggerInterfaceAPIWrapper,
formsettingsunit, DBVMDebuggerInterface;
function TfrmTracerConfig.getBreakpointmethod: TBreakpointmethod;
begin
if (CurrentDebuggerInterface<>nil) and (CurrentDebuggerInterface is TDBVMDebugInterface) then
exit(bpmDBVMNative);
result:=bpmDebugRegister;
if rbBPHardware.checked then
result:=bpmDebugRegister
else
if rbBPSoftware.checked then
begin
if datatrace=false then
result:=bpmInt3
else
result:=bpmDebugRegister;
end
else
if rbBPException.checked then
result:=bpmException
else
if rbBPDBVM.checked then
result:=bpmDBVM;
end;
procedure TfrmTracerConfig.setBreakPointMethod(m: TBreakpointmethod);
begin
case m of
bpmDebugRegister: rbBPHardware.checked:=true;
bpmInt3: rbBPSoftware.checked:=true;
bpmException: rbBPException.checked:=true;
bpmDBVM: rbBPDBVM.checked:=true;
end;
end;
procedure TfrmTracerConfig.FormCreate(Sender: TObject);
begin
if hasEPTSupport=false then
rbBPDBVM.visible:=false;
rbBPHardware.enabled:=((CurrentDebuggerInterface<>nil) and CurrentDebuggerInterface.usesDebugRegisters) or (formsettings.cbUseDBVMDebugger.checked=false);
rbBPSoftware.enabled:=((CurrentDebuggerInterface<>nil) and (dbcSoftwareBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) and (formsettings.cbKDebug.Checked=false);
rbBPException.enabled:=((CurrentDebuggerInterface<>nil) and (dbcExceptionBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) and (formsettings.cbKDebug.Checked=false);
rbBPDBVM.enabled:=((CurrentDebuggerInterface<>nil) and (dbcDBVMBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) or (formsettings.cbKDebug.Checked);
cbDBVMBreakAndTrace.visible:=isDBVMCapable;
cbDBVMBreakAndTrace.enabled:=isDBVMCapable;
if (CurrentDebuggerInterface=nil) and isRunningDBVM then //no debugger running, go for dbvm by default
cbDBVMBreakAndTrace.Checked:=true;
if (CurrentDebuggerInterface<>nil) and (CurrentDebuggerInterface is TDBVMDebugInterface) or (formSettings.cbUseDBVMDebugger.checked) then
groupbox1.visible:=false;
end;
procedure TfrmTracerConfig.FormShow(Sender: TObject);
begin
// autosize:=false;
end;
procedure TfrmTracerConfig.cbDBVMBreakAndTraceChange(Sender: TObject);
begin
if cbDBVMBreakAndTrace.Checked then
begin
cbStayInsideInitialModule.checked:=false;
cbStayInsideInitialModule.enabled:=false;
cbDBVMTriggerCOW.visible:=true;
cbDereferenceAddresses.enabled:=false;
cbStepOver.enabled:=false;
cbSkipSystemModules.enabled:=false;
groupbox1.enabled:=false;
rbBPHardware.enabled:=false;
rbBPSoftware.enabled:=false;
rbBPException.enabled:=false;
rbBPDBVM.enabled:=false;
Label3.enabled:=false;
edtStartCondition.enabled:=false;
Label2.enabled:=false;
edtStopCondition.enabled:=false;
end
else
begin
cbDBVMTriggerCOW.visible:=formSettings.cbUseDBVMDebugger.checked;
cbDereferenceAddresses.enabled:=true;
cbStepOver.enabled:=true;
cbSkipSystemModules.enabled:=true;
groupbox1.enabled:=true;
rbBPHardware.enabled:=true;
rbBPSoftware.enabled:=((CurrentDebuggerInterface<>nil) and (dbcSoftwareBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) or (formsettings.cbKDebug.Checked=false);
rbBPException.enabled:=((CurrentDebuggerInterface<>nil) and (dbcExceptionBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) or (formsettings.cbKDebug.Checked=false);
rbBPDBVM.enabled:=((CurrentDebuggerInterface<>nil) and (dbcDBVMBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities)) or (formsettings.cbKDebug.Checked);
label3.enabled:=true;
edtStartCondition.enabled:=true;
label2.enabled:=true;
edtStopCondition.enabled:=true;
cbStayInsideInitialModule.enabled:=true;
end;
end;
procedure TfrmTracerConfig.cbStepOverChange(Sender: TObject);
begin
if cbStepOver.checked then
begin
cbStepOverRep.enabled:=false;
cbStepOverRep.checked:=true;
end
else
begin
cbStepOverRep.enabled:=true;
end;
end;
procedure TfrmTracerConfig.FormConstrainedResize(Sender: TObject; var MinWidth,
MinHeight, MaxWidth, MaxHeight: TConstraintSize);
begin
MaxHeight:=panel1.top+panel1.Height+8;
MinHeight:=MaxHeight;
end;
procedure TfrmTracerConfig.setDataTrace(state: boolean);
begin
rbBreakOnAccess.visible:=state;
rbBreakOnWrite.visible:=state;
if state then
begin
btnOk.top:=rbBreakOnAccess.top+rbBreakOnAccess.Height+5;
cbDBVMBreakAndTrace.visible:=false;
cbDBVMBreakAndTrace.Checked:=false;
end
else
btnOk.top:=cbSkipSystemModules.top+cbSkipSystemModules.Height+5;
btnCancel.top:=btnOk.top;
ClientHeight:=btnOK.top+btnOK.Height+3;
rbBPSoftware.Enabled:=(not state) and ((CurrentDebuggerInterface=nil) or (dbcSoftwareBreakpoint in CurrentDebuggerInterface.DebuggerCapabilities));
if state and rbBPSoftware.checked then
rbBPHardware.checked:=true;
fDataTrace:=state;
end;
initialization
{$I frmTracerConfigUnit.lrs}
end.
|
unit wordpress_news_controller;
{$mode objfpc}{$H+}
{$include define.inc}
interface
uses
wordpress_news_model, wordpress_terms_model, wordpress_featuredimage_model,
fpcgi, fastplaz_handler, httpdefs, fpHTTP,
Classes, SysUtils;
type
{ TWPNewsWebModule }
TWPNewsWebModule = class(TMyCustomWebModule)
procedure RequestHandler(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: boolean);
private
NewsTitle: string;
News: TWordpressNews;
Terms: TWordpressTerms;
Featuredimage: TFeaturedimage;
function GetLastNews(FunctionName: string = ''; Parameter: TStrings = nil): string;
function GetRandomNews(FunctionName: string = ''; Parameter: TStrings = nil): string;
function GeneratePagesMenu(ParentMenu: integer; Parameter: TStrings = nil;
ParentBaseURL: string = ''; IsParent: boolean = True): string;
function Tag_MainContent_Handler(const TagName: string; Params: TStringList): string;
public
constructor CreateNew(AOwner: TComponent; CreateMode: integer); override;
destructor Destroy; override;
function View: string;
function GetOptions(const KeyName: string): string;
// Handler / Controller
procedure DoBlockController(Sender: TObject; FunctionName: string; Parameter: TStrings;
var ResponseString: string);
end;
implementation
uses database_lib, common, language_lib, html_lib, theme_controller,
wordpress_options_model, wordpress_nggallery_model, wordpress_pages_model,
wordpress_category_controller;
{ TWPNewsWebModule }
// example:
// http://domain/2014/04/dialog-keajaiban-silat-silat-untuk-kehidupan/
procedure TWPNewsWebModule.RequestHandler(Sender: TObject; ARequest: TRequest; AResponse: TResponse;
var Handled: boolean);
begin
DataBaseInit;
LanguageInit;
Tags['$maincontent'] := @Tag_MainContent_Handler;
Response.Content := ThemeUtil.Render(nil, '', True);
//==================================== YOUR CUSTOM CMS/FRAMEWORK - START ===
{$ifdef wordpress}
{$ifdef wordpress_nggallery}
with TWPNGGallery.Create() do
begin
Response.Content := Render(Response.Content);
Free;
end;
{$endif}
{$endif}
//==================================== YOUR CUSTOM CMS/FRAMEWORK - END ===
Handled := True;
end;
function TWPNewsWebModule.GetLastNews(FunctionName: string; Parameter: TStrings): string;
var
lst: TStringList;
_News: TWordpressNews;
limit: integer;
url, title: string;
s, div_id, div_class, item_class: string;
category_id: integer;
//category_title,
category_permalink: string;
first_news: boolean;
begin
div_id := StringReplace(Parameter.Values['id'], '"', '', [rfReplaceAll]);
div_class := StringReplace(Parameter.Values['class'], '"', '', [rfReplaceAll]);
category_permalink := StringReplace(Parameter.Values['category'], '"', '', [rfReplaceAll]);
category_id := 0;
if category_permalink <> '' then
begin
die('err: category_permalink');
with TWordpressTerms.Create() do
begin
AddJoin( 'term_taxonomy', 'term_id', 'terms.term_id', ['taxonomy']);
FindFirst(['taxonomy="category"', 'slug="' + category_permalink + '"'], 'name');
if RecordCount > 0 then
begin
category_id := Value['term_id'];
//category_title := Value['name'];
end;
Free;
end;
end;
limit := 0;
if Parameter <> nil then
limit := s2i(Parameter.Values['number']);
if limit = 0 then
limit := 20;
_News := TWordpressNews.Create();
if category_id = 0 then
_News.Find(['post_type="post"', 'post_status="publish"'], 'post_date desc', limit)
else
begin
_News.AddJoin( 'term_relationships', 'object_id', 'posts.ID', ['object_id']);
_News.Find(['post_type="post"', 'post_status="publish"', AppData.tablePrefix +
'_term_relationships.term_taxonomy_id=' + i2s(category_id)],
'post_date desc', limit);
end;
if _News.RecordCount > 0 then
begin
lst := TStringList.Create;
lst.Add( '<header class="entry-header">');
lst.Add( '<h1 class="archive-title">Last News:</h1>');
lst.Add( '</header>');
lst.Add( '<article id="post-34" class="post-34 post type-post status-publish format-standard hentry category-general tag-hello"><div class="entry-content ">');
if Parameter <> nil then
if Parameter.Values['title'] <> '' then
begin
title := StringReplace(Parameter.Values['title'], '"', '', [rfReplaceAll]);
lst.Add('<div class="news-lastnews entry-content">');
lst.Add('<h3>' + title + '</h3>');
end;
first_news := True;
item_class := ' class="first-post"';
if div_id <> '' then
lst.Add('<ul id="' + div_id + '" class="' + div_class + '">')
else
lst.Add('<ul class="' + div_class + '">');
while not _News.Data.EOF do
begin
url := '/' + FormatDateTime('YYYY', _News['post_date']) + '/' +
FormatDateTime('mm', _News['post_date']) + '/' + _News['post_name'] + '/';
lst.Add('<li' + item_class + '><a href="' + url + '">' + _News['post_title'] + '</a>');
if Parameter.Values['options'] <> '' then
begin
case Parameter.Values['options'] of
'summary':
begin
s := StripTags(_News['post_content']);
s := StripTagsCustom(s, '[', ']');
s := '<p>' + MoreLess(s) + '</p>';
lst.Add(s);
end;
end;
end;//-- if Parameter.Values['options'] <> ''
lst.Add('</li>');
if first_news then
begin
first_news := False;
item_class := '';
end;
;
_News.Data.Next;
end;
lst.Add('</ul>');
if Parameter.Values['title'] <> '' then
lst.Add('</div>');
lst.Add( '</div></article>');
Result := lst.Text;
FreeAndNil(lst);
end;
FreeAndNil(_News);
end;
function TWPNewsWebModule.GetRandomNews(FunctionName: string; Parameter: TStrings): string;
var
lst: TStringList;
_News: TWordpressNews;
limit: integer;
url, title: string;
div_class: string;
begin
div_class := StringReplace(Parameter.Values['class'], '"', '', [rfReplaceAll]);
;
limit := 0;
if Parameter <> nil then
limit := s2i(Parameter.Values['number']);
if limit = 0 then
limit := 20;
_News := TWordpressNews.Create();
_News.Find(['post_type="post"', 'post_status="publish"'], 'rand()', limit);
if _News.RecordCount > 0 then
begin
lst := TStringList.Create;
if Parameter <> nil then
if Parameter.Values['title'] <> '' then
begin
lst.Add('<div class="news-lastnews">');
title := StringReplace(Parameter.Values['title'], '"', '', [rfReplaceAll]);
lst.Add('<h3>' + title + '</h3>');
end;
lst.Add('<ul class="' + div_class + '">');
while not _News.Data.EOF do
begin
url := '/' + FormatDateTime('YYYY', _News['post_date'].AsDateTime) + '/' +
FormatDateTime('mm', _News['post_date'].AsDateTime) + '/' + _News['post_name'].AsString + '/';
lst.Add('<li><a href="' + url + '">' + _News['post_title'].AsString + '</a></li>');
_News.Next;
end;
lst.Add('</ul>');
if Parameter.Values['title'] <> '' then
lst.Add('</div>');
Result := lst.Text;
FreeAndNil(lst);
end;
FreeAndNil(_News);
end;
function TWPNewsWebModule.GeneratePagesMenu(ParentMenu: integer; Parameter: TStrings;
ParentBaseURL: string; IsParent: boolean): string;
var
where, html, title, submenu, url, page_item_has_children: string;
nav_id, nav_class: string;
begin
nav_id := StringReplace(Parameter.Values['id'], '"', '', [rfReplaceAll]);
nav_class := StringReplace(Parameter.Values['class'], '"', '', [rfReplaceAll]);
if nav_id = '' then
nav_id := 'nav';
with TWordpressPages.Create() do
begin
{$ifdef wordpress_polylang}
if Config.GetValue(_WORDPRESS_PLUGINS_POLYLANG, False) then
begin
AddJoin('term_relationships', 'object_id', 'posts.ID', ['term_taxonomy_id']);
AddJoin('terms', 'term_id', 'term_relationships.term_taxonomy_id', ['slug']);
where := AppData.tablePrefix + 'terms.slug = "' + LANG + '"';
end;
{$endif}
Find(['post_type="page"', 'post_status="publish"', 'post_parent=' + i2s(ParentMenu), where],
'post_parent, menu_order', 0,
'ID,post_title,post_name,post_parent');
if RecordCount > 0 then
begin
if ((Parameter.Values['header'] <> '') and (ParentMenu = 0)) then
html := Parameter.Values['header'];
if ((Parameter.Values['type'] = 'nav') and (ParentMenu = 0)) then
html := html + '<nav>';
if Parameter.Values['type'] = 'nav' then
begin
if IsParent then
begin
html := html + #13#10'<ul id="' + nav_id + '" class="' + nav_class + '">';
html := html + #13#10' <li><a href="' + BaseURL + '" class="on">' + __('Home') + '</a></li>';
end
else
begin
html := html + #13#10'<ul class="children sub-menu">';
end;
end;
while not Data.EOF do
begin
submenu := '';
title := '';
url := '#';
submenu := GeneratePagesMenu(Value['ID'], Parameter, ParentBaseURL + Value['post_name'] + '/', False);
if submenu = '' then
page_item_has_children := ''
else
page_item_has_children := 'menu-item-has-children';
if Parameter.Values['type'] = 'nav' then
begin
if IsParent then
begin
html := html + #13#10'<li id="menu-item-' + string(Value['ID']) +
'" class="menu-item ' + page_item_has_children + '">';
end
else
begin
html := html + #13#10' <li id="menu-item-' + string(Value['ID']) +
'" class="menu-item ' + page_item_has_children + '">';
end;
end;
title := Value['post_title'];
url := BaseURL + 'pages/' + ParentBaseURL + Value['post_name'];
html := html + '<a href="' + url + '">' + title + '</a>' + submenu;
if Parameter.Values['type'] = 'nav' then
html := html + '</li>';
Data.Next;
end;
Parameter.Values['parent_baseurl'] := '';
if Parameter.Values['type'] = 'nav' then
html := html + #13#10'</ul>';
if ((Parameter.Values['type'] = 'nav') and (ParentMenu = 0)) then
html := html + #13#10'</nav>';
if ((Parameter.Values['footer'] <> '') and (ParentMenu = 0)) then
html := html + Parameter.Values['footer'];
end;
Free;
Result := html;
end;
end;
constructor TWPNewsWebModule.CreateNew(AOwner: TComponent; CreateMode: integer);
begin
inherited CreateNew(AOwner, CreateMode);
CreateSession := True;
OnRequest := @RequestHandler;
OnBlockController := @DoBlockController;
News := TWordpressNews.Create();
Terms := TWordpressTerms.Create();
Featuredimage := TFeaturedimage.Create();
end;
destructor TWPNewsWebModule.Destroy;
begin
FreeAndNil(Featuredimage);
FreeAndNil(Terms);
FreeAndNil(News);
inherited Destroy;
end;
function TWPNewsWebModule.View: string;
var
thumbnail_url, title: string;
lst : TStringList;
begin
if Application.Request.QueryString = '' then
begin
lst := TStringList.Create;
Result := GetLastNews('', lst);
FreeAndNil( lst);
Exit;
end;
News.AddJoin( 'users', 'ID', 'posts.post_author', ['display_name']);
News.Find(['date_format( post_date, "%Y%m") = "' + _GET['year'] + _GET['month'] + '"',
'post_status="publish"', 'post_type="post"', 'post_name = "' + _GET['permalink'] + '"'],
AppData.tablePrefix + 'posts.post_date DESC');
if News.RecordCount = 0 then
begin
Result := H2(__(__Content_Not_Found));
Exit;
end;
Terms.GetObjectTerms(News['ID'], ['post_tag']);
thumbnail_url := Featuredimage.GetFeaturedImageURLByID(News['ID']);
if thumbnail_url = '' then
thumbnail_url := Config.GetValue('wordpress/base_url', '') + '/logo.png'
else
begin
thumbnail_url := Config.GetValue('wordpress/base_url', '') + Config.GetValue('wordpress/path', '') +
'/' + thumbnail_url;
ThemeUtil.Assign('featured_image', thumbnail_url);
end;
ThemeUtil.Assign('$news', @News.Data);
ThemeUtil.Assign('$terms', @Terms.Data);
//or use this : ThemeUtil.AssignVar['$news'] := @News.Data;
// facebook content sharing
title := News['post_title'];
ThemeUtil.AddMeta('og:type', 'article', 'property');
ThemeUtil.AddMeta('og:title', title, 'property');
ThemeUtil.AddMeta('og:site_name', GetOptions('blogname'), 'property');
ThemeUtil.AddMeta('og:description', GetOptions('blogdescription') + ', ' + title, 'property');
ThemeUtil.AddMeta('og:image', thumbnail_url, 'property');
// facebook content sharing - end
Result := ThemeUtil.RenderFromContent(@TagController, '', 'modules/wpnews/detail.html');
News.AddHit(News['ID']);
end;
function TWPNewsWebModule.GetOptions(const KeyName: string): string;
begin
with TWordpressOptions.Create() do
begin
FindFirst(['option_name="' + KeyName + '"'], '', 'option_value');
if RecordCount > 0 then
begin
Result := Value['option_value'];
end;
Free;
end;
end;
function TWPNewsWebModule.Tag_MainContent_Handler(const TagName: string; Params: TStringList): string;
begin
Result := View;
end;
procedure TWPNewsWebModule.DoBlockController(Sender: TObject; FunctionName: string;
Parameter: TStrings; var ResponseString: string);
begin
case FunctionName of
'getoption':
begin
ResponseString := GetOptions(Parameter.Values['name']);
end;
'newstitle':
begin
if _GET['permalink'] <> '' then
begin
if NewsTitle = '' then
begin
with TWordpressNews.Create() do
begin
FindFirst(['date_format( post_date, "%Y%m") = "' + _GET['year'] + _GET['month'] +
'"', 'post_status="publish"', 'post_type="post"', 'post_name = "' + _GET['permalink'] + '"'],
'', 'post_title');
if RecordCount > 0 then
begin
NewsTitle := Value['post_title'];
end;
Free;
end;
end;
if NewsTitle <> '' then
ResponseString := ' - ' + NewsTitle;
end;
end; //-- newstitle
'lastnews':
begin
ResponseString := GetLastNews(FunctionName, Parameter);
end;
'randomnews':
begin
ResponseString := GetRandomNews(FunctionName, Parameter);
end;
'pagesmenu':
begin
ResponseString := GeneratePagesMenu(0, Parameter);
end;
end;
end;
{$ifdef wordpress}
initialization
Route.Add('wpnews', TWPNewsWebModule);
{$endif}
end.
|
unit uSQLGenerator;
interface
uses
System.SysUtils, uTypes, System.Variants, uUtils;
type
TSQLGenerator = class
private
public
class function fpuFilterInteger(ipWhere, ipTabela, ipCampo: string; ipValor: Integer; ipOperador: String = ' And '): string; overload;
class function fpuFilterInteger(ipWhere, ipTabela, ipCampo: string; ipValores: Array of Integer): string; overload;
class function fpuFilterInteger(ipWhere, ipTabela, ipCampo: string; ipValores: Array of Integer; ipOperador: String): string; overload;
class function fpuFilterInteger(ipWhere: string; ipTabelas, ipCampos: Array of string; ipValores: array of TArray<Integer>;
ipOperadorEntre, ipOperadorApos: String): string; overload;
class function fpuFilterString(ipWhere, ipTabela, ipCampo, ipValor, ipOperador: string): string; overload;
class function fpuFilterString(ipWhere, ipTabela, ipCampo, ipValor: string; ipStartWith, ipEndWith: Boolean; ipOperador: String): string;
overload;
class function fpuFilterData(ipWhere, ipTabela, ipCampo: string; ipDataInicial, ipDataFinal: TDateTime; ipOperador: String): string;
class function fpuFilterDataSemHora(ipWhere, ipTabela, ipCampo: string;
ipDataInicial, ipDataFinal: TDateTime; ipOperador: String): string;
end;
implementation
{ TSQLGenerator }
class function TSQLGenerator.fpuFilterString(ipWhere, ipTabela, ipCampo, ipValor, ipOperador: string): string;
begin
Result := TSQLGenerator.fpuFilterString(ipWhere, ipTabela, ipCampo, ipValor, true, false, ipOperador);
end;
class function TSQLGenerator.fpuFilterInteger(ipWhere, ipTabela,
ipCampo: string; ipValores: Array of Integer): string;
begin
Result := TSQLGenerator.fpuFilterInteger(ipWhere, ipTabela, ipCampo, ipValores, TOperadores.coAnd);
end;
class function TSQLGenerator.fpuFilterData(ipWhere, ipTabela, ipCampo: string;
ipDataInicial, ipDataFinal: TDateTime; ipOperador: String): string;
var
vaDataInicial, vaDataFinal: string;
begin
vaDataInicial := QuotedStr(FormatDateTime('dd.mm.yyyy 00:00:00', ipDataInicial));
vaDataFinal := QuotedStr(FormatDateTime('dd.mm.yyyy 23:59:59', ipDataFinal));
if ipWhere <> '' then
Result := Format('(%s (%s.%s between %s and %s)) %s', [ipWhere, ipTabela, ipCampo, vaDataInicial, vaDataFinal, ipOperador])
else
Result := Format('(%s.%s between %s and %s) %s', [ipTabela, ipCampo, vaDataInicial, vaDataFinal, ipOperador]);
end;
class function TSQLGenerator.fpuFilterDataSemHora(ipWhere, ipTabela, ipCampo: string;
ipDataInicial, ipDataFinal: TDateTime; ipOperador: String): string;
var
vaDataInicial, vaDataFinal: string;
begin
vaDataInicial := QuotedStr(FormatDateTime('dd.mm.yyyy', ipDataInicial));
vaDataFinal := QuotedStr(FormatDateTime('dd.mm.yyyy', ipDataFinal));
if ipWhere <> '' then
Result := Format('(%s (%s.%s between %s and %s)) %s', [ipWhere, ipTabela, ipCampo, vaDataInicial, vaDataFinal, ipOperador])
else
Result := Format('(%s.%s between %s and %s) %s', [ipTabela, ipCampo, vaDataInicial, vaDataFinal, ipOperador]);
end;
class
function TSQLGenerator.fpuFilterInteger(ipWhere, ipTabela,
ipCampo: string; ipValores: Array of Integer; ipOperador: String): string;
var
vaCodigos: string;
begin
vaCodigos := TUtils.fpuMontarStringCodigo(ipValores, ',');
if ipWhere <> '' then
Result := Format('(%s (%s.%s in (%s) )) %s', [ipWhere, ipTabela, ipCampo, vaCodigos, ipOperador])
else
Result := Format('(%s.%s in (%s)) %s', [ipTabela, ipCampo, vaCodigos, ipOperador]);
end;
class
function TSQLGenerator.fpuFilterInteger(ipWhere, ipTabela,
ipCampo: string; ipValor: Integer; ipOperador: String): string;
begin
if ipWhere <> '' then
Result := Format('(%s (%s.%s = %d)) %s', [ipWhere, ipTabela, ipCampo, ipValor, ipOperador])
else
Result := Format('(%s.%s = %d) %s', [ipTabela, ipCampo, ipValor, ipOperador])
end;
class
function TSQLGenerator.fpuFilterString(ipWhere, ipTabela, ipCampo, ipValor: string;
ipStartWith, ipEndWith: Boolean; ipOperador: String): string;
var
vaFilter: string;
begin
vaFilter := ipValor;
if ipStartWith then
vaFilter := vaFilter + '%';
if ipEndWith then
vaFilter := '%' + vaFilter;
if ipWhere <> '' then
Result := Format('(%s (%s.%s like %s)) %s', [ipWhere, ipTabela, ipCampo, QuotedStr(vaFilter), ipOperador])
else
Result := Format('(%s.%s like %s) %s', [ipTabela, ipCampo, QuotedStr(vaFilter), ipOperador])
end;
class function TSQLGenerator.fpuFilterInteger(ipWhere: string; ipTabelas, ipCampos: array of string;
ipValores: array of TArray<Integer>;
ipOperadorEntre, ipOperadorApos: String): string;
var
vaCodigos: string;
i: Integer;
begin
Result := ipWhere;
for i := Low(ipCampos) to High(ipCampos) do
begin
vaCodigos := TUtils.fpuMontarStringCodigo(ipValores[i], ',');
if i > 0 then
Result := Format('%s %s (%s.%s in (%s))', [Result, ipOperadorEntre, ipTabelas[i], ipCampos[i], vaCodigos])
else
Result := Format('(%s.%s in (%s))', [ipTabelas[i], ipCampos[i], vaCodigos])
end;
Result := ipWhere + '(' + Result + ') ' + ipOperadorApos;
end;
end.
|
unit Marvin.VCL.GUI.Cadastro.Cliente;
interface
uses
{ marvin }
Marvin.AulaMulticamada.Classes.Cliente,
Marvin.AulaMulticamada.Listas.Cliente,
Marvin.AulaMulticamada.Classes.TipoCliente,
Marvin.AulaMulticamada.Listas.TipoCliente,
Marvin.VCL.GUI.Cadastro.Base,
{ embarcdero }
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Actions,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtActns,
Vcl.ActnList,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.WinXCtrls,
Vcl.Buttons,
Vcl.ToolWin,
Vcl.WinXCalendars;
type
TMRVFrameCadastroCliente = class(TMRVFrameCadastroBase)
PN_TituloInformacoesBasicas: TPanel;
PN_InformacoesBasicas: TPanel;
LE_Codigo: TLabeledEdit;
LE_Nome: TLabeledEdit;
PN_TituloOutrasInformacoes: TPanel;
PN_OutrasInformacoes: TPanel;
DT_DataCadastro: TDateTimePicker;
LB_DataHoraCadastro: TLabel;
DT_HoraCadastro: TDateTimePicker;
LE_NumeroDocumento: TLabeledEdit;
CB_TipoCliente: TComboBox;
LB_TipoCliente: TLabel;
private
FCliente: TMRVCliente;
FListaClientes: TMRVListaCliente;
FListaTiposCliente: TMRVListaTipoCliente;
procedure DoGetClientes;
procedure DoShowClientes;
protected
{ métodos de dados }
procedure GetTiposCliente;
procedure SetTiposCliente;
procedure DoCarregarDadosAuxiliares;
{ métodos de interface GUI }
procedure DoRefresh; override;
procedure DoSalvar; override;
procedure DoExcluir; override;
procedure DoInterfaceToObject(const AItem: TListItem); override;
procedure DoObjectToInterface;
procedure DoGetFromInterface;
function DoGetTipoClienteFromInterface: Integer;
function DoGetPositionTipoCliente: Integer;
procedure DoInitInterface; override;
procedure DoInit; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Cliente: TMRVCliente read FCliente;
end;
var
MRVFrameCadastroCliente: TMRVFrameCadastroCliente;
implementation
{$R *.dfm}
{ TMRVFrameCadastroCliente }
constructor TMRVFrameCadastroCliente.Create(AOwner: TComponent);
begin
inherited;
FCliente := TMRVCliente.Create;
FListaClientes := TMRVListaCliente.Create;
FListaTiposCliente := TMRVListaTipoCliente.Create;
end;
destructor TMRVFrameCadastroCliente.Destroy;
begin
FreeAndNil(FListaTiposCliente);
FreeAndNil(FListaClientes);
FreeAndNil(FCliente);
inherited;
end;
procedure TMRVFrameCadastroCliente.DoCarregarDadosAuxiliares;
begin
{ faz a carga dos dados no combobox de tipos de cliente }
Self.GetTiposCliente;
Self.SetTiposCliente;
end;
procedure TMRVFrameCadastroCliente.DoExcluir;
var
LMensagem: string;
LCliente: TMRVCliente;
begin
inherited;
LCliente := TMRVCliente.Create;
try
LCliente.Assign(FCliente);
{ manda o ClientModule excluir }
LMensagem := Self.ClientClasses.ClientesExcluir(LCliente);
finally
LCliente.DisposeOf;
end;
Self.ShowMessageBox(LMensagem);
{ atualiza a lista }
Self.DoRefresh;
{ muda para a aba de lista }
AT_Lista.ExecuteTarget(TS_Lista);
end;
procedure TMRVFrameCadastroCliente.DoGetClientes;
var
LCliente: TMRVCliente;
LListaClientes: TMRVListaCliente;
begin
LListaClientes := nil;
{ recupera os dados para o listview }
LCliente := TMRVCliente.Create;
try
{ pede para o ClientModule recuperar os tipos de clientes cadastrados }
LListaClientes := Self.ClientClasses.ClientesProcurarItens(LCliente) as
TMRVListaCliente;
{ limpa a lista }
if Assigned(LListaClientes) then
begin
FListaClientes.Clear;
FListaClientes.AssignObjects(LListaClientes);
LListaClientes.Free;
end;
finally
LCliente.Free;
end;
end;
procedure TMRVFrameCadastroCliente.DoGetFromInterface;
var
LId: Integer;
begin
LId := 0;
if (Trim(LE_Codigo.Text) <> EmptyStr) then
begin
LId := StrToInt(LE_Codigo.Text);
end;
{ recupera os dados da GUI }
FCliente.Clienteid := LId;
FCliente.Nome := LE_Nome.Text;
FCliente.Numerodocumento := LE_NumeroDocumento.Text;
FCliente.Datahoracadastro := DT_DataCadastro.Date + DT_HoraCadastro.Time;
{ recupera o tipo do cliente }
FCliente.TipoClienteId := Self.DoGetTipoClienteFromInterface;
end;
function TMRVFrameCadastroCliente.DoGetPositionTipoCliente: Integer;
var
LIndex: Integer;
LTipoCliente: TMRVTipoCliente;
LResult: Integer;
begin
LResult := -1;
for LIndex := 0 to FListaTiposCliente.Count - 1 do
begin
FListaTiposCliente.ProcurarPorIndice(LIndex, LTipoCliente);
if LTipoCliente.TipoClienteId = FCliente.TipoClienteId then
begin
LResult := LIndex;
Break;
end;
end;
Result := LResult;
end;
function TMRVFrameCadastroCliente.DoGetTipoClienteFromInterface: Integer;
var
LTipoCliente: TMRVTipoCliente;
begin
Result := 0;
if CB_TipoCliente.ItemIndex >= 0 then
begin
FListaTiposCliente.ProcurarPorIndice(CB_TipoCliente.ItemIndex, LTipoCliente);
Result := LTipoCliente.TipoClienteId;
end;
end;
procedure TMRVFrameCadastroCliente.DoInit;
begin
inherited;
end;
procedure TMRVFrameCadastroCliente.DoInitInterface;
begin
inherited;
{ limpa }
LE_Codigo.Text := EmptyStr;
LE_Nome.Text := EmptyStr;
LE_NumeroDocumento.Text := EmptyStr;
DT_DataCadastro.Date := Now;
DT_HoraCadastro.Time := Time;
{ vai para o index inicial }
if CB_TipoCliente.Items.Count > 0 then
begin
CB_TipoCliente.ItemIndex := -1;
end;
{ ajusta }
LE_Codigo.Enabled := False;
LE_Nome.SetFocus;
{ carrega dados auxiliares }
Self.DoCarregarDadosAuxiliares;
end;
procedure TMRVFrameCadastroCliente.DoInterfaceToObject(const AItem: TListItem);
var
LCliente: TMRVCliente;
begin
inherited;
{ recupera }
FCliente.Clear;
FCliente.ClienteId := AItem.Caption.ToInteger;
FCliente.Nome := AItem.SubItems[0];
{ recupera os dados da lista }
FListaClientes.ProcurarPorChave(FCliente.GetKey, LCliente);
FCliente.Assign(LCliente);
{ carrega dados auxiliares }
Self.DoCarregarDadosAuxiliares;
{ exibe }
Self.DoObjectToInterface;
end;
procedure TMRVFrameCadastroCliente.DoObjectToInterface;
begin
LE_Codigo.Text := FCliente.Clienteid.ToString;
LE_Nome.Text := FCliente.Nome;
LE_NumeroDocumento.Text := FCliente.Numerodocumento;
DT_DataCadastro.Date := FCliente.Datahoracadastro;
DT_HoraCadastro.Time := FCliente.Datahoracadastro;
{ carrega o combo tipos de cliente }
CB_TipoCliente.ItemIndex := Self.DoGetPositionTipoCliente;
end;
procedure TMRVFrameCadastroCliente.DoRefresh;
begin
inherited;
{ carrega a lista de clientes no listview }
Self.DoGetClientes;
{ exibe os dados }
Self.DoShowClientes;
end;
procedure TMRVFrameCadastroCliente.DoSalvar;
var
LCliente: TMRVCliente;
begin
inherited;
LCliente := nil;
Self.DoGetFromInterface;
case Self.EstadoCadastro of
ecNovo:
begin
{ manda o ClientModule incluir }
LCliente := Self.ClientClasses.ClientesInserir(FCliente) as TMRVCliente;
Self.EstadoCadastro := ecAlterar;
end;
ecAlterar:
begin
{ manda o ClientModule alterar }
LCliente := Self.ClientClasses.ClientesAlterar(FCliente) as TMRVCliente;
end;
end;
try
FCliente.Assign(LCliente);
{ exibe a resposta }
Self.DoObjectToInterface;
finally
{ libera o retorno }
LCliente.DisposeOf;
end;
end;
procedure TMRVFrameCadastroCliente.DoShowClientes;
var
LCont: Integer;
LItem: TListItem;
LCliente: TMRVCliente;
begin
LV_Lista.Items.BeginUpdate;
try
{ limpa o listview }
LV_Lista.Items.Clear;
for LCont := 0 to FListaClientes.Count - 1 do
begin
FListaClientes.ProcurarPorIndice(LCont, LCliente);
{ exibe na lista }
LItem := LV_Lista.Items.Add;
LItem.Caption := LCliente.ClienteId.ToString;
LItem.SubItems.Add(LCliente.Nome);
end;
finally
LV_Lista.Items.EndUpdate;
end;
{ carrega dados auxiliares }
Self.DoCarregarDadosAuxiliares;
end;
procedure TMRVFrameCadastroCliente.GetTiposCliente;
var
LTipoCliente: TMRVTipoCliente;
LTiposCliente: TMRVListaTipoCliente;
begin
LTipoCliente := TMRVTipoCliente.Create;
try
{ recupera os tipos de cliente no ClientModule }
LTiposCliente := Self.ClientClasses.TiposClienteProcurarItens(LTipoCliente)
as TMRVListaTipoCliente;
try
FListaTiposCliente.Clear;
FListaTiposCliente.AssignObjects(LTiposCliente);
finally
LTiposCliente.DisposeOf;
end;
finally
LTipoCliente.DisposeOf;
end;
end;
procedure TMRVFrameCadastroCliente.SetTiposCliente;
var
LCont: Integer;
LTipoCliente: TMRVTipoCliente;
begin
{ limpa os itens }
CB_TipoCliente.Items.Clear;
CB_TipoCliente.Enabled := False;
try
{ adiciona os itens da lista de objetos }
for LCont := 0 to FListaTiposCliente.Count - 1 do
begin
FListaTiposCliente.ProcurarPorIndice(LCont, LTipoCliente);
CB_TipoCliente.Items.Add(LTipoCliente.GetKey);
end;
finally
CB_TipoCliente.Enabled := True;
end;
end;
end.
|
unit uVehicles;
interface
uses
System.SysUtils
;
type
TVehicle = class abstract
procedure Go; virtual; abstract;
end;
{$REGION 'GasVehicle'}
TGasVehicle = class abstract(TVehicle)
procedure FillWithGas; virtual; abstract;
end;
{$ENDREGION}
TCar = class(TGasVehicle )
procedure Go; override;
procedure FillWithGas; override;
end;
TTruck = class(TGasVehicle)
procedure Go; override;
procedure FillWithGas; override;
end;
TBicycle = class(TVehicle)
procedure Go; override;
end;
procedure FillVehiclesWithGas;
implementation
uses
Spring.Collections
;
procedure FillVehiclesWithGas;
var
LVehicle: TVehicle;
LVehicles: IList<TVehicle>;
begin
LVehicles := TCollections.CreateList<TVehicle>;
LVehicles.Add(TCar.Create);
LVehicles.Add(TTruck.Create);
LVehicles.Add(TBicycle.Create);
for LVehicle in LVehicles do
begin
LVehicle.FillWithGas;
LVehicle.Free;
end;
end;
{$REGION 'BigIf'}
//procedure FillWithGas(aVehicle: TVehicle);
//begin
// if (aVehicle is TCar)then
// begin
// TCar(aVehicle).FillWithGas;
// end else
// begin
// if (aVehicle is TTruck) then
// begin
// TTruck(aVehicle).FillWithGas;
// end else
// begin
// raise Exception.Create('Can''t fill this vehicle with gas.');
// end;
// end
//end;
{$ENDREGION}
{ TCar }
procedure TCar.FillWithGas;
begin
WriteLn('Fill with unleaded');
end;
procedure TCar.Go;
begin
WriteLn('Step on accelerator and steer');
end;
{ TBicycle }
procedure TBicycle.Go;
begin
WriteLn('Start pedaling and steer');
end;
{ TTruck }
procedure TTruck.FillWithGas;
begin
Writeln('Fill with diesel');
end;
procedure TTruck.Go;
begin
WriteLn('Put in gear, press accellerator and steer');
end;
end.
|
unit MainWindow_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, datModule_u;
type
TMainWindow = class(TForm)
btnClose: TBitBtn;
btnLogout: TButton;
grpStats: TGroupBox;
Label1: TLabel;
Label2: TLabel;
lblInfected: TLabel;
lblHighScore: TLabel;
pnlStart: TPanel;
imgSpam: TImage;
pnlStats: TPanel;
pnlFakeExit: TPanel;
svStats: TSaveDialog;
Label3: TLabel;
Label4: TLabel;
pnlEasy: TPanel;
pnlHard: TPanel;
pnlMedium: TPanel;
procedure FormCreate(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnLogoutClick(Sender: TObject);
procedure pnlStartClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pnlStatsClick(Sender: TObject);
procedure pnlFakeExitClick(Sender: TObject);
procedure pnlEasyClick(Sender: TObject);
procedure pnlMediumClick(Sender: TObject);
procedure pnlHardClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
loggedOut : boolean;
end;
var
MainWindow: TMainWindow;
implementation
{$R *.dfm}
uses GameWindow_u, Login_u;
procedure TMainWindow.FormCreate(Sender: TObject);
begin
self.Width := Screen.Width;
self.Height := Screen.Height;
self.imgSpam.Picture.LoadFromFile('rsc\spam.bmp');
end;
procedure TMainWindow.btnCloseClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TMainWindow.btnLogoutClick(Sender: TObject);
begin
self.Hide;
LoginScreen.Show;
end;
procedure TMainWindow.pnlStartClick(Sender: TObject);
begin
self.pnlEasy.Show;
self.pnlMedium.Show;
self.pnlHard.Show;
self.pnlStart.Hide;
self.pnlStats.Hide;
self.pnlFakeExit.Hide;
self.btnClose.Hide;
self.btnLogout.Hide;
end;
procedure TMainWindow.FormShow(Sender: TObject);
begin
self.lblInfected.Caption := datModule.tblUsers['Infections'];
self.lblHighScore.Caption := datModule.tblUsers['HighScore'];
self.pnlEasy.Hide;
self.pnlMedium.Hide;
self.pnlHard.Hide;
self.pnlStart.Show;
self.pnlStats.Show;
self.pnlFakeExit.Show;
self.btnClose.Show;
self.btnLogout.Show;
end;
procedure TMainWindow.pnlStatsClick(Sender: TObject);
var
tfile : TextFile;
begin
svStats.FileName := datModule.tblUsers['Username'] + ' - stats.txt';
svStats.Execute;
AssignFile(tfile, svStats.FileName);
Rewrite(tfile);
Writeln(tfile, 'Username: ' + datModule.tblUsers['Username']);
Writeln(tfile, 'How to get rich fast and easy - goto www.scam.com');
Writeln(tfile, 'High score: ' + floattostr(datModule.tblUsers['HighScore']));
Writeln(tfile, 'Russian brides in your area - click here to meet them');
Writeln(tfile, 'Time infected with ads and the like: ' + floattostr(datModule.tblUsers['Infections']));
if datModule.tblUsers['Infections'] > 20 then
Writeln(tfile, 'Sufficient training - This person will survive on the Internet')
else
Writeln(tfile, 'Insufficient training - This person will probably get a virus');
CloseFile(tfile);
MessageDlg('User statistics exported to ''' + svStats.FileName + '''', mtInformation, [mbOK], 0);
end;
procedure TMainWindow.pnlFakeExitClick(Sender: TObject);
begin
MessageDlg('Please stop pressing big buttons. Please', mtError, [mbNo], 0);
end;
procedure TMainWindow.pnlEasyClick(Sender: TObject);
begin
GameWindow.START_TIME := 30000;
self.Hide;
GameWindow.Show;
end;
procedure TMainWindow.pnlMediumClick(Sender: TObject);
begin
GameWindow.START_TIME := 20000;
self.Hide;
GameWindow.Show;
end;
procedure TMainWindow.pnlHardClick(Sender: TObject);
begin
GameWindow.START_TIME := 10000;
self.Hide;
GameWindow.Show;
end;
procedure TMainWindow.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.Terminate;
end;
end.
|
unit DmSrvObjects;
interface
uses
System.SysUtils, System.Classes, System.Contnrs, DmSrvDoc, DmMain, ServerDocSqlManager, rtcInfo, rtcConn, CommonInterface,
fbapidatabase, fbapiquery, QueryUtils, vkvariable;
const
_VARATTR = 'f_';
_VARATTR2 = 'fname_';
FLD_IDATTRIBUTE = 'idattribute';
FLD_NUMBERVIEW = 'numberview';
FLD_NUMBEREDIT = 'numberedit';
FLD_ATTRIBUTETYPE = 'attributetype';
FLD_ATTRIBUTENAME = 'attribute_name';
FLD_IDGROUP = 'idgroup';
FLD_IDOBJECT = 'idobject';
FLD_VAL = 'val';
FLD_SET_NAME = 'set_name';
TBL_ATTRIBUTESOFOBJECT = 'ATTRIBUTESOFOBJECT';
type
TAttributeDescr = class(TObject)
private
FId: Int64;
FName: String;
public
property Name:String read FName write FName;
property Id:Int64 read FId write FId;
end;
TAttributesDocSqlManager = class(TServerDocSqlManager)
private
FFieldList: TStringList;
FObjectList: TObjectList;
public
constructor Create;override;
destructor Destroy;override;
property FieldList: TStringList read FFieldList;
property ObjectList:TObjectList read FObjectList;
end;
TSrvObjectsDm = class(TSrvDocDm)
private
{ Private declarations }
function GetAttributesDocSqlManager(ADmMain: TMainDm): TAttributesDocSqlManager;
procedure prepareAttributesOfGroup(ADmMain: TMainDm;sqlManager: TAttributesDocSqlManager; idgroup:LargeInt);
public
{ Public declarations }
procedure RtcObjectEdit(AMainDm:TMainDm; FnParams: TRtcFunctionInfo; Result: TRtcValue);
end;
var
SrvObjectsDm: TSrvObjectsDm;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TSrvObjectsDm }
function TSrvObjectsDm.GetAttributesDocSqlManager(ADmMain: TMainDm): TAttributesDocSqlManager;
begin
Result := TAttributesDocSqlManager.Create;
ADmMain.GetSQLTableProperties(TBL_ATTRIBUTESOFOBJECT, Result.SQLTableProperties);
end;
procedure TSrvObjectsDm.prepareAttributesOfGroup(ADmMain: TMainDm; sqlManager: TAttributesDocSqlManager; idgroup: LargeInt);
var
fbQuery: TFbApiQuery;
id_attr: LargeInt;
_adescr : TAttributeDescr;
i: Integer;
begin
fbQuery := ADmMain.GetNewQuery;
try
i:=1;
sqlManager.FieldList.Clear;
sqlManager.ObjectList.Clear;
with fbQuery do
begin
SQL.Clear;
SQL.Add('SELECT ag.*, gr.name as group_name, al.name as attribute_name, s.name as set_name,');
SQL.Add('al.attributetype, al.nlen, al.ndec, al.isunique, al.notempty, ua.iduavalue');
SQL.Add('FROM attributesofgroup ag');
SQL.Add('LEFT OUTER JOIN objects gr ON gr.idobject=ag.idgroup');
SQL.Add('LEFT OUTER JOIN attributelist al ON al.idattribute=ag.idattribute');
SQL.Add('LEFT OUTER JOIN attributeset s ON s.idset=ag.idset');
SQL.Add('LEFT JOIN usersaccess ua ON ua.iduatype = :iduatype AND ua.iduser=:iduser AND ua.iditem = al.idattribute');
SQL.Add('WHERE ag.idgroup=:idgroup AND ( pkg_common.IsUserAdmin(:iduser) or ua.iduavalue>0)');
SQL.Add('ORDER BY numberedit, set_name');
ParamByName('idgroup').AsInt64 := idgroup;
ParamByName('iduser').AsInt64 := ADmMain.CurrentUser.id_user;
ParamByName('iduatype').AsInt64 := 0;
ExecQuery;
while not Eof do
begin
id_attr := FieldByName('idattribute').AsInt64;
_adescr := TAttributeDescr.Create;
_adescr.Id := id_attr;
_adescr.Name := _VARATTR+IntToStr(i);
SqlManager.ObjectList.Add(_adescr);
SqlManager.FieldList.AddObject(_VARATTR+IntToStr(i),_adescr);
Next;
Inc(i);
end;
end;
finally
FreeAndNil(fbQuery);
end;
end;
procedure TSrvObjectsDm.RtcObjectEdit(AMainDm:TMainDm; FnParams: TRtcFunctionInfo; Result: TRtcValue);
var fbQuery: TFbApiQuery;
fbQueryLock: TFbApiQuery;
tr: TFbApiTransaction;
objectsSqlManager: TServerDocSqlManager;
attributesSqlManager: TAttributesDocSqlManager;
tablename: String;
new_params: TVkVariableCollection;
old_params: TVkVariableCollection;
key_params: TVkVariableCollection;
operation: TDocOperation;
i:Integer;
//AMainDm: TMainDm;
mUserName: String;
mPassword: String;
idgroup: LargeInt;
idobject: LargeInt;
isEmpty: Boolean;
procedure LockDoc(sqlManager: TServerDocSqlManager);
begin
if operation <> docInsert then
begin
fbQueryLock := AMainDm.GetNewQuery(tr);
fbQueryLock.SQL.Text := sqlManager.GenerateLockSQL;
TQueryUtils.SetQueryParams(fbQueryLock, key_params);
fbQueryLock.ExecQuery;
end;
end;
procedure UnLockDoc;
begin
if (operation <> docInsert) and Assigned(fbQueryLock) then
begin
fbQueryLock.Close;
fbQueryLock.Free;
end;
end;
{*procedure docAction(sqlManager: TServerDocSqlManager; new_params );
begin
end;*}
procedure UpdateAttributes(idobject: LargeInt);
var qr: TFbApiQuery;
i,k: Integer;
idattr: LargeInt;
val: String;
begin
idgroup := key_params.VarByName('IDGROUP').AsLargeInt;
prepareAttributesOfGroup(AMainDm, attributesSqlManager, idgroup);
qr := AMainDm.GetNewQuery(tr);
try
qr.SQL.Text := 'UPDATE OR INSERT INTO '+TBL_ATTRIBUTESOFOBJECT+
' (IDOBJECT, IDATTRIBUTE, VAL) '+
' VALUES (:IDOBJECT, :IDATTRIBUTE, :VAL)'+
'MATCHING (IDOBJECT,IDATTRIBUTE)';
qr.ParamByName('IDOBJECT').AsInt64 := idobject;
for I := 0 to new_params.count-1 do
begin
k := attributesSqlManager.FieldList.IndexOf(new_params.Items[i].Name);
if k > -1 then
begin
idattr := TAttributeDescr(attributesSqlManager.FieldList.Objects[k]).Id;
val := new_params.Items[i].AsString;
qr.ParamByName('IDATTRIBUTE').AsInt64 := idattr;
qr.ParamByName('VAL').AsString := val;
qr.ExecQuery;
end;
end;
finally
qr.Free;
end;
end;
begin
mUserName := FnParams.AsString['username'];
mPassword := FnParams.AsString['password'];
// tableName := FnParams.AsString['TABLENAME'];
// AMainDm := GetDmMainUib(Sender, mUserName, mPassword);
tr := AMainDm.GetNewTransaction(AMainDm.StabilityTransactionOptions);
fbQuery := AMainDm.GetNewQuery(tr);
tablename:= FnParams.asString['TABLENAME'];
operation := TUtils.getDocOperation(FnParams.asString['COMMAND']);
objectsSqlManager := AMainDm.GetServerDocSqlManager('OBJECTS');
attributesSqlManager := GetAttributesDocSqlManager(AMainDm);
new_params := TVkVariableCollection.Create(self);
old_params := TVkVariableCollection.Create(self);
key_params := TVkVariableCollection.Create(self);
try
try
if (operation = docUpdate) then
begin
TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['NEW'], new_params);
TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['OLD'], old_params);
TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['KEY'], key_params);
idobject := key_params.VarByName('IDOBJECT').AsLargeInt;
end else
if (operation = docDelete) then
begin
//TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['OLD'], old_params);
TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['KEY'], key_params);
idobject := key_params.VarByName('IDOBJECT').AsLargeInt;
end
else
begin
TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['NEW'], new_params);
idobject := new_params.VarByName('IDOBJECT').AsLargeInt;
end;
isEmpty := true;
fbQuery.SQL.Text := objectsSqlManager.GenerateSQL(operation, new_params, @isEmpty);
if not isEmpty then
begin
LockDoc(objectsSqlManager);
TQueryUtils.SetQueryParams(fbQuery, new_params);
TQueryUtils.SetQueryParams(fbQuery, key_params);
fbQuery.ExecQuery;
if Assigned(fbQuery.Current) then
begin
result.NewRecord.NewRecord('RESULT');
for i := 0 to fbQuery.Current.Count-1 do
begin
Result.asRecord.asRecord['RESULT'].asValue[fbQuery.Current.Data[i].Name] := fbQuery.Current.Data[i].AsVariant;
end;
end;
if (operation = docInsert) then
begin
AMainDm.WriteEventLog(objectsSqlManager, tr, operation, FnParams.asRecord['PARAMS'].asRecord['NEW'],
FnParams.asRecord['PARAMS'].asRecord['OLD'],
Result.asRecord.asRecord['RESULT']);
end
else
begin
AMainDm.WriteEventLog(objectsSqlManager, tr, operation, FnParams.asRecord['PARAMS'].asRecord['NEW'],
FnParams.asRecord['PARAMS'].asRecord['OLD'],
FnParams.asRecord['PARAMS'].asRecord['KEY']);
end;
end;
updateAttributes(idobject);
tr.Commit;
UnLockDoc;
except
on ex:Exception do
begin
if tr.Active then
tr.Rollback;
AMainDm.registerError(fbQuery.SQL.Text, ex.Message);
raise;
end;
end;
finally
FreeAndNil(objectsSqlManager);
FreeAndNil(attributesSqlManager);
FreeAndNil(fbQuery);
FreeAndNil(tr);
FreeAndNil(new_params);
FreeAndNil(old_params);
end;
end;
constructor TAttributesDocSqlManager.Create;
begin
inherited;
FFieldList := TStringList.Create;
FObjectList := TObjectList.Create;
end;
destructor TAttributesDocSqlManager.Destroy;
begin
inherited;
FreeAndNil(FFieldList);
FreeAndNil(FObjectList);
end;
end.
|
{*****************************************************************************}
{ File : complex.pas
Author : Mazen NEIFER
Creation date : 29/09/2000
Last modification date : 29/09/2000
Licence : GPL
Bug report : mazen_nefer@ayna.com }
{*****************************************************************************}
UNIT Filters;
INTERFACE
procedure FIR_Word(N,M:Word;var e{:ARRAY[0..N-1]OF Word},
h{:ARRAY[0..M-1]OF Word});
procedure FIR_DWord(N,M:Word;var e{:ARRAY[0..N-1]OF DWord},
h{:ARRAY[0..M-1]OF DWord});
procedure FIR_Real(N,M:Word;var e{:ARRAY[0..N-1]OF TReal},
h{:ARRAY[0..M-1]OF TReal});
{This procedure applaies the h filter to the e signal }
IMPLEMENTATION
uses
Reals;
{$ASMMODE INTEL}
FUNCTION min(i,j:LongInt):LongInt;INLINE;ASSEMBLER;
ASM
MOV EAX,i
MOV EDX,j
CMP EAX,EDX
JB @1
MOV EAX,EDX
@1:
end;
procedure FIR_Word(N,M:Word;var e,h);
var
i,j:Word;
E_,H_:PWord;
begin
E_:=@e;
H_:=@h;
for i:=N-1 downto 0 do begin
E_[i]*=H_[0];
for j:=1 TO min(M-1,i) do
E_[i]+=H_[j]*E_[i-j];
end;
end;
procedure FIR_DWord(N,M:Word;var e,h);
var
i,j:Word;
E_,H_:PDWord;
begin
E_:=@e;
H_:=@h;
for i:=N-1 downto 0 do begin
E_[i]*=H_[0];
for j:=1 TO min(M-1,i) do
E_[i]+=H_[j]*E_[i-j];
end;
end;
procedure FIR_Real(N,M:Word;var e,h);
var
i,j:Word;
E_,H_:PReal;
begin
E_:=@e;
H_:=@h;
for i:=N-1 downto 0 do begin
E_[i]*=H_[0];
for j:=1 TO min(M-1,i) do
E_[i]+=H_[j]*E_[i-j];
end;
end;
end .
|
program usingSets;
{
pascal has a bunch of builtin functions to work with sets
and you can add, diff, and a bunch of stuff to them,
just like you can do with numbers. which is neat.
i'm not sure "sets are first class citizen" is a concept,
but i seems it could be.
}
type { we're using colors are examples }
color = (red, blue, yellow, green, white, black, orange);
colors = set of color;
function toString(c : colors) : string;
const
names : array [color] of String[7]
= ('red', 'blue', 'yellow', 'green', 'white', 'black', 'orange');
var
cl : color;
s : string;
begin
s := ' ';
for cl := red to orange do
if cl in c then
begin
if (s <> ' ') then s := s + ', ';
s := s + names[cl];
end;
toString := '[ ' + s + ' ]';
end;
var
a, b, c : colors;
begin
a := [ red, blue, yellow ];
b := [ yellow, green, white ];
c := [ white, blue, black ];
writeln('example sets we are using ');
writeln('set a: ', toString( a ));
writeln('set b: ', toString( b ));
writeln('set c: ', toString( c ));
writeln;
writeln('union of sets with operator + ');
writeln(' a + b ', toString( a + b ));
writeln(' c + b ', toString( c + b ));
writeln;
writeln('difference of sets with operator - ');
writeln(' a - b ', toString( a - b ));
writeln(' c - b ', toString( c - b ));
writeln;
writeln('intersection of sets with operator * ');
writeln(' a * b ', toString( a * b ));
writeln(' c * b ', toString( c * b ));
writeln;
writeln('symmetric diffecence of two sets with >< ');
writeln(' a >< b ', toString( a >< b ));
writeln(' c >< b ', toString( c >< b ));
writeln;
writeln('check equality of two sets with = ');
writeln(' a = b ', a = b ); { returns a boolean }
writeln(' a = a ', a = a );
writeln;
writeln('check non-equality of two sets with <> ');
writeln(' a <> b ', a <> b ); { returns a boolean }
writeln(' a <> a ', a <> a );
writeln;
writeln('check one set contains the other with <= ');
writeln(' a <= b ', a <= b );
writeln(' a <= a ', a <= a );
writeln;
end.
|
unit TextEditor.CodeFolding.Hint.Indicator.Colors;
interface
uses
System.Classes, Vcl.Graphics, TextEditor.Consts;
type
TTextEditorCodeFoldingHintIndicatorColors = class(TPersistent)
strict private
FBackground: TColor;
FBorder: TColor;
FMark: TColor;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property Background: TColor read FBackground write FBackground default clLeftMarginBackground;
property Border: TColor read FBorder write FBorder default clLeftMarginFontForeground;
property Mark: TColor read FMark write FMark default clLeftMarginFontForeground;
end;
implementation
constructor TTextEditorCodeFoldingHintIndicatorColors.Create;
begin
inherited;
FBackground := clLeftMarginBackground;
FBorder := clLeftMarginFontForeground;
FMark := clLeftMarginFontForeground;
end;
procedure TTextEditorCodeFoldingHintIndicatorColors.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorCodeFoldingHintIndicatorColors) then
with ASource as TTextEditorCodeFoldingHintIndicatorColors do
begin
Self.FBackground := FBackground;
Self.FBorder := FBorder;
Self.FMark := FMark;
end
else
inherited Assign(ASource);
end;
end.
|
unit uDOptions;
interface {********************************************************************}
uses
Windows, Messages,
SysUtils, Classes,
Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls,
ExtCtrls_Ext, StdCtrls_Ext, ComCtrls_Ext, Forms_Ext,
BCEditor.Editor,
uPreferences, uSession,
uBase;
type
TIniFileRecord = record
Name: string;
Filename: TFileName;
end;
TDOptions = class (TForm_Ext)
ColorDialog: TColorDialog;
FBCancel: TButton;
FBEditorFont: TButton;
FBGridFont: TButton;
FBHelp: TButton;
FBLanguage: TButton;
FBOk: TButton;
FEditorCompletionEnabled: TCheckBox;
FEditorCompletionTime: TEdit;
FEditorCurrRowBGColorEnabled: TCheckBox;
FEditorFont: TEdit;
FEditorWordWrap: TCheckBox;
FGridCurrRowBGColorEnabled: TCheckBox;
FGridFont: TEdit;
FGridNullText: TCheckBox;
FGridShowMemoContent: TCheckBox;
FL2LogSize: TLabel;
FLanguage: TComboBox_Ext;
FLEditorCompletion: TLabel;
FLEditorCompletionTime: TLabel;
FLEditorCurrRowBGColor: TLabel;
FLEditorFont: TLabel;
FLEditorWordWrap: TLabel;
FLGridCurrRowBGColor: TLabel;
FLGridFont: TLabel;
FLGridNullValues: TLabel;
FLLanguage: TLabel;
FLLogFont: TLabel;
FLLogLinenumbers: TLabel;
FLLogSize: TLabel;
FLMaxColumnWidth: TLabel;
FLMaxColumnWidthCharacters: TLabel;
FLogFont: TEdit;
FLogResult: TCheckBox;
FLogSize: TEdit;
FLogTime: TCheckBox;
FLTabsVisible: TLabel;
FLViewDatas: TLabel;
FMaxColumnWidth: TEdit;
FontDialog: TFontDialog;
FTabsVisible: TCheckBox;
FUDEditorCompletionTime: TUpDown;
FUDLogSize: TUpDown;
FUDMaxColumnWidth: TUpDown;
GEditor: TGroupBox_Ext;
GGrid: TGroupBox_Ext;
GLog: TGroupBox_Ext;
GProgram: TGroupBox_Ext;
GTabs: TGroupBox_Ext;
PageControl: TPageControl;
PEditorCurrRowBGColor: TPanel_Ext;
PEditorFont: TPanel_Ext;
PGridCurrRowBGColor: TPanel_Ext;
PGridFont: TPanel_Ext;
PGridNullBGColor: TPanel_Ext;
PGridNullBGColorEnabled: TCheckBox;
PLogFont: TPanel_Ext;
TSBrowser: TTabSheet;
TSEditor: TTabSheet;
TSLog: TTabSheet;
TSView: TTabSheet;
FBLogFont: TButton;
GNavigator: TGroupBox;
FQuickAccessVisible: TCheckBox;
FLQuickAccessVisible: TLabel;
FEditorCaretBeyondEOL: TCheckBox;
FLEditorCaretBeyondEOL: TLabel;
procedure FBEditorCurrRowBGColorClick(Sender: TObject);
procedure FBEditorFontClick(Sender: TObject);
procedure FBGridCurrRowBGColorClick(Sender: TObject);
procedure FBGridFontClick(Sender: TObject);
procedure FBHelpClick(Sender: TObject);
procedure FBLanguageClick(Sender: TObject);
procedure FBLanguageKeyPress(Sender: TObject; var Key: Char);
procedure FBLogFontClick(Sender: TObject);
procedure FEditorFontKeyPress(Sender: TObject; var Key: Char);
procedure FGridFontKeyPress(Sender: TObject; var Key: Char);
procedure FLogFontKeyPress(Sender: TObject; var Key: Char);
procedure FormHide(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure PEditorCurrRowBGColorClick(Sender: TObject);
procedure PGridCurrRowBGColorClick(Sender: TObject);
procedure PGridNullBGColorClick(Sender: TObject);
procedure TSBrowserResize(Sender: TObject);
procedure TSEditorResize(Sender: TObject);
procedure FBGridFontKeyPress(Sender: TObject; var Key: Char);
procedure TSLogResize(Sender: TObject);
procedure FBLogFontKeyPress(Sender: TObject; var Key: Char);
procedure TSViewResize(Sender: TObject);
procedure FLanguageChange(Sender: TObject);
private
procedure UMPreferencesChanged(var Message: TMessage); message UM_PREFERENCES_CHANGED;
public
Languages: array of TIniFileRecord;
function Execute(): Boolean;
end;
function DOptions(): TDOptions;
implementation {***************************************************************}
{$R *.dfm}
uses
IniFiles, UITypes, DateUtils, StrUtils,
uDeveloper,
uDLanguage;
var
FDOptions: TDOptions;
function DOptions(): TDOptions;
begin
if (not Assigned(FDOptions)) then
begin
Application.CreateForm(TDOptions, FDOptions);
FDOptions.Perform(UM_PREFERENCES_CHANGED, 0, 0);
end;
Result := FDOptions;
end;
function TDOptions.Execute(): Boolean;
begin
Result := ShowModal() = mrOk;
end;
procedure TDOptions.FBEditorCurrRowBGColorClick(Sender: TObject);
begin
if (PEditorCurrRowBGColor.Color = clNone) then
ColorDialog.Color := clWindow
else
ColorDialog.Color := PEditorCurrRowBGColor.Color;
if (ColorDialog.Execute()) then
PEditorCurrRowBGColor.Color := ColorDialog.Color;
end;
procedure TDOptions.FBEditorFontClick(Sender: TObject);
begin
FontDialog.Font := PEditorFont.Font;
FontDialog.Options := FontDialog.Options + [fdFixedPitchOnly];
if (FontDialog.Execute()) then
begin
FEditorFont.Text := FontDialog.Font.Name;
PEditorFont.Font := FontDialog.Font;
end;
end;
procedure TDOptions.FBGridCurrRowBGColorClick(Sender: TObject);
begin
if (PGridCurrRowBGColor.Color = clNone) then
ColorDialog.Color := clWindow
else
ColorDialog.Color := PGridCurrRowBGColor.Color;
if (ColorDialog.Execute()) then
PGridCurrRowBGColor.Color := ColorDialog.Color;
end;
procedure TDOptions.FBGridFontClick(Sender: TObject);
begin
FontDialog.Font := PGridFont.Font;
FontDialog.Options := FontDialog.Options - [fdFixedPitchOnly];
if (FontDialog.Execute()) then
begin
FGridFont.Text := FontDialog.Font.Name;
PGridFont.Font := FontDialog.Font;
end;
end;
procedure TDOptions.FBGridFontKeyPress(Sender: TObject; var Key: Char);
begin
FBGridFontClick(Sender);
end;
procedure TDOptions.FBHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TDOptions.FBLanguageClick(Sender: TObject);
var
CheckOnlineVersionThread: TCheckOnlineVersionThread;
I: Integer;
begin
if (not UpdateAvailable and (DateOf(LastUpdateCheck) < Today())) then
begin
CheckOnlineVersionThread := TCheckOnlineVersionThread.Create();
CheckOnlineVersionThread.Execute();
CheckOnlineVersionThread.Free();
end;
if (UpdateAvailable) then
begin
MsgBox('An update of ' + LoadStr(1000) + ' is available. Please install that update first.', Preferences.LoadStr(45), MB_OK or MB_ICONERROR);
PostMessage(Application.MainForm.Handle, UM_ONLINE_UPDATE_FOUND, 0, 0);
exit;
end
else if (DateOf(LastUpdateCheck) < Today()) then
MsgBox('Can''t check, if you are using the latest update. Maybe an update of ' + LoadStr(1000) + ' is available...', Preferences.LoadStr(47), MB_OK + MB_ICONWARNING);
DLanguage.Filename := '';
for I := 0 to Length(Languages) - 1 do
if (Trim(FLanguage.Text) = Languages[I].Name) then
DLanguage.Filename := Languages[I].Filename;
if (DLanguage.Execute()) then
MsgBox('Please restart ' + LoadStr(1000) + ' to apply your changes.', Preferences.LoadStr(43), MB_OK + MB_ICONINFORMATION);
end;
procedure TDOptions.FBLanguageKeyPress(Sender: TObject; var Key: Char);
begin
FBLanguageClick(Sender);
end;
procedure TDOptions.FBLogFontClick(Sender: TObject);
begin
FontDialog.Font := PLogFont.Font;
FontDialog.Options := FontDialog.Options + [fdFixedPitchOnly];
if (FontDialog.Execute()) then
begin
FLogFont.Text := FontDialog.Font.Name;
PLogFont.Font := FontDialog.Font;
end;
end;
procedure TDOptions.FBLogFontKeyPress(Sender: TObject; var Key: Char);
begin
FBLogFontClick(Sender);
end;
procedure TDOptions.FEditorFontKeyPress(Sender: TObject; var Key: Char);
begin
FBEditorFontClick(Sender);
end;
procedure TDOptions.FGridFontKeyPress(Sender: TObject; var Key: Char);
begin
FBGridFontClick(Sender);
end;
procedure TDOptions.FLanguageChange(Sender: TObject);
var
I: Integer;
Language: string;
begin
if (FLanguage.ItemIndex = 0) then
begin
for I := 0 to Length(Languages) - 1 do
if (lstrcmpi(PChar(Preferences.LanguageFilename), PChar(Languages[I].Filename)) = 0) then
FLanguage.ItemIndex := FLanguage.Items.IndexOf(Languages[I].Name);
Language := Trim(InputBox('Add new translation', 'Language:', ''));
if (Language <> '') then
if (FileExists(Preferences.LanguagePath + Language + '.ini')) then
MsgBox('The language "' + Language + '" already exists!', Preferences.LoadStr(45), MB_OK or MB_ICONERROR)
else
begin
DLanguage.Filename := Language + '.ini';
if (DLanguage.Execute()) then
MsgBox('Please restart ' + LoadStr(1000) + ' to apply your changes.', Preferences.LoadStr(43), MB_OK + MB_ICONINFORMATION);
end;
end;
end;
procedure TDOptions.FLogFontKeyPress(Sender: TObject; var Key: Char);
begin
FBLogFontClick(Sender);
end;
{ TDOptions *******************************************************************}
procedure TDOptions.FormHide(Sender: TObject);
var
I: Integer;
begin
if (ModalResult = mrOk) then
begin
if (FLanguage.ItemIndex >= 0) then
for I := 0 to Length(Languages) - 1 do
if (Trim(FLanguage.Text) = Languages[I].Name) then
Preferences.LanguageFilename := Languages[I].Filename;
Preferences.TabsVisible := FTabsVisible.Checked;
Preferences.QuickAccessVisible := FQuickAccessVisible.Checked;
Preferences.GridFontName := PGridFont.Font.Name;
Preferences.GridFontStyle := PGridFont.Font.Style - [fsBold];
Preferences.GridFontColor := PGridFont.Font.Color;
Preferences.GridFontSize := PGridFont.Font.Size;
Preferences.GridFontCharset := PGridFont.Font.Charset;
Preferences.GridNullBGColorEnabled := PGridNullBGColorEnabled.Checked;
Preferences.GridNullBGColor := PGridNullBGColor.Color;
Preferences.GridNullText := FGridNullText.Checked;
Preferences.GridCurrRowBGColorEnabled := FGridCurrRowBGColorEnabled.Checked;
Preferences.GridCurrRowBGColor := PGridCurrRowBGColor.Color;
Preferences.SQLFontName := PEditorFont.Font.Name;
Preferences.SQLFontColor := PEditorFont.Font.Color;
Preferences.SQLFontSize := PEditorFont.Font.Size;
Preferences.SQLFontCharset := PEditorFont.Font.Charset;
Preferences.Editor.CurrRowBGColorEnabled := FEditorCurrRowBGColorEnabled.Checked;
Preferences.Editor.CurrRowBGColor := PEditorCurrRowBGColor.Color;
Preferences.Editor.CodeCompletion := FEditorCompletionEnabled.Checked;
Preferences.Editor.WordWrap := FEditorWordWrap.Checked;
Preferences.Editor.CaretBeyondEOL := FEditorCaretBeyondEOL.Checked;
TryStrToInt(FEditorCompletionTime.Text, Preferences.Editor.CodeCompletionTime);
Preferences.LogFontName := PLogFont.Font.Name;
Preferences.LogFontStyle := PLogFont.Font.Style;
Preferences.LogFontColor := PLogFont.Font.Color;
Preferences.LogFontSize := PLogFont.Font.Size;
Preferences.LogFontCharset := PLogFont.Font.Charset;
Preferences.LogTime := FLogTime.Checked;
Preferences.LogResult := FLogResult.Checked;
Preferences.LogSize := FUDLogSize.Position * 1024;
Preferences.GridMaxColumnWidth := FUDMaxColumnWidth.Position;
Preferences.GridMemoContent := FGridShowMemoContent.Checked;
end;
end;
procedure TDOptions.FormShow(Sender: TObject);
var
I: Integer;
IniFile: TMemIniFile;
SearchRec: TSearchRec;
begin
SetLength(Languages, 0);
if (FindFirst(Preferences.LanguagePath + '*.ini', faAnyFile, SearchRec) = NO_ERROR) then
begin
repeat
IniFile := TMemIniFile.Create(Preferences.LanguagePath + SearchRec.Name);
if (UpperCase(IniFile.ReadString('Global', 'Type', '')) = 'LANGUAGE') then
begin
SetLength(Languages, Length(Languages) + 1);
Languages[Length(Languages) - 1].Name := IniFile.ReadString('Global', 'Name', '');
Languages[Length(Languages) - 1].Filename := SearchRec.Name;
end;
FreeAndNil(IniFile);
until (FindNext(SearchRec) <> NO_ERROR);
FindClose(SearchRec);
end;
FLanguage.Items.Clear();
for I := 0 to Length(Languages) - 1 do
FLanguage.Items.Add(Languages[I].Name);
for I := 0 to Length(Languages) - 1 do
if (lstrcmpi(PChar(Preferences.LanguageFilename), PChar(Languages[I].Filename)) = 0) then
FLanguage.ItemIndex := FLanguage.Items.IndexOf(Languages[I].Name);
FLanguage.Items.Add('Add new...');
FTabsVisible.Checked := Preferences.TabsVisible;
FQuickAccessVisible.Checked := Preferences.QuickAccessVisible;
FUDMaxColumnWidth.Position := Preferences.GridMaxColumnWidth;
FGridShowMemoContent.Checked := Preferences.GridMemoContent;
FGridFont.Text := Preferences.GridFontName;
PGridFont.Font.Name := Preferences.GridFontName;
PGridFont.Font.Style := Preferences.GridFontStyle;
PGridFont.Font.Color := Preferences.GridFontColor;
PGridFont.Font.Size := Preferences.GridFontSize;
PGridFont.Font.Charset := Preferences.GridFontCharset;
PGridNullBGColorEnabled.Checked := Preferences.GridNullBGColorEnabled;
PGridNullBGColor.Color := Preferences.GridNullBGColor;
FGridNullText.Checked := Preferences.GridNullText;
FGridCurrRowBGColorEnabled.Checked := Preferences.GridCurrRowBGColorEnabled;
PGridCurrRowBGColor.Color := Preferences.GridCurrRowBGColor;
FEditorFont.Text := Preferences.SQLFontName;
PEditorFont.Font.Name := Preferences.SQLFontName;
PEditorFont.Font.Color := Preferences.SQLFontColor;
PEditorFont.Font.Size := Preferences.SQLFontSize;
PEditorFont.Font.Charset := Preferences.SQLFontCharset;
FEditorCurrRowBGColorEnabled.Checked := Preferences.Editor.CurrRowBGColorEnabled;
PEditorCurrRowBGColor.Color := Preferences.Editor.CurrRowBGColor;
FEditorCompletionEnabled.Checked := Preferences.Editor.CodeCompletion;
FUDEditorCompletionTime.Position := Preferences.Editor.CodeCompletionTime;
FEditorWordWrap.Checked := Preferences.Editor.WordWrap;
FEditorCaretBeyondEOL.Checked := Preferences.Editor.CaretBeyondEOL;
FLogFont.Text := Preferences.LogFontName;
PLogFont.Font.Name := Preferences.LogFontName;
PLogFont.Font.Style := Preferences.LogFontStyle;
PLogFont.Font.Color := Preferences.LogFontColor;
PLogFont.Font.Size := Preferences.LogFontSize;
PLogFont.Font.Charset := Preferences.LogFontCharset;
FLogTime.Checked := Preferences.LogTime;
FLogResult.Checked := Preferences.LogResult;
FUDLogSize.Position := Preferences.LogSize div 1024;
PageControl.ActivePage := TSView;
ActiveControl := FLanguage;
end;
procedure TDOptions.PEditorCurrRowBGColorClick(Sender: TObject);
begin
FBEditorCurrRowBGColorClick(Sender);
end;
procedure TDOptions.PGridCurrRowBGColorClick(Sender: TObject);
begin
FBGridCurrRowBGColorClick(Sender);
end;
procedure TDOptions.PGridNullBGColorClick(Sender: TObject);
begin
if (PGridNullBGColor.Color = clNone) then
ColorDialog.Color := clWindow
else
ColorDialog.Color := PGridNullBGColor.Color;
if (ColorDialog.Execute()) then
PGridNullBGColor.Color := ColorDialog.Color;
end;
procedure TDOptions.TSBrowserResize(Sender: TObject);
begin
FBGridFont.Left := FGridFont.Left + FGridFont.Width;
FBGridFont.Height := FGridFont.Height;
FBGridFont.Width := FBGridFont.Height;
end;
procedure TDOptions.TSEditorResize(Sender: TObject);
begin
FBEditorFont.Left := FEditorFont.Left + FEditorFont.Width;
FBEditorFont.Height := FEditorFont.Height;
FBEditorFont.Width := FBEditorFont.Height;
end;
procedure TDOptions.TSLogResize(Sender: TObject);
begin
FBLogFont.Left := FLogFont.Left + FLogFont.Width;
FBLogFont.Height := FLogFont.Height;
FBLogFont.Width := FBLogFont.Height;
end;
procedure TDOptions.TSViewResize(Sender: TObject);
begin
FBLanguage.Left := FLanguage.Left + FLanguage.Width;
FBLanguage.Height := FLanguage.Height;
FBLanguage.Width := FBLanguage.Height;
end;
procedure TDOptions.UMPreferencesChanged(var Message: TMessage);
begin
Canvas.Font := Font;
Caption := Preferences.LoadStr(52);
TSView.Caption := Preferences.LoadStr(491);
GProgram.Caption := Preferences.LoadStr(52);
FLLanguage.Caption := Preferences.LoadStr(32) + ':';
GTabs.Caption := Preferences.LoadStr(851);
FLTabsVisible.Caption := Preferences.LoadStr(699) + ':';
FTabsVisible.Caption := Preferences.LoadStr(851);
GNavigator.Caption := Preferences.LoadStr(10);
FLQuickAccessVisible.Caption := Preferences.LoadStr(527) + ':';
FQuickAccessVisible.Caption := Preferences.LoadStr(939);
TSBrowser.Caption := Preferences.LoadStr(739);
GGrid.Caption := Preferences.LoadStr(17);
FLGridFont.Caption := Preferences.LoadStr(430) + ':';
FLGridNullValues.Caption := Preferences.LoadStr(498) + ':';
FGridNullText.Caption := Preferences.LoadStr(499);
FLMaxColumnWidth.Caption := Preferences.LoadStr(208) + ':';
FLMaxColumnWidthCharacters.Caption := Preferences.LoadStr(869);
FLMaxColumnWidthCharacters.Left := FUDMaxColumnWidth.Left + FUDMaxColumnWidth.Width + Canvas.TextWidth(' ');
FLViewDatas.Caption := Preferences.LoadStr(574) + ':';
FGridShowMemoContent.Caption := Preferences.LoadStr(575);
FLGridCurrRowBGColor.Caption := Preferences.LoadStr(784) + ':';
TSEditor.Caption := Preferences.LoadStr(473);
GEditor.Caption := Preferences.LoadStr(473);
FLEditorFont.Caption := Preferences.LoadStr(439) + ':';
FLEditorCurrRowBGColor.Caption := Preferences.LoadStr(784) + ':';
FLEditorCurrRowBGColor.Caption := Preferences.LoadStr(784) + ':';
FLEditorCompletion.Caption := Preferences.LoadStr(660) + ':';
FEditorCompletionEnabled.Width := FEditorCurrRowBGColorEnabled.Width + Canvas.TextWidth(FEditorCompletionEnabled.Caption);
FLEditorCompletionTime.Caption := Preferences.LoadStr(843);
FLEditorCompletionTime.Left := FUDEditorCompletionTime.Left + FUDEditorCompletionTime.Width + Canvas.TextWidth(' ');
FLEditorWordWrap.Caption := Preferences.LoadStr(891) + ':';
FEditorWordWrap.Caption := Preferences.LoadStr(892);
FLEditorCaretBeyondEOL.Caption := Preferences.LoadStr(494) + ':';
FEditorCaretBeyondEOL.Caption := Preferences.LoadStr(946);
TSLog.Caption := Preferences.LoadStr(524);
GLog.Caption := Preferences.LoadStr(524);
FLLogFont.Caption := Preferences.LoadStr(525) + ':';
FLLogLinenumbers.Caption := Preferences.LoadStr(527) + ':';
FLogTime.Caption := Preferences.LoadStr(661);
FLogResult.Caption := Preferences.LoadStr(662);
FLLogSize.Caption := Preferences.LoadStr(844) + ':';
FL2LogSize.Caption := 'KB';
FBHelp.Caption := Preferences.LoadStr(167);
FBOk.Caption := Preferences.LoadStr(29);
FBCancel.Caption := Preferences.LoadStr(30);
end;
initialization
FDOptions := nil;
end.
|
unit VersionInfo;
interface
uses Windows,SysUtils;
type TVersionInfo = record
CompanyName : string;
FileDescription : string;
FileVersion : string;
InternalName : string;
LegalCopyright : string;
LegalTradeMarks : string;
OriginalFilename : string;
ProductName : string;
ProductVersion : string;
Comments : string;
end;
function ReadVersionInfo(FileName:string):TVersionInfo;
function ReadVersionInfoApp :TVersionInfo;
function CompareVersionTo (ToVersion : string) : integer;
function CompareVersions (Version1, Version2 : string) : integer;
implementation
uses Forms;
const
VerQueryHeader = 'StringFileInfo\040704E4\'; // german
// VerQueryHeader = 'StringFileInfo\040704E4\'; // english
VerQueryCompanyName = 'CompanyName';
VerQueryFileDescription = 'FileDescription';
VerQueryFileVersion = 'FileVersion';
VerQueryInternalName = 'InternalName';
VerQueryLegalCopyright = 'LegalCopyright';
VerQueryLegalTradeMarks = 'LegalTradeMarks';
VerQueryOriginalFilename = 'OriginalFilename';
VerQueryProductName = 'ProductName';
VerQueryProductVersion = 'ProductVersion';
VerQueryComments = 'Comments';
function ReadVersionInfo(FileName : string) : TVersionInfo;
var
InfoBufSize,VerBufSize : integer;
InfoBuf,VerBuf : PChar;
function VerQuery(VerInfoValue:string):string;
begin
VerQueryValue(InfoBuf,
PChar(VerQueryHeader + VerInfoValue),
Pointer(VerBuf), DWORD(VerBufSize));
if VerBufSize > 0 then Result := VerBuf
else Result := '';
end;
begin
fillchar (result, sizeof (result), 0);
InfoBufSize := GetFileVersionInfoSize(PChar(FileName),DWORD(InfoBufSize));
if InfoBufSize > 0 then
begin
InfoBuf := AllocMem(InfoBufSize);
GetFileVersionInfo(PChar(FileName),0,InfoBufSize,InfoBuf);
with Result do begin
CompanyName := VerQuery (VerQueryCompanyName);
FileDescription := VerQuery (VerQueryFileDescription);
FileVersion := VerQuery (VerQueryFileVersion);
InternalName := VerQuery (VerQueryInternalName);
LegalCopyright := VerQuery (VerQueryLegalCopyright);
LegalTradeMarks := VerQuery (VerQueryLegalTradeMarks);
OriginalFilename := VerQuery (VerQueryOriginalFilename);
ProductName := VerQuery (VerQueryProductName);
ProductVersion := VerQuery (VerQueryProductVersion);
Comments := VerQuery (VerQueryComments);
end;
FreeMem(InfoBuf, InfoBufSize);
end;
end;
function ReadVersionInfoApp :TVersionInfo;
begin
result := ReadVersionInfo (Application.ExeName);
end;
function CompareVersions (Version1, Version2 : string) : integer;
var
Version1Number : integer;
Version1Pos : integer;
Version2Number : integer;
Version2Pos : integer;
code : integer;
begin
result := 0;
Version1Pos := 0;
Version2Pos := 0;
Version1Number := 0;
Version2Number := 0;
while (Result = 0) do begin
if length (Version1) = 0 then
begin
result := -1;
break;
end else begin
val (Version1, Version1Number, code);
Version1Pos := Pos ('.', Version1);
end;
if length (Version2) = 0 then
begin
result := 1;
break;
end else begin
val (Version2, Version2Number, code);
Version2Pos := Pos ('.', Version2);
end;
if (Version1Number > Version2Number) then result := 1;
if (Version1Number < Version2Number) then result := -1;
Version1 := copy (Version1, Version1Pos+1, length (Version1));
Version2 := copy (Version2, Version2Pos+1, length (Version2));
if (Version1Pos = 0) and (Version1Pos = 0) then
begin
break;
end;
end;
end;
function CompareVersionTo (ToVersion : string) : integer;
var
ExeVersion : String;
begin
ExeVersion := ReadVersionInfo (Application.ExeName).FileVersion;
result := CompareVersions (ExeVersion, ToVersion);
end;
end.
|
unit UFuncionarioPersist;
interface
uses UIPersist, UFuncionario, System.Generics.Collections, UConexao,
UDependente, UDependentePersist, Data.DB;
type
TFuncionarioPersist = class(TInterfacedObject, IPersist<TFuncionario>)
private
procedure CarregarDependentes(entidade: TFuncionario);
public
function GetDataSet(): TDataSet; overload;
function Get(): TList<TFuncionario>;
function GetById(Id: Integer): TFuncionario;
function Save(entidade: TFuncionario): boolean;
function Delete(entidade: TFuncionario): boolean;
end;
implementation
uses
System.SysUtils;
{ TFuncionarioPersist }
procedure TFuncionarioPersist.CarregarDependentes(entidade: TFuncionario);
var
Data: TDataSet;
begin
Data := Tconexao.Instance.Get
('select * from dependente where idfuncionario=:idfuncionario',
Tconexao.Instance.NewParams(['idfuncionario'], [entidade.Id]));
try
while not Data.Eof do
begin
entidade.AddDependente(TDependente.Create(
Data.FieldByName('id').AsInteger,
Data.FieldByName('idfuncionario').AsInteger,
Data.FieldByName('nome').AsString,
Data.FieldByName('iscalculair').AsInteger = 1 ,
Data.FieldByName('iscalculainss').AsInteger = 1 ));
Data.Next;
end;
finally
if Assigned(Data) then
Data.Free;
end;
end;
function TFuncionarioPersist.Delete(entidade: TFuncionario): boolean;
begin
Tconexao.Instance.Execute('delete from funcionario where id=:id',
Tconexao.Instance.NewParams(['id'], [entidade.Id]));
end;
function TFuncionarioPersist.Get: TList<TFuncionario>;
var
Data: TDataSet;
func: TFuncionario;
begin
result := TList<TFuncionario>.Create;
try
Data := Tconexao.Instance().Get('select * from funcionario');
while not Data.Eof do
begin
func := TFuncionario.Create(Data.FieldByName('id').Value,
Data.FieldByName('nome').Value, Data.FieldByName('cpf').Value,
Data.FieldByName('salario').Value);
CarregarDependentes(func);
result.Add(func);
Data.Next;
end;
finally
if Assigned(Data) then
Data.Free;
end;
end;
function TFuncionarioPersist.GetById(Id: Integer): TFuncionario;
var
dataset: TDataSet;
nome, cpf: string;
salario: Currency;
begin
try
dataset := Tconexao.Instance().Get('select * from funcionario where id=:id',
Tconexao.Instance.NewParams(['id'], [Id]));
nome := dataset.FieldByName('nome').AsString;
cpf := dataset.FieldByName('cpf').AsString;
salario := dataset.FieldByName('salario').ascurrency;
result := TFuncionario.Create(Id, nome, cpf, salario);
CarregarDependentes(result);
finally
dataset.Free;
end;
end;
function TFuncionarioPersist.GetDataSet: TDataSet;
begin
result := Tconexao.Instance().Get('select * from funcionario');
end;
function TFuncionarioPersist.Save(entidade: TFuncionario): boolean;
var
sqlInsert: String;
sqlUpdate: String;
dep: TDependente;
dependentePersist: TDependentePersist;
begin
sqlInsert :=
'insert into funcionario (id, nome, cpf, salario) values (:id, :nome, :cpf, :salario)';
sqlUpdate :=
'update funcionario set nome=:nome, cpf=:cpf, salario=:salario where id=:id';
dependentePersist := TDependentePersist.Create();
try
if entidade.Id = 0 then
begin
entidade.Id :=Tconexao.Instance.getGenId('funcionario_gen');
if Tconexao.Instance.Execute(sqlInsert,
Tconexao.Instance.NewParams(['id', 'nome', 'cpf', 'salario'],
[entidade.Id, entidade.nome, entidade.cpf, entidade.salario])) > 0 then
begin
entidade.ForInDependentes( procedure (dep: TDependente) begin
dep.IdFuncionario := entidade.Id;
dependentePersist.Save(dep);
end);
result := true
end
else
result := false;
end
else
begin
if Tconexao.Instance.Execute(sqlUpdate,
Tconexao.Instance.NewParams(['id', 'nome', 'cpf', 'salario'],
[entidade.Id, entidade.nome, entidade.cpf, entidade.salario])) > 0 then
result := true
else
result := false;
end;
finally
dependentePersist.Free;
end;
end;
end.
|
unit Colecao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Rtti,
System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.EngExt,
Vcl.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Data.DB,
Vcl.Grids, Vcl.DBGrids;
type
TfrmColecao = class(TForm)
lblNome: TLabel;
lblDescricao: TLabel;
edtNome: TEdit;
edtDescricao: TEdit;
cbSetor: TComboBox;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkFillControlToField1: TLinkFillControlToField;
btnNovo: TButton;
btnSalvar: TButton;
btnEditar: TButton;
btnExcluir: TButton;
BindSourceDB2: TBindSourceDB;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
gridColecao: TDBGrid;
procedure FormShow(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmColecao: TfrmColecao;
implementation
{$R *.dfm}
uses datamodulo;
procedure TfrmColecao.btnEditarClick(Sender: TObject);
begin
edtNome.Enabled:= true;
edtDescricao.Enabled:= true;
cbSetor.Enabled:=true;
edtNome.SetFocus;
end;
procedure TfrmColecao.btnExcluirClick(Sender: TObject);
begin
DataModule1.FDQColecao.Delete;
ShowMessage('Coleção excluído!');
end;
procedure TfrmColecao.btnNovoClick(Sender: TObject);
begin
edtNome.Enabled:= true;
edtDescricao.Enabled:= true;
cbSetor.Enabled:=true;
DataModule1.FDQColecao.Insert;
edtNome.SetFocus;
end;
procedure TfrmColecao.btnSalvarClick(Sender: TObject);
begin
DataModule1.FDQColecao.Post;
DataModule1.FDQColecao.Refresh;
ShowMessage('Coleção salvo com sucesso.');
end;
procedure TfrmColecao.FormShow(Sender: TObject);
begin
DataModule1.FDConnection1.Connected:= True;
DataModule1.FDQColecao.Active:= True;
DataModule1.FDQSetor.Active:= True;
end;
end.
|
unit ConfigManager;
interface
uses windows,Obj_AbstractInfo,Character,UntConst,md5,SysUtils,
ComCtrls,MyCommonFuns,Forms,HotkeyManager,Classes,
Menus;
type
{ TConfig }
TConfigManager = class(TObject)
private
FInfo:TAbstractInfo;
FSoftRunTimes:Integer;
FFirstUseTime:Double;
FShoutcut_SimpleClick:Integer;
FShoutcut_RecordMouse:Integer;
FShoutcut_Playback:Integer;
FPlaybackSpeed:integer;
procedure ReloadHotkey;
protected
public
UsageTime_Sec:Integer;
procedure GetHotkeys(var HotkeyInfoArr: THotkeyInfoArr);
procedure setHotkey(hkType: THotkeyType; shortCut: Integer);
//function getPlaybackSpeed:Integer;
//procedure SetPlaybackSpeed(iSpeed:Integer);
procedure savePickLocationList(list:TCustomListView);
procedure loadPickLocationList(list:TCustomListView);
constructor Create(Info:TAbstractInfo);
destructor Destroy; override;
end;
implementation
const
sIni_FirstUseTime='Enablefutula';
sIni_LastTime_SetUsedTime='LastSetModCon';
sIni_SoftRunTimes = 'SoftRunTimes';
{ TConfig }
constructor TConfigManager.Create(Info:TAbstractInfo);
begin
FInfo:=Info;
ReloadHotkey();
UsageTime_Sec:= FInfo.ReadValue(IntToStr(GetDate), 0);
FPlaybackSpeed:= FInfo.ReadValue('PlaybackSpeed', 9);
end;
procedure TConfigManager.ReloadHotkey();
begin
FShoutcut_SimpleClick:= FInfo.ReadValue('HT_SimpleClick', TextToShortCut('F6'));
FShoutcut_RecordMouse:= FInfo.ReadValue('HT_RecordMouse', TextToShortCut('CTRL+F1'));
FShoutcut_Playback:= FInfo.ReadValue('HT_Playback', TextToShortCut('CTRL+F2'));
end;
procedure TConfigManager.savePickLocationList(list: TCustomListView);
begin
ListViewSaveToFile(list,getSysAppDataDir+'\'+'picklocation.txt');
end;
procedure TConfigManager.setHotkey(hkType:THotkeyType; shortCut:Integer);
begin
if hkType=HT_SimpleClick then
FInfo.WriteValue('HT_SimpleClick', shortCut)
else if hkType=HT_RecordMouse then
FInfo.WriteValue('HT_RecordMouse', shortCut)
else if hkType=HT_Playback then
FInfo.WriteValue('HT_Playback', shortCut)
else
ShowMsgInfoBox('error!');
ReloadHotkey();
end;
procedure TConfigManager.GetHotkeys(var HotkeyInfoArr: THotkeyInfoArr);
var
Hotkey: TShortCut;
i, AttrIndex: Integer;
begin
AttrIndex := 0;
FillChar(HotkeyInfoArr, SizeOf(HotkeyInfoArr), 0);
HotkeyInfoArr[Integer(HT_Playback)].Hotkey := FShoutcut_Playback;
HotkeyInfoArr[Integer(HT_Playback)].HotkeyType := HT_Playback;
HotkeyInfoArr[integer(HT_Playback)].HotkeyRegsteredID := 0;
end;
procedure TConfigManager.loadPickLocationList(list: TCustomListView);
begin
ListViewLoadFromFile(list,getSysAppDataDir+'\'+'picklocation.txt');
end;
//procedure TConfigManager.SetPlaybackSpeed(iSpeed:Integer);
//begin
// FPlaybackSpeed:= iSpeed;
// FInfo.WriteValue('PlaybackSpeed', iSpeed);
//end;
//
//function TConfigManager.getPlaybackSpeed: Integer;
//begin
// result:=FPlaybackSpeed;
//end;
destructor TConfigManager.Destroy;
begin
inherited;
end;
end.
|
unit uEnderecoDAO;
interface
uses uDAO, uEndereco, FireDac.comp.client, sysUtils;
type
TEnderecoDAO = class (TconectDAO)
public
Constructor Create;
Destructor Destroy; override;
function CadastrarEndereco(pEndereco : Tendereco):boolean;
function RetornarEndereco(pEndereco: TEndereco): TEndereco;
function UpdateEndereco(pEndereco : TEndereco): Boolean;
function RetornaCidades: TFDQuery;
end;
implementation
{ TEnderecoDAO }
function TEnderecoDAO.CadastrarEndereco(pEndereco: Tendereco): boolean;
var SQL:string;
begin
SQL := 'select id_cidade from cidade where nome = ' + QuotedStr(pEndereco.Cidade);
FQuery := RetornarDataSet(SQL);
pEndereco.Cidade := FQuery.FieldByName('id_cidade').AsString;
SQL := 'INSERT INTO endereco VALUES(default, ' + QuotedSTR(pEndereco.rua) +
', ' + QuotedSTR(IntToStr( pEndereco.Numero)) + ', ' +
QuotedSTR(pEndereco.bairro) + ', ' +
QuotedSTR(pEndereco.cep) + ' ,' + QuotedSTR(pEndereco.cidade) + ')';
result := executarComando(SQL) > 0;
end;
constructor TEnderecoDAO.Create;
begin
inherited;
end;
destructor TEnderecoDAO.Destroy;
begin
inherited;
end;
function TEnderecoDAO.RetornaCidades: TFDQuery;
var SQL : string;
begin
SQL := 'select * from cidade';
FQuery := RetornarDataSet(SQL);
Result := FQuery;
end;
function TEnderecoDAO.RetornarEndereco(pEndereco: TEndereco): TEndereco;
var SQL : string;
endereco : TEndereco;
begin
SQL := 'select * from endereco where id_endereco = '+
QuotedStr(IntToStr(pEndereco.ID));
FQuery := RetornarDataSet(SQL);
endereco := TEndereco.Create;
endereco.ID := FQuery.FieldByName('id_endereco').AsInteger;
endereco.Rua := FQuery.FieldByName('rua').AsString;
endereco.Numero := FQuery.FieldByName('numero').AsInteger;
endereco.Bairro := FQuery.FieldByName('bairro').AsString;
endereco.Cep := FQuery.FieldByName('cep').AsString;
SQL := 'select nome from cidade where id_cidade = ' +
QuotedStr(FQuery.FieldByName('id_cidade').AsString);
FQuery2 := RetornarDataSet2(SQL);
endereco.Cidade := FQuery2.FieldByName('nome').AsString;
Result := endereco;
end;
function TEnderecoDAO.UpdateEndereco(pEndereco: TEndereco): Boolean;
var SQL : String;
begin
SQL := 'select id_cidade from cidade where nome = ' + QuotedStr(pEndereco.Cidade);
FQuery := RetornarDataSet(SQL);
pEndereco.Cidade := FQuery.FieldByName('id_cidade').AsString;
SQL := 'update endereco Set rua = ' + QuotedSTR(pEndereco.Rua) +
', numero = ' + QuotedSTR(intToStr(pEndereco.Numero)) +
', bairro = ' + QuotedSTR(pEndereco.Bairro) +
', cep = ' + QuotedSTR(pEndereco.Cep) +
', id_cidade = ' + QuotedSTR(pEndereco.Cidade) +
' where id_endereco = ' + QuotedSTR(InttoStr(pEndereco.id));
result := executarComando(SQL) > 0;
end;
end.
|
(* @file UFunctions.pas
* @author Willi Schinmeyer
* @date 2011-10-30
*
* Contains all the methods and functions.
*)
unit UFunctions;
interface
(* @brief Displays the main menu. *)
procedure showMainMenu();
(* @brief Displays the help, i.e. how to play. *)
procedure showHelp();
(* @brief Starts the game. *)
procedure runGame();
implementation
uses
crt, //for console i/o
UConstants, //all the constants, duh
UGameplayTypes, //most gameplay types, except for:
UVector2i, //- TVector2i
UTetrominoShape,//- TTetrominoShape
//which have their own units to prevent cyclic dependencies (with constants)
UTime, //Time handling
math; //max()
/////////////
// HELPERS //
/////////////
(* @brief Waits for any key to be pressed (and handles extended keys correctly) *)
procedure waitForAnyKey();
begin
//wait for key - but watch out for extended keys...
if readKey() = #0 then
begin
//...because they mean we need to read again.
readKey();
end;
end;
(* @brief Sets the console state back to the default - white on black, full size *)
procedure resetConsoleState();
begin
crt.window(1, 1, SCREEN_WIDTH, SCREEN_HEIGHT);
crt.textbackground(BLACK);
crt.textcolor(WHITE);
end;
(* @brief Returns a random index in range [low, high] *)
function getRandomIndex(low, high : integer) : integer;
begin
//random returns a number in [0, n[
getRandomIndex := low + random(high - low + 1);
end;
(* @brief Whether a given index is outside of the bounds - more verbose than rewriting the check. *)
function isOutOfBounds(lowerBound, upperBound, index : integer) : boolean;
begin
isOutOfBounds := (index < lowerBound) or (index > upperBound);
end;
////////////
// MENUS //
////////////
procedure showMainMenu();
begin
//well, just print it :D
clrscr();
writeln('TETRIS');
writeln();
writeln(NEWGAME_KEY, ') start');
writeln(HELP_KEY, ') help');
writeln(QUIT_KEY, ') quit');
end;
procedure showHelp();
begin
//Printing a help text is not exactly an art... Just write it.
clrscr();
writeln('How to play:');
writeln();
writeln('Move the block with ', LEFT_KEY, ' and ', RIGHT_KEY, ', rotate it with ', ROTATE_KEY, ' and speed it up with ', SPEED_KEY,'.');
writeln('Press Escape at any time to return to the main menu.');
writeln();
writeln('Press any key to continue.');
waitForAnyKey();
end;
//////////////////
// GAME STUFF //
//////////////////
(* @brief Calculates the time a block needs to fall 1 step from the current level. *)
function calculateDropTime(level : integer) : integer;
begin
//0 would be bad (drop infinitely in one timestep, insta-lose), so we have a minimum of 1. (Which is still pretty much impossible to win, but it won't be reached until level 1333.)
calculateDropTime := math.max(1, round(2/(level+1))) * BASE_DROP_TIME;
end;
(* @brief Awards points and increases the level, called for each row that's removed. *)
procedure onRowRemoved(var state : TGameState);
begin
state.level := state.level + 1;
state.score := state.score + 10;
end;
(* @brief Randomizes shape & color of a tetromino. *)
procedure randomizeTetromino(var tet : TTetromino);
begin
tet.shape := TETROMINO_SHAPES[getRandomIndex(low(TETROMINO_SHAPES), high(TETROMINO_SHAPES))];
//tet.shape := TETROMINO_SHAPES[getRandomIndex(0, 3)];
tet.color := TETROMINO_COLORS[getRandomIndex(low(TETROMINO_COLORS), high(TETROMINO_COLORS))];
//tet.color := TETROMINO_COLORS[getRandomIndex(0, 3)];
end;
(* @brief Moves a given Tetromino to the top center of the gamefield where it can begin its fall. *)
procedure moveToTopCenter(var tet : TTetromino);
var
//minimum Y value - want to make sure it's directly at the top.
minY : integer = 99;
pos : TVector2i;
begin
tet.position.x := round(GAMEFIELD_WIDTH / 2);
for pos in tet.shape do
begin
minY := math.min(minY, pos.y);
end;
tet.position.y := -minY + 1; //offset by 1 since y coordinates start at 1
end;
(* @brief Moves a given tetromino in the right position to be displayed in the preview. *)
procedure moveToPreviewPosition(var tet : TTetromino);
begin
//offset by 1 since coordinates start with (1, 1)
tet.position.x := -TETROMINO_MIN_X + 1;
tet.position.y := -TETROMINO_MIN_Y + 1;
end;
(* @brief Renders a given tetromino. *)
procedure renderTet(var tet : TTetromino);
var
pos : TVector2i;
begin
//set color
crt.textcolor(tet.color);
//draw parts of shape
for pos in tet.shape do
begin
pos += tet.position;
crt.gotoxy(pos.x, pos.y);
write(TETROMINO_CHAR);
end;
end;
(* @brief Initializes the Game State (i.e. all the game variables) *)
procedure initState(var state : TGameState);
var
x, y : integer;
begin
state.score := 0;
state.level := 1;
state.timeToDrop := calculateDropTime(state.level);
state.running := true;
state.lastFrameTime := UTime.getMillisecondsSinceMidnight();
//init cells
for y := low(state.gamefield) to high(state.gamefield) do
begin
for x := low(state.gamefield[y]) to high(state.gamefield[y]) do
begin
state.gamefield[y][x].occupied := false;
end;
end;
//init tetrominoes
randomizeTetromino(state.nextTetromino);
moveToPreviewPosition(state.nextTetromino);
randomizeTetromino(state.currentTetromino);
moveToTopCenter(state.currentTetromino);
end;
(* @brief Rotates the given tetromino 90 degrees counterclockwise. *)
procedure rotateCCW(var tet : TTetromino);
var
i, temp : integer;
begin
//rotate each part
for i := low(tet.shape) to high(tet.shape) do
begin
//see: rotation matrix, inverted due to Y-Down-Coordinate System.
temp := tet.shape[i].y;
tet.shape[i].y := tet.shape[i].x;
tet.shape[i].x := - temp;
end;
end;
(* @brief Whether a given Tetronimo fits on the gamefield, i.e. not ouf of bounds or on occupied cells. *)
function doesTetrominoFit(var gamefield : TGamefield; var tet : TTetromino) : boolean;
var
curPos : TVector2i;
begin
//it fits...
doesTetrominoFit := true;
//...unless any parts of it don't.
for curPos in tet.shape do
begin
curPos := curPos + tet.position;
//is Y out of range?
if isOutOfBounds(low(gamefield), high(gamefield), curPos.y) then
begin
doesTetrominoFit := false;
end
//is X out of range?
else if isOutOfBounds(low(gamefield[curPos.y]), high(gamefield[curPos.y]), curPos.x) then
begin
doesTetrominoFit := false;
end
//is it occupied?
else if gamefield[curPos.y][curPos.x].occupied then
begin
doesTetrominoFit := false;
end;
end;
end;
(* @brief Whether a Tetromino is one the floor, i.e. would not fit one block below. *)
function isTetrominoOnFloor(var gamefield : TGamefield; var tet : TTetromino) : boolean;
var
tempTet : TTetromino;
begin
tempTet := tet;
tempTet.position.y += 1;
isTetrominoOnFloor := not doesTetrominoFit(gamefield, tempTet);
end;
(* @brief Creates a Game Over overlay and waits for the user to press any key. *)
procedure showGameOverScreen();
begin
//create window for game over
crt.window(GAMEOVER_WINDOW_POS_X, GAMEOVER_WINDOW_POS_Y, GAMEOVER_WINDOW_POS_X + GAMEOVER_WINDOW_WIDTH - 1, GAMEOVER_WINDOW_POS_Y + GAMEOVER_WINDOW_HEIGHT - 1);
//set color/background
crt.textbackground(RED);
crt.textcolor(BLACK);
//clear & write GAME OVER
crt.clrscr();
crt.gotoxy(GAMEOVER_TEXT_POS_X, GAMEOVER_TEXT_POS_Y);
write(GAMEOVER_TEXT);
//undo changes
resetConsoleState();
//wait for any key
waitForAnyKey();
end;
(* @brief Displays everything. Only clears first if initial is true (thus sets the background), only overwrites otherwise (makes missing double buffering less obvious) *)
procedure render(var state : TGameState; initial : boolean);
var
x, y, i : integer;
curPos : TVector2i;
//current tetromino shape in absolute coordinates
curTetShapeAbs : TTetrominoShape;
begin
//calculate absolute position of the current tetromino's parts so we can print them in the gamefield render loop
for i := low(state.currentTetromino.shape) to high(state.currentTetromino.shape) do
begin
curTetShapeAbs[i] := state.currentTetromino.position + state.currentTetromino.shape[i];
end;
//clear
if initial then crt.clrscr();
//all windows have gray background.
crt.textbackground(crt.LIGHTGRAY);
// display gamefield
//set window & background color accordingly
crt.window(GAMEFIELD_POS_X, GAMEFIELD_POS_Y, GAMEFIELD_POS_X + GAMEFIELD_WIDTH - 1, GAMEFIELD_POS_Y + GAMEFIELD_HEIGHT - 1);
if initial then crt.clrscr();
//make actual window 1 longer, since writing at the very end would otherwise result in scrolling since the cursor enters the next line
crt.window(GAMEFIELD_POS_X, GAMEFIELD_POS_Y, GAMEFIELD_POS_X + GAMEFIELD_WIDTH - 1, GAMEFIELD_POS_Y + GAMEFIELD_HEIGHT);
//render game field
gotoxy(1, 1);
for y := low(state.gamefield) to high(state.gamefield) do
begin
for x := low(state.gamefield[y]) to high(state.gamefield[y]) do
begin
//is a "dropped" tetromino part here?
if state.gamefield[y][x].occupied then
begin
crt.textcolor(state.gamefield[y][x].color);
write(TETROMINO_CHAR);
end
//is the current tetromino here?
else
begin
for curPos in curTetShapeAbs do
begin
if (curPos.x = x) and (curPos.y = y) then
begin
crt.textcolor(state.currentTetromino.color);
write(TETROMINO_CHAR);
end;
end;
end;
//nope, nothing here (i.e. old cursor position)
if crt.whereX() = x then
begin
write(' ');
end;
end;
//lines automatically wrap thanks to crt.window()
end;
//render current tetromino
renderTet(state.currentTetromino);
// Display next Tetromino
//set window accordingly (keep bg color)
crt.window(PREVIEW_BOX_POS_X, PREVIEW_BOX_POS_Y, PREVIEW_BOX_POS_X + PREVIEW_BOX_WIDTH - 1, PREVIEW_BOX_POS_Y + PREVIEW_BOX_HEIGHT - 1);
//always clear, checking's too much of a hassle.
crt.clrscr();
//make actual window 1 longer, since writing at the very end would otherwise result in scrolling since the cursor enters the next line
crt.window(PREVIEW_BOX_POS_X, PREVIEW_BOX_POS_Y, PREVIEW_BOX_POS_X + PREVIEW_BOX_WIDTH - 1, PREVIEW_BOX_POS_Y + PREVIEW_BOX_HEIGHT);
//display it
renderTet(state.nextTetromino);
// Display score/points
//set window accordingly (keep bg color)
crt.window(INFO_BOX_POS_X, INFO_BOX_POS_Y, INFO_BOX_POS_X + INFO_BOX_WIDTH - 1, INFO_BOX_POS_Y + INFO_BOX_HEIGHT - 1);
if initial then crt.clrscr();
//make actual window 1 longer, since writing at the very end would otherwise result in scrolling since the cursor enters the next line
crt.window(INFO_BOX_POS_X, INFO_BOX_POS_Y, INFO_BOX_POS_X + INFO_BOX_WIDTH - 1, INFO_BOX_POS_Y + INFO_BOX_HEIGHT);
//display them
crt.textcolor(crt.BLACK);
crt.gotoxy(1, 1);
write('score: ',state.score);
crt.gotoxy(1, 2);
write('level: ',state.level);
// Reset state
resetConsoleState();
end;
procedure removeFullRows(var state : TGameState);
var
curRowIndex, i : integer;
function isCurrentRowFull() : boolean;
var
curCellIndex : integer;
begin
isCurrentRowFull := true;
//when any cell is not occupied, the row's not full. duh.
for curCellIndex := low(state.gamefield[curRowIndex]) to high(state.gamefield[curRowIndex]) do
begin
if not state.gamefield[curRowIndex][curCellIndex].occupied then
begin
isCurrentRowFull := false;
end;
end;
end;
begin
//there's no down-counting for loop, I think. I do it myself.
curRowIndex := high(state.gamefield);
while curRowIndex >= low(state.gamefield) do
begin
//if the row is full...
if isCurrentRowFull() then
begin
onRowRemoved(state);
//move all above down.
i := curRowIndex;
while i > low(state.gamefield) do
begin
state.gamefield[i] := state.gamefield[i-1];
i -= 1;
end;
//and empty the top one
for i := low(state.gamefield[low(state.gamefield)]) to high(state.gamefield[low(state.gamefield)]) do
begin
state.gamefield[low(state.gamefield)][i].occupied := false;
end;
end;
curRowIndex -= 1;
end;
end;
(* @brief Called whenever the current Tet has been moved. Checks whether it's at the bottom and locks it if necessary. *)
procedure onCurTetMoved(var state : TGameState);
var
pos : TVector2i;
begin
if isTetrominoOnFloor(state.gamefield, state.currentTetromino) then
begin
//we hit the floor.
//so we need to embed this on the gamefield.
//since we only ever move stuff within the gamefield we don't have to check the array bounds.
for pos in state.currentTetromino.shape do
begin
pos += state.currentTetromino.position;
state.gamefield[pos.y][pos.x].occupied := true;
state.gamefield[pos.y][pos.x].color := state.currentTetromino.color;
end;
//remove filled rows
removeFullRows(state);
//now we need a new tetromino.
state.currentTetromino := state.nextTetromino;
moveToTopCenter(state.currentTetromino);
randomizeTetromino(state.nextTetromino);
//since the state changed, we need to re-render. But before any possible game over overlay.
render(state, false);
//which may already be hitting the blocks below, in which case the player's lost.
if isTetrominoOnFloor(state.gamefield, state.currentTetromino) or not doesTetrominoFit(state.gamefield, state.currentTetromino) then
begin
state.running := false;
showGameOverScreen();
end;
end
else
begin
//since the state changed, we need to re-render.
render(state, false);
end;
end;
(* @brief Tries moving the current Tetromino as requested by player (input) *)
procedure tryMove(var state : TGameState; requestedMove : TRequestedMove);
var
tempTet : TTetromino;
begin
//create copy...
tempTet := state.currentTetromino;
//...and do the requested move on it.
case requestedMove of
mvRight:
tempTet.position.x += 1;
mvLeft:
tempTet.position.x -= 1;
mvDown:
tempTet.position.y += 1;
mvRotate:
rotateCCW(tempTet);
end;
//is it possible?
if doesTetrominoFit(state.gamefield, tempTet) then
begin
//if so: apply to actual tetromino.
state.currentTetromino := tempTet;
onCurTetMoved(state);
end;
end;
(* @brief Handles input, i.e. block moving and quitting. *)
procedure handleInput(var state : TGameState);
var
key : char;
begin
//read complete input buffer
while keyPressed() do
begin
key := readKey();
case key of
//#0 means extended key -> read again (but ignore, they're not of interest to me.)
#0:
begin
readKey();
end;
//QUIT?
ESCAPE_KEY:
begin
state.running := false;
end;
//MOVE LEFT
LEFT_KEY,
LEFT_KEY_ALT:
begin
tryMove(state, mvLeft);
end;
//MOVE RIGHT
RIGHT_KEY,
RIGHT_KEY_ALT:
begin
tryMove(state, mvRight);
end;
//MOVE DOWN
SPEED_KEY,
SPEED_KEY_ALT:
begin
tryMove(state, mvDown);
end;
//ROTATE (why am I writing in caps?)
ROTATE_KEY,
ROTATE_KEY_ALT:
begin
tryMove(state, mvRotate);
end;
end;
end;
end;
procedure advanceFrame(var state : TGameState);
var
now : longint;
deltaT : integer;
begin
//calculate time step (delta t)
now := UTime.getMillisecondsSinceMidnight();
deltaT := UTime.getDifference(now, state.lastFrameTime);
//set last frame time so we'll be able to calculate this correctly next frame, too.
state.lastFrameTime := now;
//see if we need to drop the current tet
state.timeToDrop -= deltaT;
while (state.timeToDrop < 0) and state.running do //check for running, too, since this might cause a game over
begin
//yes, we need to. do it.
state.currentTetromino.position.y += 1;
//check if we hit the floor
onCurTetMoved(state);
//and set time to next drop (which may be in the past, hence while not if)
state.timeToDrop += calculateDropTime(state.level);
end;
end;
procedure runGame();
var
state : TGameState;
begin
randomize(); //init random number generation
initState(state);
render(state, true); //do initial rendering, i.e. draw background
while state.running do
begin
//render(state, false); //now I only call render when a tetromino's been moved.
handleInput(state);
advanceFrame(state);
end;
end;
begin
end.
|
unit LoggerInterface;
interface
uses
{$IFDEF VER320+}
System.Classes;
{$ELSE}
Classes;
{$ENDIF}
const
MsgLen = 100;
type
TLogInfo = (
lNone, lInfo, lEvent, lDebug, lPortWrite, lPortRead, lTrace, lWarning, lError,
lEnter, lLeave,
lLastError, lException, lExceptionOS, lMemory, lStackTrace,
lFail, lSQL, lCache, lResult, lDB, lHTTP, lClient, lServer,
lServiceCall, lServiceReturn, lUserAuth, lCustom2);
TLogInfos = set of TLogInfo;
pLogConfig = ^TLogConfig;
TLogConfig = record
Levels: TLogInfos;
ArhiveBeforeDelete : boolean;
ArchiveAfterDays,
MaxMBSize,
AutoFlushTimeOut : Word;
procedure Assign(ASource : pLogConfig);
end;
pLogClassConfig = ^TLogClassConfig;
TLogClassConfig = record
ConfigGUID : TGUID;
EnabledLevels,
DefaultLevelsView : TLogInfos;
FileExtension,
ArhiveExtension,
ModuleName : String;
procedure Assign(ASource : pLogClassConfig);
end;
ILogger = interface(IInterface)
['{1A2589E0-0BCA-45BC-BF5E-6B90EE658438}']
procedure GetConfig(AConfig: pLogConfig); stdcall;
procedure SetConfig(AConfig: pLogConfig); stdcall;
procedure GetClassConfig(Config : pLogClassConfig);stdcall;
/// call this method to add some information to the log at a specified level
// - if Instance is set and Text is not '', it will log the corresponding
// class name and address (to be used e.g. if you didn't call TSynLog.Enter()
// method first)
// - if Instance is set and Text is '', will behave the same as
// Log(Level,Instance), i.e. write the Instance as JSON content
procedure Log(Level: TLogInfo; const Text: String;
Instance: TObject=nil); overload; stdcall;
/// call this method to add the content of an object to the log at a
// specified level
// - TSynLog will write the class and hexa address - TSQLLog will write the
// object JSON content
procedure Log(Level: TLogInfo; Instance: TObject); overload; stdcall;
/// call this method to add the caller address to the log at the specified level
// - if the debugging info is available from TSynMapFile, will log the
// unit name, associated symbol and source code line
procedure Log(Level: TLogInfo=lTrace); overload; stdcall;
function LevelEnabled(ALevel : TLogInfo):boolean; stdcall;
procedure Flush(ForceDiskWrite: boolean); stdcall;
end;
ILoggers = interface;
ILoggingConfStoreAccess = interface (IInterface)
['{6303826E-FDFC-4792-8D57-55E335AF844D}']
procedure LoadLoggerConfig(const ALogger : ILogger); stdcall;
procedure SaveLoggerConfig(const ALogger : ILogger); stdcall;
procedure LoadLoggersConfig(const ALoggers : ILoggers); stdcall;
procedure SaveLoggersConfig(const ALoggers : ILoggers); stdcall;
end;
ILoggers = interface(IInterface)
['{2AB87410-E63B-4E6B-9264-66BE61149CB4}']
function Count : Word; stdcall;
function GetItem(Index : Word; const IID: TGUID; out obj):Boolean; stdcall;
function FindByGUID(const IID: TGUID; out Obj):boolean;stdcall;
procedure SetStoreInterface(const Value: ILoggingConfStoreAccess); stdcall;
property Item[Index : Word; const IID: TGUID; out obj]:Boolean read GetItem;
function ShowLogFrm(AOwner : TComponent):TComponent; stdcall;
procedure ShowModalLogFrm(AOwner : TComponent); stdcall;
end;
TLoggerFunct = record
strict private
fLibHandle : THandle;
fLoggers : ILoggers;
fInitLogers : function (const StoreInterface :ILoggingConfStoreAccess; out Obj):boolean; stdcall;
fAddLogger : function (AConfig : pLogClassConfig; out Obj):boolean; stdcall;
fAchLogs : procedure(AOwner : TComponent); stdcall;
fShowLogFrm : function(AOwner : TComponent):TComponent; stdcall;
fShowModalLogFrm : procedure(AOwner : TComponent); stdcall;
function GetItem(Index : Word; out obj):Boolean; stdcall;
public
function Count : Word;
function FindByGUID(const IID: TGUID; out Obj):boolean;
property Item[Index : Word; out obj]:Boolean read GetItem; default;
function AddLogger(AConfig : pLogClassConfig; out Obj):boolean;
procedure AchLogs(AOwner : TComponent);
function ShowLogFrm(AOwner : TComponent):TComponent;
procedure ShowModalLogFrm(AOwner : TComponent);
function Init(const StoreInterface :ILoggingConfStoreAccess=nil) : boolean;
procedure SetStoreInterface(const Value: ILoggingConfStoreAccess);
procedure FlushAll;
procedure Done;
end;
pLoggerFunct = ^TLoggerFunct;
const
C_EventCaption: array[TLogInfo] of String = (
'None', 'Info', 'Event', 'Debug', 'Port Write', 'Port Read', 'Trace', 'Warning', 'Error',
'Enter', 'Leave',
'LastError', 'Exception', 'ExceptionOS', 'Memory', 'StackTrace', 'Fail',
'SQL', 'Cache', 'Result', 'DB', 'http', 'Client', 'Server',
'ServiceCall', 'ServiceReturn', 'UserAuth', 'Custom2');
implementation
uses
{$IFDEF VER320+}
System.SysUtils, Winapi.Windows;
{$ELSE}
SysUtils, Windows;
{$ENDIF}
type
TPackageLoad = procedure;
TPackageUnload = procedure;
{ TLogConfig }
procedure TLogConfig.Assign(ASource: pLogConfig);
begin
Self.Levels := ASource^.Levels;
Self.ArhiveBeforeDelete := ASource^.ArhiveBeforeDelete;
Self.ArchiveAfterDays := ASource^.ArchiveAfterDays;
Self.MaxMBSize := ASource^.MaxMBSize;
Self.AutoFlushTimeOut := ASource^.AutoFlushTimeOut;
end;
{ TLogClassConfig }
procedure TLogClassConfig.Assign(ASource: pLogClassConfig);
begin
Self.ConfigGUID := ASource^.ConfigGUID;
Self.EnabledLevels := ASource^.EnabledLevels;
Self.DefaultLevelsView := ASource^.DefaultLevelsView;
Self.FileExtension := ASource^.FileExtension;
Self.ArhiveExtension := ASource^.ArhiveExtension;
Self.ModuleName := ASource^.ModuleName;
end;
function TLoggerFunct.Init(const StoreInterface :ILoggingConfStoreAccess=nil) : boolean;
var GetLoggers : function (out Obj):Boolean;stdcall;
vInitProc: TPackageLoad;
begin
Result := False;
if not FileExists('Logger.bpl') then
Exit;
fLibHandle := GetModuleHandle('Logger.bpl');
if fLibHandle <> 0 then
begin
@GetLoggers := GetProcAddress(fLibHandle, 'GetLoggers');
if Assigned(GetLoggers) and GetLoggers(fLoggers) then
begin
@fInitLogers := GetProcAddress(fLibHandle, 'InitLogers');
@fAddLogger := GetProcAddress(fLibHandle, 'AddLogger');
@fAchLogs := GetProcAddress(fLibHandle, 'AchLogs');
@fShowLogFrm := GetProcAddress(fLibHandle, 'ShowLogFrm');
@fShowModalLogFrm := GetProcAddress(fLibHandle, 'ShowModalLogFrm');
Result := True;
Exit;
end else
begin
FreeLibrary(fLibHandle);
fLibHandle := 0;
end;
end;
if fLibHandle <> 0 then
Exit;
fLibHandle := SafeLoadLibrary('Logger.bpl',
SEM_NOOPENFILEERRORBOX or SEM_FAILCRITICALERRORS or SEM_NOGPFAULTERRORBOX);
@vInitProc := GetProcAddress(fLibHandle, 'Initialize');
@fInitLogers := GetProcAddress(fLibHandle, 'InitLogers');
@fAddLogger := GetProcAddress(fLibHandle, 'AddLogger');
@fAchLogs := GetProcAddress(fLibHandle, 'AchLogs');
@fShowLogFrm := GetProcAddress(fLibHandle, 'ShowLogFrm');
@fShowModalLogFrm := GetProcAddress(fLibHandle, 'ShowModalLogFrm');
if Assigned(vInitProc)
and Assigned(fInitLogers)
and Assigned(fAddLogger)
and Assigned(fAchLogs)
and Assigned(fShowLogFrm)
and Assigned(fShowModalLogFrm) then
begin
vInitProc;
Result := fInitLogers(StoreInterface, fLoggers);
end;
if (not result) and (fLibHandle <> 0) then
begin
UnloadPackage(fLibHandle);
fLibHandle := 0;
end;
end;
function TLoggerFunct.FindByGUID(const IID: TGUID; out Obj): boolean;
begin
Result := Assigned(fLoggers) and fLoggers.FindByGUID(IID, Obj);
end;
procedure TLoggerFunct.FlushAll;
var
i : word;
vLogger : ILogger;
begin
if Assigned(fLoggers) then
begin
i := 0;
while i < fLoggers.Count do
begin
if fLoggers.Item[i, ILogger, vLogger] then
vLogger.Flush(true);
vLogger := nil;
Inc(i);
end;
end;
end;
function TLoggerFunct.GetItem(Index: Word; out obj): Boolean;
begin
Result := Assigned(fLoggers) and fLoggers.GetItem(Index, ILogger, Obj);
end;
procedure TLoggerFunct.AchLogs(AOwner: TComponent);
begin
if Assigned(fAchLogs) then
fAchLogs(AOwner);
end;
function TLoggerFunct.AddLogger(AConfig: pLogClassConfig; out Obj): boolean;
begin
Result := Assigned(fAddLogger) and fAddLogger(AConfig, Obj);
end;
function TLoggerFunct.Count: Word;
begin
if Assigned(fLoggers) then
Result := fLoggers.Count
else
Result := 0;
end;
procedure TLoggerFunct.SetStoreInterface(const Value: ILoggingConfStoreAccess);
begin
if Assigned(fLoggers) then
fLoggers.SetStoreInterface(Value);
end;
function TLoggerFunct.ShowLogFrm(AOwner: TComponent):TComponent;
begin
if Assigned(fShowLogFrm) then
result := fShowLogFrm(AOwner)
else
Result := nil;
end;
procedure TLoggerFunct.ShowModalLogFrm(AOwner: TComponent);
begin
if Assigned(fShowModalLogFrm) then
fShowModalLogFrm(AOwner);
end;
procedure TLoggerFunct.Done;
var
vFinalizeProc: TPackageUnload;
begin
fLoggers := nil;
if (fLibHandle <> 0) then
try
@vFinalizeProc := GetProcAddress(fLibHandle, 'Finalize'); //Do not localize
if Assigned(vFinalizeProc) then
vFinalizeProc;
FreeLibrary(fLibHandle);
finally
fLibHandle := 0;
end;
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/Products/prodProductForm.pas,v 1.7 2004/05/06 15:24:06 paladin Exp $
------------------------------------------------------------------------}
unit prodProductForm;
interface
uses
Forms, cxLookAndFeelPainters, dxExEdtr, ExtDlgs, Dialogs, TB2Item, Menus,
Classes, ActnList, cxCheckBox, cxDBEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, dxInspct, dxInspRw, dxCntner,
cxMaskEdit, cxMemo, cxControls, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxButtons, Controls, ExtCtrls, Graphics, Types,
PluginManagerIntf, DB;
type
TProductForm = class(TForm)
Panel4: TPanel;
OK: TcxButton;
Cancel: TcxButton;
ActionList: TActionList;
ActionOK: TAction;
title: TcxDBTextEdit;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
product_article: TcxDBTextEdit;
full_title: TcxDBMemo;
Label5: TLabel;
Label6: TLabel;
name: TcxDBMaskEdit;
Go: TcxButton;
PricesList: TAction;
TBPopupMenu1: TTBPopupMenu;
UnitsList: TAction;
Action1: TAction;
TBItem1: TTBItem;
TBItem2: TTBItem;
Label7: TLabel;
description: TcxDBMemo;
EditDescription: TcxButton;
InspPanel: TPanel;
Inspector: TdxInspector;
type_id: TcxDBLookupComboBox;
is_visible: TcxDBCheckBox;
is_printable: TcxDBCheckBox;
Label3: TLabel;
OpenDialog: TOpenDialog;
OpenPictureDialog: TOpenPictureDialog;
InspectorRow1: TdxInspectorTextButtonRow;
cxButton1: TcxButton;
procedure UnitsListExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionOKExecute(Sender: TObject);
procedure InspectorEnter(Sender: TObject);
procedure InspectorExit(Sender: TObject);
procedure InspectorDrawValue(Sender: TdxInspectorRow; ACanvas: TCanvas;
ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor;
var ADone: Boolean);
procedure InspectorEdited(Sender: TObject; Node: TdxInspectorNode;
Row: TdxInspectorRow);
procedure InspectorGetEditFont(Sender: TdxInspectorRow;
var AFont: TFont);
procedure EditDescriptionClick(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure titlePropertiesEditValueChanged(Sender: TObject);
private
FPluginManager: IPluginManager;
procedure AddStringRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddIntRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddBooleanRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddEnumRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddSetRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddTextRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddUrlRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddPictureRow(Row: TdxInspectorRow; DataSet: TDataSet);
procedure AddFileRow(Row: TdxInspectorRow; DataSet: TDataSet);
//
procedure SetRowChange(Sender: TObject);
function GetInspectorRecord(DataSet: TDataSet; const FieldName, KeyName: String): TObject;
procedure TextRowButtonClick(Sender: TObject; AbsoluteIndex: Integer);
procedure FileRowButtonClick(Sender: TObject; AbsoluteIndex: Integer);
procedure PictureRowButtonClick(Sender: TObject; AbsoluteIndex: Integer);
//
procedure LoadPrices;
procedure LoadUnitns;
procedure LoadProperties(type_id: Integer);
//
function AddRecord(DataSet: TDataSet; Row: TdxInspectorRow;
AddText: Boolean = True): String;
public
procedure LoadInspector;
procedure SaveInspector;
property PluginManager: IPluginManager read FPluginManager write FPluginManager;
end;
function GetProductForm(PluginManager: IPluginManager): Integer;
implementation
uses progDataModule, prodMainForm, prodUnitsListForm,
DBClient, SysUtils, DeviumLib, HTMLEditorIntf, prodTypes, Variants, Math,
Windows, prodShowImage;
{$R *.dfm}
const
ABoldFlag = 01;
function GetProductForm;
var
Form: TProductForm;
begin
Form := TProductForm.Create(Application);
try
Form.PluginManager := PluginManager;
if DM.Products['is_folder'] = 1 then
Form.Caption := 'Карточка группы';
Result := Form.ShowModal;
if Result = mrOK then
Form.SaveInspector;
finally
Form.Free;
end;
end;
procedure PrepareValueFont(ARow: TdxInspectorRow; AFont: TFont);
begin
if ARow.Tag and ABoldFlag <> 0 then
AFont.Style := AFont.Style + [fsBold];
end;
procedure RowChanged(ARow: TdxInspectorRow);
begin
ARow.Tag := aRow.Tag or ABoldFlag;
end;
{
procedure GetText(ARow: TdxInspectorTextCheckRow; var AText: string);
begin
if ARow.GetCheckBoxState(ARow.EditText) = dxExEdtr.cbsChecked then
begin
if AText <> '' then
AText := AText + ', ';
AText := AText + ARow.Caption;
end;
end;
}
procedure TProductForm.UnitsListExecute(Sender: TObject);
begin
GetUnitsListForm;
end;
procedure TProductForm.FormCreate(Sender: TObject);
begin
LoadInspector;
end;
procedure TProductForm.LoadInspector;
begin
Inspector.ClearNodes;
Inspector.ClearRows;
LoadPrices;
LoadUnitns;
if not type_id.DataBinding.Field.IsNull then
LoadProperties(type_id.DataBinding.Field.Value);
end;
procedure TProductForm.SaveInspector;
var
i, j: Integer;
R: TInspectorRecord;
s: String;
LFileName, LFilePath, LFileExt: String;
begin
LFileName := '';
with DM.Values, Inspector do
begin
for i := 0 to Inspector.TotalRowCount - 1 do
if Assigned(Rows[i].LinkObject) then
begin
R := TInspectorRecord(Rows[i].LinkObject);
if Locate(R.KeyName, R.KeyValue, []) then
begin
s := Rows[i].EditText;
// (copy|delete) file before (save|delete)
// 1. проверка та тип
if Rows[i] is TInspectorTextRow then
begin
LFilePath := Dm.GetLocalPath(DM.Values);
if (Length(Trim(s)) = 0)
and (Length(Trim(FieldValues['value'])) > 0)
and (FileExists(LFilePath + FieldValues['value']))
then
SysUtils.DeleteFile(LFilePath + FieldValues['value']);
// сравнение на то что это путь
if Length(ExtractFilePath(s)) > 0 then
begin
if FileExists(s) then
begin
LFileName := ExtractFileName(s);
LFileExt := ExtractFileExt(LFileName);
j := Pos(LFileExt, LFileName);
LFileName := copy(LFileName, 1, j);
LFileName := TransLiterStr(LFileName) + LFileExt;
ForceDirectories(LFilePath);
if CopyFile(PChar(s), PChar(LFilePath + LFileName), False) then
s := LFileName;
end;
end;
end;
// end
Edit;
FieldValues['value'] := s;
Post;
end;
end;
end;
end;
procedure TProductForm.ActionOKExecute(Sender: TObject);
begin
OK.SetFocus;
ModalResult := mrOK;
end;
procedure TProductForm.AddTextRow;
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorTextRow);
Node.Row.Caption := DataSet['property_title'];
Node.Row.ReadOnly := True;
//Node.Row.EditText := '(Текст)';
AddRecord(DataSet, Node.Row);
TInspectorTextRow(Node.Row).OnButtonClick := TextRowButtonClick;
end;
procedure TProductForm.AddEnumRow;
var
Node: TdxInspectorRowNode;
ARow: TInspectorEnumRow;
begin
Node := Row.Node.AddChildEx(TInspectorEnumRow);
ARow := TInspectorEnumRow(Node.Row);
ARow.PopupBorder := pbFlat;
ARow.Caption := DataSet['property_title'];
ARow.DropDownListStyle := True;
ARow.Items.DelimitedText := DataSet['length_set'];
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.AddIntRow;
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorIntRow);
Node.Row.Caption := DataSet['property_title'];
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.AddPictureRow;
var
Node: TdxInspectorRowNode;
B: TdxEditButton;
begin
Node := Row.Node.AddChildEx(TInspectorTextRow);
Node.Row.Caption := DataSet['property_title'];
B := TInspectorTextRow(Node.Row).Buttons.Add;
B.Glyph.LoadFromResourceName(HInstance, 'GLYPH_VIEW');
B.Kind := dxExEdtr.bkGlyph;
TInspectorTextRow(Node.Row).OnButtonClick := PictureRowButtonClick;
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.AddSetRow;
var
Node: TdxInspectorRowNode;
ANode: TdxInspectorRowNode;
sl, sl_value: TStringList;
i: Integer;
begin
Node := Row.Node.AddChildEx(TInspectorStringRow);
Node.Row.Caption := DataSet['property_title'];
Node.Row.EditText := AddRecord(DataSet, Node.Row, False);
Node.Row.ReadOnly := True;
sl_value := TStringList.Create;
try
sl_value.DelimitedText := Node.Row.EditText;
sl := TStringList.Create;
try
sl.DelimitedText := DataSet['length_set'];
for i := 0 to sl.Count - 1 do
begin
ANode := Node.AddChildEx(TdxInspectorTextCheckRow);
ANode.Row.Caption := sl[i];
ANode.Row.OnChange := SetRowChange;
if sl_value.IndexOf(sl[i]) > -1 then
TdxInspectorTextCheckRow(ANode.Row).EditText := 'True';
end;
{ TODO : Проверить на сложные назавания (содержащие пробел) }
finally
sl.Free;
end;
finally
sl_value.Free;
end;
end;
procedure TProductForm.InspectorEnter(Sender: TObject);
begin
InspPanel.Color := clActiveCaption;
end;
procedure TProductForm.InspectorExit(Sender: TObject);
begin
InspPanel.Color := clBtnShadow;
end;
procedure TProductForm.SetRowChange(Sender: TObject);
var
Row: TdxInspectorRow;
Node, CNode: TdxInspectorRowNode;
i: Integer;
sl: TStringList;
CheckRow: TdxInspectorTextCheckRow;
begin
Inspector.PostEditor;
Row := TdxInspectorRow(Sender);
Node := TdxInspectorRowNode(Row.Node.Parent);
sl := TStringList.Create;
try
for i := 0 to Node.Count - 1 do
begin
CNode := TdxInspectorRowNode(Node[i]);
CheckRow := TdxInspectorTextCheckRow(CNode.Row);
if CheckRow.GetCheckBoxState(CheckRow.EditText) = dxExEdtr.cbsChecked then
sl.Add(CheckRow.Caption);
end;
Node.Row.EditText := sl.DelimitedText;
finally
sl.Free;
end;
RowChanged(Node.Row);
end;
procedure TProductForm.InspectorDrawValue(Sender: TdxInspectorRow;
ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont;
var AColor: TColor; var ADone: Boolean);
begin
PrepareValueFont(Sender, AFont);
end;
procedure TProductForm.InspectorEdited(Sender: TObject;
Node: TdxInspectorNode; Row: TdxInspectorRow);
begin
RowChanged(Row);
end;
procedure TProductForm.InspectorGetEditFont(Sender: TdxInspectorRow;
var AFont: TFont);
begin
PrepareValueFont(Sender, AFont);
end;
{ TInspectorRecord }
function TProductForm.GetInspectorRecord(DataSet: TDataSet;
const FieldName, KeyName: String): TObject;
var
R: TInspectorRecord;
begin
R := TInspectorRecord.Create;
R.DataSet := DataSet;
R.FieldName := FieldName;
R.Value := DataSet[FieldName];
R.KeyName := KeyName;
R.KeyValue := DataSet[KeyName];
Result := R;
end;
procedure TProductForm.TextRowButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
Editor: IHTMLEditor;
s: String;
R: TInspectorRecord;
begin
R := TInspectorRecord(TdxInspectorRow(Sender).LinkObject);
DM.Values.Locate(R.KeyName, R.KeyValue, []);
TdxInspectorRow(Sender).Tag := ABoldFlag; // делаем жирным
if FPluginManager.GetPlugin(IHTMLEditor, Editor) then
begin
s := TInspectorTextRow(Sender).EditText;
Editor.LocalPath := DM.GetLocalPath(DM.Values);
Editor.RemotePath := DM.GetRemotePath(Editor.LocalPath);
if Editor.Execute(s) then
begin
TInspectorTextRow(Sender).EditText := s;
end;
end;
end;
procedure TProductForm.LoadPrices;
var
Row: TdxInspectorRow;
Node: TdxInspectorRowNode;
begin
with DM.Prices do
begin
Filter := Format('product_id=%s', [DM.Products['product_id']]);
Filtered := True;
if RecordCount > 0 then
begin
Row := Inspector.CreateRow(TdxInspectorTextRow);
Row.Caption := 'Цены';
Row.ReadOnly := True;
First;
while not EOF do
begin
Node := Row.Node.AddChildEx(TdxInspectorTextCurrencyRow);
DM.PriceTypes.Locate('price_type_id', FieldValues['price_type_id'], []);
Node.Row.Caption := DM.PriceTypes['price_title'];
Node.Row.EditText := FieldValues['price'];
//,0.00р'.';-,0.00р'.'
TdxInspectorTextCurrencyRow(Node.Row).DisplayFormat := ',0.00$;-,0.00$';
Node.Row.LinkObject := GetInspectorRecord(DM.Prices, 'price', 'price_id');
Next;
end;
end;
Filtered := False;
end;
end;
procedure TProductForm.LoadUnitns;
var
Row: TdxInspectorRow;
Node: TdxInspectorRowNode;
begin
with DM.Units do
begin
Filter := Format('product_id=%s', [DM.Products['product_id']]);
Filtered := True;
if RecordCount > 0 then
begin
Row := Inspector.CreateRow(TdxInspectorTextRow);
Row.Caption := 'Еденицы';
Row.ReadOnly := True;
First;
while not EOF do
begin
Node := Row.Node.AddChildEx(TdxInspectorTextSpinRow);
DM.UnitNames.Locate('unit_name_id', FieldValues['unit_name_id'], []);
Node.Row.Caption := DM.UnitNames['unit_title'];
Node.Row.EditText := FieldValues['multiplier'];
Node.Row.LinkObject := GetInspectorRecord(DM.Units, 'multiplier', 'unit_id');
Next;
end;
end;
Filtered := False;
end;
end;
procedure TProductForm.LoadProperties(type_id: Integer);
var
Row: TdxInspectorRow;
begin
// Свойства
with DM.Properties do
begin
DM.Types.Locate('type_id', type_id, []);
Filter := Format('type_id=%d', [type_id]);
Filtered := True;
if RecordCount > 0 then
begin
Row := Inspector.CreateRow(TdxInspectorTextRow);
Row.Caption := 'Свойства';
Row.EditText := DM.Types['type_title'];
Row.ReadOnly := True;
First;
while not EOF do
begin
if FieldValues['is_public'] = 1 then
case GetPropertyIndex(FieldByName('datatype').AsString) of
1: AddStringRow(Row, DM.Properties);
2: AddIntRow(Row, DM.Properties);
3: AddBooleanRow(Row, DM.Properties);
4: AddEnumRow(Row, DM.Properties);
5: AddSetRow(Row, DM.Properties);
6: AddTextRow(Row, DM.Properties);
7: AddUrlRow(Row, DM.Properties);
8: AddPictureRow(Row, DM.Properties);
9: AddFileRow(Row, DM.Properties);
end;
Next;
end;
Row.Node.Expanded := True;
end;
Filtered := False;
end;
// будем подниматся выше
if DM.Types['parent_id'] > 0 then
LoadProperties(DM.Types['parent_id']);
end;
procedure TProductForm.AddStringRow(Row: TdxInspectorRow;
DataSet: TDataSet);
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorStringRow);
Node.Row.Caption := DataSet['property_title'];
AddRecord(DataSet, Node.Row);
end;
function TProductForm.AddRecord(DataSet: TDataSet; Row: TdxInspectorRow;
AddText: Boolean): String;
begin
with DM.Values do
begin
if not Locate('product_id;property_id', VarArrayOf([DM.Products['product_id'],
DataSet['property_id']]), [loPartialKey]) then
begin
Append;
FieldValues['product_id'] := DM.Products['product_id'];
FieldValues['property_id'] := DataSet['property_id'];
FieldValues['value'] := DataSet['default_value'];
Post;
end;
Result := Trim(FieldValues['value']);
if AddText then Row.EditText := Result;
Row.LinkObject := GetInspectorRecord(DM.Values, 'value', 'value_id');
end;
end;
procedure TProductForm.AddBooleanRow(Row: TdxInspectorRow;
DataSet: TDataSet);
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorBooleanRow);
Node.Row.Caption := DataSet['property_title'];
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.AddUrlRow(Row: TdxInspectorRow; DataSet: TDataSet);
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorUrlRow);
Node.Row.Caption := DataSet['property_title'];
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.AddFileRow(Row: TdxInspectorRow; DataSet: TDataSet);
var
Node: TdxInspectorRowNode;
begin
Node := Row.Node.AddChildEx(TInspectorTextRow);
Node.Row.Caption := DataSet['property_title'];
TInspectorTextRow(Node.Row).OnButtonClick := FileRowButtonClick;
AddRecord(DataSet, Node.Row);
end;
procedure TProductForm.FileRowButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
begin
if OpenDialog.Execute then
TInspectorTextRow(Sender).EditText := OpenDialog.FileName;
end;
procedure TProductForm.PictureRowButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
R: TInspectorRecord;
begin
// select
if AbsoluteIndex = 0 then
if OpenPictureDialog.Execute then
TInspectorTextRow(Sender).EditText := OpenPictureDialog.FileName;
// show
if AbsoluteIndex = 1 then
begin
R := TInspectorRecord(TdxInspectorRow(Sender).LinkObject);
DM.Values.Locate(R.KeyName, R.KeyValue, []);
GetShowImageForm(DM.GetLocalPath(DM.Values) + TInspectorTextRow(Sender).EditText);
end;
end;
procedure TProductForm.EditDescriptionClick(Sender: TObject);
var
Editor: IHTMLEditor;
s: String;
begin
if FPluginManager.GetPlugin(IHTMLEditor, Editor) then
begin
s := description.Text;
Editor.LocalPath := DM.GetLocalPath(DM.Products);
Editor.RemotePath := DM.GetRemotePath(Editor.LocalPath);
if Editor.Execute(s) then
description.DataBinding.Field.Value := s;
end;
end;
procedure TProductForm.cxButton1Click(Sender: TObject);
begin
name.DataBinding.Field.Value := TransLiterStr(title.Text);
end;
procedure TProductForm.titlePropertiesEditValueChanged(Sender: TObject);
begin
if Trim(full_title.Text) = '' then
full_title.DataBinding.Field.Value := title.Text;
if Trim(name.Text) = '' then
name.DataBinding.Field.Value := TransLiterStr(title.Text);
end;
end.
|
unit frmFreeOTFEHdrDump;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
//delphi
Classes, ComCtrls, Buttons,
Controls, Dialogs,
Forms, Graphics, Messages, PasswordRichEdit, Spin64,
StdCtrls, SysUtils, Windows,
//sdu / lc utils
lcTypes, OTFEFreeOTFEBase_U, lcDialogs, SDUFilenameEdit_U, SDUForms, SDUFrames,
SDUGeneral, SDUSpin64Units, OTFE_U,
//librecrypt forms
frmHdrDump,
fmeVolumeSelect,
fmePassword;
type
TfrmFreeOTFEHdrDump = class (TfrmHdrDump)
lblOffset: TLabel;
seSaltLength: TSpinEdit64;
lblSaltLengthBits: TLabel;
lblSaltLength: TLabel;
seKeyIterations: TSpinEdit64;
lblKeyIterations: TLabel;
se64UnitOffset: TSDUSpin64Unit_Storage;
frmePassword1: TfrmePassword;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ControlChanged(Sender: TObject);
procedure pbOKClick(Sender: TObject);
private
function GetUserKey(): TSDUBytes;
function GetOffset(): Int64;
function GetSaltLength(): Integer;
function GetKeyIterations(): Integer;
protected
procedure _EnableDisableControls(); override;
function _DumpHdrDataToFile(): Boolean; override;
procedure SetPassword(const Value: string); override;
public
// property UserKey: TSDUBytes Read GetUserKey;
//
// property Offset: Int64 Read GetOffset;
// property SaltLength: Integer Read GetSaltLength;
// property KeyIterations: Integer Read GetKeyIterations;
end;
implementation
{$R *.DFM}
uses
//sdu / lc utils
lcConsts, SDUi18n;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
function TfrmFreeOTFEHdrDump.GetUserKey(): TSDUBytes;
begin
Result := frmePassword1.GetKeyPhrase;
end;
function TfrmFreeOTFEHdrDump.GetOffset(): Int64;
begin
Result := se64UnitOffset.Value;
end;
function TfrmFreeOTFEHdrDump.GetSaltLength(): Integer;
begin
Result := seSaltLength.Value;
end;
function TfrmFreeOTFEHdrDump.GetKeyIterations(): Integer;
begin
Result := seKeyIterations.Value;
end;
procedure TfrmFreeOTFEHdrDump.FormCreate(Sender: TObject);
begin
inherited;
self.Caption := _('Dump FreeOTFE Header');
// se64UnitOffset set in OnShow event (otherwise units not shown correctly)
seSaltLength.Increment := 8;
seSaltLength.Value := DEFAULT_SALT_LENGTH;
seKeyIterations.MinValue := 1;
seKeyIterations.MaxValue := 999999;
// Need *some* upper value, otherwise setting MinValue won't work properly
seKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT;
seKeyIterations.Value := DEFAULT_KEY_ITERATIONS;
end;
procedure TfrmFreeOTFEHdrDump._EnableDisableControls();
begin
inherited;
pbOK.Enabled := pbOK.Enabled and (GetKeyIterations > 0);
end;
procedure TfrmFreeOTFEHdrDump.FormShow(Sender: TObject);
begin
inherited;
se64UnitOffset.Value := 0;
_EnableDisableControls();
end;
procedure TfrmFreeOTFEHdrDump.ControlChanged(Sender: TObject);
begin
_EnableDisableControls();
end;
function TfrmFreeOTFEHdrDump._DumpHdrDataToFile(): Boolean;
begin
Result := GetFreeOTFEBase().DumpCriticalDataToFile(GetVolumeFilename, GetOffset,
GetUserKey, GetSaltLength, // In bits
GetKeyIterations, GetDumpFilename);
end;
procedure TfrmFreeOTFEHdrDump.pbOKClick(Sender: TObject);
begin
_PromptDumpData('FreeOTFE');
end;
procedure TfrmFreeOTFEHdrDump.SetPassword(const Value: string);
begin
inherited;
frmePassword1.SetKeyPhrase(Value);
end;
end.
|
program helloworld(output);
begin
writeln('hello world!')
end.
|
unit uIniFileProcs;
(*
IniFile procedures
Force Read
Force Write
*)
interface
uses
IniFiles;
function INIFReadString(var ini: TIniFile;
const sSect, sKey, sDefault: string): string;
function INIFReadInteger(var ini: TIniFile;
const sSect, sKey: string; iDefault: integer): integer;
function INIFReadFloat(var ini: TIniFile;
const sSect, sKey: string; iDefault: double): double;
function INIFReadBool(var ini: TIniFile;
const sSect, sKey: string; iDefault: boolean): Boolean;
{ ValidateIniFile dan GetGeosetLocation jangan ditaruh disini.
unit init berisi function umum untuk membaca file ini.
untuk implementasi spesifik di tcms tolong dibuat unit sendiri di tcms.prj
}
implementation
uses
SysUtils, Forms;
function INIFReadString(var ini: TIniFile;
const sSect, sKey, sDefault: string): string;
begin
if not ini.ValueExists(sSect, sKey) then
ini.WriteString(sSect, sKey, sDefault);
result := ini.ReadString(sSect, sKey, '');
end;
function INIFReadInteger(var ini: TIniFile;
const sSect, sKey: string; iDefault: integer): integer;
begin
if not ini.ValueExists(sSect, sKey) then
ini.WriteInteger(sSect, sKey, iDefault);
result := ini.ReadInteger(sSect, sKey, 0);
end;
function INIFReadFloat(var ini: TIniFile;
const sSect, sKey: string; iDefault: double): double;
begin
if not ini.ValueExists(sSect, sKey) then
ini.WriteFloat(sSect, sKey, iDefault);
result := ini.ReadFloat(sSect, sKey, 0.0);
end;
function INIFReadBool(var ini: TIniFile;
const sSect, sKey: string; iDefault: boolean): Boolean;
begin
if not ini.ValueExists(sSect, sKey) then
ini.WriteBool(sSect, sKey, iDefault);
result := ini.ReadBool(sSect, sKey, iDefault);
end;
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 datetime_helpers;
{
[x] USAGE
variable
d : TDateTime;
s : String;
d.FromString( '17-08-1945 09:59:00');
s := d.Format( 'yyyy-mm-dd HH:nn:ss');
d.AsString;
if d.IsAM then begin end;
if d.IsPM then begin end;
if d.IsToday then begin end;
if Tomorrow.IsSaturday then begin ... end;
if d.HourOf = 9 then ....
d := d.IncMinute(1);
if d.YearsDiff( Now) > 40 then begin ... end;
s := d.HumanReadable;
// 'more than 73 years ago'
}
{$mode objfpc}{$H+}
{$modeswitch typehelpers}
interface
uses
common, datetime_lib,
dateutils, Classes, SysUtils;
type
{ TDateTimeSmartHelper }
TDateTimeSmartHelper = Type Helper for TDateTime
private
public
function AsString: String; overload; inline;
function Format( AFormat: String = 'yyyy-mm-dd HH:nn:ss'): String; overload; inline;
function HumanReadable: String; overload; inline;
function FromString( ADateTimeString: String; AFormat: String = 'yyyy-mm-dd HH:nn:ss'): TDateTime; overload; inline;
function DayOfWeek: Word; overload; inline;
function YearOf: Word; overload; inline;
function MonthOf: Word; overload; inline;
function DayOf: Word; overload; inline;
function HourOf: Word; overload; inline;
function MinuteOf: Word; overload; inline;
function SecondOf: Word; overload; inline;
function YearsDiff( ADateTime: TDateTime): Word; overload; inline;
function MonthsDiff( ADateTime: TDateTime): Word; overload; inline;
function WeeksDiff( ADateTime: TDateTime): Word; overload; inline;
function DaysDiff( ADateTime: TDateTime): Word; overload; inline;
function HoursDiff( ADateTime: TDateTime): Word; overload; inline;
function MinutesDiff( ADateTime: TDateTime): Word; overload; inline;
function SecondsDiff( ADateTime: TDateTime): Word; overload; inline;
function IncYear( AValue: Integer = 1): TDateTime; overload; inline;
function IncWeek( AValue: Integer = 1): TDateTime; overload; inline;
function IncDay( AValue: Integer = 1): TDateTime; overload; inline;
function IncHour( AValue: Integer = 1): TDateTime; overload; inline;
function IncMinute( AValue: Integer = 1): TDateTime; overload; inline;
function IncSecond( AValue: Integer = 1): TDateTime; overload; inline;
function IsAM: boolean; overload; inline;
function IsPM: boolean; overload; inline;
function IsToday: boolean; overload; inline;
function IsMonday: boolean; overload; inline;
function IsTuesday: boolean; overload; inline;
function IsWednesday: boolean; overload; inline;
function IsThursday: boolean; overload; inline;
function IsFriday: boolean; overload; inline;
function IsSaturday: boolean; overload; inline;
function IsSunday: boolean; overload; inline;
end;
implementation
{ TDateTimeSmartHelper }
function TDateTimeSmartHelper.AsString: String;
begin
Result := Format;
end;
function TDateTimeSmartHelper.Format(AFormat: String): String;
begin
Result := FormatDateTime( AFormat, Self);
end;
function TDateTimeSmartHelper.HumanReadable: String;
begin
Result := DateTimeHuman( Self);
end;
function TDateTimeSmartHelper.FromString(ADateTimeString: String;
AFormat: String): TDateTime;
var
FS: TFormatSettings;
begin
FS := DefaultFormatSettings;
FS.ShortDateFormat := AFormat;
Self := StrToDateTime( ADateTimeString, FS);
Result := Self;
end;
function TDateTimeSmartHelper.DayOfWeek: Word;
begin
Result := DayOfTheWeek( Self);
end;
function TDateTimeSmartHelper.YearOf: Word;
begin
Result := dateutils.YearOf( Self);
end;
function TDateTimeSmartHelper.MonthOf: Word;
begin
Result := dateutils.MonthOf( Self);
end;
function TDateTimeSmartHelper.DayOf: Word;
begin
Result := dateutils.DayOf( Self);
end;
function TDateTimeSmartHelper.HourOf: Word;
begin
Result := dateutils.HourOf( Self);
end;
function TDateTimeSmartHelper.MinuteOf: Word;
begin
Result := dateutils.MinuteOf( Self);
end;
function TDateTimeSmartHelper.SecondOf: Word;
begin
Result := dateutils.SecondOf( Self);
end;
function TDateTimeSmartHelper.YearsDiff(ADateTime: TDateTime): Word;
begin
Result := YearsBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.MonthsDiff(ADateTime: TDateTime): Word;
begin
Result := MonthsBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.WeeksDiff(ADateTime: TDateTime): Word;
begin
Result := WeeksBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.DaysDiff(ADateTime: TDateTime): Word;
begin
Result := DaysBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.HoursDiff(ADateTime: TDateTime): Word;
begin
Result := HoursBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.MinutesDiff(ADateTime: TDateTime): Word;
begin
Result := MinutesBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.SecondsDiff(ADateTime: TDateTime): Word;
begin
Result := SecondsBetween( Self, ADateTime);
end;
function TDateTimeSmartHelper.IncYear(AValue: Integer): TDateTime;
begin
Result := dateutils.IncYear( Self, AValue);
end;
function TDateTimeSmartHelper.IncWeek(AValue: Integer): TDateTime;
begin
Result := dateutils.IncWeek( Self, AValue);
end;
function TDateTimeSmartHelper.IncDay(AValue: Integer): TDateTime;
begin
Result := dateutils.IncDay( Self, AValue);
end;
function TDateTimeSmartHelper.IncHour(AValue: Integer): TDateTime;
begin
Result := dateutils.IncHour( Self, AValue);
end;
function TDateTimeSmartHelper.IncMinute(AValue: Integer): TDateTime;
begin
Result := dateutils.IncMinute( Self, AValue);
end;
function TDateTimeSmartHelper.IncSecond(AValue: Integer): TDateTime;
begin
Result := dateutils.IncSecond( Self, AValue);
end;
function TDateTimeSmartHelper.IsAM: boolean;
begin
Result := NOT dateutils.IsPM( Self);
end;
function TDateTimeSmartHelper.IsPM: boolean;
begin
Result := dateutils.IsPM( Self);
end;
function TDateTimeSmartHelper.IsToday: boolean;
begin
Result := dateutils.IsToday( Self);
end;
function TDateTimeSmartHelper.IsMonday: boolean;
begin
if DayOfTheWeek( Self) = 1 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsTuesday: boolean;
begin
if DayOfTheWeek( Self) = 2 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsWednesday: boolean;
begin
if DayOfTheWeek( Self) = 3 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsThursday: boolean;
begin
if DayOfTheWeek( Self) = 4 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsFriday: boolean;
begin
if DayOfTheWeek( Self) = 5 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsSaturday: boolean;
begin
if DayOfTheWeek( Self) = 6 Then
Result := True
else
Result := False;
end;
function TDateTimeSmartHelper.IsSunday: boolean;
begin
if DayOfTheWeek( Self) = 7 Then
Result := True
else
Result := False;
end;
end.
|
{$i deltics.inc}
unit Test.Memory.AllocZeroed;
interface
uses
Deltics.Smoketest;
type
MemoryAllocZeroed = class(TTest)
procedure AllocatesNewMemoryWithBytesZeroed;
end;
implementation
uses
Deltics.Pointers;
{ CopyBytes }
procedure MemoryAllocZeroed.AllocatesNewMemoryWithBytesZeroed;
const
ZEROES: array[1..100] of Byte = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
var
dest: Pointer;
begin
Memory.AllocZeroed(dest, Length(ZEROES));
try
Test('dest').Assert(dest).IsNotNIL;
Test('dest').Assert(dest).EqualsBytes(@ZEROES, Length(ZEROES));
finally
FreeMem(dest);
end;
end;
end.
|
unit BSphereComparatorTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath, BZVectorMathEx;
type
{ TBSphereFunctionalTest }
// may split this out later to group/enable functional tests.
// but for now it can stay here
TBSphereFunctionalTest = class(TBBoxBaseTestCase)
published
procedure TestCreateSingles;
procedure TestCreateAffineVector;
procedure TestCreateVector;
procedure TestContains;
procedure TestIntersect;
end;
{ TBSphereComparatorTest }
TBSphereComparatorTest = class(TBBoxBaseTestCase)
published
procedure TestCompare;
procedure TestCompareFalse;
procedure TestContains;
procedure TestIntersect;
end;
implementation
{ TBSphereFunctionalTest }
// Our default values are.
// vt1.Create(5.850,-15.480,8.512,1.5);
// abs1.Create(vt1, 1.356);
procedure TBSphereFunctionalTest.TestCreateSingles;
begin
abs3.Create(5.850,-15.480,8.512,1.356);
AssertTrue('BoundingSphere CreateSingles do not match' + abs3.ToString+' --> '+abs1.ToString, Compare(abs3,abs1));
end;
procedure TBSphereFunctionalTest.TestCreateAffineVector;
var vec: TBZAffineVector;
begin
vec := vt1.AsVector3f;
abs3.Create(vec,1.356);
AssertTrue('BoundingSphere CreateAffine do not match' + abs3.ToString+' --> '+abs1.ToString, Compare(abs3,abs1));
end;
procedure TBSphereFunctionalTest.TestCreateVector;
begin
abs3.Create(vt1,1.356);
AssertTrue('BoundingSphere CreateAffine do not match' + abs3.ToString+' --> '+abs1.ToString, Compare(abs3,abs1));
AssertTrue('BoundingSphere Center W is not 1.0', IsEqual(abs3.Center.W,1.0));
end;
procedure TBSphereFunctionalTest.TestContains;
var
aCont: TBZSpaceContains;
begin
// default spheres do not overlap
fs1 := abs1.Center.Distance(abs2.Center);
AssertTrue('BoundingSphere: Someone changed the base values and broke the tests', (fs1 - abs1.Radius) > abs2.Radius);
aCont := abs1.Contains(abs2);
AssertTrue('BoundingSphere: spheres should be isolated', aCont = ScNoOverlap);
// make the radius the same as the distance between centers so we have
// a partial containment
abs1.Radius:=fs1;
aCont := abs1.Contains(abs2);
AssertTrue('BoundingSphere: spheres should partially contained', aCont = ScContainsPartially);
// fully enclose abs2
abs1.Radius:=fs1 + abs2.Radius + 1.0;
aCont := abs1.Contains(abs2);
AssertTrue('BoundingSphere: spheres should fully contained', aCont = ScContainsFully);
end;
procedure TBSphereFunctionalTest.TestIntersect;
begin
fs1 := abs1.Center.Distance(abs2.Center);
AssertTrue('BoundingSphere: Someone changed the base values and broke the tests', (fs1 - abs1.Radius) > abs2.Radius);
vb := abs1.Intersect(abs2);
AssertFalse( 'BoundingSphere: spheres should not intersect', vb);
// slight overlap
abs1.Radius:= fs1 - abs2.Radius + 1.0;
vb := abs1.Intersect(abs2);
AssertTrue( 'BoundingSphere: spheres should intersect', vb);
// fully enclose abs2
abs1.Radius:=fs1 + abs2.Radius + 1.0;
vb := abs1.Intersect(abs2);
AssertTrue( 'BoundingSphere: spheres should intersect', vb);
end;
{ TBSphereComparatorTest }
procedure TBSphereComparatorTest.TestCompare;
begin
AssertTrue('Test Values do not match', Compare(nbs1,abs1));
end;
procedure TBSphereComparatorTest.TestCompareFalse;
begin
AssertFalse('Test Values should not match', Compare(nbs2,abs1));
end;
procedure TBSphereComparatorTest.TestContains;
var nCont, aCont: TBZSpaceContains;
begin
nCont := nbs1.Contains(nbs2);
aCont := abs1.Contains(abs2);
AssertEquals('BoundingSphere Contains do not match',ord(nCont),ord(aCont));
end;
procedure TBSphereComparatorTest.TestIntersect;
begin
nb := nbs1.Intersect(nbs2);
vb := abs1.Intersect(abs2);
AssertEquals('BoundingSphere Intersect do not match', nb, vb);
end;
initialization
RegisterTest(REPORT_GROUP_BSPHERE, TBSphereFunctionalTest);
RegisterTest(REPORT_GROUP_BSPHERE, TBSphereComparatorTest);
end.
|
unit aOPCConnectionList;
interface
uses
System.Classes, System.SysUtils, System.IniFiles,
aOPCClass, uDCObjects, uAppStorage,
aOPCLookupList,
aCustomOPCSource, aOPCSource, aCustomOPCTCPSource,
aOPCTCPSource, aOPCTCPSource_V30, aOPCTCPSource_V31, aOPCTCPSource_V32, aOPCTCPSource_V33;
type
EOPCConnectionCollectionError = class(Exception);
TOPCConnectionCollection = class;
TaOPCConnectionList = class;
TOPCProtocolVersion = (
opv0 = 0,
opv30 = 1,
opv31 = 2,
opv32 = 3,
opv33 = 4);
TOPCConnectionCollectionItem = class(TCollectionItem)
private
FID: Integer;
FName: string;
FOPCSource: TaCustomOPCTCPSource;
FOPCObjectList: TDCObjectList;
FLookupsList: TStringList;
FEnable: boolean;
FProtocolVersion: TOPCProtocolVersion;
function GetName: string;
function GetOPCConnectionCollection: TOPCConnectionCollection;
procedure SetEnable(const Value: boolean);
procedure SetProtocolVersion(const Value: TOPCProtocolVersion);
public
constructor Create(Collection: TCollection); override;
constructor CreateProtocol(Collection: TCollection; aProtocol: TOPCProtocolVersion);
destructor Destroy; override;
function CreateOPCSource: TaCustomOPCTCPSource;
function GetDisplayName: string; override;
procedure Assign(Source: TPersistent); override;
procedure LoadChildsFromServer(aParent: TDCObject; aLevelCount: Integer);
//список объектов (иерархия, пространство имён...)
property OPCObjectList: TDCObjectList read FOPCObjectList;
//список Lookup-ов:
// строка - имя справочника в базе данных
// объект - LookupList для этого справочника
property LookupsList: TStringList read FLookupsList;
//ссылка на владельца (коллекцию подключений)
property OPCConnectionCollection: TOPCConnectionCollection read GetOPCConnectionCollection;
procedure Clear;
function GetLookupByTableName(aRefTableName: string): TaOPCLookupList;
procedure LoadLookups(aAppStorage: TCustomIniFile; aKey: string); overload;
// procedure LoadLookups(aRegistrySection:string);overload;
function GetStatesLookup: TaOPCLookupList;
procedure InitObjectList(aNameSpace: TStrings; aStartObject: TDCObject = nil);
function InitOPCObjectList(aObjectSID: string = ''; aLevelCount: Integer = 0): boolean;
procedure StringsToHierarchy(aNameSpace: TStrings; aHierarchy: TDCObjectList);
// заполнить список объектов из списка строк иерархии
procedure FillHierarchy(aHierarchy: TDCObjectList; aRootID: string = ''; aLevelCount: Integer = 0;
aKinds: TDCObjectKindSet = []);
published
// идентификатор подключения (для поиска)
property ID: Integer read FID write FID;
//имя подключения (состоит из имени сервера+порт)
property Name: string read GetName write FName;
property Enable: boolean read FEnable write SetEnable default True;
property ProtocolVersion: TOPCProtocolVersion read FProtocolVersion write SetProtocolVersion default opv0;
//источник данных для этого подключения
property OPCSource: TaCustomOPCTCPSource read FOPCSource;
end;
TOPCConnectionCollection = class(TCollection)
private
FConnectionList: TaOPCConnectionList;
function GetItem(Index: Integer): TOPCConnectionCollectionItem;
protected
public
constructor Create(AOwner: TPersistent);
destructor Destroy; override;
function Find(aOPCSource: TaCustomOPCSource): TOPCConnectionCollectionItem;
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(const FileName: string);
procedure SaveToStream(Stream: TStream);
property Items[Index: Integer]: TOPCConnectionCollectionItem read GetItem; default;
property ConnectionList: TaOPCConnectionList read FConnectionList;
end;
TaOPCCustomConnectionList = class(TComponent)
private
FItems: TOPCConnectionCollection;
procedure SetItems(Value: TOPCConnectionCollection);
function GetConnection(const Name: string): TOPCConnectionCollectionItem;
public
constructor Create(AOnwer: TComponent); override;
destructor Destroy; override;
property Items: TOPCConnectionCollection read FItems write SetItems;
property Connections[const Name: string]: TOPCConnectionCollectionItem read GetConnection;
end;
{
TConnectionNotifyEvent = procedure(Sender: TObject; OPCSource:TaOPCTCPSource) of object;
TConnectionMsgEvent = procedure(Sender: TObject; OPCSource:TaOPCTCPSource; Msg:string) of object;
}
{ TaOPCConnectionList }
TaOPCConnectionList = class(TaOPCCustomConnectionList)
private
FOnDeactivate: TNotifyEvent;
FOnRequest: TNotifyEvent;
FOnActivate: TNotifyEvent;
FOnError: TMessageStrEvent;
FDescription: string;
FOnConnect: TNotifyEvent;
FOnDisconnect: TNotifyEvent;
procedure SetActive(const Value: boolean);
procedure SetOnActivate(const Value: TNotifyEvent);
procedure SetOnDeactivate(const Value: TNotifyEvent);
procedure SetOnError(const Value: TMessageStrEvent);
procedure SetOnRequest(const Value: TNotifyEvent);
procedure SetDescription(const Value: string);
procedure SetOnConnect(const Value: TNotifyEvent);
procedure SetOnDisconnect(const Value: TNotifyEvent);
public
function IndexOf(aObject: TObject): integer;
function IndexOfOPCSource(aOPCSource: TaCustomOPCSource): Integer;
function IndexOfConnectionID(aID: Integer): Integer;
function IndexOfConnectionName(const aName: string): Integer;
function FindObjectByID(aConnectionID: integer; ID: integer): TDCObject;
function FindObjectBySourceAndID(aOPCSource: TaCustomOPCSource; ID: integer): TDCObject;
function GetOPCSourceByConnectionName(const aConnectionName: string): TaCustomOPCSource;
function GetConnectionByName(const aConnectionName: string): TOPCConnectionCollectionItem;
procedure LoadSettings(aCustomIniFile: TCustomIniFile; aSectionName: string; aNotClearItems: Boolean = False);
procedure SaveSettings(aCustomIniFile: TCustomIniFile; aSectionName: string);
// procedure Connect(aUser: string; aLoadNameSpace, aLoadLookups, aActivate: Boolean;
// aStatusNotify: TOPCStatusNotify = nil; aPassword: string = '');
published
property Items;
property Active: boolean write SetActive;
property Description: string read FDescription write SetDescription;
// случается, когда прошел цикл опроса датчиков
property OnRequest: TNotifyEvent read FOnRequest write SetOnRequest;
property OnError: TMessageStrEvent read FOnError write SetOnError;
property OnActivate: TNotifyEvent read FOnActivate write SetOnActivate;
property OnDeactivate: TNotifyEvent read FOnDeactivate write SetOnDeactivate;
property OnConnect: TNotifyEvent read FOnConnect write SetOnConnect;
property OnDisconnect: TNotifyEvent read FOnDisconnect write SetOnDisconnect;
end;
implementation
uses
uCommonClass, DC.StrUtils;
{ TOPCConnectionCollectionItem }
procedure TOPCConnectionCollectionItem.Assign(Source: TPersistent);
begin
if Source is TOPCConnectionCollectionItem then
begin
FOPCSource.Assign(TOPCConnectionCollectionItem(Source).FOPCSource);
FOPCObjectList.Assign(TOPCConnectionCollectionItem(Source).FOPCObjectList);
end
else
inherited Assign(Source);
end;
procedure TOPCConnectionCollectionItem.Clear;
var
i: integer;
begin
FOPCObjectList.Clear;
//FOPCObjectList.SortedKind := skNone;
for i := 0 to FLookupsList.Count - 1 do
FLookupsList.Objects[i].Free;
FLookupsList.Clear;
end;
constructor TOPCConnectionCollectionItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FEnable := true;
FProtocolVersion := opv30;
FOPCSource := CreateOPCSource;
FOPCObjectList := TDCObjectList.Create;//(False);
FLookupsList := TStringList.Create;
end;
function TOPCConnectionCollectionItem.CreateOPCSource: TaCustomOPCTCPSource;
var
aOwner: TComponent;
aConnectionList: TaOPCConnectionList;
begin
Result := nil;
if (Collection is TOPCConnectionCollection) then
aOwner := TOPCConnectionCollection(Collection).ConnectionList
else
aOwner := nil;
case ProtocolVersion of
opv0: Result := TaOPCTCPSource.Create(aOwner);
opv30: Result := TaOPCTCPSource_V30.Create(aOwner);
opv31: Result := TaOPCTCPSource_V31.Create(aOwner);
opv32: Result := TaOPCTCPSource_V32.Create(aOwner);
opv33: Result := TaOPCTCPSource_V33.Create(aOwner);
end;
Result.SetSubComponent(true);
if Assigned(Collection) then
begin
aConnectionList := (Collection as TOPCConnectionCollection).ConnectionList;
Result.Description := aConnectionList.Description;
Result.OnRequest := aConnectionList.OnRequest;
Result.OnError := aConnectionList.OnError;
Result.OnActivate := aConnectionList.OnActivate;
Result.OnDeactivate := aConnectionList.OnDeactivate;
Result.OnConnect := aConnectionList.OnConnect;
Result.OnDisconnect := aConnectionList.OnDisconnect;
end;
end;
constructor TOPCConnectionCollectionItem.CreateProtocol(Collection: TCollection; aProtocol: TOPCProtocolVersion);
begin
inherited Create(Collection);
FEnable := true;
FProtocolVersion := aProtocol;
FOPCSource := CreateOPCSource;
FOPCObjectList := TDCObjectList.Create;//(False);
FLookupsList := TStringList.Create;
end;
destructor TOPCConnectionCollectionItem.Destroy;
var
i: integer;
begin
// удаляем датчики и группы
if Assigned(FOPCObjectList) then
begin
for i := FOPCObjectList.Count - 1 downto 0 do
FOPCObjectList.Items[i].Free;
end;
FreeAndNil(FOPCObjectList);
// удаляем справочники
if Assigned(FLookupsList) then
begin
for i := FLookupsList.Count - 1 downto 0 do
FLookupsList.Objects[i].Free;
end;
FreeAndNil(FLookupsList);
// удаляем источник данных
FreeAndNil(FOPCSource);
inherited Destroy;
end;
procedure TOPCConnectionCollectionItem.FillHierarchy(aHierarchy: TDCObjectList; aRootID: string; aLevelCount: Integer;
aKinds: TDCObjectKindSet);
var
aNameSpace: TStrings;
begin
aNameSpace := TStringList.Create;
try
OPCSource.FillNameSpaceStrings(aNameSpace, aRootID, aLevelCount, aKinds);
StringsToHierarchy(aNameSpace, aHierarchy);
finally
aNameSpace.Free;
end;
end;
{
function TOPCConnectionCollectionItem.GetCorrectName: string;
begin
Result := OPCSource.RemoteMachine;
end;
}
function TOPCConnectionCollectionItem.GetDisplayName: string;
begin
Result := Format('%s(%d)', [OPCSource.RemoteMachine, OPCSource.Port]);
end;
function TOPCConnectionCollectionItem.GetLookupByTableName(
aRefTableName: string): TaOPCLookupList;
var
i: integer;
begin
if aRefTableName = '' then
Exit(nil);
for i := 0 to FLookupsList.Count - 1 do
begin
if aRefTableName = FLookupsList.Strings[i] then
begin
Result := TaOPCLookupList(FLookupsList.Objects[i]);
exit;
end;
end;
// не нашли нужный - создадим новый
Result := TaOPCLookupList.Create(nil);
FLookupsList.AddObject(aRefTableName, Result);
Result.TableName := aRefTableName;
Result.OPCSource := FOPCSource;
Result.AutoUpdate := true;
end;
function TOPCConnectionCollectionItem.GetName: string;
begin
if FName <> '' then
Result := FName
else
Result := Format('%s(%d)', [OPCSource.RemoteMachine, OPCSource.Port]);
end;
function TOPCConnectionCollectionItem.GetOPCConnectionCollection:
TOPCConnectionCollection;
begin
Result := Collection as TOPCConnectionCollection;
end;
function TOPCConnectionCollectionItem.GetStatesLookup: TaOPCLookupList;
begin
Result := GetLookupByTableName('States');
end;
// aNameSpace - иерархия полученная с сервера (строки)
// aStartObject - объект, стоящий на верхушке этой иерархии
procedure TOPCConnectionCollectionItem.InitObjectList(aNameSpace: TStrings; aStartObject: TDCObject);
var
i: Integer;
ALevel: Integer;
aCaption: string;
Data: TStrings;
CurrStr: string;
aObject, aNewObject, aNextObject: TDCObject;
CaseStairs: integer;
aRefTableName: string;
aIndexStart: Integer;
aLevelStart: Integer;
begin
if not Assigned(aNameSpace) then
Exit;
aObject := aStartObject;
// если уже есть добавленный в список объект, то пропускаем первую строку
if Assigned(aStartObject) then
begin
aIndexStart := 1;
aLevelStart := aStartObject.Level;
end
else
begin
aIndexStart := 0;
aLevelStart := 0;
end;
// проходим по предварительно загруженной иерархии
for i := aIndexStart to aNameSpace.Count - 1 do
begin
// вычитываем информационную строку и определяем грубину вложенности
CurrStr := GetBufStart(PChar(aNameSpace[i]), ALevel);
ALevel := aLevelStart + ALevel;
// вычитываем наименование объекта
aCaption := ExtractData(CurrStr);
// вычитываем данные по объекту, создаем и наполняем объект
Data := TStringList.Create;
try
while CurrStr<>'' do
Data.Add(ExtractData(CurrStr));
if Data.Strings[1] = '1' then
begin
aNewObject := TDCObject.Create;
aNewObject.Kind := StrToIntDef(Data.Strings[2],1000);
aNewObject.ServerChildCount := StrToIntDef(Data.Strings[5], 0);
end
else
begin
aNewObject := TSensor.Create;
aNewObject.Kind := 0;
with TSensor(aNewObject) do
begin
DisplayFormat := Data.Strings[2];
SensorUnitName := Data.Strings[3];
// SensorKind := StrToIntDef(Data.Strings[1],0);
//
aRefTableName := Data.Strings[6];
if aRefTableName <> '' then
begin
LookupList := GetLookupByTableName(aRefTableName);
if Data.Count >= 10 then
begin
if Data.Strings[9] = '1' then
LookupList.ShowValue := svLeft
else if Data.Strings[9] = '2' then
LookupList.ShowValue := svRight;
end;
end;
CaseStairs := StrToIntDef(Data.Strings[5],0);
case CaseStairs of
0: StairsOptions := [soIncrease,soDecrease];
1: StairsOptions := [];
2: StairsOptions := [soIncrease];
3: StairsOptions := [soDecrease];
end;
end;
end;
// добавляем объект в список
OPCObjectList.Add(aNewObject);
aNewObject.Owner := Self;
aNewObject.Name := aCaption;
aNewObject.IDStr := Data.Strings[0];
// определяем родителя объекта и добавляемся в список детей родителя
if aObject = nil then
aNewObject.Parent := nil
else if aObject.Level = ALevel then
aNewObject.Parent := aObject.Parent
else if aObject.Level = (ALevel - 1) then
aNewObject.Parent := aObject
else if aObject.Level > ALevel then
begin
aNextObject := aObject.Parent;
while Assigned(aNextObject) and (aNextObject.Level >= ALevel) do
aNextObject := aNextObject.Parent;
aNewObject.Parent := aNextObject;
end
else
raise Exception.CreateFmt('ALevel=%d - aObject.Level=%d',[ALevel, aObject.Level]);
aObject := aNewObject;
finally
FreeAndNil(Data);
end;
end;
// добавляем табличу состояний для отображения ошибок
if OPCObjectList.Count > 0 then
OPCSource.States := GetLookupByTableName('States');
// сортируем дерево так, чтобы папки были сверху
// 1 вариант - проверяем все объекты
if not Assigned(aStartObject) then
begin
for i := 0 to OPCObjectList.Count - 1 do
if OPCObjectList.Items[i].Childs.Count > 0 then
OPCObjectList.Items[i].Childs.SortedKind := skFolderAndName;
end
// 2 вариант - проверяем только объекты подгруженные для указанного родителя
else
begin
aStartObject.SortChilds(skFolderAndName);
end;
end;
function TOPCConnectionCollectionItem.InitOPCObjectList(aObjectSID: string; aLevelCount: Integer): boolean;
var
ALevel, i: Integer;
lastLevel: Integer;
CurrStr: string;
Data: TStringList;
newObject, lastObject, aParent: TDCObject;
CaseStairs: integer;
aRefTableName: string;
aCaption : string;
begin
//newObject := nil;
lastObject := nil;
lastLevel := 0;
OPCObjectList.Clear;
//if OPCSource.FNameSpaceCash.Count = 0 then
if not OPCSource.GetNameSpace(aObjectSID, aLevelCount) then
Exit(False);
for i := 0 to OPCSource.FNameSpaceCash.Count - 1 do
begin
CurrStr := GetBufStart(PChar(OPCSource.FNameSpaceCash[i]), ALevel);
aCaption := ExtractData(CurrStr);
Data := TStringList.Create;
try
while CurrStr<>'' do
Data.Add(ExtractData(CurrStr));
if Data.Strings[1] = '1' then // это группа
begin
// 0 - id (идентификатор)
// 1 - вид объкта (датчик-0 или группа - 1)
// 2 - Kind
// 3 - NameEn
// 4 - права доступа (rwahex)
// 5 - ChildCount
// 6 - SID
// 7 - UseParentSID
newObject := TDCObject.Create;
newObject.Kind := StrToIntDef(Data.Strings[2],1000);
newObject.NameEn := Data.Strings[3];
newObject.SID := Data.Strings[6];
if Data.Count > 7 then
newObject.UseParentSID := StrToBool(Data.Strings[7]);
end
else //это датчик
begin
// Наименование = ANode.Text
// формат получаемых данных Data.Strings
// 0 - id (идентификатор)
// 1 - вид объкта (датчик-0 или группа - 1)
// 2 - DisplayFormat (форматирование)
// 3 - UnitName (единица измерения: строка)
// 4 - вид датчика
// 5 - Stairs (вид лесенки:
// 0 - возрастает, убывает
// 1 - лесенка
// 2 - возрастает
// 3 - убывает
// 6 - refTableName (наименование таблицы-справочника расшифровки показаний датчика)
// 7 - EnName
// 8 - права доступа (rwahex)
// 9 - RefValue
// 10 - SID
// 11 - UseParentSID
newObject := TSensor.Create;
newObject.Kind := StrToInt(Data.Strings[1]);
newObject.NameEn := Data.Strings[7];
newObject.SID := Data.Strings[10];
if Data.Count > 11 then
newObject.UseParentSID := StrToBool(Data.Strings[11]);
with TSensor(newObject) do
begin
SensorKind := StrToIntDef(Data.Strings[1],0);
DisplayFormat := Data.Strings[2];
SensorUnitName := Data.Strings[3];
//определим (и в случае необходимости создадим) LookupList для датчика
aRefTableName := Data.Strings[6];
if aRefTableName <> '' then
begin
LookupList := GetLookupByTableName(aRefTableName);
if Data.Count >= 10 then
begin
if Data.Strings[9] = '1' then
LookupList.ShowValue := svLeft
else if Data.Strings[9] = '2' then
LookupList.ShowValue := svRight;
end;
end;
CaseStairs := StrToIntDef(Data.Strings[5],0);
case CaseStairs of
0:
begin
StairsOptions := [soIncrease,soDecrease];
ImageIndex := 1
end;
1:
begin
StairsOptions := [];
ImageIndex := 2
end;
2:
begin
StairsOptions := [soIncrease];
ImageIndex := 3
end;
3:
begin
StairsOptions := [soDecrease];
ImageIndex := 4
end;
end;
end;
end;
OPCObjectList.Add(newObject);
newObject.Owner := Self;
newObject.Name := aCaption;
newObject.IDStr := Data.Strings[0];
// проставляем родителя
if lastObject = nil then
newObject.Parent := nil
else if lastLevel = ALevel then
newObject.Parent := lastObject.Parent
else if lastLevel = (ALevel - 1) then
newObject.Parent := lastObject
else if lastLevel > ALevel then
begin
aParent := lastObject.Parent;
while lastLevel > ALevel do
begin
aParent := aParent.Parent;
Dec(lastLevel);
end;
newObject.Parent := aParent;
end;
lastObject := newObject;
lastLevel := ALevel;
finally
FreeAndNil(Data);
end;
end;
// добавим в список лукапов подключения информацию о состояниях датчиков
// если есть хоть один объект
if OPCSource.FNameSpaceCash.Count > 0 then
OPCSource.States := GetLookupByTableName('States');
Result := True;
end;
//procedure TOPCConnectionCollectionItem.LoadLookups(aRegistrySection: string);
//var
// i:integer;
//begin
// for i := 0 to FLookupsList.Count - 1 do
// begin
// (FLookupsList.Objects[i] as TaOPCLookupList).RegistrySection := aRegistrySection;
// (FLookupsList.Objects[i] as TaOPCLookupList).CheckForNewLookup;
// end;
//end;
procedure TOPCConnectionCollectionItem.LoadChildsFromServer(aParent: TDCObject; aLevelCount: Integer);
var
aParentID: Integer;
begin
if Assigned(aParent) then
begin
// если по этому объекту все дети уже загружены, то
// - либо очищаем и загружаем их по новой
// - либо выходим (если равно)
// if aParent.Childs.Count = aParent.ServerChildCount then
if (aParent.Childs.Count <> 0) or (aParent.ServerChildCount = 0) then
Exit
else
begin
{ TODO : Если на сервере количество изменилось, то можно все почистить и загрузить заново... }
end;
aParentID := aParent.ID;
end
else
begin
// если в списке уже есть объекты, то нужно
// - либо очистить список и загрузить их по новой (для этого нужно ручками их удалить предварительно)
// - либо ничего не делать, а ждать запроса с выбранным объктом этого списка
if FOPCObjectList.Count > 0 then
Exit;
aParentID := 0;
end;
OPCSource.GetNameSpace(IntToStr(aParentID), aLevelCount);
InitObjectList(OPCSource.FNameSpaceCash, aParent);
end;
procedure TOPCConnectionCollectionItem.LoadLookups(aAppStorage: TCustomIniFile;
aKey: string);
var
i: integer;
begin
for i := 0 to FLookupsList.Count - 1 do
begin
(FLookupsList.Objects[i] as TaOPCLookupList).RegistrySection := aKey;
(FLookupsList.Objects[i] as TaOPCLookupList).CheckForNewLookup(aAppStorage);
end;
end;
procedure TOPCConnectionCollectionItem.SetEnable(const Value: boolean);
begin
FEnable := Value;
end;
procedure TOPCConnectionCollectionItem.SetProtocolVersion(const Value: TOPCProtocolVersion);
var
aSource: TaCustomOPCTCPSource;
begin
if FProtocolVersion <> Value then
begin
FProtocolVersion := Value;
// для реализации другого протокола используется другой источник данных
aSource := CreateOPCSource;
aSource.Assign(FOPCSource);
FOPCSource.Free;
FOPCSource := aSource;
end;
end;
procedure TOPCConnectionCollectionItem.StringsToHierarchy(aNameSpace: TStrings; aHierarchy: TDCObjectList);
var
ALevel, i: Integer;
lastLevel: Integer;
CurrStr: string;
Data: TStringList;
newObject, lastObject, aParent: TDCObject;
CaseStairs: integer;
aRefTableName: string;
aCaption : string;
begin
//newObject := nil;
lastObject := nil;
lastLevel := 0;
for i := 0 to aNameSpace.Count - 1 do
begin
CurrStr := GetBufStart(PChar(aNameSpace[i]), ALevel);
aCaption := ExtractData(CurrStr);
Data := TStringList.Create;
try
while CurrStr<>'' do
Data.Add(ExtractData(CurrStr));
if Data.Strings[1] = '1' then // это группа
begin
// 0 - id (идентификатор)
// 1 - вид объкта (датчик-0 или группа - 1)
// 2 - Kind
// 3 - NameEn
// 4 - права доступа (rwahex)
// 5 - ChildCount
// 6 - SID или FullSID-для верхнего элемента
// 7 - UseParentSID
newObject := TDCObject.Create;
newObject.Kind := StrToIntDef(Data.Strings[2],1000);
newObject.NameEn := Data.Strings[3];
newObject.SID := Data.Strings[6];
if Data.Count > 7 then
newObject.UseParentSID := StrToBool(Data.Strings[7]);
end
else //это датчик
begin
// Наименование = ANode.Text
// формат получаемых данных Data.Strings
// 0 - id (идентификатор)
// 1 - вид объкта (датчик-0 или группа - 1)
// 2 - DisplayFormat (форматирование)
// 3 - UnitName (единица измерения: строка)
// 4 - вид датчика
// 5 - Stairs (вид лесенки:
// 0 - возрастает, убывает
// 1 - лесенка
// 2 - возрастает
// 3 - убывает
// 6 - refTableName (наименование таблицы-справочника расшифровки показаний датчика)
// 7 - EnName
// 8 - права доступа (rwahex)
// 9 - RefValue
// 10 - SID или FullSID-для верхнего элемента
// 11 - UseParentSID
newObject := TSensor.Create;
newObject.Kind := StrToInt(Data.Strings[1]);
newObject.NameEn := Data.Strings[7];
newObject.SID := Data.Strings[10];
if Data.Count > 11 then
newObject.UseParentSID := StrToBool(Data.Strings[11]);
with TSensor(newObject) do
begin
SensorKind := StrToIntDef(Data.Strings[1],0);
DisplayFormat := Data.Strings[2];
SensorUnitName := Data.Strings[3];
//определим (и в случае необходимости создадим) LookupList для датчика
aRefTableName := Data.Strings[6];
if aRefTableName <> '' then
begin
LookupList := GetLookupByTableName(aRefTableName);
if Data.Count >= 10 then
begin
if Data.Strings[9] = '1' then
LookupList.ShowValue := svLeft
else if Data.Strings[9] = '2' then
LookupList.ShowValue := svRight;
end;
end;
CaseStairs := StrToIntDef(Data.Strings[5],0);
case CaseStairs of
0:
begin
StairsOptions := [soIncrease,soDecrease];
ImageIndex := 1
end;
1:
begin
StairsOptions := [];
ImageIndex := 2
end;
2:
begin
StairsOptions := [soIncrease];
ImageIndex := 3
end;
3:
begin
StairsOptions := [soDecrease];
ImageIndex := 4
end;
end;
end;
end;
aHierarchy.Add(newObject);
newObject.Owner := Self;
newObject.Name := aCaption;
newObject.IDStr := Data.Strings[0];
// проставляем родителя
if lastObject = nil then
newObject.Parent := nil
else if lastLevel = ALevel then
newObject.Parent := lastObject.Parent
else if lastLevel = (ALevel - 1) then
newObject.Parent := lastObject
else if lastLevel > ALevel then
begin
aParent := lastObject.Parent;
while lastLevel > ALevel do
begin
aParent := aParent.Parent;
Dec(lastLevel);
end;
newObject.Parent := aParent;
end;
lastObject := newObject;
lastLevel := ALevel;
finally
FreeAndNil(Data);
end;
end;
// добавим в список лукапов подключения информацию о состояниях датчиков
// если есть хоть один объект
if OPCSource.FNameSpaceCash.Count > 0 then
OPCSource.States := GetLookupByTableName('States');
end;
{ TOPCConnectionCollection }
constructor TOPCConnectionCollection.Create(AOwner: TPersistent);
begin
inherited Create(TOPCConnectionCollectionItem);
// FOwner := AOwner;
FConnectionList := (AOwner as TaOPCConnectionList);
end;
destructor TOPCConnectionCollection.Destroy;
begin
inherited Destroy;
end;
function TOPCConnectionCollection.Find(
aOPCSource: TaCustomOPCSource): TOPCConnectionCollectionItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if aOPCSource = Items[i].OPCSource then
begin
Result := Items[i];
break;
end;
end;
function TOPCConnectionCollection.GetItem(
Index: Integer): TOPCConnectionCollectionItem;
begin
Result := TOPCConnectionCollectionItem(inherited Items[Index]);
end;
type
TOPCConnectionCollectionComponent = class(TComponent)
private
FList: TOPCConnectionCollection;
published
property List: TOPCConnectionCollection read FList write FList;
end;
procedure TOPCConnectionCollection.LoadFromFile(const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TOPCConnectionCollection.LoadFromStream(Stream: TStream);
var
Component: TOPCConnectionCollectionComponent;
begin
Clear;
Component := TOPCConnectionCollectionComponent.Create(nil);
try
Component.FList := Self;
Stream.ReadComponentRes(Component);
finally
Component.Free;
end;
end;
procedure TOPCConnectionCollection.SaveToFile(const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TOPCConnectionCollection.SaveToStream(Stream: TStream);
var
Component: TOPCConnectionCollectionComponent;
begin
Component := TOPCConnectionCollectionComponent.Create(nil);
try
Component.FList := Self;
Stream.WriteComponentRes('OPCConnectionCollection', Component);
finally
Component.Free;
end;
end;
{ TaOPCCustomConnectionList }
constructor TaOPCCustomConnectionList.Create(AOnwer: TComponent);
begin
inherited Create(AOnwer);
FItems := TOPCConnectionCollection.Create(Self);
end;
destructor TaOPCCustomConnectionList.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
function TaOPCCustomConnectionList.GetConnection(
const Name: string): TOPCConnectionCollectionItem;
var
i: integer;
begin
Result := nil;
for i := 0 to Items.Count - 1 do
begin
if Items[i].Name = Name then
begin
Result := Items[i];
exit;
end;
end;
end;
procedure TaOPCCustomConnectionList.SetItems(Value: TOPCConnectionCollection);
begin
FItems.Assign(Value);
end;
{ TaOPCConnectionList }
//procedure TaOPCConnectionList.Connect(aUser: string; aLoadNameSpace, aLoadLookups, aActivate: Boolean;
// aStatusNotify: TOPCStatusNotify = nil; aPassword: string = '');
//var
// i: integer;
// Authorization: TaDCAuthorization;
// Connection: TOPCConnectionCollectionItem;
// aCancel: Boolean;
//begin
// if Items.Count = 0 then
// exit;
//
// aCancel := False;
// Authorization := TaDCAuthorization.Create(nil);
// try
// Authorization.ReadCommandLineExt;
// if Authorization.User = '' then
// Authorization.User := aUser;
// if Authorization.Password = '' then
// Authorization.Password := aPassword;
//
//
// for i := 0 to Items.Count - 1 do
// begin
// Connection := Items[i];
// if Connection.OPCSource.Connected then
// Continue;
//
// // 1. Авторизация
// if Assigned(aStatusNotify) then
// begin
//// aStatusNotify(
//// Format(Connection.OPCSource.GetStringRes(idxConnection_Authorization),
//// [Connection.Name, Connection.OPCSource.RemoteMachine, Connection.OPCSource.Port]), aCancel);
// aStatusNotify(
// Format(Connection.OPCSource.GetStringResStr('StateAuthorization'),
// [Connection.Name, Connection.OPCSource.RemoteMachine, Connection.OPCSource.Port]), aCancel);
//
//
// if aCancel then
// raise EOPCTCPOperationCanceledException.Create(
// Connection.OPCSource.GetStringRes(idxTCPCommand_OperationCanceledByUser));
// end;
//
// Authorization.OPCSource := Connection.OPCSource;
//// if not Authorization.CheckPermissions then
// if not Authorization.Login then
// begin
// if not Authorization.Execute(nil, True) then
// raise EOPCTCPOperationCanceledException.Create(
// Connection.OPCSource.GetStringRes(idxTCPCommand_OperationCanceledByUser));
// end;
// Connection.OPCSource.User := Authorization.User;
// Connection.OPCSource.Password := Authorization.Password;
//
// // 2. Загрузка иерархии
// if aLoadNameSpace then
// begin
// if Assigned(aStatusNotify) then
//// aStatusNotify(
//// Format(Connection.OPCSource.GetStringRes(idxConnection_LoadNameSpace),
//// [Items[i].Name, Items[i].OPCSource.RemoteMachine, Items[i].OPCSource.Port]), aCancel);
// aStatusNotify(
// Format(Connection.OPCSource.GetStringResStr('StateLoadNameSpace'),
// [Items[i].Name, Items[i].OPCSource.RemoteMachine, Items[i].OPCSource.Port]), aCancel);
//
// if aCancel then
// raise EOPCTCPOperationCanceledException.Create(
// Connection.OPCSource.GetStringRes(idxTCPCommand_OperationCanceledByUser));
//
// Connection.LoadChildsFromServer(nil, 2);
//// Connection.OPCSource.GetNameSpace;
//// Connection.InitObjectList;
// end;
//
// // 3. Загрузка справочников
// if aLoadLookups then
// begin
// if Assigned(aStatusNotify) then
//// aStatusNotify(Format(Connection.OPCSource.GetStringRes(idxConnection_LoadLookups),
//// [Items[i].Name, Items[i].OPCSource.RemoteMachine, Items[i].OPCSource.Port]), aCancel);
// aStatusNotify(Format(Connection.OPCSource.GetStringResStr('StateLoadLookups'),
// [Items[i].Name, Items[i].OPCSource.RemoteMachine, Items[i].OPCSource.Port]), aCancel);
//
// if aCancel then
// raise EOPCTCPOperationCanceledException.Create(
// Connection.OPCSource.GetStringRes(idxTCPCommand_OperationCanceledByUser));
//
// Connection.LoadLookups(nil, '');
// end;
//
// // 4. Активируем сбор данных в потоке
// if aActivate then
// Connection.OPCSource.Active := true;
// end;
// finally
// Authorization.Free;
// end;
//end;
function TaOPCConnectionList.FindObjectByID(aConnectionID, ID: integer): TDCObject;
begin
Result := nil;
if (aConnectionID >= Items.Count) or (aConnectionID < 0) then
exit;
Result := Items[aConnectionID].OPCObjectList.FindObjectByID(ID);
end;
function TaOPCConnectionList.FindObjectBySourceAndID(aOPCSource: TaCustomOPCSource; ID: integer): TDCObject;
begin
Result := FindObjectByID(IndexOfOPCSource(aOPCSource), ID);
end;
function TaOPCConnectionList.GetConnectionByName(const aConnectionName: string): TOPCConnectionCollectionItem;
var
i: Integer;
begin
i := IndexOfConnectionName(aConnectionName);
if i > -1 then
Result := Items[i]
else
Result := nil;
end;
function TaOPCConnectionList.GetOPCSourceByConnectionName(const aConnectionName: string): TaCustomOPCSource;
var
i: Integer;
begin
i := IndexOfConnectionName(aConnectionName);
if i > -1 then
Result := TaCustomOPCTCPSource(Items[i].OPCSource)
else
Result := nil;
end;
function TaOPCConnectionList.IndexOf(aObject: TObject): integer;
begin
Result := 0;
while (Result < Items.Count) and (Items[Result] <> aObject) do
Inc(Result);
if Result = Items.Count then
Result := -1;
end;
function TaOPCConnectionList.IndexOfConnectionID(aID: Integer): Integer;
begin
Result := 0;
while (Result < Items.Count) and (Items[Result].ID <> aID) do
Inc(Result);
if Result = Items.Count then
Result := -1;
end;
function TaOPCConnectionList.IndexOfConnectionName(const aName: string): Integer;
begin
Result := 0;
while (Result < Items.Count) and not AnsiSameText(Items[Result].Name, aName) do
Inc(Result);
if Result = Items.Count then
Result := -1;
end;
function TaOPCConnectionList.IndexOfOPCSource(
aOPCSource: TaCustomOPCSource): Integer;
begin
Result := 0;
while (Result < Items.Count) and (Items[Result].OPCSource <> aOPCSource) do
Inc(Result);
if Result = Items.Count then
Result := -1;
end;
procedure TaOPCConnectionList.LoadSettings(aCustomIniFile: TCustomIniFile;
aSectionName: string; aNotClearItems: Boolean = False);
var
i: integer;
aConnectionName: string;
aOPCConnection: TOPCConnectionCollectionItem;
aConnectionSection: string;
aConnections: TStrings;
begin
// чистим список, если не указано обратное
if not aNotClearItems then
Items.Clear;
aConnections := TStringList.Create;
try
aCustomIniFile.ReadSectionValues(aSectionName + '\Connection', aConnections);
for i := 0 to aConnections.Count - 1 do
begin
aConnectionSection := aSectionName + '\Connection\' + aConnections.ValueFromIndex[i];
aConnectionName := aCustomIniFile.ReadString(aConnectionSection, 'Name', '');
// повторяющиеся пропускаем
if IndexOfConnectionName(aConnectionName) <> -1 then
Continue;
aOPCConnection := TOPCConnectionCollectionItem.Create(Items);
aOPCConnection.ID := aCustomIniFile.ReadInteger(aConnectionSection, 'ID', i);
aOPCConnection.Name := aConnectionName;
//aCustomIniFile.ReadString(aConnectionSection, 'Name', '');
aOPCConnection.Enable := aCustomIniFile.ReadBool(aConnectionSection, 'Enable', true);
aOPCConnection.ProtocolVersion :=
TOPCProtocolVersion(aCustomIniFile.ReadInteger(aConnectionSection, 'Protocol', Ord(opv30)));
aOPCConnection.OPCSource.RemoteMachine := aCustomIniFile.ReadString(aConnectionSection, 'RemoteMashine', '');
aOPCConnection.OPCSource.Port := aCustomIniFile.ReadInteger(aConnectionSection, 'Port', cDefPort);
aOPCConnection.OPCSource.AltAddress := aCustomIniFile.ReadString(aConnectionSection, 'AltAddress', '');
aOPCConnection.OPCSource.User := aCustomIniFile.ReadString(aConnectionSection, 'UserName', '');
aOPCConnection.OPCSource.Password := aCustomIniFile.ReadString(aConnectionSection, 'Password', '');
aOPCConnection.OPCSource.ConnectTimeOut := aCustomIniFile.ReadInteger(aConnectionSection, 'ConnectTimeOut', cDefConnectTimeout);
aOPCConnection.OPCSource.ReadTimeOut := aCustomIniFile.ReadInteger(aConnectionSection, 'ReadTimeOut', cDefReadTimeout);
aOPCConnection.OPCSource.Interval := aCustomIniFile.ReadInteger(aConnectionSection, 'Interval', 1000);
aOPCConnection.OPCSource.Encrypt := aCustomIniFile.ReadBool(aConnectionSection, 'Encrypt', cDefEncrypt);
aOPCConnection.OPCSource.CompressionLevel := aCustomIniFile.ReadInteger(aConnectionSection, 'CompressionLevel', cDefCompressionLevel);
aOPCConnection.OPCSource.ServerTimeID := aCustomIniFile.ReadString(aConnectionSection, 'ServerTimeID', '');
aOPCConnection.OPCSource.Language := aCustomIniFile.ReadString(aConnectionSection, 'Language', 'ru');
aOPCConnection.OPCSource.Description := Description;
aOPCConnection.OPCSource.OnError := FOnError;
aOPCConnection.OPCSource.OnActivate := FOnActivate;
aOPCConnection.OPCSource.OnDeActivate := FOnDeActivate;
aOPCConnection.OPCSource.OnRequest := FOnRequest;
end;
finally
aConnections.Free;
end;
end;
procedure TaOPCConnectionList.SaveSettings(aCustomIniFile: TCustomIniFile;
aSectionName: string);
var
i: integer;
aConnectionSection: string;
aConnectionName: string;
aConnections: TStringList;
begin
aConnections := TStringList.Create;
try
aCustomIniFile.ReadSectionValues(aSectionName + '\Connection', aConnections);
for i := 0 to aConnections.Count - 1 do
begin
aConnectionName := aConnections.ValueFromIndex[i];
if Connections[aConnectionName] = nil then
begin
aCustomIniFile.DeleteKey(aSectionName + '\Connection', aConnectionName);
aCustomIniFile.EraseSection(aSectionName + '\Connection\' + aConnectionName);
end;
end;
finally
aConnections.Free;
end;
for i := 0 to Items.Count - 1 do
aCustomIniFile.WriteString(aSectionName + '\Connection', Items[i].Name, Items[i].Name);
for i := 0 to Items.Count - 1 do
begin
aConnectionSection := aSectionName + '\Connection\' + Items[i].Name;
aCustomIniFile.WriteInteger(aConnectionSection, 'ID', Items[i].ID);
aCustomIniFile.WriteString(aConnectionSection, 'Name', Items[i].Name);
aCustomIniFile.WriteBool(aConnectionSection, 'Enable', Items[i].Enable);
aCustomIniFile.WriteInteger(aConnectionSection, 'Protocol', Ord(Items[i].ProtocolVersion));
aCustomIniFile.WriteString(aConnectionSection, 'RemoteMashine', Items[i].OPCSource.MainHost);
aCustomIniFile.WriteInteger(aConnectionSection, 'Port', Items[i].OPCSource.MainPort);
aCustomIniFile.WriteString(aConnectionSection, 'AltAddress', Items[i].OPCSource.AltAddress);
aCustomIniFile.WriteInteger(aConnectionSection, 'ConnectTimeOut', Items[i].OPCSource.ConnectTimeOut);
aCustomIniFile.WriteInteger(aConnectionSection, 'ReadTimeOut', Items[i].OPCSource.ReadTimeOut);
aCustomIniFile.WriteInteger(aConnectionSection, 'Interval', Items[i].OPCSource.Interval);
aCustomIniFile.WriteBool(aConnectionSection, 'Encrypt', Items[i].OPCSource.Encrypt);
aCustomIniFile.WriteInteger(aConnectionSection, 'CompressionLevel', Items[i].OPCSource.CompressionLevel);
aCustomIniFile.WriteString(aConnectionSection, 'ServerTimeID', Items[i].OPCSource.ServerTimeID);
end;
end;
procedure TaOPCConnectionList.SetActive(const Value: boolean);
var
i: Integer;
begin
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.Active := Value;
end;
procedure TaOPCConnectionList.SetDescription(const Value: string);
var
i: Integer;
begin
if FDescription <> Value then
begin
FDescription := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.Description := FDescription;
end;
end;
procedure TaOPCConnectionList.SetOnActivate(const Value: TNotifyEvent);
var
i: Integer;
begin
// if FOnActivate <> Value then
begin
FOnActivate := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnActivate := FOnActivate;
end;
end;
procedure TaOPCConnectionList.SetOnConnect(const Value: TNotifyEvent);
var
i: Integer;
begin
FOnConnect := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnConnect := FOnConnect;
end;
procedure TaOPCConnectionList.SetOnDeactivate(const Value: TNotifyEvent);
var
i: Integer;
begin
// if FOnDeactivate <> Value then
begin
FOnDeactivate := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnDeactivate := FOnDeactivate;
end;
end;
procedure TaOPCConnectionList.SetOnDisconnect(const Value: TNotifyEvent);
var
i: Integer;
begin
FOnDisconnect := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnDisconnect := FOnDisconnect;
end;
procedure TaOPCConnectionList.SetOnError(const Value: TMessageStrEvent);
var
i: Integer;
begin
// if FOnError <> Value then
begin
FOnError := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnError := FOnError;
end;
end;
procedure TaOPCConnectionList.SetOnRequest(const Value: TNotifyEvent);
var
i: Integer;
begin
// if FOnRequest <> Value then
begin
FOnRequest := Value;
for i := 0 to Items.Count - 1 do
Items[i].OPCSource.OnRequest := FOnRequest;
end;
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Marcel Bestebroer
<marcelb att zeelandnet dott nl>.
Portions created by Marcel Bestebroer are Copyright (C) 2000 - 2001 mbeSoft.
All Rights Reserved.
Contributor(s): Michael Beck [mbeck att bigfoot dott com].
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Description:
JvInspector XVCL data layer. Provides access to TJvxNode and descendants.
XVCL can be obtained from the XVCL home page, located at
http://xvcl.sourceforge.net
Known Issues:
-----------------------------------------------------------------------------}
// $Id: JvInspXVCL.pas 12461 2009-08-14 17:21:33Z obones $
unit JvInspXVCL;
{$I jvcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
JvInspector, JvxClasses;
type
TJvInspectorxNodeData = class(TJvCustomInspectorData)
private
FJvxNode: TJvxNode;
protected
function GetAsFloat: Extended; override;
function GetAsInt64: Int64; override;
function GetAsMethod: TMethod; override;
function GetAsOrdinal: Int64; override;
function GetAsString: string; override;
function GetJvxNode: TJvxNode; virtual;
function IsEqualReference(const Ref: TJvCustomInspectorData): Boolean; override;
procedure NodeNotifyEvent(Sender: TJvxNode; Operation: TJvxNodeOperation); virtual;
procedure SetAsFloat(const Value: Extended); override;
procedure SetAsInt64(const Value: Int64); override;
procedure SetAsMethod(const Value: TMethod); override;
procedure SetAsOrdinal(const Value: Int64); override;
procedure SetAsString(const Value: string); override;
procedure SetJvxNode(Value: TJvxNode); virtual;
public
procedure GetAsSet(var Buf); override;
function HasValue: Boolean; override;
function IsAssigned: Boolean; override;
function IsInitialized: Boolean; override;
class function New(const AParent: TJvCustomInspectorItem; const AName: string; const AJvxNode: TJvxNode): TJvCustomInspectorItem;
procedure SetAsSet(const Buf); override;
property JvxNode: TJvxNode read GetJvxNode write SetJvxNode;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvInspXVCL.pas $';
Revision: '$Revision: 12461 $';
Date: '$Date: 2009-08-14 19:21:33 +0200 (ven. 14 août 2009) $';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
Consts,
SysUtils, TypInfo,
JvConsts, JvTypes, JvResources;
function TJvInspectorxNodeData.GetAsFloat: Extended;
begin
CheckReadAccess;
if JvxNode.TypeInfo^.Kind = tkFloat then
Result := JvxNode.AsFloat
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorFloat]);
end;
function TJvInspectorxNodeData.GetAsInt64: Int64;
begin
CheckReadAccess;
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorInt64]);
end;
function TJvInspectorxNodeData.GetAsMethod: TMethod;
begin
CheckReadAccess;
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorTMethod]);
end;
function TJvInspectorxNodeData.GetAsOrdinal: Int64;
begin
CheckReadAccess;
if JvxNode.TypeInfo^.Kind in
[tkInteger, tkChar, tkEnumeration, tkSet, tkWChar, tkClass] then
begin
if GetTypeData(JvxNode.TypeInfo).OrdType = otULong then
Result := Cardinal(JvxNode.AsInteger)
else
Result := JvxNode.AsInteger;
end
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorOrdinal]);
end;
function TJvInspectorxNodeData.GetAsString: string;
begin
CheckReadAccess;
if JvxNode.TypeInfo^.Kind in tkStrings then
Result := JvxNode.AsString
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorString]);
end;
function TJvInspectorxNodeData.GetJvxNode: TJvxNode;
begin
Result := FJvxNode;
end;
function TJvInspectorxNodeData.IsEqualReference(const Ref: TJvCustomInspectorData): Boolean;
begin
Result := (Ref is TJvInspectorxNodeData) and (TJvInspectorxNodeData(Ref).JvxNode = JvxNode);
end;
procedure TJvInspectorxNodeData.NodeNotifyEvent(Sender: TJvxNode;
Operation: TJvxNodeOperation);
begin
if (Sender = JvxNode) and (Operation = noChange) then
begin
InvalidateData;
Invalidate;
end;
end;
procedure TJvInspectorxNodeData.SetAsFloat(const Value: Extended);
begin
CheckWriteAccess;
if JvxNode.TypeInfo^.Kind = tkFloat then
JvxNode.AsFloat := Value
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorFloat]);
end;
procedure TJvInspectorxNodeData.SetAsInt64(const Value: Int64);
begin
CheckWriteAccess;
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorInt64]);
end;
procedure TJvInspectorxNodeData.SetAsMethod(const Value: TMethod);
begin
CheckWriteAccess;
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorTMethod]);
end;
procedure TJvInspectorxNodeData.SetAsOrdinal(const Value: Int64);
var
MinValue: Int64;
MaxValue: Int64;
begin
CheckWriteAccess;
if TypeInfo.Kind in [tkInteger, tkChar, tkEnumeration, tkWChar] then
begin
case GetTypeData(TypeInfo).OrdType of
otSByte:
begin
MinValue := GetTypeData(TypeInfo).MinValue;
MaxValue := GetTypeData(TypeInfo).MaxValue;
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Shortint(Value)
end;
otUByte:
begin
MinValue := GetTypeData(TypeInfo).MinValue;
MaxValue := GetTypeData(TypeInfo).MaxValue;
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Byte(Value)
end;
otSWord:
begin
MinValue := GetTypeData(TypeInfo).MinValue;
MaxValue := GetTypeData(TypeInfo).MaxValue;
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Smallint(Value)
end;
otUWord:
begin
MinValue := GetTypeData(TypeInfo).MinValue;
MaxValue := GetTypeData(TypeInfo).MaxValue;
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Word(Value)
end;
otSLong:
begin
MinValue := GetTypeData(TypeInfo).MinValue;
MaxValue := GetTypeData(TypeInfo).MaxValue;
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Integer(Value)
end;
otULong:
begin
MinValue := Longword(GetTypeData(TypeInfo).MinValue);
MaxValue := Longword(GetTypeData(TypeInfo).MaxValue);
if (Value < MinValue) or (Value > MaxValue) then
raise ERangeError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
JvxNode.AsInteger := Integer(Value)
end;
end;
end
else
if TypeInfo.Kind = tkClass then
JvxNode.AsInteger := Integer(Value)
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorOrdinal]);
end;
procedure TJvInspectorxNodeData.SetAsString(const Value: string);
begin
CheckWriteAccess;
if JvxNode.TypeInfo.Kind in tkStrings then
JvxNode.AsString := Value
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorString]);
end;
procedure TJvInspectorxNodeData.SetJvxNode(Value: TJvxNode);
begin
if Value <> JvxNode then
begin
if JvxNode <> nil then
JvxNode.OnNotifyEvents.Remove(NodeNotifyEvent);
FJvxNode := Value;
if JvxNode <> nil then
begin
JvxNode.OnNotifyEvents.Add(NodeNotifyEvent);
TypeInfo := Value.TypeInfo;
end
end;
end;
procedure TJvInspectorxNodeData.GetAsSet(var Buf);
var
CompType: PTypeInfo;
EnumMin: Integer;
EnumMax: Integer;
ResBytes: Integer;
TmpInt: Integer;
begin
CheckReadAccess;
if JvxNode.TypeInfo.Kind <> tkSet then
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorSet]);
CompType := GetTypeData(TypeInfo).CompType^;
EnumMin := GetTypeData(CompType).MinValue;
EnumMax := GetTypeData(CompType).MaxValue;
ResBytes := (EnumMax div 8) - (EnumMin div 8) + 1;
if ResBytes > 4 then
ResBytes := 4;
TmpInt := JvxNode.AsInteger;
Move(TmpInt, Buf, ResBytes);
end;
function TJvInspectorxNodeData.HasValue: Boolean;
begin
Result := IsInitialized and (JvxNode.TypeInfo <> nil);
end;
function TJvInspectorxNodeData.IsAssigned: Boolean;
begin
Result := IsInitialized and JvxNode.Assigned;
end;
function TJvInspectorxNodeData.IsInitialized: Boolean;
begin
Result := (JvxNode <> nil);
end;
class function TJvInspectorxNodeData.New(const AParent: TJvCustomInspectorItem;
const AName: string; const AJvxNode: TJvxNode): TJvCustomInspectorItem;
var
Data: TJvInspectorxNodeData;
begin
if AJvxNode = nil then
raise EJVCLException.CreateRes(@RsENoNodeSpecified);
if AJvxNode.NodeName <> '' then
Data := TJvInspectorxNodeData.CreatePrim(AJvxNode.NodeName, AJvxNode.TypeInfo))
else
Data := TJvInspectorxNodeData.CreatePrim(AName, AJvxNode.TypeInfo));
Data.JvxNode := AJvxNode;
Data := TJvInspectorxNodeData(RegisterInstance(Data));
if Data <> nil then
Result := Data.NewItem(AParent)
else
Result := nil;
end;
procedure TJvInspectorxNodeData.SetAsSet(const Buf);
var
CompType: PTypeInfo;
EnumMin: Integer;
EnumMax: Integer;
ResBytes: Integer;
TmpInt: Integer;
begin
CheckWriteAccess;
if JvxNode.TypeInfo.Kind <> tkSet then
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorSet]);
CompType := GetTypeData(TypeInfo).CompType^;
EnumMin := GetTypeData(CompType).MinValue;
EnumMax := GetTypeData(CompType).MaxValue;
ResBytes := (EnumMax div 8) - (EnumMin div 8) + 1;
if ResBytes > 4 then
ResBytes := 4;
TmpInt := 0;
Move(Buf, TmpInt, ResBytes);
JvxNode.AsInteger := TmpInt;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end. |
unit ULogger;
interface
uses
Windows,
SysUtils,
UServerTypes;
type
TBaseLogger = class(TInterfacedObject, ILogger)
function LogPrefix(): string;
procedure Log(messageText: string; level: TErrorLevel); overload; virtual; abstract;
procedure Log(messageText: string; formatString: string); overload; virtual; abstract;
procedure Log(formatString: string; const args: array of const); overload; virtual; abstract;
end;
TConsoleLogger = class(TBaseLogger)
private
FOemConvert: bool;
FCritical: TRTLCriticalSection;
function StringToOem(const value: string): AnsiString;
public
constructor Create(oemConvert: bool = true);
destructor Destroy; override;
procedure Log(messageText: string; level: TErrorLevel = elInformation); overload; override;
procedure Log(messageText: string; formatString: string); overload; override;
procedure Log(formatString: string; const args: array of const); overload; override;
end;
TDebugLogger = class(TBaseLogger)
public
constructor Create;
destructor Destroy; override;
procedure Log(messageText: string; level: TErrorLevel = elInformation); overload; override;
procedure Log(messageText: string; formatString: string); overload; override;
end;
TFileLogger = class(TBaseLogger)
private
FFileName: string;
public
constructor Create(fileName: string);
destructor Destroy; override;
end;
TStubLogger = class(TBaseLogger)
public
constructor Create;
destructor Destroy; override;
procedure Log(messageText: string; level: TErrorLevel = elInformation); overload; override;
procedure Log(messageText: string; formatString: string); overload; override;
end;
implementation
const
DATETIME_FORMAT = 'yyyy-mm-dd hh:nn:ss.zzz';
LOG_MESSAGE = '%s %s';
constructor TConsoleLogger.Create(oemConvert: bool = true);
begin
inherited Create();
FOemConvert := oemConvert;
InitializeCriticalSection(FCritical);
end;
destructor TConsoleLogger.Destroy;
begin
Log('Console log destroyed');
DeleteCriticalSection(FCritical);
inherited;
end;
procedure TConsoleLogger.Log(messageText: string; level: TErrorLevel = elInformation);
var
sDateTime: string;
sOut: string;
color: byte;
hConsole: THandle;
bufferInfo: TConsoleScreenBufferInfo;
newAttributes: short;
oldAttributes: short;
const
hlNotice = BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED;
hlWarning = FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_INTENSITY;
hlError = FOREGROUND_RED or FOREGROUND_INTENSITY;
hlInfo = FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED;
begin
sDateTime := FormatDateTime(DATETIME_FORMAT, Now);
sOut := Format(LOG_MESSAGE, [sDateTime, messageText]);
if FOemConvert then
sOut := StringToOem(sOut);
case level of
elInformation:
color := hlInfo;
elNotice:
color := hlNotice;
elWarning:
color := hlWarning;
elError:
color := hlError;
end;
try
EnterCriticalSection(FCritical);
hConsole := GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, bufferInfo);
oldAttributes := bufferInfo.wAttributes;
//newAttributes := (color and $0F) or ((oldAttributes shr 4) and $0F) shl 4;
newAttributes := color;
SetConsoleTextAttribute(hConsole, newAttributes);
Writeln(sOut);
SetConsoleTextAttribute(hConsole, oldAttributes);
finally
LeaveCriticalSection(FCritical);
end;
end;
procedure TConsoleLogger.Log(messageText, formatString: string);
begin
Self.Log(Format(formatString, [messageText]));
end;
procedure TConsoleLogger.Log(formatString: string; const args: array of const);
begin
Self.Log(Format(formatString, args));
end;
function TConsoleLogger.StringToOem(const value: string): AnsiString;
begin
SetLength(Result, Length(value));
if value <> '' then
CharToOem(PChar(value), PAnsiChar(Result));
end;
constructor TDebugLogger.Create;
begin
inherited;
end;
destructor TDebugLogger.Destroy;
begin
inherited;
end;
procedure TDebugLogger.Log(messageText: string; level: TErrorLevel = elInformation);
begin
OutputDebugString(PChar(messageText));
end;
procedure TDebugLogger.Log(messageText, formatString: string);
begin
Self.Log(Format(formatString, [messageText]));
end;
constructor TFileLogger.Create(fileName: string);
begin
inherited Create();
FFileName := fileName;
end;
destructor TFileLogger.Destroy;
begin
inherited;
end;
constructor TStubLogger.Create;
begin
end;
destructor TStubLogger.Destroy;
begin
inherited;
end;
procedure TStubLogger.Log(messageText: string; level: TErrorLevel = elInformation);
begin
Exit;
end;
procedure TStubLogger.Log(messageText, formatString: string);
begin
Exit;
end;
function TBaseLogger.LogPrefix: string;
begin
Result := FormatDateTime(DATETIME_FORMAT, Now);
end;
end.
|
unit VectorOtherTestCase;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath;
type
{ TVectorOtherTestCase }
TVectorOtherTestCase = class(TVectorBaseTestCase)
published
procedure TestCompare; // these two test ensure we have data to play
procedure TestCompareFalse; // with and tests the compare function.
procedure TestMinXYZComponent;
procedure TestMaxXYZComponent;
procedure TestShuffle;
procedure TestSwizzle;
procedure TestMinVector;
procedure TestMaxVector;
procedure TestMinSingle;
procedure TestMaxSingle;
procedure TestClampVector;
procedure TestClampSingle;
procedure TestLerp;
// procedure TestMoveAround;
procedure TestCombine;
procedure TestCombine2;
procedure TestCombine3;
end;
implementation
{%region%====[ TVectorOtherTestCase ]==========================================}
procedure TVectorOtherTestCase.TestCompare;
begin
AssertTrue('Test Values do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1));
end;
procedure TVectorOtherTestCase.TestCompareFalse;
begin
AssertFalse('Test Values should not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt2));
end;
procedure TVectorOtherTestCase.TestMinXYZComponent;
begin
Fs1 := nt1.MinXYZComponent;
Fs2 := vt1.MinXYZComponent;
AssertTrue('Vector MinXYZComponents do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2));
end;
procedure TVectorOtherTestCase.TestMaxXYZComponent;
begin
Fs1 := nt1.MaxXYZComponent;
Fs2 := vt1.MaxXYZComponent;
AssertTrue('Vector MaxXYZComponents do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2));
end;
procedure TVectorOtherTestCase.TestShuffle;
begin
nt3 := nt1.Shuffle(1,2,3,0);
vt3 := vt1.Shuffle(1,2,3,0);
AssertTrue('Vector Shuffle no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestSwizzle;
begin
nt3 := nt1.Swizzle(swWZYX);
vt3 := vt1.Swizzle(swWZYX);
AssertTrue('Vector Swizzle no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestMinVector;
begin
nt3 := nt1.Min(nt2);
vt3 := vt1.Min(vt2);
AssertTrue('Vector Min vectors do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestMaxVector;
begin
nt3 := nt1.Max(nt2);
vt3 := vt1.Max(vt2);
AssertTrue('Vector Max vectors do not match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestMinSingle;
begin
nt3 := nt1.Min(Fs1);
vt3 := vt1.Min(Fs1);
AssertTrue('Vector Min Singles do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestMaxSingle;
begin
nt3 := nt1.Max(Fs1);
vt3 := vt1.Max(Fs1);
AssertTrue('Vector Max Singles do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestClampVector;
begin
nt3 := nt1.Clamp(nt2,nt1);
vt3 := vt1.Clamp(vt2,vt1);
AssertTrue('Vector Clamp vectors do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestClampSingle;
begin
nt3 := nt1.Clamp(fs2,fs1);
vt3 := vt1.Clamp(fs2,fs1);
AssertTrue('Vector Clamp vectors do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestLerp;
begin
nt3 := nt1.Lerp(nt1,0.8);
vt3 := vt1.Lerp(vt1,0.8);
AssertTrue('Vector Clamp vectors do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestCombine;
begin
nt3 := nt1.Combine(nt2, fs1);
vt3 := vt1.Combine(vt2, fs1);
AssertTrue('Vector Combines do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestCombine2;
begin
nt3 := nt1.Combine2(nt2, fs1, fs2);
vt3 := vt1.Combine2(vt2, fs1, fs2);
AssertTrue('Vector Combine2s do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TVectorOtherTestCase.TestCombine3;
begin
nt3 := nt1.Combine3(nt2, nt1, fs1, fs2, fs2);
vt3 := vt1.Combine3(vt2, vt1, fs1, fs2, fs2);
AssertTrue('Vector Combine3s do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
{
procedure TVectorOtherTestCase.TestMoveAround;
begin
nt3 := nt1.m(nt2);
vt3 := vt1.Reflect(vt2);
AssertTrue('Vector Reflects do not match', Compare(nt3,vt3));
end;
}
{%endregion%}
initialization
RegisterTest(REPORT_GROUP_VECTOR4F, TVectorOtherTestCase);
end.
|
unit UfrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ButtonGroup, Vcl.Menus,
UProject, Vcl.ExtCtrls, Vcl.AppEvnts, UFastKeysSO, USnapshot, USlideTemplate,
UframeProjectProperties;
type
TfrmMain = class(TForm)
MainMenu1: TMainMenu;
mniFile: TMenuItem;
mniFileNew: TMenuItem;
mniFileOpen: TMenuItem;
mniFileSave: TMenuItem;
mniFileSaveAs: TMenuItem;
N1: TMenuItem;
mniFileBuildPPT: TMenuItem;
lbSlides: TListBox;
Label1: TLabel;
OpenDialogProject: TOpenDialog;
SaveDialogProject: TSaveDialog;
SaveDialogPPT: TSaveDialog;
ppmSlides: TPopupMenu;
mniSlidesDelete: TMenuItem;
mniSlidesCopy: TMenuItem;
CategoryPanelGroup1: TCategoryPanelGroup;
CategoryPanel1: TCategoryPanel;
ApplicationEvents1: TApplicationEvents;
mniSettings: TMenuItem;
N2: TMenuItem;
mniFileRecentlyUsed: TMenuItem;
mniEdit: TMenuItem;
mniEditUndo: TMenuItem;
mniEditRedo: TMenuItem;
lblVersion: TLabel;
FrameProjectProperties1: TFrameProjectProperties;
procedure FormCreate(Sender: TObject);
procedure ButtonGroupNewSlideButtonClicked(Sender: TObject; Index: Integer);
procedure lbSlidesDblClick(Sender: TObject);
procedure lbSlidesDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure lbSlidesDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure lbSlidesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mniFileOpenClick(Sender: TObject);
procedure mniFileSaveClick(Sender: TObject);
procedure mniFileSaveAsClick(Sender: TObject);
procedure mniFileBuildPPTClick(Sender: TObject);
procedure ppmSlidesPopup(Sender: TObject);
procedure mniSlidesDeleteClick(Sender: TObject);
procedure mniSlidesCopyClick(Sender: TObject);
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure edtCollecte1Exit(Sender: TObject);
procedure lbSlidesDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure FormResize(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure mniSettingsClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mniFileClick(Sender: TObject);
procedure mniEditUndoClick(Sender: TObject);
procedure mniEditRedoClick(Sender: TObject);
private
{ Private declarations }
FStartingPoint: TPoint;
FFileName: string;
FSavedProjectHash: string;
FLastProjectHash: string;
FHasChanged: boolean;
FPictos: TFastKeyValuesSO;
FShowQuickstart: boolean;
procedure ClearSlides;
procedure DoBuild;
function DoProjectCreate(strLiturgy: string): string;
function DoOpen(strFileName: string): string;
function DoSave(strFileName: string): string;
function PerformOpen(strFileName: string): string;
procedure DoSlideCopy;
procedure DoSlideDelete;
procedure FillTemplates;
procedure FillLiturgies;
procedure ShowSettings;
procedure mniFileNewClick(Sender: TObject);
procedure mniRecentFileClick(Sender: TObject);
function CreateProjectHash: string;
function CheckChanged: boolean;
procedure SetHasChanged(const Value: boolean);
protected
FSnapshotList: TSnapshotList;
function GetHasUndo: boolean;
function GetHasRedo: boolean;
procedure DoUndo;
procedure DoRedo;
procedure AddSnapshot;
procedure StartSnapshot;
public
procedure DoShowQuickStart;
procedure ProjectToForm(project: TProject);
procedure ProjectFromForm(var project: TProject);
function SlidesToString: string;
procedure SlidesFromString(strText: string);
property HasChanged: boolean read FHasChanged write SetHasChanged;
{ Public declarations }
end;
TPictoObject = class(TValueObject)
private
FPicto: TBitmap;
public
constructor Create(strPictoFileName: string); virtual;
destructor Destroy; override;
property Picto: TBitmap read FPicto;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
PNGImage, GR32, GR32_Misc2,
GnuGetText, UUtils, UUtilsForms, USlide, UBuildPowerpoint, UMRUList,
ULiturgy, USourceInfo, UfrmSettings, USettings, UfrmSelectString,
UfrmQuickStart, UfrmNewProjectOptions;
procedure TfrmMain.AddSnapshot;
var
project: TProject;
begin
if FSnapshotList.Active then begin
project := nil;
try
ProjectFromForm(project);
FSnapshotList.ActionDo(TSnapshotProject.Create(project));
finally
project.Free;
end;
end;
end;
procedure TfrmMain.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
begin
HasChanged := FLastProjectHash <> FSavedProjectHash;
mniEditUndo.Enabled := GetHasUndo;
mniEditRedo.Enabled := GetHasRedo;
if FShowQuickstart then begin
FShowQuickstart := False;
DoShowQuickStart;
end;
end;
procedure TfrmMain.ButtonGroupNewSlideButtonClicked(Sender: TObject;
Index: Integer);
var
buttongroup: TButtonGroup;
button: TGrpButtonItem;
slide: TSlide;
template: TSlideTemplate;
iInsertPos: integer;
begin
AddSnapshot;
iInsertPos := lbSlides.ItemIndex;
if iInsertPos = -1 then begin
iInsertPos := lbSlides.Items.Count;
end else begin
//inc(iInsertPos);
end;
buttongroup := Sender as TButtonGroup;
if Assigned(buttongroup) then begin
button := buttongroup.Items[Index];
if Assigned(button) then begin
template := TSlideTemplate(button.Data);
if Assigned(template) then begin
slide := template.DoOnAdd(true);
if Assigned(slide) then begin
lbSlides.Items.InsertObject(iInsertPos, slide.SlideName, slide);
lbSlides.ItemIndex := iInsertPos;
FLastProjectHash := CreateProjectHash;
end;
end;
end;
end;
AddSnapshot;
end;
function TfrmMain.CheckChanged: boolean;
begin
Result := True;
if (FLastProjectHash <> '') and (FLastProjectHash <> FSavedProjectHash) then begin
case QuestionYNC(_('Do you want to save changes?')) of
cbUnknown: Result := false;
cbTrue: FFileName := DoSave(FFileName);
end;
end;
end;
procedure TfrmMain.ClearSlides;
var
i: integer;
begin
for i := 0 to lbSlides.Items.Count -1 do begin
lbSlides.Items.Objects[i].Free;
end;
lbSlides.Clear;
end;
function TfrmMain.CreateProjectHash: string;
var
project: TProject;
begin
project := nil;
ProjectFromForm(project);
try
Result := project.CreateHash;
finally
project.Free;
end;
end;
procedure TfrmMain.DoBuild;
var
project: TProject;
begin
AddSnapshot;
if SaveDialogPPT.Execute then begin
project := nil;
ProjectFromForm(project);
try
BuildPowerpoint(SaveDialogPPT.FileName, project);
finally
project.Free;
end;
end;
end;
function TfrmMain.DoProjectCreate(strLiturgy: string): string;
var
project: TProject;
liturgy: TLiturgy;
LSlideTypeOptions: TSlideTypeOptions;
begin
// if FFileName <> '' then begin
// DoSave(FFileName);
// end;
if CheckChanged then begin
project := TProject.Create;
try
liturgy := GetLiturgies.FindByName(strLiturgy);
if Assigned(liturgy) then begin
liturgy.FillProjectProperties(project);
LSlideTypeOptions := liturgy.GetSlideTypeOptions;
if (LSlideTypeOptions <> []) and (LSlideTypeOptions <> [stNone]) then
begin
if not GetProjectInfo(project, LSlideTypeOptions) then
begin
Result := '';
Exit;
end;
end;
liturgy.FillProjectSlides(project, LSlideTypeOptions);
end;
ProjectToForm(project);
FSavedProjectHash := project.CreateHash;
FLastProjectHash := FSavedProjectHash;
StartSnapshot;
finally
project.Free;
end;
Result := '';
end else
Result := FFileName;
end;
procedure TfrmMain.DoRedo;
var
oSnapshot: TSnapshotProject;
project: TProject;
begin
oSnapshot := FSnapshotList.ActionRedo as TSnapshotProject;
if Assigned(oSnapshot) then begin
project := TProject.Create;
try
oSnapshot.RestoreSnapshot(project);
ProjectToForm(project);
finally
project.Free;
end;
end;
end;
function TfrmMain.DoOpen(strFileName: string): string;
begin
if CheckChanged then begin
OpenDialogProject.InitialDir := extractFilePath(strFileName);
if OpenDialogProject.Execute and FileExists(OpenDialogProject.FileName) then begin
Result := PerformOpen(OpenDialogProject.FileName);
end;
end;
end;
function TfrmMain.DoSave(strFileName: string): string;
var
project: TProject;
begin
if strFileName = '' then begin
if SaveDialogProject.Execute then begin
strFileName := SaveDialogProject.FileName;
end;
end;
project := nil;
try
if strFileName <> '' then begin
GetMRUList.AddMRU(strFileName);
ProjectFromForm(project);
SaveUnicodeToFile(strFileName, project.AsJSon);
FSavedProjectHash := project.CreateHash;
FLastProjectHash := FSavedProjectHash;
end;
finally
project.Free;
end;
Result := strFileName;
end;
procedure TfrmMain.DoSlideCopy;
var
index: integer;
begin
AddSnapshot;
index := lbSlides.ItemIndex;
if index <> -1 then begin
lbSlides.Items.InsertObject(
index + 1,
lbSlides.Items[index],
TSlide.Create(TSlide(lbSlides.Items.Objects[index]).AsJSon)
);
FLastProjectHash := CreateProjectHash;
end;
AddSnapshot;
end;
procedure TfrmMain.DoSlideDelete;
begin
AddSnapshot;
if lbSlides.ItemIndex <> -1 then begin
lbSlides.Items.Objects[lbSlides.ItemIndex].Free;
lbSlides.Items.Delete(lbSlides.ItemIndex);
FLastProjectHash := CreateProjectHash;
end;
AddSnapshot;
end;
procedure TfrmMain.DoUndo;
var
oSnapshot: TSnapshotProject;
project: TProject;
begin
oSnapshot := FSnapshotList.ActionUndo as TSnapshotProject;
if Assigned(oSnapshot) then begin
project := TProject.Create;
try
oSnapshot.RestoreSnapshot(project);
ProjectToForm(project);
finally
project.Free;
end;
end;
end;
procedure TfrmMain.edtCollecte1Exit(Sender: TObject);
begin
FLastProjectHash := CreateProjectHash;
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := CheckChanged;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
TranslateComponent(self);
FShowQuickstart := False;
FHasChanged := False;
FillTemplates;
FillLiturgies;
FPictos := TFastKeyValuesSO.Create;
FSnapshotList := TSnapshotList.Create;
FSnapshotList.Clear;
FrameProjectProperties1.OnChanged := edtCollecte1Exit;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FreeAndNil(FSnapshotList);
ClearSlides;
FPictos.Free;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
lbSlides.Repaint;
end;
procedure TfrmMain.FormShow(Sender: TObject);
var
datBuild: TDateTime;
begin
if (GetSettings.FTPUserName = '') or (GetSettings.FTPPassword = '') then begin
ShowSettings;
end;
datBuild := PImageNtHeaders(HInstance + PImageDosHeader(HInstance)^._lfanew)^.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
lblVersion.Caption := _('Version') + ': ' + FormatDateTime('d-m-yyyy', datBuild);
FShowQuickstart := True;
end;
function TfrmMain.GetHasRedo: boolean;
begin
Result := Assigned(FSnapshotList) and FSnapshotList.HasRedo;
end;
function TfrmMain.GetHasUndo: boolean;
begin
Result := Assigned(FSnapshotList) and FSnapshotList.HasUndo;
end;
procedure TfrmMain.FillLiturgies;
var
liturgies: TLiturgies;
i: Integer;
mniNew: TmenuItem;
begin
liturgies := GetLiturgies;
while mniFileNew.Count > 0 do
mniFileNew.Delete(0);
for i := 0 to liturgies.Count -1 do begin
mniNew := TMenuItem.Create(mniFileNew);
mniNew.Caption := liturgies[i].Name;
mniNew.OnClick := mniFileNewClick;
mniFileNew.Add(mniNew);
end;
end;
procedure TfrmMain.FillTemplates;
var
i, iTemplate, iPanel: integer;
templates: TSlideTemplates;
button: TGrpButtonItem;
panel, panelFound: TCategoryPanel;
group: TButtonGroup;
begin
templates := GetSlideTemplates;
for i := 0 to CategoryPanelGroup1.Panels.Count -1 do begin
TObject(CategoryPanelGroup1.Panels[i]).Free;
end;
CategoryPanelGroup1.Panels.Clear;
for iTemplate := 0 to templates.Count -1 do begin
if templates[iTemplate].CategoryName <> '' then begin
panelFound := nil;
for iPanel := 0 to CategoryPanelGroup1.Panels.Count -1 do begin
panel := CategoryPanelGroup1.Panels[iPanel];
if panel.Caption = templates[iTemplate].CategoryName then begin
panelFound := panel;
break;
end;
end;
if not Assigned(panelFound) then begin
panelFound := TCategoryPanel.Create(CategoryPanelGroup1);
panelFound.Caption := templates[iTemplate].CategoryName;
panelFound.PanelGroup := CategoryPanelGroup1;
panelFound.Height := 25;
end;
group := nil;
for i := 0 to panelFound.ComponentCount -1 do begin
if panelFound.Components[i] is TButtonGroup then begin
group := panelFound.Components[i] as TButtonGroup;
break;
end;
end;
if not Assigned(group) then begin
group := TButtonGroup.Create(panelFound);
group.Parent := panelFound;
group.ButtonOptions := [gboFullSize, gboShowCaptions];
group.Align := alClient;
group.OnButtonClicked := ButtonGroupNewSlideButtonClicked;
end;
button := group.Items.Add;
button.Caption := templates[iTemplate].Name;
button.Data := templates[iTemplate];
panelFound.Height := 30 + group.Items.Count * group.ButtonHeight;
end;
end;
CategoryPanelGroup1.CollapseAll;
end;
procedure TfrmMain.lbSlidesDblClick(Sender: TObject);
var
slide: TSlide;
templates: TSlideTemplates;
template: TSlideTemplate;
begin
if lbSlides.ItemIndex <> -1 then begin
AddSnapshot;
slide := lbSlides.Items.Objects[lbSlides.ItemIndex] as TSlide;
if Assigned(slide) then begin
templates := GetSlideTemplates;
template := templates.FindByName(slide.SlideTemplateName);
if Assigned(template) then begin
template.DoOnEdit(slide);
lbSlides.Items[lbSlides.ItemIndex] := slide.SlideName;
end;
end;
FLastProjectHash := CreateProjectHash;
AddSnapshot;
end;
end;
procedure TfrmMain.lbSlidesDragDrop(Sender, Source: TObject; X, Y: Integer);
var
DropPosition, StartPosition: Integer;
DropPoint: TPoint;
strSlide: string;
oSlide: TObject;
begin
AddSnapshot;
DropPoint.X := X;
DropPoint.Y := Y;
with Source as TListBox do begin
StartPosition := ItemAtPos(FStartingPoint, True);
DropPosition := ItemAtPos(DropPoint,True);
if StartPosition < DropPosition then
dec(DropPosition);
if (StartPosition <> DropPosition) and (StartPosition <> -1) then begin
strSlide := Items[StartPosition];
oSlide := Items.Objects[StartPosition];
Items.Delete(StartPosition);
if DropPosition < 0 then begin
items.AddObject(strSlide, oSlide);
ItemIndex := Items.Count -1;
end else begin
items.InsertObject(DropPosition, strSlide, oSlide);
ItemIndex := DropPosition;
end;
FLastProjectHash := CreateProjectHash;
end;
end;
AddSnapshot;
end;
procedure TfrmMain.lbSlidesDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := Source = lbSlides;
end;
procedure TfrmMain.lbSlidesDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
const
aColors: array[0..1] of TColor = (clWhite, $f0f0f0);
var
rectText: TRect;
rectPicto: TRect;
slide: TSlide;
strText: string;
begin
rectText := Rect;
rectText.Left := rectText.Left + 32 + 6;
strText := lbSlides.Items[Index];
if odFocused in State then begin
lbSlides.Canvas.Font.Color := clWhite;
lbSlides.Canvas.Brush.Color := clBlue;
end;
lbSlides.Canvas.FillRect(Rect);
slide := TSlide(lbSlides.Items.Objects[Index]);
if Assigned(slide) then begin
if slide.IsSubOverview then
lbSlides.Canvas.Font.Style := lbSlides.Canvas.Font.Style + [fsItalic];
lbSlides.Canvas.TextRect(rectText, strText, [tfSingleLine, tfVerticalCenter]);
if FPictos[slide.PictoName.FileName] = nil then begin
FPictos[slide.PictoName.FileName] := TPictoObject.Create(slide.PictoName.FileName);
end;
rectPicto := Rect;
rectPicto.Right := rectPicto.Left + 32;
lbSlides.Canvas.Draw(rectPicto.Left+1, rectPicto.Top+1, TPictoObject(FPictos[slide.PictoName.FileName]).Picto);
end;
if odFocused in State then
begin
lbSlides.Canvas.Brush.Color := aColors[Index mod 2] xor $132828;
lbSlides.Canvas.DrawFocusRect(Rect);
end;
end;
procedure TfrmMain.lbSlidesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FStartingPoint.X := X;
FStartingPoint.Y := Y;
end;
procedure TfrmMain.mniEditRedoClick(Sender: TObject);
begin
DoRedo;
end;
procedure TfrmMain.mniEditUndoClick(Sender: TObject);
begin
DoUndo;
end;
procedure TfrmMain.mniFileBuildPPTClick(Sender: TObject);
begin
DoBuild;
end;
procedure TfrmMain.mniFileClick(Sender: TObject);
var
i: integer;
mniRecentFile: TMenuItem;
mrus: TMRUList;
begin
mniFileRecentlyUsed.Clear;
while mniFileRecentlyUsed.Count > 0 do
mniFileRecentlyUsed.Delete(0);
mrus := GetMRUList;
for i := 0 to mrus.Count -1 do begin
mniRecentFile := TMenuItem.Create(mniFileRecentlyUsed);
mniRecentFile.Caption := mrus[i];
mniRecentFile.OnClick := mniRecentFileClick;
mniFileRecentlyUsed.Add(mniRecentFile);
end;
end;
procedure TfrmMain.mniFileNewClick(Sender: TObject);
begin
FFileName := DoProjectCreate( (Sender as TMenuItem).Caption );
end;
procedure TfrmMain.mniFileOpenClick(Sender: TObject);
begin
FFileName := DoOpen(FFileName);
end;
procedure TfrmMain.mniFileSaveAsClick(Sender: TObject);
begin
FFileName := DoSave('');
end;
procedure TfrmMain.mniFileSaveClick(Sender: TObject);
begin
FFileName := DoSave(FFileName);
end;
procedure TfrmMain.mniRecentFileClick(Sender: TObject);
begin
FFileName := PerformOpen( (Sender as TMenuItem).Caption );
end;
procedure TfrmMain.mniSettingsClick(Sender: TObject);
begin
ShowSettings;
end;
procedure TfrmMain.mniSlidesCopyClick(Sender: TObject);
begin
DoSlideCopy;
end;
procedure TfrmMain.mniSlidesDeleteClick(Sender: TObject);
begin
DoSlideDelete;
end;
function TfrmMain.PerformOpen(strFileName: string): string;
var
project: TProject;
begin
project := TProject.Create;
project.AsJSon := LoadUnicodeFromFile(strFileName);
if Assigned(project) then begin
try
GetMRUList.AddMRU(strFileName);
ProjectToForm(project);
FSavedProjectHash := project.CreateHash;
FLastProjectHash := FSavedProjectHash;
StartSnapshot;
Result := strFileName;
finally
project.Free;
end;
end;
end;
procedure TfrmMain.ppmSlidesPopup(Sender: TObject);
begin
// enabled state
mniSlidesDelete.Enabled := lbSlides.ItemIndex <> -1;
end;
procedure TfrmMain.ProjectFromForm(var project: TProject);
begin
if not Assigned(project) then begin
project := TProject.Create;
end;
project.Properties['speaker'] := FrameProjectProperties1.Speaker;
project.Properties['collecte1'] := FrameProjectProperties1.Collecte1;
project.Properties['collecte2'] := FrameProjectProperties1.Collecte2;
project.Slides.Text := SlidesToString;
end;
procedure TfrmMain.ProjectToForm(project: TProject);
begin
FrameProjectProperties1.Speaker := project.Properties['speaker'];
FrameProjectProperties1.Collecte1 := project.Properties['collecte1'];
FrameProjectProperties1.Collecte2 := project.Properties['collecte2'];
SlidesFromString(project.Slides.Text);
end;
procedure TfrmMain.SetHasChanged(const Value: boolean);
var
strCaption: string;
begin
if FHasChanged <> Value then begin
FHasChanged := Value;
strCaption := _('Powerpoint Builder');
if FHasChanged then
strCaption := strCaption + ' ' + _('(changed)');
Caption := strCaption;
end;
end;
procedure TfrmMain.DoShowQuickStart;
var
strLiturgy: string;
begin
case ShowQuickStart(strLiturgy) of
qsCancel: Exit;
qsOpen: FFileName := DoOpen(FFileName);
qsOpenFile: FFileName := PerformOpen(strLiturgy);
qsNew: FFileName := DoProjectCreate( strLiturgy );
end;
end;
procedure TfrmMain.ShowSettings;
var
frmSettings: TfrmSettings;
begin
frmSettings := TfrmSettings.Create(Application.MainForm);
try
frmSettings.ShowModal;
finally
frmSettings.Free;
end;
end;
procedure TfrmMain.SlidesFromString(strText: string);
var
slSlides: TStringList;
strSlide: string;
slide: TSlide;
i: integer;
begin
ClearSlides;
slSlides := TStringList.Create;
try
slSlides.Text := strText;
for i := 0 to slSlides.Count-1 do begin
strSlide := slSlides[i];
if strSlide <> '' then begin
slide := TSlide.Create(strSlide);
lbSlides.Items.AddObject(slide.SlideName, slide);
end;
end;
finally
slSlides.Free;
end;
end;
function TfrmMain.SlidesToString: string;
var
slSlides: TStringList;
slide: TSlide;
i: integer;
begin
Result := '';
slSlides := TStringList.Create;
try
for i := 0 to lbSlides.Items.Count-1 do begin
slide := lbSlides.Items.Objects[i] as TSlide;
slSlides.Add(slide.AsJSon);
Result := slSlides.Text;
end;
finally
slSlides.Free;
end;
end;
procedure TfrmMain.StartSnapshot;
begin
FSnapshotList.Clear;
FSnapshotList.Active := True;
AddSnapshot;
end;
{ TPictoObject }
constructor TPictoObject.Create(strPictoFileName: string);
var
bmp32, bmp32Dest: TBitmap32;
bAlphaChannelUsed: boolean;
begin
inherited Create;
FPicto := TBitmap.Create;
bmp32 := TBitmap32.Create;
bmp32Dest := TBitmap32.Create;
try
bmp32Dest.SetSize(32, 32);
if strPictoFileName = '' then
bmp32Dest.Clear(clWhite32)
else
bmp32Dest.Clear(clBlack32);
if FileExists(strPictoFileName) then begin
LoadPNGintoBitmap32(bmp32, strPictoFileName, bAlphaChannelUsed);
bmp32.DrawTo(bmp32Dest, bmp32Dest.BoundsRect);
end;
FPicto.Assign(bmp32Dest);
finally
bmp32Dest.Free;
bmp32.Free;
end;
end;
destructor TPictoObject.Destroy;
begin
FPicto.Free;
inherited;
end;
end.
|
unit Stream;
interface
type
HCkBinData = Pointer;
HCkByteData = Pointer;
HCkString = Pointer;
HCkStream = Pointer;
HCkTask = Pointer;
HCkStringBuilder = Pointer;
function CkStream_Create: HCkStream; stdcall;
procedure CkStream_Dispose(handle: HCkStream); stdcall;
function CkStream_getAbortCurrent(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_putAbortCurrent(objHandle: HCkStream; newPropVal: wordbool); stdcall;
function CkStream_getCanRead(objHandle: HCkStream): wordbool; stdcall;
function CkStream_getCanWrite(objHandle: HCkStream): wordbool; stdcall;
function CkStream_getDataAvailable(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_getDebugLogFilePath(objHandle: HCkStream; outPropVal: HCkString); stdcall;
procedure CkStream_putDebugLogFilePath(objHandle: HCkStream; newPropVal: PWideChar); stdcall;
function CkStream__debugLogFilePath(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_getDefaultChunkSize(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putDefaultChunkSize(objHandle: HCkStream; newPropVal: Integer); stdcall;
function CkStream_getEndOfStream(objHandle: HCkStream): wordbool; stdcall;
function CkStream_getIsWriteClosed(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_getLastErrorHtml(objHandle: HCkStream; outPropVal: HCkString); stdcall;
function CkStream__lastErrorHtml(objHandle: HCkStream): PWideChar; stdcall;
procedure CkStream_getLastErrorText(objHandle: HCkStream; outPropVal: HCkString); stdcall;
function CkStream__lastErrorText(objHandle: HCkStream): PWideChar; stdcall;
procedure CkStream_getLastErrorXml(objHandle: HCkStream; outPropVal: HCkString); stdcall;
function CkStream__lastErrorXml(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_getLastMethodSuccess(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_putLastMethodSuccess(objHandle: HCkStream; newPropVal: wordbool); stdcall;
function CkStream_getLength(objHandle: HCkStream): Int64; stdcall;
procedure CkStream_putLength(objHandle: HCkStream; newPropVal: Int64); stdcall;
function CkStream_getLength32(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putLength32(objHandle: HCkStream; newPropVal: Integer); stdcall;
function CkStream_getNumReceived(objHandle: HCkStream): Int64; stdcall;
function CkStream_getNumSent(objHandle: HCkStream): Int64; stdcall;
function CkStream_getReadFailReason(objHandle: HCkStream): Integer; stdcall;
function CkStream_getReadTimeoutMs(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putReadTimeoutMs(objHandle: HCkStream; newPropVal: Integer); stdcall;
procedure CkStream_getSinkFile(objHandle: HCkStream; outPropVal: HCkString); stdcall;
procedure CkStream_putSinkFile(objHandle: HCkStream; newPropVal: PWideChar); stdcall;
function CkStream__sinkFile(objHandle: HCkStream): PWideChar; stdcall;
procedure CkStream_getSourceFile(objHandle: HCkStream; outPropVal: HCkString); stdcall;
procedure CkStream_putSourceFile(objHandle: HCkStream; newPropVal: PWideChar); stdcall;
function CkStream__sourceFile(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_getSourceFilePart(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putSourceFilePart(objHandle: HCkStream; newPropVal: Integer); stdcall;
function CkStream_getSourceFilePartSize(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putSourceFilePartSize(objHandle: HCkStream; newPropVal: Integer); stdcall;
function CkStream_getStringBom(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_putStringBom(objHandle: HCkStream; newPropVal: wordbool); stdcall;
procedure CkStream_getStringCharset(objHandle: HCkStream; outPropVal: HCkString); stdcall;
procedure CkStream_putStringCharset(objHandle: HCkStream; newPropVal: PWideChar); stdcall;
function CkStream__stringCharset(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_getVerboseLogging(objHandle: HCkStream): wordbool; stdcall;
procedure CkStream_putVerboseLogging(objHandle: HCkStream; newPropVal: wordbool); stdcall;
procedure CkStream_getVersion(objHandle: HCkStream; outPropVal: HCkString); stdcall;
function CkStream__version(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_getWriteFailReason(objHandle: HCkStream): Integer; stdcall;
function CkStream_getWriteTimeoutMs(objHandle: HCkStream): Integer; stdcall;
procedure CkStream_putWriteTimeoutMs(objHandle: HCkStream; newPropVal: Integer); stdcall;
function CkStream_ReadBd(objHandle: HCkStream; binData: HCkBinData): wordbool; stdcall;
function CkStream_ReadBdAsync(objHandle: HCkStream; binData: HCkBinData): HCkTask; stdcall;
function CkStream_ReadBytes(objHandle: HCkStream; outData: HCkByteData): wordbool; stdcall;
function CkStream_ReadBytesAsync(objHandle: HCkStream): HCkTask; stdcall;
function CkStream_ReadBytesENC(objHandle: HCkStream; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkStream__readBytesENC(objHandle: HCkStream; encoding: PWideChar): PWideChar; stdcall;
function CkStream_ReadBytesENCAsync(objHandle: HCkStream; encoding: PWideChar): HCkTask; stdcall;
function CkStream_ReadNBytes(objHandle: HCkStream; numBytes: Integer; outData: HCkByteData): wordbool; stdcall;
function CkStream_ReadNBytesAsync(objHandle: HCkStream; numBytes: Integer): HCkTask; stdcall;
function CkStream_ReadNBytesENC(objHandle: HCkStream; numBytes: Integer; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkStream__readNBytesENC(objHandle: HCkStream; numBytes: Integer; encoding: PWideChar): PWideChar; stdcall;
function CkStream_ReadNBytesENCAsync(objHandle: HCkStream; numBytes: Integer; encoding: PWideChar): HCkTask; stdcall;
function CkStream_ReadSb(objHandle: HCkStream; sb: HCkStringBuilder): wordbool; stdcall;
function CkStream_ReadSbAsync(objHandle: HCkStream; sb: HCkStringBuilder): HCkTask; stdcall;
function CkStream_ReadString(objHandle: HCkStream; outStr: HCkString): wordbool; stdcall;
function CkStream__readString(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_ReadStringAsync(objHandle: HCkStream): HCkTask; stdcall;
function CkStream_ReadToCRLF(objHandle: HCkStream; outStr: HCkString): wordbool; stdcall;
function CkStream__readToCRLF(objHandle: HCkStream): PWideChar; stdcall;
function CkStream_ReadToCRLFAsync(objHandle: HCkStream): HCkTask; stdcall;
function CkStream_ReadUntilMatch(objHandle: HCkStream; matchStr: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkStream__readUntilMatch(objHandle: HCkStream; matchStr: PWideChar): PWideChar; stdcall;
function CkStream_ReadUntilMatchAsync(objHandle: HCkStream; matchStr: PWideChar): HCkTask; stdcall;
procedure CkStream_Reset(objHandle: HCkStream); stdcall;
function CkStream_RunStream(objHandle: HCkStream): wordbool; stdcall;
function CkStream_RunStreamAsync(objHandle: HCkStream): HCkTask; stdcall;
function CkStream_SaveLastError(objHandle: HCkStream; path: PWideChar): wordbool; stdcall;
function CkStream_SetSinkStream(objHandle: HCkStream; strm: HCkStream): wordbool; stdcall;
function CkStream_SetSourceBytes(objHandle: HCkStream; sourceData: HCkByteData): wordbool; stdcall;
function CkStream_SetSourceStream(objHandle: HCkStream; strm: HCkStream): wordbool; stdcall;
function CkStream_SetSourceString(objHandle: HCkStream; srcStr: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkStream_WriteBd(objHandle: HCkStream; binData: HCkBinData): wordbool; stdcall;
function CkStream_WriteBdAsync(objHandle: HCkStream; binData: HCkBinData): HCkTask; stdcall;
function CkStream_WriteByte(objHandle: HCkStream; byteVal: Integer): wordbool; stdcall;
function CkStream_WriteByteAsync(objHandle: HCkStream; byteVal: Integer): HCkTask; stdcall;
function CkStream_WriteBytes(objHandle: HCkStream; byteData: HCkByteData): wordbool; stdcall;
function CkStream_WriteBytesAsync(objHandle: HCkStream; byteData: HCkByteData): HCkTask; stdcall;
function CkStream_WriteBytesENC(objHandle: HCkStream; byteData: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkStream_WriteBytesENCAsync(objHandle: HCkStream; byteData: PWideChar; encoding: PWideChar): HCkTask; stdcall;
function CkStream_WriteClose(objHandle: HCkStream): wordbool; stdcall;
function CkStream_WriteSb(objHandle: HCkStream; sb: HCkStringBuilder): wordbool; stdcall;
function CkStream_WriteSbAsync(objHandle: HCkStream; sb: HCkStringBuilder): HCkTask; stdcall;
function CkStream_WriteString(objHandle: HCkStream; str: PWideChar): wordbool; stdcall;
function CkStream_WriteStringAsync(objHandle: HCkStream; str: PWideChar): HCkTask; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkStream_Create; external DLLName;
procedure CkStream_Dispose; external DLLName;
function CkStream_getAbortCurrent; external DLLName;
procedure CkStream_putAbortCurrent; external DLLName;
function CkStream_getCanRead; external DLLName;
function CkStream_getCanWrite; external DLLName;
function CkStream_getDataAvailable; external DLLName;
procedure CkStream_getDebugLogFilePath; external DLLName;
procedure CkStream_putDebugLogFilePath; external DLLName;
function CkStream__debugLogFilePath; external DLLName;
function CkStream_getDefaultChunkSize; external DLLName;
procedure CkStream_putDefaultChunkSize; external DLLName;
function CkStream_getEndOfStream; external DLLName;
function CkStream_getIsWriteClosed; external DLLName;
procedure CkStream_getLastErrorHtml; external DLLName;
function CkStream__lastErrorHtml; external DLLName;
procedure CkStream_getLastErrorText; external DLLName;
function CkStream__lastErrorText; external DLLName;
procedure CkStream_getLastErrorXml; external DLLName;
function CkStream__lastErrorXml; external DLLName;
function CkStream_getLastMethodSuccess; external DLLName;
procedure CkStream_putLastMethodSuccess; external DLLName;
function CkStream_getLength; external DLLName;
procedure CkStream_putLength; external DLLName;
function CkStream_getLength32; external DLLName;
procedure CkStream_putLength32; external DLLName;
function CkStream_getNumReceived; external DLLName;
function CkStream_getNumSent; external DLLName;
function CkStream_getReadFailReason; external DLLName;
function CkStream_getReadTimeoutMs; external DLLName;
procedure CkStream_putReadTimeoutMs; external DLLName;
procedure CkStream_getSinkFile; external DLLName;
procedure CkStream_putSinkFile; external DLLName;
function CkStream__sinkFile; external DLLName;
procedure CkStream_getSourceFile; external DLLName;
procedure CkStream_putSourceFile; external DLLName;
function CkStream__sourceFile; external DLLName;
function CkStream_getSourceFilePart; external DLLName;
procedure CkStream_putSourceFilePart; external DLLName;
function CkStream_getSourceFilePartSize; external DLLName;
procedure CkStream_putSourceFilePartSize; external DLLName;
function CkStream_getStringBom; external DLLName;
procedure CkStream_putStringBom; external DLLName;
procedure CkStream_getStringCharset; external DLLName;
procedure CkStream_putStringCharset; external DLLName;
function CkStream__stringCharset; external DLLName;
function CkStream_getVerboseLogging; external DLLName;
procedure CkStream_putVerboseLogging; external DLLName;
procedure CkStream_getVersion; external DLLName;
function CkStream__version; external DLLName;
function CkStream_getWriteFailReason; external DLLName;
function CkStream_getWriteTimeoutMs; external DLLName;
procedure CkStream_putWriteTimeoutMs; external DLLName;
function CkStream_ReadBd; external DLLName;
function CkStream_ReadBdAsync; external DLLName;
function CkStream_ReadBytes; external DLLName;
function CkStream_ReadBytesAsync; external DLLName;
function CkStream_ReadBytesENC; external DLLName;
function CkStream__readBytesENC; external DLLName;
function CkStream_ReadBytesENCAsync; external DLLName;
function CkStream_ReadNBytes; external DLLName;
function CkStream_ReadNBytesAsync; external DLLName;
function CkStream_ReadNBytesENC; external DLLName;
function CkStream__readNBytesENC; external DLLName;
function CkStream_ReadNBytesENCAsync; external DLLName;
function CkStream_ReadSb; external DLLName;
function CkStream_ReadSbAsync; external DLLName;
function CkStream_ReadString; external DLLName;
function CkStream__readString; external DLLName;
function CkStream_ReadStringAsync; external DLLName;
function CkStream_ReadToCRLF; external DLLName;
function CkStream__readToCRLF; external DLLName;
function CkStream_ReadToCRLFAsync; external DLLName;
function CkStream_ReadUntilMatch; external DLLName;
function CkStream__readUntilMatch; external DLLName;
function CkStream_ReadUntilMatchAsync; external DLLName;
procedure CkStream_Reset; external DLLName;
function CkStream_RunStream; external DLLName;
function CkStream_RunStreamAsync; external DLLName;
function CkStream_SaveLastError; external DLLName;
function CkStream_SetSinkStream; external DLLName;
function CkStream_SetSourceBytes; external DLLName;
function CkStream_SetSourceStream; external DLLName;
function CkStream_SetSourceString; external DLLName;
function CkStream_WriteBd; external DLLName;
function CkStream_WriteBdAsync; external DLLName;
function CkStream_WriteByte; external DLLName;
function CkStream_WriteByteAsync; external DLLName;
function CkStream_WriteBytes; external DLLName;
function CkStream_WriteBytesAsync; external DLLName;
function CkStream_WriteBytesENC; external DLLName;
function CkStream_WriteBytesENCAsync; external DLLName;
function CkStream_WriteClose; external DLLName;
function CkStream_WriteSb; external DLLName;
function CkStream_WriteSbAsync; external DLLName;
function CkStream_WriteString; external DLLName;
function CkStream_WriteStringAsync; external DLLName;
end.
|
unit uSquare;
interface
type
TRectangle = class
private
FWidth: integer;
FHeight: integer;
function GetArea: integer;
protected
procedure SetHeight(const Value: integer); virtual;
procedure SetWidth(const Value: integer); virtual;
public
property Height: integer read FHeight write SetHeight;
property Width: integer read FWidth write SetWidth;
property Area: integer read GetArea;
end;
TSquare = class(TRectangle)
private
procedure SetHeight(const Value: integer); override;
procedure SetWidth(const Value: integer); override;
end;
procedure DoRectangleStuff;
implementation
uses
Spring.Collections
;
procedure DoRectangleStuff;
var
LRectangle: TRectangle;
Rectangles: IList<TRectangle>;
begin
Rectangles := TCollections.CreateList<TRectangle>;
LRectangle := TRectangle.Create;
LRectangle.Height := 7;
LRectangle.Width := 3;
Rectangles.Add(LRectangle);
LRectangle := TSquare.Create;
LRectangle.Height := 7;
LRectangle.Width := 3;
Rectangles.Add(LRectangle);
for LRectangle in Rectangles do
begin
WriteLn(LRectangle.GetArea);
end;
end;
{ TRectangle }
function TRectangle.GetArea: integer;
begin
Result := Height * Width;
end;
procedure TRectangle.SetHeight(const Value: integer);
begin
FHeight := Value;
end;
procedure TRectangle.SetWidth(const Value: integer);
begin
FWidth := Value;
end;
{ TSquare }
procedure TSquare.SetHeight(const Value: integer);
begin
FHeight := Value;
FWidth := Value;
end;
procedure TSquare.SetWidth(const Value: integer);
begin
FHeight := Value;
FWidth := Value;
end;
end.
|
unit unSobre;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, jpeg, uniGUIBaseClasses, uniGUIClasses, uniButton,
uniLabel, UniGuiForm, uniMemo;
type
TfrmSobre = class(TUniForm)
btnOK: TUniButton;
lblVersao: TUniLabel;
lblEmpresa: TUniLabel;
lblCNPJ: TUniLabel;
mmoOS: TUniMemo;
procedure btnOKClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
procedure Carrega;
public
constructor Create(Aowner: TComponent); override;
end;
var
frmSobre: TfrmSobre;
implementation
uses Funcoes, VarGlobal;
{$R *.dfm}
procedure TfrmSobre.btnOKClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSobre.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
constructor TfrmSobre.Create(Aowner: TComponent);
begin
inherited;
BorderStyle := bsSingle;
SetDialogForm(Self);
end;
procedure TfrmSobre.FormShow(Sender: TObject);
begin
Caption := 'Sobre o ' + Sistema.AppCaption;
lblVersao.Caption := 'Versão e Revisão: ' + Sistema.VersaoApp;
lblEmpresa.Caption := 'Empresa: ' + Empresa.Nome;
lblCNPJ.Caption := 'CNPJ: ' + empresa.Cnpj;
end;
procedure TfrmSobre.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmSobre.Carrega;
var
verInfo: TOsVersionInfo;
str: string;
I: Word;
begin
mmoOS.Lines.Clear;
verInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
if GetVersionEx(verInfo) then
begin
mmoOS.Lines.Add('Versão : ' + IntToStr(verInfo.dwMajorVersion) + '.' +
IntToStr(verInfo.dwMinorVersion));
mmoOS.Lines.Add('Compilação : ' + IntToStr(verInfo.dwBuildNumber));
case verInfo.dwPlatformId of
VER_PLATFORM_WIN32s: mmoOS.Lines.Add('Sistema Operacional : Windows 95');
VER_PLATFORM_WIN32_WINDOWS:
mmoOS.Lines.Add('Sistema Operacional : Windows 95 Osr2 / 98');
VER_PLATFORM_WIN32_NT:
mmoOS.Lines.Add('Sistema Operacional : Windows NT');
end;
str := '';
for I := 0 to 127 do
str := str + verInfo.szCSDVersion[I];
mmoOS.Lines.Add('Informações Adicionais : ' + str);
end;
end;
procedure TfrmSobre.FormCreate(Sender: TObject);
begin
Carrega;
end;
initialization
RegisterClass(TfrmSobre);
finalization
UnRegisterClass(TfrmSobre);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.