text stringlengths 14 6.51M |
|---|
unit uUserAction;
interface
uses
System.Classes, system.SysUtils, xDBActionBase, uUserInfo,
FireDAC.Stan.Param;
type
TUserAction = class(TDBActionBase)
public
/// <summary>
/// 读取用户列表
/// </summary>
procedure GetAllUsers( Users : TStringList );
/// <summary>
/// 读取用户权限列表
/// </summary>
procedure GetAllUserRights( UserRights : TStringList);
/// <summary>
/// 读取用户组列表
/// </summary>
procedure GetAllUserGroups( UserGroups : TStringList);
/// <summary>
/// 读取用户的权限
/// </summary>
/// <param name="nGroupID">用户组Id</param>
/// <param name="Rights">权限列表</param>
procedure GetUserRights( nGroupID : Integer; Rights : TStringList );
/// <summary>
/// 保存用户
/// </summary>
procedure SaveUser(AUser : TUser);
/// <summary>
/// 修改密码
/// </summary>
procedure UpUserPass(AUser: TUser);
/// <summary>
/// 获取用户MAX(ID)
/// </summary>
function GetMaxUserId : Integer;
/// <summary>
/// 删除用户
/// </summary>
procedure DelUser(nUname : string);
/// <summary>
/// 用户名是否存在
/// </summary>
function CheckUNameExists(sUname : string) : Boolean;
/// <summary>
/// 根据Name获取用户信息
/// </summary>
function GetUserInfo(sUname : string;AUser : TUser) : Boolean;
/// <summary>
/// 保存用户权限
/// </summary>
procedure SaveUserRight(AUserRight : TUserRight);
/// <summary>
/// 获取用户权限MAX(ID)
/// </summary>
function GetMaxUserRightId : Integer;
/// <summary>
/// 删除用户权限
/// </summary>
procedure DelUserRight(sUserRightName: string);
/// <summary>
/// 保存用户组(新增/编辑)
/// </summary>
procedure SaveUserGroup(AUserGroup : TUserGroup);
/// <summary>
/// 删除用户组
/// </summary>
procedure DelUserGroup(sUserGroupName : string);
/// <summary>
/// 获取用户组最大ID
/// </summary>
function GetMaxUserGroupId : Integer;
/// <summary>
/// 检查组是否存在
/// </summary>
function CheckUGNameExists(sUGname: string): Boolean;
end;
implementation
uses
xFunction;
{ TUserAction }
function TUserAction.CheckUGNameExists(sUGname: string): Boolean;
const
C_SQLSEL = 'select count(*) from UA_GROUP where G_Name = ''%s''';
begin
Result := False;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(Format(C_SQLSEL, [sUGname]));
Result := Fields[0].AsInteger > 0;
Close;
end;
end;
end;
function TUserAction.CheckUNameExists(sUname: string) : Boolean;
const
C_SQLSEL = 'select count(*) from UA_USER where U_NAME = ''%s''';
begin
Result := False;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(Format(C_SQLSEL, [sUname]));
Result := Fields[0].AsInteger > 0;
Close;
end;
end;
end;
procedure TUserAction.DelUser(nUname: string);
const
C_SQL_USER = 'delete from UA_USER where U_NAME= ''%s''';
begin
if Assigned(FQuery) then
begin
with FQuery do
begin
ExecSQL(Format(C_SQL_USER, [nUname]));
end;
end;
end;
procedure TUserAction.DelUserGroup(sUserGroupName: string);
const
C_SQL_RIGHTS = 'delete from UA_GROUP_RIGHT where G_ID in' +
'(select G_ID from UA_GROUP where G_NAME = ''%s'')';
C_SQL_GROUP = 'delete from UA_GROUP where G_NAME=''%s''';
begin
if Assigned(FQuery) then
begin
with FQuery do
begin
ExecSQL(Format(C_SQL_RIGHTS, [sUserGroupName]));
ExecSQL(Format(C_SQL_GROUP, [sUserGroupName]));
end;
end;
end;
procedure TUserAction.DelUserRight(sUserRightName: string);
const
C_SQL_USER = 'delete from UA_RIGHT where R_NAME = ''%s''';
begin
if Assigned(FQuery) then
begin
with FQuery do
begin
ExecSQL(Format(C_SQL_USER, [sUserRightName]));
end;
end;
end;
procedure TUserAction.GetAllUserGroups(UserGroups: TStringList);
const
C_SEL_USR = 'select * from UA_GROUP order by G_ID';
var
AUserGroup : TUserGroup;
i : Integer;
begin
if Assigned(FQuery) then
begin
if Assigned(UserGroups) then
begin
ClearStringList(UserGroups);
with FQuery do
begin
Open(C_SEL_USR);
First;
while not Eof do
begin
AUserGroup := TUserGroup.Create;
with AUserGroup do
begin
Id := FieldByName( 'G_ID' ).AsInteger;
GroupName := FieldByName( 'G_NAME' ).AsString;
Description := FieldByName( 'G_DESCRIPTION' ).AsString;
Embedded := FieldByName( 'G_EMBEDDED' ).AsBoolean;
end;
UserGroups.AddObject(AUserGroup.GroupName, AUserGroup);
Next;
end;
Close;
end;
for i := 0 to UserGroups.Count - 1 do
begin
AUserGroup := TUserGroup(UserGroups.Objects[i]);
GetUserRights(AUserGroup.ID, AUserGroup.Rights);
end;
end;
end;
end;
procedure TUserAction.GetAllUserRights(UserRights: TStringList);
const
C_SEL_USR = 'select * from UA_RIGHT order by R_ID';
var
AUserRight : TUserRight;
begin
if Assigned(FQuery) then
begin
if Assigned(UserRights) then
begin
ClearStringList(UserRights);
with FQuery do
begin
Open(C_SEL_USR);
First;
while not Eof do
begin
AUserRight := TUserRight.Create;
with AUserRight do
begin
Id := FieldByName( 'R_ID' ).AsInteger;
RightName := FieldByName( 'R_NAME' ).AsString;
Description := FieldByName( 'R_DESCRIPTION' ).AsString;
end;
UserRights.AddObject(AUserRight.RightName, AUserRight);
Next;
end;
Close;
end;
end;
end;
end;
procedure TUserAction.GetAllUsers(Users: TStringList);
const
C_SEL_USR = 'select * from UA_USER order by U_ID';
var
AUser : TUser;
begin
if Assigned(FQuery) then
begin
if Assigned(Users) then
begin
ClearStringList(Users);
with FQuery do
begin
Open(C_SEL_USR);
First;
while not Eof do
begin
AUser := TUser.Create;
with AUser do
begin
ID := FieldByName( 'U_ID' ).AsInteger;
GroupID := FieldByName( 'G_ID' ).AsInteger;
LoginName := FieldByName( 'U_NAME' ).AsString;
Password := FieldByName( 'U_PASSWORD' ).AsString;
FullName := FieldByName( 'U_FULL_NAME' ).AsString;
Description := FieldByName( 'U_DESCRIPTION' ).AsString;
ChangePwd := FieldByName( 'U_CHANGE_PWD' ).AsBoolean;
Disabled := FieldByName( 'U_DISABLEED' ).AsBoolean;
Embedded := FieldByName( 'U_EMBEDDED' ).AsBoolean;
end;
Users.AddObject(AUser.LoginName, AUser);
Next;
end;
Close;
end;
end;
end;
end;
function TUserAction.GetMaxUserGroupId: Integer;
const
C_SEL = 'select max(G_ID) + 1 from UA_GROUP';
C_SEL1='select count(*) from UA_GROUP';
begin
Result := -1;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(C_SEL1);
if Fields[0].AsInteger = 0 then
begin
Result := 1;
Close;
end
else
begin
Close;
Open(C_SEL);
Result := Fields[0].AsInteger;
Close;
end;
end;
end;
end;
function TUserAction.GetMaxUserId: Integer;
const
C_SEL_COU = 'select max(u_id) + 1 from UA_USER';
C_SEL_COU1='select count(*) from UA_USER';
begin
result := -1;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(C_SEL_COU1);
if Fields[0].AsInteger = 0 then
begin
Result := 1;
Close;
end
else
begin
if Active then
Close;
Open(C_SEL_COU);
Result := Fields[0].AsInteger;
Close;
end;
end;
end;
end;
function TUserAction.GetMaxUserRightId: Integer;
const
C_SEL_COU = 'select max(R_ID) + 1 from UA_RIGHT';
C_SEL_COU1='select count(*) from UA_RIGHT';
begin
result := -1;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(C_SEL_COU1);
if Fields[0].AsInteger = 0 then
begin
Close;
Result := 1;
end
else
begin
Close;
Open(C_SEL_COU);
Result := Fields[0].AsInteger;
Close;
end;
end;
end;
end;
function TUserAction.GetUserInfo(sUname: string; AUser: TUser) : Boolean;
const
C_SQLSEL = 'select * from UA_USER where U_NAME = ''%s''';
var
sSqlText : string;
begin
Result := False;
if Assigned(FQuery) then
begin
if Assigned(AUser) then
begin
sSqlText := Format(C_SQLSEL, [sUname]);
with FQuery do
begin
Open(sSqlText);
First;
if RecordCount > 0 then
begin
AUser.ID := FieldByName('U_ID').AsInteger;
AUser.GroupID := FieldByName('G_ID').AsInteger;
AUser.LoginName := FieldByName('U_NAME').AsString;
AUser.Password := FieldByName('U_PASSWORD').AsString;
AUser.FullName := FieldByName('U_FULL_NAME').AsString;
AUser.Description := FieldByName('U_DESCRIPTION').AsString;
AUser.ChangePwd := FieldByName('U_CHANGE_PWD').AsBoolean;
AUser.Disabled := FieldByName('U_DISABLEED').AsBoolean;
AUser.Embedded := FieldByName('U_EMBEDDED').AsBoolean;
Result := True;
end;
Close;
end;
end;
end;
end;
procedure TUserAction.GetUserRights(nGroupID: Integer; Rights: TStringList);
const
C_SEL_RIGHT = 'select * from ua_right where r_id in ' +
'( select r_id from ua_group_right where g_id = %d )';
var
ARight : TUserRight;
begin
if Assigned(FQuery) then
begin
if Assigned(Rights) then
begin
ClearStringList(Rights);
with FQuery do
begin
Open(Format(C_SEL_RIGHT, [nGroupID]));
First;
while not Eof do
begin
ARight := TUserRight.Create;
with ARight do
begin
ID := FieldByName('R_ID').AsInteger;
RightName := FieldByName('R_NAME').AsString;
Description := FieldByName('R_DESCRIPTION').AsString;
end;
Rights.AddObject(ARight.RightName, ARight);
Next;
end;
Close;
end;
end;
end;
end;
procedure TUserAction.SaveUser(AUser: TUser);
const
C_UPT_USR = 'update UA_USER set G_ID = %d, U_NAME = :U_NAME, ' +
'U_FULL_NAME = :U_FULL_NAME, U_DESCRIPTION = :U_DESCRIPTION, ' +
'U_PASSWORD = :U_PASSWORD, U_CHANGE_PWD = :U_CHANGE_PWD, ' +
'UPDATE_TIME = :UPDATE_TIME where U_ID = %d';
C_SAVE_USR = 'insert into UA_USER(U_ID, G_ID, U_NAME, U_FULL_NAME, U_DESCRIPTION, '
+ 'U_PASSWORD, U_CHANGE_PWD, UPDATE_TIME ) values( '
+ '%d, %d, :U_NAME, :U_FULL_NAME, :U_DESCRIPTION, :U_PASSWORD, '
+ ':U_CHANGE_PWD, :UPDATE_TIME) ';
var
sSQL : string;
begin
if Assigned(FQuery) then
begin
if Assigned(AUser) then
begin
if AUser.ID = -1 then
AUser.ID := GetMaxUserId;
with FQuery do
begin
sSQL := Format(C_UPT_USR, [ AUser.GroupID, AUser.ID]);
SQL.Text := sSQL;
ParamByName('U_NAME').Value := AUser.LoginName;
ParamByName('U_FULL_NAME').Value := AUser.FullName;
ParamByName('U_DESCRIPTION').Value := AUser.Description;
ParamByName('U_PASSWORD').Value := UpperCase(AUser.Password);
ParamByName('U_CHANGE_PWD').Value := AUser.ChangePwd;
ParamByName('UPDATE_TIME').Value := Now;
if ExecSQL(sSQL) = 0 then
begin
AUser.Password := UpperCase(GetMD5(AUser.Password));
SQL.Text := Format(C_SAVE_USR, [AUser.ID, AUser.GroupID]);
ParamByName('U_NAME').Value := AUser.LoginName;
ParamByName('U_FULL_NAME').Value := AUser.FullName;
ParamByName('U_DESCRIPTION').Value := AUser.Description;
ParamByName('U_PASSWORD').Value := AUser.Password;
ParamByName('U_CHANGE_PWD').Value := AUser.ChangePwd;
ParamByName('UPDATE_TIME').Value := Now;
ExecSQL;
end;
end;
end;
end;
end;
procedure TUserAction.SaveUserGroup(AUserGroup: TUserGroup);
const
C_UPTGRP = 'update UA_GROUP set G_NAME = :G_NAME, '
+ 'G_DESCRIPTION = :G_DESCRIPTION, UPDATE_TIME = :UPDATE_TIME where '
+ 'G_ID = %d';
C_INSGRP_RGT = 'insert into UA_GROUP_RIGHT ( G_ID, R_ID, UPDATE_TIME '
+ ') values ( %d, %d, :UPDATE_TIME )';
C_DEL_RIGHT = 'delete from UA_GROUP_RIGHT where G_ID = %d';
C_INSGRP = 'insert into UA_GROUP ( G_ID, G_NAME, G_DESCRIPTION, '
+ 'UPDATE_TIME ) values ( %d, :G_NAME, :G_DESCRIPTION, '
+ ':UPDATE_TIME )';
var
SqlTest : string;
i : Integer;
begin
if Assigned(FQuery) then
begin
if Assigned(AUserGroup) then
begin
if AUserGroup.ID = -1 then
AUserGroup.ID := GetMaxUserGroupId;
with FQuery do
begin
SqlTest := Format( C_UPTGRP, [ AUserGroup.ID ] );
SQL.Text := SqlTest;
ParamByName( 'G_NAME' ).Value := AUserGroup.GroupName ;
ParamByName( 'G_DESCRIPTION' ).Value := AUserGroup.Description;
ParamByName( 'UPDATE_TIME' ).Value := Now ;
if ExecSQL(SqlTest) = 0 then
begin
SQL.Text := Format( C_INSGRP, [ AUserGroup.ID ] );
ParamByName( 'G_NAME' ).Value := AUserGroup.GroupName ;
ParamByName( 'G_DESCRIPTION' ).Value := AUserGroup.Description;
ParamByName( 'UPDATE_TIME' ).Value := Now ;
ExecSQL;
end;
SQL.Text := Format( C_DEL_RIGHT, [ AUserGroup.ID ] );
ExecSQL;
for i := 0 to AUserGroup.Rights.Count - 1 do
begin
with TUserRight( AUserGroup.Rights.Objects[ i ] ) do
begin
SQL.Text := Format( C_INSGRP_RGT, [ AUserGroup.ID, ID ] );
ParamByName( 'UPDATE_TIME' ).Value := Now ;
ExecSQL;
end;
end;
end;
end;
end;
end;
procedure TUserAction.SaveUserRight(AUserRight: TUserRight);
const
C_EDIT = 'update UA_RIGHT set R_NAME = :R_NAME,'+
' R_DESCRIPTION = :R_DESCRIPTION, UPDATE_TIME = :UPDATE_TIME'+
' where R_ID = :R_ID';
C_INS = 'insert into UA_RIGHT(R_ID, R_NAME, R_DESCRIPTION, UPDATE_TIME)'+
' values(:R_ID, :R_NAME, :R_DESCRIPTION, :UPDATE_TIME)';
var
sSQL : string;
begin
if Assigned(FQuery) then
begin
if Assigned(AUserRight) then
begin
if AUserRight.ID = -1 then
AUserRight.ID := GetMaxUserRightId;
with FQuery do
begin
sSQL := C_EDIT;
SQL.Text := sSQL;
ParamByName('R_ID').Value := AUserRight.ID;
ParamByName('R_NAME').Value := AUserRight.RightName;
ParamByName('R_DESCRIPTION').Value := AUserRight.Description;
ParamByName('UPDATE_TIME').Value := Now;
if ExecSQL(sSQL) = 0 then
begin
SQL.Text := C_INS;
ParamByName('R_ID').Value := AUserRight.ID;
ParamByName('R_NAME').Value := AUserRight.RightName;
ParamByName('R_DESCRIPTION').Value := AUserRight.Description;
ParamByName('UPDATE_TIME').Value := Now;
ExecSQL;
end;
end;
end;
end;
end;
procedure TUserAction.UpUserPass(AUser: TUser);
const
C_UPT_USR = 'update UA_USER set U_PASSWORD = ''%s'' where U_ID = %d';
begin
if Assigned(AUser) then
begin
if Assigned(FQuery) then
begin
with FQuery do
begin
ExecSQL(Format(C_UPT_USR, [AUser.Password, AUser.ID]));
end;
end;
end;
end;
end.
|
unit UnitSineGenerator;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AudioIO, StdCtrls, ComCtrls, Buttons;
type
TFormSineGenerator = class(TForm)
TbFreq: TTrackBar;
BtSound: TButton;
TbVol: TTrackBar;
procedure BtSoundClick(Sender: TObject);
function AudioOut1FillBuffer(Buffer: PAnsiChar;
var Size: Integer): Boolean;
procedure TbFreqChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormSineGenerator: TFormSineGenerator;
TotalBuffers : Integer;
Freq : Integer;
implementation
uses UnitMainForm;
{$R *.dfm}
procedure TFormSineGenerator.BtSoundClick(Sender: TObject);
begin
if BtSound.Caption = 'Start' then
begin
AudioOut.Start(AudioOut);
BtSound.Caption := 'Stop';
end else
begin
AudioOut.StopGraceFully;
BtSound.Caption := 'Start';
end;
end;
function TFormSineGenerator.AudioOut1FillBuffer(Buffer: PAnsiChar;
var Size: Integer): Boolean;
{
Whenever the component needs another buffer, this routine is called,
N is the number of BYTES required, B the the address of the buffer.
}
Var
NW, i, ts : Integer;
P : ^SmallInt;
begin
{ See if we want to quit. Process TotalBuffers except if TotalBuffer
is <= 0, then process forever. }
If (AudioOut.QueuedBuffers >= TotalBuffers) and (TotalBuffers > 0) Then
Begin
{ Stop processing by just returning FALSE }
Result := FALSE;
Exit;
End;;
{ First step, cast the buffer as the proper data size, if this output
was 8 bits, then the cast would be to ^Byte. N now represents the
total number of 16 bit words to process. }
P := Pointer(Buffer);
NW := Size div 2;
{ Now create a sine wave, because the buffer may not align with the end
of a full sine cycle, we must compute it using the total number of
points processed. FilledBuffers give the total number of buffer WE
have filled, so we know the number of point WE processed }
ts := NW*AudioOut.FilledBuffers;
{ Note: Freq is set from the TrackBar }
For i := 0 to NW-1 Do
Begin
P^ := Round((FormSineGenerator.TbVol.Position/100)*(8192*Sin((ts+i)/AudioOut.FrameRate*
3.14159*2*Freq)));
Inc(P);
End;
{ True will continue Processing }
Result := True;
end;
procedure TFormSineGenerator.TbFreqChange(Sender: TObject);
var cp: String;
begin
cp := 'Generator tonów, f = ';
Freq := 20 + (TbFreq.Position * TbFreq.Position);
if Freq < 1000 then Self.Caption := cp + IntToStr(Freq) + ' Hz';
if Freq > 1000 then Self.Caption := cp + CurrToStr(Freq/1000) + ' kHz';
end;
procedure TFormSineGenerator.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
AudioOut.StopGraceFully;
BtSound.Caption := 'Start';
end;
procedure TFormSineGenerator.FormCreate(Sender: TObject);
begin
TbFreqChange(Sender);
Self.ClientHeight := 80;
Application.ProcessMessages;
Self.Constraints.MaxHeight := Self.Height;
Self.Constraints.MinHeight := Self.Height;
Self.Constraints.MinWidth := 320;
end;
procedure TFormSineGenerator.FormResize(Sender: TObject);
begin
TbFreq.Width := Self.ClientWidth - TbFreq.Left - 8;
TbVol.Width := Self.ClientWidth - TbVol.Left - 8;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.DSProd;
interface
uses System.Classes, Web.HTTPApp, Web.HTTPProd, Data.DB, System.SysUtils;
type
TCustomDataSetPageProducer = class(TCustomPageProducer)
private
FDataSet: TDataSet;
protected
function GetDataSet: TDataSet; virtual;
procedure SetDataSet(ADataSet: TDataSet); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings;
var ReplaceText: string); override;
public
function Content: string; override;
property DataSet: TDataSet read GetDataSet write SetDataSet;
end;
TDataSetPageProducer = class(TCustomDataSetPageProducer)
published
property HTMLDoc;
property HTMLFile;
property DataSet;
property OnHTMLTag;
property ScriptEngine;
end;
implementation
function TCustomDataSetPageProducer.GetDataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TCustomDataSetPageProducer.SetDataSet(ADataSet: TDataSet);
begin
if FDataSet <> ADataSet then
begin
if ADataSet <> nil then ADataSet.FreeNotification(Self);
FDataSet := ADataSet;
end;
end;
procedure TCustomDataSetPageProducer.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FDataSet) then
FDataSet := nil;
end;
procedure TCustomDataSetPageProducer.DoTagEvent(Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string);
var
Field: TField;
begin
if (TagParams.Count = 0) and Assigned(FDataSet) then
begin
Field := FDataSet.FindField(TagString);
if Assigned(Field) then
ReplaceText := Field.DisplayText;
end;
inherited DoTagEvent(Tag, TagString, TagParams, ReplaceText);
end;
function TCustomDataSetPageProducer.Content: string;
begin
if (FDataSet <> nil) and not FDataSet.Active then
FDataSet.Open;
Result := inherited Content;
end;
end.
|
unit ops;
interface
{$mode objfpc}
{$modeswitch advancedrecords}
uses
sysutils, base, math, matrix;
type
Decompose = record
type
QR = record
class procedure GramSchmidt(const AMatrix: TMatrix; out AQ, AR: TMatrix); static;
class procedure Householder(const AMatrix: TMatrix; out AQ, AR: TMatrix); static;
end;
class procedure LU(const AMatrix: TMatrix; out AL, AU: TMatrix); static;
class function Cholesky(const AMatrix: TMatrix): TMatrix; static;
end;
Solve = record
class function LU(const AL, AU, AB: TMatrix): TMatrix; static;
end;
Invert = record
class function GaussJordan(const AMatrix: TMatrix): TMatrix; static;
class function LU(const AL, AU: TMatrix): TMatrix; static;
end;
Determinant = record
class function Gen(const AMatrix: TMatrix): double; static;
class function Tridiagonal(const AMatrix: TMatrix): double; static;
class function Triangular(const AMatrix: TMatrix): double; static;
class function Unitary(const AMatrix: TMatrix): double; static;
end;
Helpers = record helper for TMatrix
strict private
function GetDeterminant: double;
function GetInverse: TMatrix;
public
property Inverse: TMatrix read GetInverse;
property Determinant: double read GetDeterminant;
end;
operator +(const a,b: TVector): TVector;
operator -(const a,b: TVector): TVector;
operator *(const a,b: TVector): TVector;
operator /(const a,b: TVector): TVector;
operator +(const a: TVector; const b: double): TVector;
operator +(const a: double; const b: TVector): TVector;
operator -(const a: TVector; const b: double): TVector;
operator -(const a: double; const b: TVector): TVector;
operator *(const a: TVector; const b: double): TVector;
operator *(const a: double; const b: TVector): TVector;
operator /(const a: TVector; const b: double): TVector;
operator /(const a: double; const b: TVector): TVector;
operator **(const a, b: double): double;
operator **(const a: TVector; const b: double): TVector;
operator :=(const a: TVector): ansistring;
implementation
operator +(const a,b: TVector): TVector;
var i: longint;
begin
assert(length(a)=length(b));
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]+b[i];
end;
operator -(const a,b: TVector): TVector;
var i: longint;
begin
assert(length(a)=length(b));
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]-b[i];
end;
operator *(const a,b: TVector): TVector;
var i: longint;
begin
assert(length(a)=length(b));
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]*b[i];
end;
operator /(const a,b: TVector): TVector;
var i: longint;
begin
assert(length(a)=length(b));
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]/b[i];
end;
operator +(const a: TVector; const b: double): TVector;
var i: longint;
begin
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]+b;
end;
operator +(const a: double; const b: TVector): TVector;
var i: longint;
begin
setlength(result, length(b));
for i := 0 to high(b) do
result[i] := a+b[i];
end;
operator -(const a: TVector; const b: double): TVector;
var i: longint;
begin
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]-b;
end;
operator -(const a: double; const b: TVector): TVector;
var i: longint;
begin
setlength(result, length(b));
for i := 0 to high(b) do
result[i] := a-b[i];
end;
operator *(const a: TVector; const b: double): TVector;
var i: longint;
begin
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]*b;
end;
operator *(const a: double; const b: TVector): TVector;
var i: longint;
begin
setlength(result, length(b));
for i := 0 to high(b) do
result[i] := a*b[i];
end;
operator /(const a: TVector; const b: double): TVector;
var i: longint;
begin
assert(b<>0, 'Cannot divide by zero');
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := a[i]/b;
end;
operator /(const a: double; const b: TVector): TVector;
var i: longint;
begin
setlength(result, length(b));
for i := 0 to high(b) do
begin
if b[i] = 0 then
result[i] := 0
else
result[i] := a/b[i];
end;
end;
operator **(const a, b: double): double;
begin
result := power(a,b);
end;
operator **(const a: TVector; const b: double): TVector;
var i: longint;
begin
setlength(result, length(a));
for i := 0 to high(a) do
result[i] := power(a[i],b);
end;
operator :=(const a: TVector): ansistring;
var i: longint;
begin
result := '[';
for i := 0 to high(a) do
begin
if i > 0 then
result := result + format(', %3.4F',[a[i]])
else
result := result + format('%3.4F',[a[i]]);
end;
result := result + ']';
end;
function Helpers.GetDeterminant: double;
begin
result:=Ops.Determinant.Gen(self);
end;
function Helpers.GetInverse: TMatrix;
begin
result:=Invert.GaussJordan(self);
end;
class function Determinant.Gen(const AMatrix: TMatrix): double;
begin
result:=Matrix.Determinant(AMatrix);
end;
class function Determinant.Tridiagonal(const AMatrix: TMatrix): double;
begin
result:=DeterminantTriangular(AMatrix);
end;
class function Determinant.Triangular(const AMatrix: TMatrix): double;
begin
result:=DeterminantTriangular(AMatrix);
end;
class function Determinant.Unitary(const AMatrix: TMatrix): double;
begin
result:=DeterminantUnitary(AMatrix);
end;
class procedure Decompose.QR.GramSchmidt(const AMatrix: TMatrix; out AQ, AR: TMatrix);
begin
QRDecomposeGS(AMatrix, AQ,AR);
end;
class procedure Decompose.QR.Householder(const AMatrix: TMatrix; out AQ, AR: TMatrix);
begin
QRDecomposeHR(AMatrix, AQ,AR);
end;
class procedure Decompose.LU(const AMatrix: TMatrix; out AL, AU: TMatrix);
begin
LUDecompose(AMatrix, al, au);
end;
class function Decompose.Cholesky(const AMatrix: TMatrix): TMatrix;
begin
result:=CholeskyDecompose(AMatrix);
end;
class function Invert.GaussJordan(const AMatrix: TMatrix): TMatrix;
begin
result:=InvertGJ(AMatrix);
end;
class function Invert.LU(const AL, AU: TMatrix): TMatrix;
begin
result:=InvertLU(AL, AU);
end;
class function Solve.LU(const AL, AU, AB: TMatrix): TMatrix;
begin
result:=SolveLU(al,au,ab);
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIURLLabel.pas
// Creator : Shen Min
// Date : 2002-07-22
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIURLLabel;
interface
{$I SUIPack.inc}
uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, Graphics,
ShellAPI;
type
TsuiURLLabel = class(TCustomLabel)
private
m_Cursor : TCursor;
m_URL : TCaption;
m_HoverColor : TColor;
m_LinkColor : TColor;
procedure OnMouseLeave(var Msg : TMessage); message CM_MOUSELEAVE;
procedure OnMouseEnter(var Msg : TMessage); message CM_MOUSEENTER;
procedure SetLinkColor(const Value: TColor);
procedure SetURL(value : TCaption);
protected
procedure Click(); override;
public
constructor Create(AOwner: TComponent); override;
published
property Anchors;
property BiDiMode;
property Caption;
property AutoSize;
property Color;
property Enabled;
property ShowHint;
property Transparent;
property Visible;
property WordWrap;
property PopupMenu;
property Cursor read m_Cursor;
property URL : TCaption read m_URL write SetURL;
property FontHoverColor : TColor read m_HoverColor write m_HoverColor;
property FontLinkColor : TColor read m_LinkColor write SetLinkColor;
property Font;
property OnClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
implementation
uses SUIPublic;
{ TsuiURLLabel }
procedure TsuiURLLabel.Click;
begin
if Trim(m_URL) <> '' then
ShellExecute(0, 'open', PChar(m_URL), nil, nil, SW_SHOW);
inherited;
end;
constructor TsuiURLLabel.Create(AOwner: TComponent);
begin
inherited;
Font.Style := [fsUnderline];
Font.Color := clBlue;
inherited Cursor := crHandPoint;
m_Cursor := inherited Cursor;
AutoSize := true;
m_HoverColor := clRed;
m_LinkColor := clBlue;
Caption := 'Welcome to Sunisoft';
URL := 'http://www.sunisoft.com';
end;
procedure TsuiURLLabel.OnMouseEnter(var Msg: TMessage);
begin
if csDesigning in ComponentState then
begin
Font.Color := clBlue;
Exit;
end;
Font.Color := m_HoverColor;
end;
procedure TsuiURLLabel.OnMouseLeave(var Msg: TMessage);
begin
Font.Color := m_LinkColor;
end;
procedure TsuiURLLabel.SetLinkColor(const Value: TColor);
begin
m_LinkColor := Value;
Font.Color := m_LinkColor;
end;
procedure TsuiURLLabel.SetURL(value: TCaption);
begin
if value <> m_URL then
m_URL := value;
end;
end.
|
{ *************************************************************************** }
{ }
{ Kylix and Delphi Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 1995, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit SqlTimSt;
// need to implement CastOLE, dispatch and stream (from Eddie?)
interface
uses Variants;
type
{ TSQLTimeStamp }
PSQLTimeStamp = ^TSQLTimeStamp;
TSQLTimeStamp = packed record
Year: SmallInt;
Month: Word;
Day: Word;
Hour: Word;
Minute: Word;
Second: Word;
Fractions: LongWord;
end;
{ TSQLTimeStamp variant creation utils }
procedure VarSQLTimeStampCreate(var aDest: Variant; const ASQLTimeStamp: TSQLTimeStamp); overload;
function VarSQLTimeStampCreate: Variant; overload;
function VarSQLTimeStampCreate(const AValue: string): Variant; overload;
function VarSQLTimeStampCreate(const AValue: TDateTime): Variant; overload;
function VarSQLTimeStampCreate(const ASQLTimeStamp: TSQLTimeStamp): Variant; overload;
function VarSQLTimeStamp: TVarType;
function VarIsSQLTimeStamp(const aValue: Variant): Boolean; overload;
//function VarAsSQLTimeStamp(const aValue: Variant): Variant;
{ TSQLTimeStamp conversion support }
// converts Variant SQLTimeStamp to record TSQLTimeStamp
function VarToSQLTimeStamp(const aValue: Variant): TSQLTimeStamp;
function SQLTimeStampToStr(const Format: string;
DateTime: TSQLTimeStamp): string;
function SQLDayOfWeek(const DateTime: TSQLTimeStamp): integer;
function DateTimeToSQLTimeStamp(const DateTime: TDateTime): TSQLTimeStamp;
function SQLTimeStampToDateTime(const DateTime: TSQLTimeStamp): TDateTime;
function TryStrToSQLTimeStamp(const S: string; var TimeStamp: TSQLTimeStamp) : Boolean;
function StrToSQLTimeStamp(const S: string): TSQLTimeStamp;
{ utility }
procedure CheckSqlTimeStamp(const ASQLTimeStamp: TSQLTimeStamp);
const
NullSQLTimeStamp: TSQLTimeStamp = (Year: 0; Month: 0; Day: 0; Hour: 0; Minute: 0; Second: 0; Fractions: 0);
implementation
uses
VarUtils, SysUtils, DateUtils, SysConst, DBConsts, TypInfo, Classes, {$IFDEF MSWINDOWS}Windows{$ENDIF}{$IFDEF LINUX}Types, Libc{$ENDIF};
const
IncrementAmount: array[Boolean] of Integer = (1, -1);
type
{ TSQLTimeStampVariantType }
TSQLTimeStampVariantType = class(TPublishableVariantType)
protected
function GetInstance(const V: TVarData): TObject; override;
public
procedure Clear(var V: TVarData); override;
procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override;
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override;
procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override;
procedure Compare(const Left, Right: TVarData; var Relationship: TVarCompareResult); override;
end;
var
{ SQLTimeStamp that the complex variant points to }
SQLTimeStampVariantType: TSQLTimeStampVariantType = nil;
type
{ TSQLTimeStampData }
TSQLTimeStampData = class(TPersistent)
private
FDateTime: TSQLTimeStamp;
function GetAsDateTime: TDateTime;
function GetAsString: string;
procedure SetAsString(const Value: string);
procedure SetAsDateTime(const Value: TDateTime);
procedure AdjustMonths(Reverse: Boolean);
procedure AdjustDays(Reverse: Boolean);
procedure AdjustHours(Reverse: Boolean);
procedure AdjustMinutes(Reverse: Boolean);
procedure AdjustSeconds(Reverse: Boolean);
function DaysInMonth: Integer;
function GetIsBlank: Boolean;
procedure SetDay(const Value: Word);
procedure SetFractions(const Value: LongWord);
procedure SetHour(const Value: Word);
procedure SetMinute(const Value: Word);
procedure SetMonth(const Value: Word);
procedure SetSecond(const Value: Word);
procedure SetYear(const Value: SmallInt);
protected
procedure AdjustDate(Reverse: Boolean);
property IsBlank: Boolean read GetIsBlank;
public
// the many ways to create
constructor Create(const AValue: SmallInt); overload;
constructor Create(const AValue: Integer); overload;
constructor Create(const AValue: TDateTime); overload;
constructor Create(const AText: string); overload;
constructor Create(const ASQLTimeStamp: TSQLTimeStamp); overload;
constructor Create(const ASource: TSQLTimeStampData); overload;
// access to the private bits
property DateTime: TSQLTimeStamp read FDateTime write FDateTime;
// non-destructive operations
// check this one!
function Compare(const Value: TSQLTimeStampData): TVarCompareResult;
// destructive operations
procedure DoAdd(const ADateTime: TSQLTimeStampData); overload;
procedure DoSubtract(const ADateTime: TSQLTimeStampData); overload;
// property access
published
// conversion
property AsDateTime: TDateTime read GetAsDateTime write SetAsDateTime;
property AsString: string read GetAsString write SetAsString;
property Day: Word read FDateTime.Day write SetDay;
property Fractions: LongWord read FDateTime.Fractions write SetFractions;
property Hour: Word read FDateTime.Hour write SetHour;
property Minute: Word read FDateTime.Minute write SetMinute;
property Month: Word read FDateTime.Month write SetMonth;
property Second: Word read FDateTime.Second write SetSecond;
property Year: SmallInt read FDateTime.Year write SetYear;
end;
{ Helper record that helps crack open TSQLTimeStampObject }
TSQLTimeStampVarData = packed record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
VDateTime: TSQLTimeStampData;
Reserved4: DWord;
end;
function IsSQLTimeStampBlank(const TimeStamp: TSQLTimeStamp): Boolean;
begin
Result := (TimeStamp.Year = 0) and
(TimeStamp.Month = 0) and
(TimeStamp.Day = 0) and
(TimeStamp.Hour = 0) and
(TimeStamp.Minute = 0) and
(TimeStamp.Second = 0) and
(TimeStamp.Fractions = 0);
end;
{ TSQLTimeStampData }
function TSQLTimeStampData.GetIsBlank: Boolean;
begin
Result := IsSQLTimeStampBlank(FDateTime);
end;
// Adjust for Month > 12 or < 1
procedure TSQLTimeStampData.AdjustMonths(Reverse: Boolean);
const
AdjustAmt: array[Boolean] of Integer = (-12, 12);
begin
while (FDateTime.Month < 1) or(FDateTime.Month > 12) do
begin
Inc(FDateTime.Year, IncrementAmount[Reverse]);
Inc(FDateTime.Month, AdjustAmt[Reverse]);
end;
end;
// Adjust for Days > 28/30/31 or < 1
procedure TSQLTimeStampData.AdjustDays(Reverse: Boolean);
var
Days: Integer;
begin
Days := DaysInMonth;
while (FDateTime.Day < 1) or (FDateTime.Day > Days) do
begin
Inc(FDateTime.Month, IncrementAmount[Reverse]);
if Reverse then
Dec(FDateTime.Day, Days)
else
Inc(FDateTime.Day, Days);
AdjustMonths(Reverse);
Days := DaysInMonth;
end;
end;
// Adjust for Hours over 23 or less than 0
procedure TSQLTimeStampData.AdjustHours(Reverse: Boolean);
const
AdjustAmt: array[Boolean] of Integer = (-24, 24);
begin
while (FDateTime.Hour > 23) or (Integer(FDateTime.Hour) < 0) do
begin
Inc(FDateTime.Day, IncrementAmount[Reverse]);
Inc(FDateTime.Hour, AdjustAmt[Reverse]);
AdjustDays(Reverse);
end;
end;
// Adjust Minutes for Hours over 59 or less than 0
procedure TSQLTimeStampData.AdjustMinutes(Reverse: Boolean);
const
AdjustAmt: array[Boolean] of Integer = (-60, 60);
begin
while (FDateTime.Minute > 59) or (Integer(FDateTime.Minute) < 0) do
begin
Inc(FDateTime.Hour, IncrementAmount[Reverse]);
Inc(FDateTime.Minute, AdjustAmt[Reverse]);
AdjustHours(Reverse);
end;
end;
// Adjust Seconds for Hours over 59 or less than 0
procedure TSQLTimeStampData.AdjustSeconds(Reverse: Boolean);
const
AdjustAmt: array[Boolean] of Integer = (-60, 60);
begin
while (FDateTime.Second > 59) or (Integer(FDateTime.Second) < 0) do
begin
Inc(FDateTime.Minute, IncrementAmount[Reverse]);
Inc(FDateTime.Second, AdjustAmt[Reverse]);
AdjustMinutes(Reverse);
end;
end;
procedure TSQLTimeStampData.AdjustDate(Reverse: Boolean);
begin
if Reverse then
begin
AdjustSeconds(Reverse);
AdjustMinutes(Reverse);
AdjustHours(Reverse);
AdjustDays(Reverse);
AdjustMonths(Reverse);
end else
begin
AdjustMonths(Reverse);
AdjustDays(Reverse);
AdjustHours(Reverse);
AdjustMinutes(Reverse);
AdjustSeconds(Reverse);
end;
end;
function TSQLTimeStampData.DaysInMonth: Integer;
begin
Result := DaysInAMonth(DateTime.Year, DateTime.Month);
end;
procedure TSQLTimeStampData.DoSubtract(const ADateTime: TSQLTimeStampData);
begin
Dec(FDateTime.Year, ADateTime.Year);
Dec(FDateTime.Hour, ADateTime.Month);
Dec(FDateTime.Day, ADateTime.Day);
Dec(FDateTime.Hour, ADateTime.Hour);
Dec(FDateTime.Minute, ADateTime.Minute);
Dec(FDateTime.Second, ADateTime.Second);
Dec(FDateTime.Fractions, ADateTime.Fractions);
AdjustDate(True);
end;
procedure TSQLTimeStampData.DoAdd(const ADateTime: TSQLTimeStampData);
begin
if not IsBlank then
begin
Inc(FDateTime.Year, ADateTime.Year);
Inc(FDateTime.Hour, ADateTime.Month);
Inc(FDateTime.Day, ADateTime.Day);
Inc(FDateTime.Hour, ADateTime.Hour);
Inc(FDateTime.Minute, ADateTime.Minute);
Inc(FDateTime.Second, ADateTime.Second);
Inc(FDateTime.Fractions, ADateTime.Fractions);
AdjustDate(False);;
end;
end;
function TSQLTimeStampData.Compare(const Value: TSQLTimeStampData): TVarCompareResult;
var
Status: Integer;
begin
Status := FDateTime.Year - Value.Year;
if Status = 0 then
Status := FDateTime.Month - Value.Month;
if Status = 0 then
Status := FDateTime.Day - Value.Day;
if Status = 0 then
Status := FDateTime.Hour - Value.Hour;
if Status = 0 then
Status := FDateTime.Hour - Value.Hour;
if Status = 0 then
Status := FDateTime.Minute - Value.Minute;
if Status = 0 then
Status := FDateTime.Second - Value.Second;
if Status = 0 then
Status := FDateTime.Fractions - Value.Fractions;
if Status = 0 then
Result := crEqual
else
if Status > 0 then
Result := crGreaterThan
else
Result := crLessThan;
end;
function TSQLTimeStampData.GetAsString: string;
begin
Result := SQLTimeStampToStr('', FDateTime);
end;
function TSQLTimeStampData.GetAsDateTime: TDateTime;
begin
Result := SQLTimeStampToDateTime(FDateTime);
end;
procedure TSQLTimeStampData.SetAsString(const Value: string);
begin
FDateTime := StrToSQLTimeStamp(Value);
end;
procedure TSQLTimeStampData.SetAsDateTime(const Value: TDateTime);
begin
FDateTime := DateTimeToSQLTimeStamp(Value);
end;
constructor TSQLTimeStampData.Create(const AValue: Integer);
begin
inherited Create;
FDateTime := NullSQLTimeStamp;
FDateTime.Day := AValue;
end;
constructor TSQLTimeStampData.Create(const AValue: SmallInt);
begin
inherited Create;
FDateTime := NullSQLTimeStamp;
FDateTime.Day := AValue;
end;
constructor TSQLTimeStampData.Create(const AValue: TDateTime);
begin
inherited Create;
FDateTime := DateTimeToSqlTimeStamp(AValue);
end;
constructor TSQLTimeStampData.Create(const AText: string);
var
ts: TSQLTimeStamp;
begin
ts := StrToSQLTimeStamp(AText);
inherited Create;
FDateTime := ts;
end;
constructor TSQLTimeStampData.Create(const ASQLTimeStamp: TSQLTimeStamp);
begin
CheckSqlTimeStamp( ASQLTimeStamp );
inherited Create;
move(ASQLTimeStamp, FDateTime, sizeof(TSQLTimeStamp));
end;
constructor TSQLTimeStampData.Create(const ASource: TSQLTimeStampData);
begin
Create(aSource.DateTime);
end;
procedure TSQLTimeStampData.SetDay(const Value: Word);
begin
Assert((Value >= 1) and (Value <= DaysInAMonth(Year, Month)));
FDateTime.Day := Value;
end;
procedure TSQLTimeStampData.SetFractions(const Value: LongWord);
begin
FDateTime.Fractions := Value;
end;
procedure TSQLTimeStampData.SetHour(const Value: Word);
begin
Assert(Value <= 23); // no need to check for > 0 on Word
FDateTime.Hour := Value;
end;
procedure TSQLTimeStampData.SetMinute(const Value: Word);
begin
Assert(Value <= 59); // no need to check for > 0 on Word
FDateTime.Minute := Value;
end;
procedure TSQLTimeStampData.SetMonth(const Value: Word);
begin
Assert((Value >= 1) and (Value <= 12));
FDateTime.Month := Value;
end;
procedure TSQLTimeStampData.SetSecond(const Value: Word);
begin
Assert(Value <= 59); // no need to check for > 0 on Word
FDateTime.Second := Value;
end;
procedure TSQLTimeStampData.SetYear(const Value: SmallInt);
begin
FDateTime.Year := Value;
end;
{ TSQLTimeStampVariantType }
procedure TSQLTimeStampVariantType.Clear(var V: TVarData);
begin
V.VType := varEmpty;
FreeAndNil(TSQLTimeStampVarData(V).VDateTime);
end;
procedure TSQLTimeStampVariantType.Cast(var Dest: TVarData;
const Source: TVarData);
var
LSource, LTemp: TVarData;
begin
VarDataInit(LSource);
try
VarDataCopyNoInd(LSource, Source);
if VarDataIsStr(LSource) then
TSQLTimeStampVarData(Dest).VDateTime := TSQLTimeStampData.Create(VarDataToStr(LSource))
else
begin
VarDataInit(LTemp);
try
VarDataCastTo(LTemp, LSource, varDate);
TSQLTimeStampVarData(Dest).VDateTime := TSQLTimeStampData.Create(LTemp.VDate);
finally
VarDataClear(LTemp);
end;
end;
Dest.VType := VarType;
finally
VarDataClear(LSource);
end;
end;
procedure TSQLTimeStampVariantType.CastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: TVarType);
var
LTemp: TVarData;
begin
if Source.VType = VarType then
case AVarType of
varOleStr:
VarDataFromOleStr(Dest, TSQLTimeStampVarData(Source).VDateTime.AsString);
varString:
VarDataFromStr(Dest, TSQLTimeStampVarData(Source).VDateTime.AsString);
else
VarDataInit(LTemp);
try
LTemp.VType := varDate;
LTemp.VDate := TSQLTimeStampVarData(Source).VDateTime.AsDateTime;
VarDataCastTo(Dest, LTemp, AVarType);
finally
VarDataClear(LTemp);
end;
end
else
inherited;
end;
procedure TSQLTimeStampVariantType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
with TSQLTimeStampVarData(Dest) do
begin
VType := VarType;
VDateTime := TSQLTimeStampData.Create(TSQLTimeStampVarData(Source).VDateTime);
end;
end;
function TSQLTimeStampVariantType.GetInstance(const V: TVarData): TObject;
begin
Result := TSQLTimeStampVarData(V).VDateTime;
end;
procedure TSQLTimeStampVariantType.BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp);
begin
case Operator of
opAdd:
TSQLTimeStampVarData(Left).VDateTime.DoAdd(TSQLTimeStampVarData(Right).VDateTime);
opSubtract:
TSQLTimeStampVarData(Left).VDateTime.DoSubtract(TSQLTimeStampVarData(Right).VDateTime);
else
RaiseInvalidOp;
end;
end;
procedure TSQLTimeStampVariantType.Compare(const Left, Right: TVarData; var Relationship: TVarCompareResult);
begin
Relationship := TSQLTimeStampVarData(Left).VDateTime.Compare(TSQLTimeStampVarData(Right).VDateTime);
end;
{ SQLTimeStamp variant create utils }
function VarSQLTimeStampCreate(const AValue: string): Variant; overload;
begin
VarClear(Result);
TSQLTimeStampVarData(Result).VType := SQLTimeStampVariantType.VarType;
TSQLTimeStampVarData(Result).VDateTime := TSQLTimeStampData.Create(AValue);
end;
function VarSQLTimeStampCreate(const AValue: TDateTime): Variant; overload;
begin
VarClear(Result);
TSQLTimeStampVarData(Result).VType := SQLTimeStampVariantType.VarType;
TSQLTimeStampVarData(Result).VDateTime := TSQLTimeStampData.Create(AValue);
end;
procedure VarSQLTimeStampCreate(var aDest: Variant; const ASQLTimeStamp: TSQLTimeStamp);
begin
VarClear(aDest);
TSQLTimeStampVarData(aDest).VType := SQLTimeStampVariantType.VarType;
TSQLTimeStampVarData(aDest).VDateTime := TSQLTimeStampData.Create(ASQLTimeStamp);
end;
function VarSQLTimeStampCreate: Variant;
begin
VarSQLTimeStampCreate(Result, NullSQLTimeStamp);
end;
function VarSQLTimeStampCreate(const ASQLTimeStamp: TSQLTimeStamp): Variant;
begin
VarSQLTimeStampCreate(Result, ASQLTimeStamp);
end;
function VarSQLTimeStamp: TVarType;
begin
Result := SQLTimeStampVariantType.VarType;
end;
function VarIsSQLTimeStamp(const aValue: Variant): Boolean;
begin
Result := TVarData(aValue).VType = SQLTimeStampVariantType.VarType;
end;
function VarToSQLTimeStamp(const aValue: Variant): TSQLTimeStamp;
begin
if TVarData(aValue).VType in [varNULL, varEMPTY] then
Result := NullSqlTimeStamp
else if (TVarData(aValue).VType = varString) then
Result := TSQLTimeStampData.Create(String(aValue)).FDateTime
else if (TVarData(aValue).VType = varOleStr) then
Result := TSQLTimeStampData.Create(String(aValue)).FDateTime
else if (TVarData(aValue).VType = varDouble) or (TVarData(aValue).VType = varDate) then
Result := DateTimeToSqlTimeStamp(TDateTime(aValue))
else if (TVarData(aValue).VType = SQLTimeStampVariantType.VarType) then
Result := TSQLTimeStampVarData(aValue).VDateTime.DateTime
else
Raise EVariantError.Create(SInvalidVarCast)
end;
{ SQLTimeStamp to string conversion }
function SQLTimeStampToStr(const Format: string;
DateTime: TSQLTimeStamp): string;
var
FTimeStamp: TDateTime;
begin
FTimeStamp := SqlTimeStampToDateTime(DateTime);
DateTimeToString(Result, Format, FTimeStamp);
end;
function IsSqlTimeStampValid(const ts: TSQLTimeStamp): Boolean;
begin
if (ts.Month > 12) or (ts.Day > DaysInAMonth(ts.Year, ts.Month)) or
(ts.Hour > 23) or (ts.Minute > 59) or (ts.Second > 59) then
Result := False
else
Result := True;
end;
function TryStrToSQLTimeStamp(const S: string; var TimeStamp: TSQLTimeStamp): Boolean;
var
DT: TDateTime;
begin
Result := TryStrToDateTime(S, DT);
if Result then
begin
TimeStamp := DateTimeToSQLTimeStamp(DT);
Result := IsSqlTimeStampValid(TimeStamp);
end;
if not Result then
TimeStamp := NullSQLTimeStamp;
end;
function StrToSQLTimeStamp(const S: string): TSQLTimeStamp;
begin
if not TryStrToSqlTimeStamp(S, Result) then
raise EConvertError.Create(SCouldNotParseTimeStamp);
end;
function DateTimeToSQLTimeStamp(const DateTime: TDateTime): TSQLTimeStamp;
var
FFractions, FYear: Word;
begin
with Result do
begin
DecodeDate(DateTime, FYear, Month, Day);
Year := FYear;
DecodeTime(DateTime, Hour, Minute, Second, FFractions);
Fractions := FFractions;
end;
end;
function SQLTimeStampToDateTime(const DateTime: TSQLTimeStamp): TDateTime;
begin
if IsSQLTimeStampBlank(DateTime) then
Result := 0
else with DateTime do
begin
Result := EncodeDate(Year, Month, Day);
if Result >= 0 then
Result := Result + EncodeTime(Hour, Minute, Second, Fractions)
else
Result := Result - EncodeTime(Hour, Minute, Second, Fractions);
end;
end;
function SQLDayOfWeek(const DateTime: TSQLTimeStamp): integer;
var
dt: TDateTime;
begin
dt := SQLTimeStampToDateTime(DateTime);
Result := DayOfWeek(dt);
end;
procedure CheckSqlTimeStamp(const ASQLTimeStamp: TSQLTimeStamp);
begin // only check if not an empty timestamp
if ASQLTimeStamp.Year + ASQLTimeStamp.Month + ASQLTimeStamp.day +
ASQLTimeStamp.Hour + ASQLTimeStamp.Minute + ASQLTimeStamp.Second > 0 then
begin
if ASQLTimeStamp.Year + ASQLTimeStamp.Month + ASQLTimeStamp.Day > 0 then
if (ASQLTimeStamp.Year = 0) or (ASQLTimeStamp.Month = 0) or
(ASQLTimeStamp.Day =0) or (ASQLTimeStamp.Month > 31) or (ASQLTimeStamp.Day >
DaysInAMonth(ASQLTimeStamp.Year,ASQLTimeStamp.Month)) then
raise EConvertError.Create(SInvalidSQLTimeStamp);
if ASQLTimeStamp.Hour + ASQLTimeStamp.Minute + ASQLTimeStamp.Second > 0 then
if (ASQLTimeStamp.Hour > 23) or (ASQLTimeStamp.Second > 59) or
(ASQLTimeStamp.Minute > 59) then
raise EConvertError.Create(SInvalidSQLTimeStamp);
end;
end;
initialization
SQLTimeStampVariantType := TSQLTimeStampVariantType.Create;
finalization
FreeAndNil(SQLTimeStampVariantType);
end.
|
unit ShowXML;
interface
uses Classes, HTTPApp, Db, DbClient, Midas,
XMLBrokr, WebComp, MidComp, MidItems;
type
TCustomShowXMLButton = class(TXMLButton, IScriptComponent)
protected
XMLMethodName: string;
{ IScriptComponent }
procedure AddElements(AddIntf: IAddScriptElements);
function GetSubComponents: TObject;
{ IWebContent implementation }
function ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string; override;
end;
TShowXMLButton = class(TCustomShowXMLButton)
public
constructor Create(AOwner: TComponent); override;
published
property Custom;
property Style;
property StyleRule;
property Caption;
property XMLBroker;
property XMLUseParent;
end;
TShowDeltaButton = class(TCustomShowXMLButton)
public
constructor Create(AOwner: TComponent); override;
published
property Custom;
property Style;
property StyleRule;
property Caption;
property XMLBroker;
property XMLUseParent;
end;
implementation
uses sysutils, MidProd;
resourcestring
sShowXML = 'Show XML';
sShowDelta = 'Show Delta';
procedure TCustomShowXMLButton.AddElements(
AddIntf: IAddScriptElements);
begin
AddIntf.AddIncludeFile('xmlshow.js');
end;
function TCustomShowXMLButton.GetSubComponents: TObject;
begin
Result := nil;
end;
function TCustomShowXMLButton.ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string;
var
Attrs: string;
Intf: ILayoutWebContent;
FormVarName: string;
RowSetVarName: string;
begin
AddQuotedAttrib(Attrs, 'NAME', Name);
AddQuotedAttrib(Attrs, 'STYLE', Style);
AddQuotedAttrib(Attrs, 'CLASS', StyleRule);
AddQuotedAttrib(Attrs, 'VALUE', Self.Caption);
AddCustomAttrib(Attrs, Custom);
if Assigned(XMLData.XMLBroker) then
begin
FormVarName := XMLData.XMLBroker.SubmitFormVarName;
RowSetVarName := XMLData.XMLBroker.RowSetVarName(nil); // Row row set var name
end;
if not (coNoScript in Options.Flags) then
Result :=
Format('<INPUT TYPE=BUTTON %0:s onclick=''if(%3:s)ShowXML(%1:s.%2:s);''>'#13#10,
[Attrs, RowSetVarName, XMLMethodName, sXMLReadyVar])
else
Result :=
Format('<INPUT TYPE=BUTTON %0:s>'#13#10,
[Attrs]);
if Assigned(ParentLayout) and ParentLayout.GetInterface(ILayoutWebContent, Intf) then
Result := Intf.LayoutButton(Result, GetLayoutAttributes);
end;
{ TShowXMLButton }
constructor TShowXMLButton.Create(AOwner: TComponent);
begin
inherited;
DefaultCaption := sShowXML;
XMLMethodName := 'root';
end;
{ TShowDeltaButton }
constructor TShowDeltaButton.Create(AOwner: TComponent);
begin
inherited;
DefaultCaption := sShowDelta;
XMLMethodName := 'getDelta()';
end;
{ Register procedure }
end.
|
unit fClientForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
uROClient, uROClientIntf, uRORemoteService, uROBinMessage,
uROWinInetHTTPChannel,
System.TypInfo, uROAsync, uROServerLocator, uROChannelAwareComponent,
uROBaseConnection, uROTransportChannel, uROBaseHTTPClient, uROComponent,
uROMessage, Vcl.ComCtrls, uLd, OtlComm, uInterfaces, OtlParallel, OtlCommon,
OtlSync, OtlTask, OtlTaskControl, OtlEventMonitor;
type
TClientForm = class(TForm)
ROMessage: TROBinMessage;
ROChannel: TROWinInetHTTPChannel;
RORemoteService: TRORemoteService;
pgc1: TPageControl;
tsEmulator: TTabSheet;
btnLaunch: TButton;
btnQuit: TButton;
btnQuitAll: TButton;
lblEmulatorIndex: TLabel;
edtEmulatorIndex: TEdit;
lblPackageName: TLabel;
edtPackageName: TEdit;
btnRunApp: TButton;
btnKillApp: TButton;
btnList2: TButton;
mmoLog: TMemo;
tsBase: TTabSheet;
btnStart: TButton;
btnStop: TButton;
btnStartExistWnds: TButton;
btnSortWnd: TButton;
btnTest: TButton;
OEM: TOmniEventMonitor;
procedure btnLaunchClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnQuitClick(Sender: TObject);
procedure btnRunAppClick(Sender: TObject);
procedure btnKillAppClick(Sender: TObject);
procedure btnQuitAllClick(Sender: TObject);
procedure btnList2Click(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure btnStartExistWndsClick(Sender: TObject);
procedure btnSortWndClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OEMTaskMessage(const task: IOmniTaskControl;
const msg: TOmniMessage);
procedure OEMTaskTerminated(const task: IOmniTaskControl);
private
{ Private declarations }
FGameManager: IGameManger;
procedure ExcuteTask(const task: IOmniTask);
public
{ Public declarations }
procedure OnLogMessage(var msg: TOmniMessage); message WM_LOG;
procedure OnStopMessage(var msg: TOmniMessage); message WM_STOP;
procedure OnStartOrStop(IsStart: Boolean);
procedure Log(msg: string);
end;
var
ClientForm: TClientForm;
implementation
{
The unit GameLibrary_Intf.pas will be generated by the RemObjects preprocessor the first time you
compile your server application. Make sure to do that before trying to compile the client.
To invoke your server simply typecast your server to the name of the service interface like this:
(RORemoteService as IGameService).Sum(1,2)
}
uses GameLibrary_Intf, uRegistrations, Spring.Container;
{$R *.dfm}
procedure TClientForm.btnKillAppClick(Sender: TObject);
var
index: integer;
begin
if TryStrToInt(edtEmulatorIndex.Text, index) then
TLd.KillApp(index, edtPackageName.Text)
else
ShowMessage('索引错误');
end;
procedure TClientForm.btnLaunchClick(Sender: TObject);
var
index: integer;
begin
if TryStrToInt(edtEmulatorIndex.Text, index) then
TLd.Launch(index)
else
ShowMessage('索引错误');
end;
procedure TClientForm.btnList2Click(Sender: TObject);
var
arr, arrAll: TArray<string>;
I: integer;
s: string;
curr: string;
begin
arrAll := TLd.List2.Split([#10]);
if Length(arrAll) > 1 then
begin
for I := Low(arrAll) to High(arrAll) do
begin
arr := arrAll[I].Split([',']);
// 索引,标题,顶层窗口句柄,绑定窗口句柄,是否进入android,进程PID,VBox进程PID
if Length(arr) = 7 then
begin
mmoLog.Lines.Add('------------begin--------------');
curr := Format
('索引:%s,标题:%s,顶层窗口句柄:%s,绑定窗口句柄:%s,是否进入android:%s,进程PID:%s,VBox进程PID:%s',
[arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7]]);
mmoLog.Lines.Add(curr);
mmoLog.Lines.Add('------------end----------------');
// s := s + #10 + '----------------------------' + #10 + curr;
end;
end;
end;
// ShowMessage(s);
end;
procedure TClientForm.btnQuitAllClick(Sender: TObject);
begin
TLd.QuitAll;
end;
procedure TClientForm.btnQuitClick(Sender: TObject);
var
index: integer;
begin
if TryStrToInt(edtEmulatorIndex.Text, index) then
TLd.Quit(index)
else
ShowMessage('索引错误');
end;
procedure TClientForm.btnRunAppClick(Sender: TObject);
var
index: integer;
begin
if TryStrToInt(edtEmulatorIndex.Text, index) then
TLd.RunApp(index, edtPackageName.Text)
else
ShowMessage('索引错误');
end;
procedure TClientForm.btnSortWndClick(Sender: TObject);
begin
FGameManager.SortWnd;
Log('SortWindows')
end;
procedure TClientForm.btnStartClick(Sender: TObject);
begin
IF FGameManager.StartAll(OEM) then
OnStartOrStop(True);
end;
procedure TClientForm.btnStartExistWndsClick(Sender: TObject);
begin
if FGameManager.StartExistWnds(OEM) then
OnStartOrStop(True);
end;
procedure TClientForm.btnStopClick(Sender: TObject);
begin
FGameManager.StopAll;
OnStartOrStop(False);
end;
procedure TClientForm.btnTestClick(Sender: TObject);
var
p: TOmniValueContainer;
e: TEmulatorInfo;
begin
p := TOmniValueContainer.Create;
// p['aaa'] := '1212';
// p['aqw'] := self;
// p['a1'] := 1212;
// Log(p['a1']);
p.Free;
Log(SizeOf(TEmulatorInfo).ToString);
// TLd.SetPropByFile(1, 'networkSettings.networkSwitching', true);
// TLd.SetPropByFile(1, 'networkSettings.networkStatic', False);
// TLd.SetPropByFile(1, 'networkSettings.networkAddress', '0.0.0.0');
// TLd.SetPropByFile(1, 'networkSettings.networkGateway', '0.0.0.0');
// TLd.SetPropByFile(1, 'networkSettings.networkSubnetMask', '255.255.255.0');
// TLd.SetPropByFile(1, 'networkSettings.networkDNS1', '223.5.5.5');
// TLd.SetPropByFile(1, 'networkSettings.networkDNS2', '114.114.114.114');
end;
procedure TClientForm.ExcuteTask(const task: IOmniTask);
var
emulatorInfo: TEmulatorInfo;
begin
emulatorInfo := task.Param.ByName('EmnuatorInfo').ToRecord<TEmulatorInfo>;
repeat
task.Comm.Send(WM_LOG, emulatorInfo.title);
Sleep(1000);
until (task.Terminated);
end;
procedure TClientForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FGameManager.StopAll;
end;
procedure TClientForm.FormCreate(Sender: TObject);
begin
gContainer := GlobalContainer;
ReportMemoryLeaksOnShutdown := DebugHook <> 0;
RegisterTypes(gContainer);
TLd.FilePath := 'D:\Changzhi\dnplayer2\dnconsole.exe';
mmoLog.Clear;
FGameManager := gContainer.Resolve<IGameManger>;
OnStartOrStop(False);
end;
procedure TClientForm.Log(msg: string);
begin
mmoLog.Lines.Add(msg);
end;
procedure TClientForm.OEMTaskMessage(const task: IOmniTaskControl;
const msg: TOmniMessage);
begin
Log(Format('[thread:%s]%s %s', [task.Name, DateTimeToStr(now),
msg.MsgData.AsString]));
end;
procedure TClientForm.OEMTaskTerminated(const task: IOmniTaskControl);
begin
Log(Format('[thread:%s]%s %s', [task.Name, DateTimeToStr(now), 'terminate']));
end;
procedure TClientForm.OnLogMessage(var msg: TOmniMessage);
begin
Log(msg.MsgData);
end;
procedure TClientForm.OnStartOrStop(IsStart: Boolean);
begin
btnStartExistWnds.Enabled := not IsStart;
btnStart.Enabled := not IsStart;
btnStop.Enabled := IsStart;
end;
procedure TClientForm.OnStopMessage(var msg: TOmniMessage);
begin
OnStartOrStop(False);
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit FileArea;
interface
uses Global;
procedure faAskListFiles;
procedure faBatchAdd(Par : String);
function faChangeArea(Area : Word) : Boolean;
function faCloseEnough(f1,f2 : String) : Boolean;
procedure faDownload(Par : String);
procedure faDownloadAny(Par : String);
procedure faEditFileDesc(var Fil : tFileRec);
procedure faFindAreaWithAccess;
procedure faGetFileInfo(Par : String);
function faIsSponsor : Boolean;
procedure faKillDesc(var F : tFileRec; var Desc : pFileDesc);
procedure faListAreas(Change : Boolean);
function faListFiles(Scn : Boolean; Idx : pFileScanIdx; idxFiles : Word) : Boolean;
function faLoad : Boolean;
procedure faLoadDesc(var aFile : tFileRec; var Desc : pFileDesc);
function faLoadDescFile(Fn : String; var P : pFileDesc) : Word;
function faLoadFile(N : Word; var D : tFileRec) : Boolean;
procedure faLocalUpload;
procedure faNewScanAsk(Par : String);
procedure faNextArea;
procedure faPrevArea;
procedure faReset;
procedure faSave;
function faSaveFile(N : Word; var D : tFileRec) : Boolean;
procedure faSearchFile(fs : Boolean);
procedure faSetNewScanDate;
function faTestFile(Fn : String) : Boolean;
procedure faUpload;
procedure faViewFile(Par : String);
var pDesc : pFileDesc;
nDescLns : Word;
implementation
uses Dos,
Strings, Misc, Output, Input, Logs, ShowFile, DateTime, Files, Comm,
Archive, Users, Transfer, Stats, History, Config13, fsEditor, Sauce;
var skipOk : Boolean;
procedure faReset;
begin
with fArea^ do
begin
Name := 'New '+bbsTitle+' file area';
Filename := 'NEWAREA';
Path := StartDir;
Sponsor := Cfg^.SysOpAlias;
acs := 's25';
acsUL := 's50';
acsDL := 's50';
Password := '';
Files := 0;
SortType := sortFilename;
SortAcen := True;
end;
end;
function faCloseEnough(f1,f2 : String) : Boolean;
begin
f1 := UpStr(f1);
f2 := UpStr(f2);
faCloseEnough := (f1 = f2) or
((Pos('.',f1) = 0) and
(Pos('.',f2) > 0) and
(f1 = Copy(f2,1,Pos('.',f2)-1)));
end;
function faLoad : Boolean;
var F : file of tFileAreaRec;
begin
faLoad := False;
Assign(F,Cfg^.pathData+fileFileArea);
{$I-}
Reset(F);
if ioResult = 0 then numFileArea := FileSize(F) else Exit;
{$I+}
if (User^.curFileArea < 1) or (User^.curFileArea > numFileArea) then
begin
Close(F);
Exit;
end;
{$I-}
Seek(F,User^.curFileArea-1);
Read(F,fArea^);
{$I+}
faLoad := ioResult = 0;
Close(F);
end;
procedure faSave;
var F : file of tFileAreaRec;
begin
Assign(F,Cfg^.pathData+fileFileArea);
{$I-}
Reset(F);
{$I+}
if ioResult = 0 then numFileArea := FileSize(F) else Exit;
if (User^.curFileArea < 1) or (User^.curFileArea > numFileArea) then
begin
Close(F);
Exit;
end;
Seek(F,User^.curFileArea-1);
{$I-}
Write(F,fArea^);
numFileArea := FileSize(F);
{$I+}
Close(F);
end;
function faHasAccess : Boolean;
begin
faHasAccess := acsOk(fArea^.Acs);
end;
function faIsSponsor : Boolean;
begin
faIsSponsor := (faHasAccess) and ((UpStr(User^.UserName) = UpStr(fArea^.Sponsor)) or
(UpStr(User^.RealName) = UpStr(fArea^.Sponsor)));
end;
function faHasULaccess : Boolean;
begin
faHasULaccess := acsOk(fArea^.AcsUL);
end;
function faHasDLaccess : Boolean;
begin
faHasDLaccess := acsOk(fArea^.AcsDL);
end;
function faChangeArea(Area : Word) : Boolean;
var OldArea : Word; Ok : Boolean; Pw : String;
begin
faChangeArea := False;
if (Area < 1) or (Area > numFileArea) then Exit;
OldArea := User^.curFileArea;
User^.curFileArea := Area;
Ok := (faLoad) and (faHasAccess);
if (Ok) and (fArea^.Password <> '') then
begin
oString(strFaAskPassword);
Pw := iReadString('',inUpper,chNormal,rsPassword,20);
Ok := Pw = UpStr(fArea^.Password);
end;
if not Ok then
begin
User^.curFileArea := OldArea;
faLoad;
Exit;
end;
logWrite('Changed to file area: '+fArea^.Name);
faChangeArea := True;
end;
procedure faListAreas(Change : Boolean);
var Ans, Hil : Boolean; F : file of tFileAreaRec; A : tFileAreaRec; N, cN : Word;
S : String; Ref : array[1..maxFileArea] of Word;
begin
if not Change then logWrite('Listed file areas');
Assign(F,Cfg^.pathData+fileFileArea);
{$I-}
Reset(F);
{$I+}
if ioResult <> 0 then Exit;
Ans := (sfGetTextFile(txListFareaTop,ftTopLine) <> '') and
(sfGetTextFile(txListFareaMid,ftListFarea) <> '') and
(sfGetTextFile(txListFareaBot,ftNormal) <> '');
Hil := (not Ans) or (sfGetTextFile(txListFareaHil,ftListFarea) <> '');
PausePos := 1;
PauseAbort := False;
if Ans then
begin
sfShowTextFile(txListFareaTop,ftTopLine);
oUpPause(ansiRows-1);
sfGotoPos(1);
sfLoadRepeat(txListFareaMid);
end else
begin
oClrScr;
oDnLn(1);
oSetCol(colInfo);
oCWriteLn(' Num Area Title Files Sponsor');
oSetCol(colBorder);
oWriteLn(sRepeat('Ä',79));
oUpPause(2);
end;
N := 0;
cN := 0;
FillChar(Ref,SizeOf(Ref),0);
while not Eof(F) do
begin
Read(F,A);
Inc(N);
if not Cfg^.compFileAreas then
begin
Inc(cN);
Ref[cN] := N;
end;
if acsOk(A.Acs) then
begin
if Cfg^.compFileAreas then
begin
Inc(cN);
Ref[cN] := N;
end;
if PauseAbort then begin end else
if Ans then
begin
sfStr[1] := A.Name;
sfStr[2] := St(cN);
sfStr[3] := Stc(A.Files);
sfStr[4] := A.Sponsor;
if (Hil) and (N = User^.curFileArea) then
begin
sfKillRepeat;
sfLoadRepeat(txListFareaHil);
sfShowRepeat(ftListFarea);
sfKillRepeat;
sfLoadRepeat(txListFareaMid);
end else sfShowRepeat(ftListFarea);
if oWhereX <> 1 then oDnLn(1);
oUpPause(1);
end else
begin
if N = User^.curFileArea then oSetCol(colTextHi) else oSetCol(colText);
oWriteLn(' '+Resize(St(cN),6)+
' '+Resize(A.Name,30)+
' '+Resize(Stc(A.Files),7)+
' '+strSquish(A.Sponsor,36));
oUpPause(1);
end;
end;
end;
sfKillRepeat;
Close(F);
if Ans then
begin
sfShowTextFile(txListFareaBot,ftNormal);
oUpPause(ansiRows);
end else
begin
oSetCol(colBorder);
oWriteLn(sRepeat('Ä',79));
oUpPause(1);
end;
PausePos := 0;
if Change then
begin
oString(strFaAskChangeArea);
S := iReadString('',inUpper,chNumeric,'',4);
N := strToInt(S);
if (S <> '') and (N > 0) and (N <= cN) and (faChangeArea(Ref[N])) then
oStrLn(strCode(mStr(strFaChangedAreas),1,fArea^.Name));
end;
end;
procedure faPrevArea;
var A, oa : Word; Found : Boolean;
begin
oa := User^.curFileArea;
Found := False;
while (not Found) and (User^.curFileArea > 1) do
begin
Dec(User^.curFileArea);
Found := faChangeArea(User^.curFileArea);
end;
if not Found then
begin
User^.curFileArea := oa;
faLoad;
oStringLn(strFaLowestArea);
end else oStrLn(strCode(mStr(strFaChangedAreas),1,fArea^.Name));
end;
procedure faNextArea;
var A, oa : Word; Found : Boolean;
begin
oa := User^.curFileArea;
Found := False;
while (not Found) and (User^.curFileArea < numFileArea) do
begin
Inc(User^.curFileArea);
Found := faChangeArea(User^.curFileArea);
end;
if not Found then
begin
User^.curFileArea := oa;
faLoad;
oStringLn(strFaHighestArea);
end else oStrLn(strCode(mStr(strFaChangedAreas),1,fArea^.Name));
end;
function faAddFile(var aFile : tFileRec; var Desc) : Boolean;
var F : file of tFileRec; eF : file of tFileDescLn; pD : pFileDesc; N : Word;
begin
pD := @Desc;
faAddFile := False;
Inc(fArea^.Files,1);
if aFile.DescLns > 0 then
begin
if aFile.DescLns > maxDescLns then aFile.DescLns := maxDescLns;
Assign(eF,Cfg^.pathData+fileFileDesc);
{$I-}
Reset(eF);
{$I+}
if ioResult <> 0 then
begin
{$I-}
Rewrite(eF);
{$I+}
if ioResult <> 0 then Exit;
end else Seek(eF,FileSize(eF));
aFile.DescPtr := FilePos(eF);
for N := 1 to aFile.DescLns do Write(eF,pD^[N]);
Close(eF);
end;
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F);
{$I+}
if ioResult <> 0 then
begin
{$I-}
Rewrite(F);
{$I+}
if ioResult <> 0 then Exit;
end else Seek(F,FileSize(F));
Write(F,aFile);
fArea^.Files := FileSize(F);
Close(F);
faSave;
faAddFile := True;
end;
procedure faLoadDesc(var aFile : tFileRec; var Desc : pFileDesc);
var eF : file of tFileDescLn; N : Word;
begin
if aFile.DescLns > 0 then
begin
Assign(eF,Cfg^.pathData+fileFileDesc);
{$I-}
Reset(eF);
{$I+}
if ioResult <> 0 then Exit;
Seek(eF,aFile.descPtr);
GetMem(Desc,aFile.DescLns*(maxDescLen+1));
FillChar(Desc^,SizeOf(Desc^),0);
for N := 1 to aFile.DescLns do Read(eF,Desc^[N]);
Close(eF);
end;
end;
procedure faReadDesc(var F : file; var aFile : tFileRec; var Desc : pFileDesc);
var N : Word;
begin
if (FileSize(F) > 0) and (aFile.DescLns > 0) then
begin
Seek(F,aFile.descPtr);
GetMem(Desc,aFile.DescLns*(maxDescLen+1));
FillChar(Desc^,SizeOf(Desc^),0);
for N := 1 to aFile.DescLns do BlockRead(F,Desc^[N],1);
end;
end;
procedure faKillDesc(var F : tFileRec; var Desc : pFileDesc);
begin
if F.DescLns > 0 then FreeMem(Desc,F.DescLns*(maxDescLen+1));
end;
function faFileExists(Fn : String) : Boolean;
var F : file; D : tFileRec; Found : Boolean;
begin
faFileExists := False;
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F,SizeOf(tFileRec));
{$I+}
if ioResult <> 0 then Exit;
Found := False;
while (not Found) and (not Eof(F)) do
begin
BlockRead(F,D,1);
Found := D.Filename = Fn;
end;
Close(F);
faFileExists := Found;
end;
function faFileSearch(Fn : String; var D : tFileRec; var Area : Word) : Word;
var F : file; Found, A, cA, cF : Word;
begin
faFileSearch := 0;
Area := User^.curFileArea;
A := User^.curFileArea;
Found := 0;
cF := 0;
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F,SizeOf(tFileRec));
{$I+}
if ioResult = 0 then
begin
while (Found = 0) and (not Eof(F)) do
begin
BlockRead(F,D,1);
Inc(cF);
if faCloseEnough(Fn,D.Filename) then Found := cF;
end;
Close(F);
end;
faFileSearch := Found;
if Found <> 0 then Exit;
cA := 0;
repeat
Inc(cA);
User^.curFileArea := cA;
if (cA <> A) and (faLoad) and (faHasAccess) and (fArea^.Password = '') then
begin
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F,SizeOf(tFileRec));
{$I+}
cF := 0;
if ioResult = 0 then
begin
while (Found = 0) and (not Eof(F)) do
begin
BlockRead(F,D,1);
Inc(cF);
if faCloseEnough(Fn,D.Filename) then Found := cF;
end;
Close(F);
end;
end;
until (Found <> 0) or (cA >= numFileArea);
faFileSearch := Found;
Area := cA;
User^.curFileArea := A;
faLoad;
end;
function faLoadDescFile(Fn : String; var P : pFileDesc) : Word;
var Lns, nL, lfs : Word; dF : file; S : String[maxDescLen]; Z : String; lastLf : Boolean;
C : Char; Po : Byte;
begin
faLoadDescFile := 0;
Lns := 0;
Assign(dF,Fn);
{$I-}
Reset(dF,1);
{$I+}
if ioResult <> 0 then Exit;
if Eof(dF) then Lns := 0 else Lns := 1;
lastLf := False;
C := #0;
Po := 0;
lfs := 0;
while (C <> #26) and (Lns <= maxDescLns) and (ioResult = 0) and (not Eof(dF)) do
begin
BlockRead(dF,C,1);
if (C = #13) or ((C = #10) and (not lastLf)) then
begin
Inc(Lns);
Inc(lfs);
Po := 0;
end else if not (C in [#10,#13,#26]) then begin lfs := 0; Inc(Po); end;
lastLf := C = #13;
end;
Close(dF);
if Po > 0 then Inc(Lns) else Dec(Lns,lfs);
if Lns = 0 then Exit;
GetMem(P,Lns*(maxDescLen+1));
FillChar(P^,Lns*(maxDescLen+1),0);
nL := Lns;
Reset(dF,1);
Lns := 1;
lastLf := False;
C := #0;
while (C <> #26) and (Lns <= nL) and (ioResult = 0) and (not Eof(dF)) do
begin
BlockRead(dF,C,1);
if (not (C in [#10,#13,#26,#8])) and (Ord(P^[Lns,0]) < maxDescLen) then
P^[Lns] := P^[Lns]+C else if (C = #13) or
((C = #10) and (not lastLf)) then Inc(Lns);
lastLf := C = #13;
end;
Close(dF);
faLoadDescFile := nL;
end;
(*
function faLoadDescFile(Fn : String; var P : pFileDesc) : Word;
var Lns : Word; dF : Text; S : String[maxDescLen]; Z : String;
begin
faLoadDescFile := 0;
Lns := 0;
Assign(dF,Fn);
{$I-}
Reset(dF);
{$I+}
if ioResult <> 0 then Exit;
while not Eof(dF) do
begin
ReadLn(dF);
Inc(Lns);
end;
Close(dF);
if Lns = 0 then Exit;
GetMem(P,Lns*(maxDescLen+1));
FillChar(P^,Lns*(maxDescLen+1),0);
Reset(dF);
Lns := 0;
while not Eof(dF) do
begin
ReadLn(dF,S);
Inc(Lns);
Move(S,P^[Lns],Length(S)+1);
end;
Close(dF);
faLoadDescFile := Lns;
end;
*)
procedure faLocalUpload;
var sr, sr2 : SearchRec; F : tFileRec; None, ca, fa, la, oa, X, xp, xa : Byte; dF : Text;
fn, S, Tp : String; P : pFileDesc; pX : array[1..5] of String; Auto, error, no, sa : Boolean;
procedure luOut(v : String);
begin
oMoveLeft(80);
oClrEol;
oStrCtr(v);
end;
begin
oa := User^.curFileArea;
oDnLn(1);
oStrCtr('|U2(|U1upload|U2) |U1Upload to which file area(s)|U2? ');
pX[1] := 'Current';
pX[2] := 'Conference';
pX[3] := 'All';
pX[4] := 'Abort';
xa := iXprompt(pX,4,1);
if xa = 4 then Exit;
oStrCtr('|U2(|U1upload|U2) |U1File process method|U2: ');
pX[1] := 'None';
pX[2] := 'Import';
pX[3] := 'Test';
pX[4] := 'Recompress';
xp := iXprompt(pX,4,3);
if xa = 1 then begin fa := oa; la := oa; end else
if xa in [2,3] then begin fa := 1; la := numFileArea; end;
pX[1] := 'Add';
pX[2] := 'Skip';
pX[3] := 'Kill';
pX[4] := 'Auto';
pX[5] := 'Quit';
Auto := False;
Tp := fTempPath('A');
fClearDir(Tp);
X := 1;
for ca := fa to la do if ((xa <> 2) or (acsOk(fArea^.acs))) and (not hangup) and (x <> 5) then
begin
User^.curFileArea := ca;
faLoad;
oDnLn(1);
oStrCtrLn('|U2(|U1upload|U2) |U1Processing area|U2: |U3'+fArea^.Name+'|U2, |U3'+st(fArea^.files)+'|U1 file(s)');
FindFirst(fArea^.Path+'*.*',0,Sr);
while (X <> 5) and (not HangUp) and (dosError = 0) do
begin
if not faFileExists(Sr.Name) then
begin
oStrCtr('|U2- |U1Found|U2: |U3'+Resize(Sr.Name,12)+' ');
fn := upStr(fArea^.path+sr.Name);
if iKeypressed then Auto := False;
if Auto then oStrLn('|U2[|U1auto mode|U2]') else
begin
oStr('|U2- |U1Command|U2: ');
X := iXprompt(pX,5,1);
end;
if X = 3 then fDeleteFile(fArea^.Path+Sr.Name) else
if X = 4 then Auto := True;
if (Auto) or (X = 1) then with F do
begin
luOut('|U2- |U1Analyzing file|U2 ...');
fClearDir(Tp);
FillChar(F,SizeOf(F),0);
DescLns := 0;
error := False;
no := ArchType(fn) = 0;
if no then error := True;
if (not error) and (xp in [3,4]) and (Cfg^.delFile <> '') and
(fExists(Cfg^.pathData+Cfg^.delFile)) then
begin
luOut('|U2- |U1Removing useless file(s) from archive|U2 ...');
archDelete(fn,'@'+Cfg^.pathData+Cfg^.delFile);
end;
if (not error) and (xp in [3,4]) and (Cfg^.addFile <> '') and
(fExists(Cfg^.pathData+Cfg^.addFile)) then
begin
luOut('|U2- |U1Adding file(s) to archive|U2 ...');
archZip(fn,'@'+Cfg^.pathData+Cfg^.addFile,0);
end;
if (not error) and (xp in [3,4]) then
begin
luOut('|U2- |U1Decompressing file|U2 ...');
if not archUnzip(fn,'*.*',tp) then error := True;
end;
if (not error) and (xp in [3,4]) then
begin
luOut('|U2- |U1Scanning for viruses|U2 ...');
if not archScan(tp+'*.*') then error := True;
end;
if (not error) and (xp = 4) then
begin
luOut('|U2- |U1Recompressing archive|U2 ...');
s := fTempPath('F')+'COMPTEMP.$$$';
fDeleteFile(s);
fRenameFile(fn,s);
if archZip(fn,tp+'*.*',0) then fDeleteFile(s) else
begin
error := True;
fRenameFile(s,fn);
end;
end;
if (not error) and (xp in [2,3,4]) and (Cfg^.comFile <> '') and
(fExists(Cfg^.pathData+Cfg^.comFile)) then
begin
luOut('|U2- |U1Applying bbs comment to archive|U2 ...');
archComment(fn,Cfg^.pathData+cfg^.comFile);
end;
if (not error) and (xp in [2,3,4]) then
begin
luOut('|U2- |U1Checking for description |U2(|U1'+cfg^.fileDesc1+' or '+cfg^.fileDesc2+'|U2) ...');
fClearDir(tp);
if (Cfg^.ImportDescs) and
(archUnzip(fn,Cfg^.fileDesc1+' '+Cfg^.fileDesc2,Tp)) then
begin
if fExists(Tp+Cfg^.fileDesc1) then
begin
luOut('|U2- |U1Importing file description|U2: |U3'+Cfg^.fileDesc1);
DescLns := faLoadDescFile(Tp+Cfg^.fileDesc1,P);
end else if fExists(Tp+Cfg^.fileDesc2) then
begin
luOut('|U2- |U1Importing file description|U2: |U3'+Cfg^.fileDesc2);
DescLns := faLoadDescFile(Tp+Cfg^.fileDesc2,P);
end;
end;
end;
if (descLns = 0) and ((no) or (not error)) and (xp in [2,3,4]) then
begin
luOut('|U2- |U1Checking for sauce comment|U2 ...');
fClearDir(tp);
if (Cfg^.ImportDescs) and (sauceDiz(fn,tp+cfg^.fileDesc1)) then
begin
luOut('|U2- |U1Importing sauce comment |U2...');
DescLns := faLoadDescFile(Tp+Cfg^.fileDesc1,P);
end;
end;
if no then error := False;
luOut('|U2- |U1Loading file information|U2 ...');
FindFirst(fn,0,sr2);
if dosError <> 0 then error := True else
begin
Filename := Sr2.Name;
Downloads := 0;
Size := Sr2.Size;
Uploader := User^.UserName;
Date := dtDatePackedString(Sr2.Time);
ulDate := dtDateString;
Valid := True;
filePts := Size div (Cfg^.kbPerFilePoint*1024);
end;
fClearDir(tp);
if (not error) and (DescLns = 0) and (not Auto) then
begin
Assign(dF,fTempPath('A')+'FILEDESC.TMP');
{$I-}
Rewrite(dF);
{$I+}
if ioResult = 0 then
begin
luOut('|U2- |U1Enter file description|U2. |U1Hit |U3enter |U1on a blank line to end|U2.');
oDnLn(1);
repeat
Inc(DescLns);
oStrCtr('|U6'+ResizeRt(St(DescLns),3)+'|U5: |U4');
S := iReadString('',inNormal,chNormal,rsNoCR,maxDescLen);
if S <> '' then
begin
WriteLn(dF,S);
oDnLn(1);
end else
begin
oMoveLeft(70);
oClrEol;
end;
until (HangUp) or (DescLns >= maxDescLns) or (S = '');
Close(dF);
if HangUp then DescLns := 0;
DescLns := faLoadDescFile(fTempPath('A')+'FILEDESC.TMP',P);
end;
end;
if not error then
begin
faAddFile(F,P^);
luOut('|U2- |U3'+Sr.Name+'|U2: |U1file added|U2.');
if F.DescLns > 0 then oStrCtr(' |U2[|U1'+St(F.DescLns)+'|U1 line description|U2]');
end else luOut('|U2- |U3'+Sr.Name+'|U2: |U1error processing file|U2.');
oDnLn(1);
faKillDesc(F,P);
end;
end;
FindNext(Sr);
{ if dosError <> 0 then oDnLn(1);}
end;
faSave;
end;
User^.curfileArea := oa;
faLoad;
end;
function faLoadFile(N : Word; var D : tFileRec) : Boolean;
var fD : file of tFileRec;
begin
faLoadFile := False;
Assign(fD,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(fD);
{$I+}
if ioResult <> 0 then Exit;
fArea^.Files := FileSize(fD);
if N > FileSize(fD) then Exit;
Seek(fD,N-1);
Read(fD,D);
Close(fD);
faLoadFile := True;
end;
function faSaveFile(N : Word; var D : tFileRec) : Boolean;
var fD : file of tFileRec;
begin
faSaveFile := False;
Assign(fD,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(fD);
{$I+}
if ioResult <> 0 then Exit;
fArea^.Files := FileSize(fD);
if N > FileSize(fD) then Exit;
Seek(fD,N-1);
Write(fD,D);
Close(fD);
faSaveFile := True;
end;
procedure faFileInfo(var F : tFileRec);
var Ans : boolean;
begin
faLoadDesc(F,pDesc);
nDescLns := F.DescLns;
with F do
begin
sfStr[1] := Filename;
sfStr[2] := Stc(Downloads);
sfStr[3] := Stc(Size);
sfStr[4] := Uploader;
sfStr[5] := Date;
sfStr[6] := ulDate;
sfStr[7] := St(mXferTimeSec(Size) div 60);
sfStr[8] := St(filePts);
end;
Ans := sfShowTextFile(txFileInfo,ftFileInfo);
if not Ans then with F do
begin
oStrCtrLn('|U5'+sRepeat('Ä',79));
oStrCtrLn('|U4 Filename |U5: |U6'+Filename);
oStrCtrLn('|U4 Downloads |U5: |U6'+Stc(Downloads));
oStrCtrLn('|U4 Size |U5: |U6'+Stc(Size));
oStrCtrLn('|U4 Uploader |U5: |U6'+Uploader);
oStrCtrLn('|U4 Date |U5: |U6'+Date);
oStrCtrLn('|U4 Upload date |U5: |U6'+ulDate);
oStrCtrLn('|U4 Transfer time |U5: |U6'+St(mXferTimeSec(Size) div 60)+' |U4min');
oStrCtrLn('|U5'+sRepeat('Ä',79));
end;
faKillDesc(F,pDesc);
end;
function faReqDownload(var D : tFileRec; TimAdd, dlAdd, dlkbAdd, fpAdd : LongInt) : Boolean;
begin
faReqDownload := False;
fConfAll := True;
if not (faHasAccess and faHasDLAccess) then
begin
fConfAll := False;
oStrLn(strCode(mStr(strFaDLaccessDenied),1,D.Filename));
logWrite(D.Filename+': Access to area denied');
Exit;
end;
fConfAll := False;
if not fExists(fArea^.path+D.Filename) then
begin
oStrLn(strCode(mStr(strFaFileNotThere),1,D.Filename));
logWrite('-'+D.Filename+': File did not actually exist');
Exit;
end;
if (not acsOk(Cfg^.acsCoSysOp)) and (not D.Valid) then
begin
oStrLn(strCode(mStr(strFaFileNotValid),1,D.Filename));
logWrite(D.Filename+': File not validated for transfer');
Exit;
end;
if mTimeLeft('S')-TimAdd < mXferTimeSec(D.Size) then
begin
oStrLn(strCode(mStr(strFaNoTimeForDL),1,D.Filename));
logWrite(D.Filename+': Insufficient time for transfer');
Exit;
end;
if (Cfg^.useFilePoints) and (D.filePts > User^.filePts-fpAdd) then
begin
oStrLn(strCode(strCode(strCode(mStr(strFaNoFilePts),1,St(User^.filePts)),2,St(D.filePts)),3,D.Filename));
logWrite(D.Filename+': Not enough file points');
Exit;
end;
if (Cfg^.useDLlimit) and (User^.todayDL+dlAdd >= User^.limitDL) then
begin
oStrLn(strCode(strCode(mStr(strFaOverDLlimit),1,St(User^.limitDL)),2,D.Filename));
logWrite(D.Filename+': Over daily download limit');
Exit;
end;
if (Cfg^.useDLkbLimit) and (User^.todayDLkb+dlKbAdd >= User^.limitDLkb) then
begin
oStrLn(strCode(strCode(mStr(strFaOverDLkbLimit),1,St(User^.limitDLkb)),2,D.Filename));
logWrite(D.Filename+': Over daily download kilobyte limit');
Exit;
end;
if (Cfg^.useUlDlratio) and (User^.Downloads+dlAdd >= User^.Uploads*User^.uldlRatio+User^.uldlRatio) then
begin
oStrLn(strCode(mStr(strFaULDLratioBad),1,D.Filename));
logWrite(D.Filename+': Upload/download ratio out of balance');
Exit;
end;
if (Cfg^.useKbratio) and (User^.DownloadKb+dlKbAdd >= User^.UploadKb*User^.kbRatio+User^.kbRatio) then
begin
oStrLn(strCode(mStr(strFaKBratioBad),1,D.Filename));
logWrite(D.Filename+': Upload/download kilobyte ratio out of balance');
Exit;
end;
faReqDownload := True;
end;
procedure faDownload(Par : String);
var Fn : String; D : tFileRec; Ch : Char; bDL : Boolean;
dlSize : LongInt; dlTime, dlKb, dlFp, dlFiles, dlOk, N, oldA, A : Word; fB : Text;
dlIdx : array[1..maxBatch] of record
Num : Word;
Area : Word;
Ok : Boolean;
end;
begin
oldA := User^.curFileArea;
oDnLn(1);
bDL := False;
if (Par = '') and (numBatch > 0) then
begin
oStr(strCode(mStr(strFaBatchAskDL),1,St(numBatch)));
bDL := iYesNo(True);
end;
if bDL then
begin
oDnLn(1);
dlTime := 0;
dlFiles := 0;
dlSize := 0;
dlKb := 0;
dlFp := 0;
Assign(fB,fTempPath('F')+fileTempDL);
{$I-}
Rewrite(fB);
{$I+}
if ioResult <> 0 then Exit;
for N := 1 to numBatch do
begin
if User^.curFileArea <> batchDL[N].Area then
begin
User^.curFileArea := batchDL[N].Area;
faLoad;
end;
if (faLoadFile(batchDL[N].Num,D)) and (faReqDownload(D,dlTime,dlFiles,dlKb,dlFp)) then
begin
Inc(dlSize,D.Size);
Inc(dlFiles);
Inc(dlKb,D.Size div 1024);
Inc(dlFp,D.FilePts);
Inc(dlTime,mXferTimeSec(D.Size));
dlIdx[dlFiles].Num := batchDL[N].Num;
dlIdx[dlFiles].Area := batchDL[N].Area;
dlIdx[dlFiles].Ok := False;
oStrLn(strCode(strCode(strCode(mStr(strFaBatchFileDL),1,D.Filename),
2,Stc(D.Size)),
3,mTimeSec(mXferTimeSec(D.Size))));
WriteLn(fB,fArea^.Path+D.Filename);
end;
end;
Close(fB);
User^.curFileArea := oldA;
faLoad;
if dlFiles = 0 then Exit;
oDnLn(1);
oStrLn(strCode(strCode(strCode(mStr(strFaBatchDLtotal),1,St(dlFiles)),
2,Stc(dlSize)),
3,mTimeSec(mXferTimeSec(dlSize))));
oDnLn(1);
oString(strFaDownloadPrompt);
repeat
Ch := UpCase(iReadKey);
until (HangUp) or ((extKey = #0) and (Ch in ['D','C','A',#27,#13]));
if Ch in ['D','C',#13] then
begin
oWriteLn('Continue');
if xferSend('',[protActive,protBatch]) then
begin
dlOk := 0;
dlSize := 0;
for N := 1 to dlFiles do
begin
if User^.curFileArea <> dlIdx[N].Area then
begin
User^.curFileArea := dlIdx[N].Area;
faLoad;
end;
if faLoadFile(dlIdx[N].Num,D) then
begin
if xferGood(D.Filename,True) then
begin
Inc(dlOk);
Inc(dlSize,D.Size);
Inc(User^.Downloads);
Inc(User^.DownloadKb,D.Size div 1024);
Inc(Stat^.Downloads);
Inc(Stat^.DownloadKb,D.Size div 1024);
Inc(His^.Downloads);
Inc(His^.DownloadKb,D.Size div 1024);
Inc(User^.todayDL);
Inc(User^.todayDLkb,D.Size div 1024);
Inc(D.Downloads);
faSaveFile(dlIdx[N].Num,D);
end;
end;
end;
oDnLn(1);
if dlOk = 0 then
begin
logWrite('Transfer failed');
oStringLn(strFaXferFailed);
end else
begin
logWrite('Transfer successful ['+St(dlOk)+' files, '+Stc(dlSize)+' bytes]');
oStringLn(strFaXferSuccess);
oStrLn(strCode(strCode(mStr(strFaXferFilesSent),1,St(dlOk)),2,Stc(dlSize)));
end;
userSave(User^);
hisSave;
statSave;
oDnLn(1);
numBatch := 0;
end else logWrite('-Transfer failed');
end else
if Ch in ['A',#27] then
begin
oWriteLn('Abort');
logWrite('Transfer aborted');
end;
Exit;
end;
oString(strFaAskFileDownload);
Par := UpStr(Par);
if Par = '' then
begin
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then Exit;
end else
begin
Fn := Par;
oWriteLn(Par);
end;
oString(strFaSearching);
N := faFileSearch(Fn,D,A);
oDnLn(1);
if N = 0 then
begin
oStringLn(strFaFileNotFound);
Exit;
end;
if A <> User^.curFileArea then
begin
User^.curFileArea := A;
faLoad;
oStrLn(strCode(strCode(mStr(strFaFoundInArea),2,fArea^.Name),1,D.Filename));
end;
logWrite('File download: '+D.Filename+' ('+fArea^.Name+')');
faFileInfo(D);
if not faReqDownload(D,0,0,0,0) then
begin
User^.curFileArea := oldA;
faLoad;
Exit;
end;
oString(strFaDownloadPrompt);
repeat
Ch := UpCase(iReadKey);
until (HangUp) or ((extKey = #0) and (Ch in ['D','C','A',#27,#13]));
if Ch in ['D','C',#13] then
begin
oWriteLn('Continue');
if xferSend(fArea^.Path+D.Filename,[protActive]) then
begin
Inc(User^.Downloads);
Inc(User^.DownloadKb,D.Size div 1024);
Inc(Stat^.Downloads);
Inc(Stat^.DownloadKb,D.Size div 1024);
Inc(His^.Downloads);
Inc(His^.DownloadKb,D.Size div 1024);
Inc(User^.todayDL);
Inc(User^.todayDLkb,D.Size div 1024);
Inc(D.Downloads);
userSave(User^);
hisSave;
statSave;
faSaveFile(N,D);
logWrite('Transfer successful');
end else logWrite('-Transfer failed');
end else
if Ch in ['A',#27] then
begin
oWriteLn('Abort');
logWrite('Transfer aborted');
end;
User^.curFileArea := oldA;
faLoad;
end;
procedure faFindAreaWithAccess;
var old, N : Word; F : file of tFileAreaRec; Found : Boolean;
begin
faLoad;
if faHasAccess then Exit;
old := User^.curFileArea;
Assign(F,Cfg^.pathData+fileFileArea);
{$I-}
Reset(F);
{$I+}
if ioResult <> 0 then Exit;
N := 0;
Found := False;
while (not Found) and (not Eof(F)) do
begin
Read(F,fArea^);
Inc(N);
Found := faHasAccess;
end;
if Found then User^.curFileArea := N else User^.curFileArea := old;
Close(F);
faLoad;
end;
procedure faDownloadAny(Par : String);
begin
if Par <> '' then fFindFile(Par) else FileFound := False;
if not FileFound then
begin
oStrLn('|U2-- |U1Enter filename to download|U2.');
oStr('|U2: |U3');
Par := iReadString('',inUpper,chDirectory,'',76);
if Par = '' then Exit;
fFindFile(Par);
if not fileFound then
begin
oStrLn('|U1File not found|U2.');
Exit;
end;
end;
xferSend(Par,[protActive]);
end;
function faInBatch(n, a : Word) : Boolean;
var Z : Word; There : Boolean;
begin
There := False;
for Z := 1 to numBatch do
if (n = batchDL[Z].Num) and (a = batchDL[Z].Area) then There := True;
faInBatch := There;
end;
function faAddToBatch(N, A : Word) : Byte;
begin
faAddToBatch := 1;
if numBatch >= maxBatch then Exit;
if faInBatch(n,a) then
begin
faAddToBatch := 2;
Exit;
end;
Inc(numBatch);
with batchDL[numBatch] do
begin
Num := N;
Area := A;
end;
faAddToBatch := 0;
end;
procedure faBatchAdd(Par : String);
var Fn : String; D : tFileRec; A, N : Word;
begin
oDnLn(1);
if numBatch >= maxBatch then
begin
oStringLn(strFaBatchFull);
Exit;
end;
oString(strFaBatchAskAdd);
Par := UpStr(Par);
if Par = '' then
begin
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then Exit;
end else
begin
Fn := Par;
oWriteLn(Par);
end;
oString(strFaSearching);
N := faFileSearch(Fn,D,A);
oDnLn(1);
if N = 0 then
begin
oStringLn(strFaFileNotFound);
Exit;
end;
faFileInfo(D);
case faAddToBatch(N,A) of
0 : begin
logWrite('File added to batch: '+D.Filename);
oStrLn(strCode(mStr(strFaBatchAdded),1,D.Filename));
end;
1 : oStringLn(strFaBatchFull);
2 : oStringLn(strFaBatchAlready);
end;
end;
procedure faViewFile(Par : String);
var Fn : String; D : tFileRec; oA, A, N : Word;
begin
oDnLn(1);
oA := User^.curFileArea;
oString(strFaViewAskFile);
Par := UpStr(Par);
if Par = '' then
begin
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then Exit;
end else
begin
Fn := Par;
oWriteLn(Par);
end;
oString(strFaSearching);
N := faFileSearch(Fn,D,A);
oDnLn(1);
if N = 0 then
begin
oStringLn(strFaFileNotFound);
Exit;
end;
User^.curFileArea := A;
faLoad;
archView(fArea^.Path+D.Filename);
User^.curFileArea := oA;
faLoad;
end;
procedure faGetFileInfo(Par : String);
var Fn : String; D : tFileRec; oA, A, N : Word;
begin
oDnLn(1);
oA := User^.curFileArea;
oString(strFaInfoAskFile);
Par := UpStr(Par);
if Par = '' then
begin
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then Exit;
end else
begin
Fn := Par;
oWriteLn(Par);
end;
oString(strFaSearching);
N := faFileSearch(Fn,D,A);
oDnLn(1);
if N = 0 then
begin
oStringLn(strFaFileNotFound);
Exit;
end;
faFileInfo(D);
end;
function faListFiles(Scn : Boolean; Idx : pFileScanIdx; idxFiles : Word) : Boolean;
var Ans, lfDone, lfQuit, listDraw, infoDraw, First, scrnDraw, fwd, neDesc : Boolean; listTop, listBot,
ListLns, xx : Byte; cl : array[1..6] of tColorRec;
numFiles, fileTop, fileBot, aFile : Word; pD : pFileDesc;
fD : file of tFileRec; F : tFileRec; Ch : Char; SplitPos : Word;
descF : file; Page : array[1..25] of record Filename : String[12]; Y : Byte; inbat : Boolean; end;
onPage, barPos, curMnu, sel : Byte;
mnu : array[1..2] of record
num : Byte;
pos : Byte;
cmd : array[1..10] of String[15];
off : array[1..10] of Boolean;
xp : array[1..10] of Byte;
end;
procedure lfDoFn(pn : Word; hi : Boolean);
var S, fns : String; P : Byte;
begin
P := Pos('.',page[pn].Filename);
if P = 0 then fns := '' else fns := Copy(page[pn].Filename,P+1,3);
if P = 0 then P := Length(page[pn].Filename)+1;
fns := Resize(Copy(page[pn].Filename,1,P-1),9)+fns;
if hi then
begin
if Page[pn].inbat then
begin
oSetColRec(cl[6]);
oWriteChar('(');
end else
begin
oSetColRec(cl[4]);
oWriteChar(' ');
end;
oSetColRec(cl[4]);
oWrite(fns);
if Page[pn].inbat then
begin
oSetColRec(cl[6]);
oWriteChar(')');
end else oWriteChar(' ');
end else
begin
if Page[pn].inbat then
begin
oSetColRec(cl[3]);
oWriteChar('(');
end else
begin
oSetColRec(cl[1]);
oWriteChar(' ');
end;
oSetColRec(cl[1]);
oWrite(fns);
if Page[pn].inbat then
begin
oSetColRec(cl[3]);
oWriteChar(')');
end else oWriteChar(' ');
end;
end;
procedure lfDescLn(Num, pn : Word; Ext : String; First : Boolean);
begin
if First then
begin
if sfPos[5].Ok then
begin
oPosX(sfPos[5].X);
oSetColRec(cl[1]);
oWrite(St(Num));
end;
if sfPos[6].Ok then
begin
oPosX(sfPos[6].X-1);
lfDoFn(pn,False);
end;
if sfPos[7].Ok then
begin
oPosX(sfPos[7].X);
oSetColRec(cl[1]);
oWrite(St(F.Size div 1024)+'k');
{ oSetColRec(cl[2]);
oWritechar('k');}
end;
if sfPos[8].Ok then
begin
oPosX(sfPos[8].X);
oSetColRec(cl[1]);
oWrite(St(F.filePts));
end;
end;
if sfPos[9].Ok then
begin
oPosX(sfPos[9].X);
oSetColRec(cl[1]);
oStrCtrLn(strSquish(Ext,79-oWhereX));
end;
end;
procedure lfClearWindow;
var N : Word;
begin
oGotoXY(1,listTop);
if First then
begin
First := False;
Exit;
end;
oSetColRec(cl[1]);
oClrEol;
for N := listTop+1 to listBot do
begin
oDnLn(1);
oClrEol;
end;
oGotoXY(1,listTop);
end;
procedure lfShowDesc(cf,pn, fl,ll : Word);
var X : Word;
begin
if neDesc then faReadDesc(descF,F,pD);
if ll > F.DescLns then ll := F.DescLns;
for X := fl to ll do lfDescLn(cf,pn, pD^[X],X=1);
faKillDesc(F,pD);
end;
procedure lfUpdateBar;
var Len, X : Byte; num1, num2 : Integer;
begin
if not ((sfPos[17].Ok) and (sfPos[18].Ok)) then Exit;
oGotoXY(sfPos[17].X,sfPos[17].Y);
Len := sfPos[18].X-sfPos[17].X+1;
if fileTop = 1 then num1 := 1 else num1 := Len*fileTop div numFiles;
if fileBot = numFiles then num2 := Len else num2 := Len*fileBot div numFiles;
if num1 < 1 then num1 := 1;
if num2 < num1 then num2 := num1;
if num2 > Len then num2 := Len;
if num1 > 1 then
begin
oSetColRec(sfPos[17].C);
for X := 1 to num1-1 do oWriteChar(userCfg['A']);
end;
oSetColRec(sfPos[18].C);
for X := num1 to num2 do oWriteChar(userCfg['B']);
if num2 < Len then
begin
oSetColRec(sfPos[17].C);
for X := num2+1 to Len do oWriteChar(userCfg['A']);
end;
end;
procedure lfNoBar;
begin
if (barPos = 0) or (not sfPos[6].Ok) then Exit;
oGotoXY(sfPos[6].X-1,Page[barPos].Y);
lfDoFn(barPos,False);
end;
procedure lfBar;
begin
if (barPos = 0) or (not sfPos[6].Ok) then Exit;
oGotoXY(sfPos[6].X-1,Page[barPos].Y);
lfDoFn(barPos,True);
end;
procedure lfDrawList(redraw : boolean);
var Cur, Lines, X, Sze : Word; Done : Boolean;
begin
if not listDraw then Exit;
listDraw := False;
onPage := 0;
lfClearWindow;
FillChar(Page,SizeOf(Page),0);
if (splitPos > 0) or (not redraw) then barPos := 0;
Done := False;
if Scn then Seek(fD,Idx^[fileTop]-1) else Seek(fD,fileTop-1);
Read(fD,F);
Cur := fileTop;
fileBot := fileTop;
if (SplitPos > 0) and (fwd) then
begin
lfShowDesc(fileTop,1,SplitPos,SplitPos+listLns);
if SplitPos+listLns >= F.DescLns then SplitPos := 0;
onPage := 0;
Done := True;
end else
if (Cfg^.descWrap) and (F.DescLns > listLns) then
begin
SplitPos := 1;
onPage := 1;
Page[1].Filename := F.Filename;
Page[1].Y := oWhereY;
Page[1].inbat := faInBatch(cur,User^.curFileArea);
lfShowDesc(fileTop,1,1,listLns);
Done := True;
end else
begin
SplitPos := 0;
Done := False;
if F.DescLns > listLns then F.DescLns := listLns;
Lines := F.DescLns;
onPage := 1;
Page[1].Filename := F.Filename;
Page[1].Y := oWhereY;
Page[1].inbat := faInBatch(cur,User^.curFileArea);
if Lines = 0 then Lines := 1;
if F.DescLns > 0 then lfShowDesc(Cur,1,1,F.DescLns) else
lfDescLn(Cur,1,Cfg^.noDescLine,True);
end;
while (Cur < numFiles) and (not Done) do
begin
Inc(Cur);
if Scn then Seek(fD,Idx^[Cur]-1);
Read(fD,F);
Sze := F.DescLns;
if Sze = 0 then Sze := 1;
if Sze+Lines <= listLns then
begin
Inc(Lines,Sze);
Inc(onPage);
Page[onPage].Y := oWhereY;
Page[onPage].Filename := F.Filename;
Page[onPage].inbat := faInBatch(cur,User^.curFileArea);
if F.DescLns > 0 then lfShowDesc(Cur,onPage,1,F.DescLns)
else lfDescLn(Cur,onPage,Cfg^.noDescLine,True);
fileBot := Cur;
end else Done := True;
end;
lfUpdateBar;
if barPos > onPage then barPos := 0;
fwd := False;
if (barPos <> 0) and (redraw) then lfBar;
end;
procedure lfMenuDraw;
var N : Byte;
begin
oGotoXY(1,sfPos[3].Y);
oSetColRec(cl[1]);
oClrEol;
oWrite(' ');
for N := 1 to mnu[curMnu].Num do
begin
if mnu[curMnu].off[N] then
begin
if mnu[curMnu].Pos = N then oSetColRec(cl[4])
else oSetColRec(cl[1]);
end else
begin
if mnu[curMnu].Pos = N then oSetColRec(cl[6])
else oSetColRec(cl[3]);
end;
mnu[curMnu].xp[N] := oWhereX;
oWrite(' '+mnu[curMnu].cmd[N,1]);
if mnu[curMnu].off[N] then
begin
if mnu[curMnu].Pos = N then oSetColRec(cl[5])
else oSetColRec(cl[2]);
end else
begin
if mnu[curMnu].Pos = N then oSetColRec(cl[4])
else oSetColRec(cl[1]);
end;
oWrite(Copy(mnu[curMnu].cmd[N],2,255)+' ');
end;
oSetColRec(cl[1]);
end;
procedure lfWriteInfo(S : String);
begin
oGotoXY(1,sfPos[4].Y);
oSetColRec(cl[1]);
oClrEol;
oStr(S);
end;
procedure lfInfo;
begin
case curMnu of
1 : lfWriteInfo(mStr(strFaListInfo));
2 : lfWriteInfo(mStr(strFaListInfoBar));
end;
infoDraw := False;
end;
procedure lfBarUp;
begin
if onPage = 0 then Exit;
if barPos = 0 then
begin
barPos := onPage;
lfBar;
curMnu := 2;
lfMenuDraw;
lfInfo;
end else
begin
lfNoBar;
Dec(barPos);
if barPos = 0 then
begin
curMnu := 1;
lfMenuDraw;
lfInfo;
end;
lfBar;
end;
if barPos = 0 then curMnu := 1 else curMnu := 2;
end;
procedure lfBarDown;
begin
if onPage = 0 then Exit;
if barPos = 0 then
begin
barPos := 1;
lfBar;
curMnu := 2;
lfMenuDraw;
lfInfo;
end else
begin
lfNoBar;
Inc(barPos);
if barPos > onPage then
begin
barPos := 0;
curMnu := 1;
lfMenuDraw;
lfInfo;
end;
lfBar;
end;
end;
procedure lfMoveForward;
begin
if SplitPos > 0 then
begin
Inc(SplitPos,listLns);
fwd := True;
listDraw := True;
end else if fileBot < numFiles then
begin
fileTop := fileBot+1;
fwd := True;
listDraw := True;
end else lfDone := True;
end;
procedure lfMoveBackward;
begin
if SplitPos > 0 then
begin
if fileTop > 1 then Dec(fileTop);
SplitPos := 0;
listDraw := True;
end else if fileTop > 1 then
begin
Dec(fileTop);
listDraw := True;
end;
end;
procedure lfDownload;
begin
oClrScr;
if barPos <> 0 then faDownload(Page[barPos].Filename) else
faDownload('');
listDraw := True;
scrnDraw := True;
oPromptKey;
end;
procedure lfDrawScreen;
begin
if not scrnDraw then Exit;
if Scn then numFiles := idxFiles else numFiles := FileSize(fD);
sfStr[1] := fArea^.Name;
Ans := sfShowTextFile(txListFiles,ftListFiles);
if Ans then
begin
listTop := sfPos[1].Y;
listBot := sfPos[2].Y;
cl[1] := sfPos[11].C;
cl[2] := sfPos[12].C;
cl[3] := sfPos[13].C;
cl[4] := sfPos[14].C;
cl[5] := sfPos[15].C;
cl[6] := sfPos[16].C;
end else
begin
oClrScr;
listTop := 3;
listBot := 20;
sfPos[4].Ok := True;
oGotoXY(1,21);
oStrCtr('|U2-- |U1File Listing Command|U2: ');
sfPos[4].X := oWhereX;
sfPos[4].Y := 21;
sfPos[4].C := User^.Color[3];
cl[1] := User^.Color[1];
cl[2] := User^.Color[2];
cl[3] := User^.Color[3];
cl[4] := User^.Color[4];
cl[5] := User^.Color[5];
cl[6] := User^.Color[6];
end;
listLns := ListBot-listTop+1;
end;
procedure lfDoHelp;
begin
sfShowTextfile(txFileListHelp,ftNormal);
oPromptKey;
scrnDraw := True;
listDraw := True;
end;
procedure lfEdit;
var Num : Word;
begin
if not acsOk(cfg^.acsCoSysOp) then Exit;
if Scn then
begin
if barPos = 0 then Num := Idx^[fileTop] else
Num := Idx^[fileTop+barPos-1];
end else
begin
if barPos = 0 then Num := fileTop else
Num := fileTop+barPos-1;
end;
cfgFileEditor(Num,False);
scrnDraw := True;
listDraw := True;
end;
procedure lfMenuBar;
begin
oGotoXY(mnu[curMnu].xp[mnu[curMnu].pos],sfPos[3].Y);
if mnu[curMnu].off[mnu[curMnu].pos] then oSetColRec(cl[4]) else oSetColRec(cl[6]);
oWrite(' '+mnu[curMnu].cmd[mnu[curMnu].pos,1]);
if mnu[curMnu].off[mnu[curMnu].pos] then oSetColRec(cl[5]) else oSetColRec(cl[4]);
oWrite(Copy(mnu[curMnu].cmd[mnu[curMnu].pos],2,255)+' ');
oSetColRec(cl[1]);
end;
procedure lfMenuNoBar;
begin
oGotoXY(mnu[curMnu].xp[mnu[curMnu].pos],sfPos[3].Y);
if mnu[curMnu].off[mnu[curMnu].pos] then oSetColRec(cl[1]) else oSetColRec(cl[3]);
oWrite(' '+mnu[curMnu].cmd[mnu[curMnu].pos,1]);
if mnu[curMnu].off[mnu[curMnu].pos] then oSetColRec(cl[2]) else oSetColRec(cl[1]);
oWrite(Copy(mnu[curMnu].cmd[mnu[curMnu].pos],2,255)+' ');
oSetColRec(cl[1]);
end;
procedure lfFlagFile;
var Fn : String; D : tFileRec; A, N : Word;
begin
A := User^.curFileArea;
if barPos <> 0 then
begin
if Scn then N := Idx^[fileTop+barPos-1] else N := fileTop+barPos-1;
faLoadFile(N,D);
case faAddToBatch(N,A) of
0 : begin
logWrite('File added to batch: '+D.Filename);
lfWriteInfo(strCode(mStr(strFaBatchAdded),1,D.Filename));
Page[barPos].inbat := True;
if not Cfg^.advFileBar then lfBar;
end;
1 : lfWriteInfo(mStr(strFaBatchFull));
2 : lfWriteInfo(mStr(strFaBatchAlready));
end;
infoDraw := True;
if Cfg^.advFileBar then
begin
lfNoBar;
Inc(barPos);
if barPos > onPage then
begin
barPos := 0;
curMnu := 1;
lfMenuDraw;
end;
lfBar;
end;
Exit;
end;
lfWriteInfo(mStr(strFaBatchAskAdd));
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then
begin
lfInfo;
Exit;
end;
lfWriteInfo(mStr(strFaSearching));
N := faFileSearch(Fn,D,A);
if N = 0 then
begin
lfWriteInfo(mStr(strFaFileNotFound));
infoDraw := True;
Exit;
end;
case faAddToBatch(N,A) of
0 : begin
logWrite('File added to batch: '+D.Filename);
lfWriteInfo(strCode(mStr(strFaBatchAdded),1,D.Filename));
for n := 1 to onPage do if D.Filename = Page[n].Filename then
begin
barPos := n;
Page[n].inbat := True;
lfNoBar;
end;
barPos := 0;
end;
1 : lfWriteInfo(mStr(strFaBatchFull));
2 : lfWriteInfo(mStr(strFaBatchAlready));
end;
infoDraw := True;
end;
procedure lfView;
var Fn : String; D : tFileRec; oA, A, N : Word;
begin
oA := User^.curFileArea;
if barPos <> 0 then
begin
if Scn then N := Idx^[fileTop+barPos-1] else N := fileTop+barPos-1;
faLoadFile(N,D);
if not archView(fArea^.Path+D.Filename) then Exit;
oPromptKey;
listDraw := True;
scrnDraw := True;
Exit;
end;
lfWriteInfo(mStr(strFaViewAskFile));
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then
begin
lfInfo;
Exit;
end;
lfWriteInfo(mStr(strFaSearching));
N := faFileSearch(Fn,D,A);
if N = 0 then
begin
lfWriteInfo(mStr(strFaFileNotFound));
infoDraw := True;
Exit;
end;
User^.curFileArea := A;
faLoad;
if archView(fArea^.Path+D.Filename) then
begin
oPromptKey;
scrnDraw := True;
listDraw := True;
end else lfInfo;
User^.curFileArea := oA;
faLoad;
end;
procedure lfFileInfo;
var Fn : String; D : tFileRec; oA, A, N : Word;
begin
oA := User^.curFileArea;
if barPos <> 0 then
begin
if Scn then N := Idx^[fileTop+barPos-1] else N := fileTop+barPos-1;
faLoadFile(N,D);
oClrScr;
faFileInfo(D);
oPromptKey;
listDraw := True;
scrnDraw := True;
Exit;
end;
lfWriteInfo(mStr(strFaInfoAskFile));
Fn := iReadString('',inUpper,chFilename,'',12);
if Fn = '' then
begin
lfInfo;
Exit;
end;
lfWriteInfo(mStr(strFaSearching));
N := faFileSearch(Fn,D,A);
if N = 0 then
begin
lfWriteInfo(mStr(strFaFileNotFound));
infoDraw := True;
Exit;
end;
oClrScr;
faFileInfo(D);
oPromptKey;
scrnDraw := True;
listDraw := True;
faLoad;
end;
begin
Assign(fD,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(fD);
{$I+}
if ioResult <> 0 then
begin
if not Scn then oStringLn(strFaNoFilesInArea);
Exit;
end else if FileSize(fD) = 0 then
begin
Close(fD);
if not Scn then oStringLn(strFaNoFilesInArea);
Exit;
end;
fArea^.Files := FileSize(fD);
Assign(descF,Cfg^.pathData+fileFileDesc);
{$I-}
Reset(descF,SizeOf(tFileDescLn));
{$I+}
neDesc := ioResult = 0;
scrnDraw := True;
fileTop := 1;
lfDone := False;
lfQuit := False;
listDraw := True;
infoDraw := False;
SplitPos := 0;
barPos := 0;
First := True;
fwd := False;
curMnu := 1;
FillChar(mnu,SizeOf(mnu),0);
with mnu[1] do
begin
num := 10;
pos := 1;
cmd[1] := 'next';
cmd[2] := 'previous';
cmd[3] := 'flag';
cmd[4] := 'download';
cmd[5] := 'view';
cmd[6] := 'info';
cmd[7] := 'edit';
cmd[8] := 'help';
cmd[9] := 'skip';
cmd[10] := 'quit';
off[7] := not acsOk(Cfg^.acsCoSysOp);
off[9] := not skipOk;
end;
with mnu[2] do
begin
num := 6;
pos := 1;
cmd[1] := 'flag';
cmd[2] := 'download';
cmd[3] := 'view';
cmd[4] := 'info';
cmd[5] := 'edit';
cmd[6] := 'quit';
off[5] := not acsOk(Cfg^.acsCoSysOp);
end;
repeat
lfDrawScreen;
if scrnDraw then
begin
lfMenuDraw;
lfInfo;
end;
lfDrawList(scrnDraw);
if (barPos = 0) and (curMnu > 1) then
begin
curMnu := 1;
lfMenuDraw;
end else
if (barPos > 0) and (curMnu = 1) then
begin
curMnu := 2;
lfMenuDraw;
end;
scrnDraw := False;
Ch := UpCase(iReadKey);
if Ch = #27 then Ch := 'Q';
if Ch = '?' then Ch := 'H';
if infoDraw then lfInfo;
if extKey <> #0 then
case extKey of
rtArrow : begin
lfMenuNoBar;
Inc(mnu[curMnu].Pos);
if mnu[curMnu].Pos > mnu[curMnu].Num then
mnu[curMnu].Pos := 1;
lfMenuBar;
end;
lfArrow : begin
lfMenuNoBar;
Dec(mnu[curMnu].Pos);
if mnu[curMnu].Pos < 1 then
mnu[curMnu].Pos := mnu[curMnu].Num;
lfMenuBar;
end;
upArrow : lfBarUp;
dnArrow : lfBarDown;
end else
begin
Sel := 0;
for xx := 1 to mnu[curMnu].Num do
if (Ch = UpCase(mnu[curMnu].Cmd[xx,1])) and
(not mnu[curMnu].off[xx]) then
begin
if mnu[curMnu].Pos <> xx then
begin
lfMenuNoBar;
mnu[curMnu].Pos := xx;
lfMenuBar;
end;
Sel := xx;
end;
if Ch = #13 then Sel := mnu[curMnu].Pos;
if curMnu = 1 then
case Sel of
1 : lfMoveForward;
2 : lfMoveBackward;
3 : lfFlagFile;
4 : lfDownload;
5 : lfView;
6 : lfFileInfo;
7 : lfEdit;
8 : lfDoHelp;
9 : if skipOk then begin lfDone := True; end;
10 : begin lfDone := True; lfQuit := True; end;
end else
if curMnu = 2 then
case Sel of
1 : lfFlagFile;
2 : lfDownload;
3 : lfView;
4 : lfFileInfo;
5 : lfEdit;
6 : begin lfDone := True; lfQuit := True; end;
end;
end;
until (HangUp) or (lfDone);
faListfiles := (not lfQuit) and (not HangUp);
sfGotoPos(maxPos);
Close(fD);
if neDesc then Close(descF);
faSave;
end;
function faBuildScanIdx(var Idx : tFileScanIdx; Typ : Char; nfo : String) : Word;
var F : file; x, N, rN : Word; D : tFileRec; pd : pFileDesc; fnd : Boolean;
begin
faBuildScanIdx := 0;
FillChar(Idx,SizeOf(Idx),0);
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F,SizeOf(D));
{$I+}
if ioResult <> 0 then Exit;
N := 0;
rN := 0;
while (N < maxFiles) and (not Eof(F)) do
begin
BlockRead(F,D,1);
Inc(N);
if Typ = 'N' then
begin
if dtDateToJulian(D.ulDate) >= dtDateToJulian(User^.fileScan) then
begin
Inc(rN);
Idx[rN] := N;
end;
end else
if Typ = 'L' then
begin
if strWildCard(D.Filename,nfo) then
begin
Inc(rN);
Idx[rN] := N;
end;
end else
if Typ = 'D' then
begin
fnd := False;
faLoadDesc(d,pd);
for x := 1 to d.descLns do if Pos(nfo,upStr(pd^[x])) > 0 then fnd := True;
faKillDesc(d,pd);
if fnd then
begin
Inc(rN);
Idx[rN] := N;
end;
end;
end;
Close(F);
faBuildScanIdx := rN;
end;
procedure faNewScan(AllAreas : Boolean; Num : Word);
var N, Z, A : Word; Ok : Boolean; Idx : pFileScanIdx;
begin
if numFileArea < 1 then Exit;
A := User^.curFileArea;
Ok := True;
New(Idx);
if AllAreas then
begin
logWrite('Global file newscan');
{ oStringLn(strFaNewScanInit);}
skipOk := numFileArea <> 1;
for N := 1 to numFileArea do if Ok then
begin
User^.curFileArea := N;
faLoad;
if faHasAccess then
begin
oStr(strCode(strCode(mStr(strFaNewScanning),1,fArea^.Name),2,St(fArea^.Files)));
Z := faBuildScanIdx(Idx^,'N','');
cCheckUser;
oDnLn(1);
if Z > 0 then Ok := (not HangUp) and (faListFiles(True,Idx,Z)) and (not (iKeyPressed and (iReadKey = ' ')));
end;
end;
skipOk := False;
{ oStringLn(strFaNewScanDone);}
end else
begin
skipOk := False;
if Num = 0 then N := User^.curFileArea else N := Num;
if N > numFileArea then N := numFileArea else if N < 1 then N := 1;
User^.curFileArea := N;
faLoad;
if faHasAccess then
begin
logWrite('Newscanned file area "'+fArea^.Name+'"');
oStr(strCode(strCode(mStr(strFaNewScanning),1,fArea^.Name),2,St(fArea^.Files)));
Z := faBuildScanIdx(Idx^,'N','');
oDnLn(1);
if Z > 0 then faListFiles(True,Idx,Z);
end;
end;
Dispose(Idx);
User^.curFileArea := A;
faLoad;
end;
procedure faNewScanAsk(Par : String);
var All : Boolean; Num : Word;
begin
oDnLn(1);
All := False;
Num := 0;
if Par <> '' then
begin
Par := UpStr(Par);
All := (Par[1] = 'A');
if not All then Num := StrToInt(Par);
end;
if (not All) and (Num = 0) then
begin
oString(strFaNewScanAskAll);
All := iYesNo(True);
oDnLn(1);
end;
faNewScan(All,Num);
end;
procedure faSetNewScanDate;
var D : String;
begin
oString(strFaAskNewScanDate);
D := iReadDate(User^.FileScan);
if not dtValidDate(D) then Exit;
User^.fileScan := D;
userSave(User^);
end;
procedure faEditFileDesc(var Fil : tFileRec);
var Head : ^tMsgHeaderRec; Txt : ^tMessage; X, nS : Word; pD : pFileDesc;
S : tFileDescLn; Ok : Boolean; eF : file of tFileDescLn;
begin
faLoadDesc(Fil,pD);
New(Txt);
New(Head);
FillChar(Head^,SizeOf(Head^),0);
Head^.Status := [];
with Head^.ToInfo do
begin
UserNum := 0;
Alias := 'None';
RealName := 'None';
Name := 'n/a';
UserNote := 'None';
end;
Head^.Subject := #10'Desc ['+Fil.Filename+']';
with Head^.FromInfo do
begin
UserNum := User^.Number;
Alias := User^.UserName;
RealName := User^.RealName;
Name := User^.UserName;
UserNote := User^.UserNote;
end;
Head^.Replies := 0;
Head^.Date := dtDateTimePacked;
FillChar(Txt^,SizeOf(Txt^),0);
for X := 1 to Fil.DescLns do Txt^[X] := pD^[X];
Head^.Size := Fil.DescLns;
Head^.sigPos := 0;
Head^.incFile := 0;
if Fil.DescLns > 0 then faKillDesc(Fil,pD);
Ok := fsEdit(Txt^,Head^,False,nil,nil,False,False);
if Ok then
begin
if Head^.Size > maxDescLns then Head^.Size := maxDescLns;
while (Head^.Size > 0) and (CleanUp(Txt^[Head^.Size]) = '') do Dec(Head^.Size);
nS := Head^.Size;
if nS = 0 then
begin
Fil.DescLns := 0;
Fil.DescPtr := 0;
end else
if nS > Fil.DescLns then
begin
Fil.DescLns := nS;
Assign(eF,Cfg^.pathData+fileFileDesc);
{$I-}
Reset(eF);
{$I+}
if ioResult <> 0 then {$I-} Rewrite(eF) {$I+} else
Seek(eF,FileSize(eF));
Fil.DescPtr := FilePos(eF);
for X := 1 to Fil.DescLns do
begin
S := Txt^[X];
Write(eF,S);
end;
Close(eF);
end else
if nS <= Fil.DescLns then
begin
Fil.DescLns := nS;
Assign(eF,Cfg^.pathData+fileFileDesc);
{$I-}
Reset(eF);
{$I+}
if ioResult = 0 then
begin
Seek(eF,Fil.DescPtr);
for X := 1 to Fil.DescLns do
begin
S := Txt^[X];
Write(eF,S);
end;
Close(eF);
end;
end;
end;
Dispose(Txt);
Dispose(Head);
end;
procedure faAskListFiles;
var S : String; All : Boolean; Idx : pFileScanIdx; Z : Word;
begin
if not faHasAccess then Exit;
oString(strFaAskListFiles);
skipOk := False;
S := iReadString('',inUpper,chFilename+['*','?'],'',12);
All := (S = '*.*') or (S = '') or (S = '*') or (S = '????????.???') or (S = '????????');
if All then faListFiles(False,nil,0) else
begin
if Pos('.',S) = 0 then S := S+'.';
New(Idx);
Z := faBuildScanIdx(Idx^,'L',S);
if Z > 0 then faListFiles(True,Idx,Z) else oStringLn(strFaNoMatchingFiles);
Dispose(Idx);
end;
end;
function faTestFile(Fn : String) : Boolean;
var Ans, ok : Boolean; tp, fnp : String; sl : Byte; old, new : LongInt;
{ yup ... GOTOs. I know, they suck, but tell me there isn't a better
way to do this ... :) }
label gInteg, gDecomp, gVirus, gAge, gDel, gAdd, gComment, gExternal, gDiz, gSauce, gDone;
procedure tfStat(S : String);
begin
if not sfGotoPos(3) then Exit;
oStr(strEnlarge(S,sl));
sl := Length(NoColor(S));
end;
begin
faTestFile := False;
if not fExists(Fn) then Exit;
faTestFile := True;
fn := UpStr(fn);
if ArchType(Fn) = 0 then Exit;
faTestFile := False;
fnp := strFilename(fn);
tp := fTempPath('A');
fCreateDir(tp,False);
fClearDir(tp);
oDnLn(1);
ok := True;
sl := 0;
sfStr[1] := fnp;
sfStr[2] := Stc(fFileSize(Fn));
Ans := sfShowTextFile(txFileTest,ftFileTest);
if not Ans then oStrLn('|U2-- |U1Processing |U3'+fnp+'|U2, |U3'+stc(fFileSize(Fn))+'|U1 bytes|U2 ...');
{ integrity check }
gInteg:
if Ans then sfLight(5) else oStr('|U2-- |U1File integrity check|U2 ... ');
if archTest(fn) then
begin
if Ans then sfOkLight(5) else oStrLn('|U1passed|U2.');
tfStat(strCode(mStr(strFaTestCRCok),1,fnp));
end else
begin
if Ans then sfFailLight(5) else oStrLn('|U1failed|U2.');
tfStat(strCode(mStr(strFaTestCRCfail),1,fnp));
Ok := False;
end;
if not Ok then goto gDone;
{ archive decompression }
gDecomp:
if Ans then sfLight(6) else oStr('|U2-- |U1Decompressing archive|U2 ... ');
if archUnzip(fn,'*.*',tp) then
begin
if Ans then sfOkLight(6) else oStrLn('|U1ok|U2.');
tfStat(strCode(mStr(strFaTestDecompOk),1,fnp));
end else
begin
if Ans then sfFailLight(6) else oStrLn('|U1error|U2.');
tfStat(strCode(mStr(strFaTestDecompFail),1,fnp));
Ok := False;
end;
if not Ok then goto gDone;
{ virus scan }
gVirus:
if Ans then sfLight(7) else oStr('|U2-- |U1Scanning for viruses|U2 ... ');
if archScan(tp+'*.*') then
begin
if Ans then sfOkLight(7) else oStrLn('|U1passed|U2.');
tfStat(strCode(mStr(strFaTestVirusOk),1,fnp));
end else
begin
if Ans then sfFailLight(7) else oStrLn('|U1failed|U2.');
tfStat(strCode(mStr(strFaTestVirusFail),1,fnp));
Ok := False;
end;
if not Ok then goto gDone;
{ age test }
gAge:
if Ans then sfLight(8) else oStr('|U2-- |U1Performing age test|U2 ... ');
fFindFile(tp+'*.*');
old := dtDateTimePacked;
new := 0;
while FileFound do
begin
if Search.Time < old then old := Search.Time;
if Search.Time > new then new := Search.Time;
fFindNext;
end;
if not Cfg^.strictAge then old := new;
if dtAge(dtDatePackedString(old)) <= Cfg^.maxFileAge then
begin
if Ans then sfOkLight(8) else oStrLn('|U1passed|U2.');
tfStat(strCode(strCode(mStr(strFaTestAgeOk),1,fnp),2,dtDatePackedString(old)));
end else
begin
if Ans then sfFailLight(8) else oStrLn('|U1failed|U2.');
tfStat(strCode(strCode(mStr(strFaTestAgeFail),1,fnp),2,dtDatePackedString(old)));
Ok := False;
end;
if not Ok then goto gDone;
{ delete crap files }
gDel:
if Ans then sfLight(9) else oStr('|U2-- |U1Removing useless files from archive|U2 ... ');
if (Cfg^.delFile <> '') and (fExists(Cfg^.pathData+Cfg^.delFile)) then
archDelete(fn,'@'+Cfg^.pathData+Cfg^.delFile);
if Ans then sfOkLight(9) else oStrLn('|U1done|U2.');
tfStat(strCode(mStr(strFaTestFilesRemoved),1,fnp));
{ add new files }
gAdd:
if Ans then sfLight(10) else oStr('|U2-- |U1Adding BBS files|U2 ... ');
if (Cfg^.addFile <> '') and (fExists(Cfg^.pathData+Cfg^.addFile)) then
archZip(fn,'@'+Cfg^.pathData+Cfg^.addFile,0);
if Ans then sfOkLight(10) else oStrLn('|U1done|U2.');
tfStat(strCode(mStr(strFaTestFilesAdded),1,fnp));
{ add comment }
gComment:
if Ans then sfLight(11) else oStr('|U2-- |U1Adding archive comment|U2 ... ');
if (Cfg^.comFile <> '') and (fExists(Cfg^.pathData+Cfg^.comFile)) then
archComment(fn,Cfg^.pathData+cfg^.comFile);
if Ans then sfOkLight(11) else oStrLn('|U1done|U2.');
tfStat(strCode(mStr(strFaTestCommented),1,fnp));
{ external maintenence }
gExternal:
if Ans then sfLight(12) else oStr('|U2-- |U1External maintenence|U2 ... ');
if (Cfg^.extMaint) and (fExists(Cfg^.pathData+fileExtMaint)) then
fShellDos(Cfg^.pathData+fileExtMaint+' '+Fn,Cfg^.ArchiverSwap,False,False);
if Ans then sfOkLight(12) else oStrLn('|U1done|U2.');
tfStat(strCode(mStr(strFaTestExternal),1,fnp));
gDiz:
if Ans then sfLight(13) else oStr('|U2-- |U1Searching for description|U2 ... ');
fClearDir(tp);
if (Cfg^.importDescs) and (archUnzip(fn,Cfg^.fileDesc1+' '+Cfg^.fileDesc2,Tp)) then
begin
if Ans then sfOkLight(13) else oStrLn('|U1found|U2.');
tfStat(strCode(mStr(strFaTestDescFound),1,fnp));
end else
begin
if Ans then sfOkLight(13) else oStrLn('|U1none found|U2.');
tfStat(strCode(mStr(strFaTestNoDesc),1,fnp));
end;
gSauce:
if Ans then sfLight(14) else oStr('|U2-- |U1Checking for sauce description|U2 ... ');
if (Cfg^.importDescs) and (sauceDiz(fn,tp+cfg^.fileDesc1)) then
begin
if Ans then sfOkLight(14) else oStrLn('|U1found|U2.');
tfStat(strCode(mStr(strFaTestDescFound),1,fnp));
end else
begin
if Ans then sfOkLight(14) else oStrLn('|U1none found|U2.');
tfStat(strCode(mStr(strFaTestNoSauce),1,fnp));
end;
gDone:
if Ok then
begin
tfStat(strCode(mStr(strFaTestPassed),1,fnp));
faTestFile := True;
end else
begin
tfStat(strCode(mStr(strFaTestFailed),1,fnp));
faTestFile := False;
end;
sfGotoPos(maxPos);
end;
function faUploadSearch(var Fn : String) : Boolean;
var F : file; A, cA : Word; D : tFileRec; Found : Boolean;
begin
faUploadSearch := True;
if Cfg^.ulSearch = 1 then Exit;
if Cfg^.ulSearch = 2 then
begin
faUploadSearch := faFileExists(fn);
Exit;
end;
A := User^.curFileArea;
Found := False;
cA := 0;
oString(strFaSearching);
fConfAll := Cfg^.ulSearch = 4;
repeat
Inc(cA);
User^.curFileArea := cA;
if (faLoad) and (faHasAccess) and (fArea^.Password = '') then
begin
Assign(F,Cfg^.pathData+fArea^.Filename+extFileDir);
{$I-}
Reset(F,SizeOf(tFileRec));
{$I+}
if ioResult = 0 then
begin
while (not Found) and (not Eof(F)) do
begin
BlockRead(F,D,1);
Found := faCloseEnough(UpStr(Fn),D.Filename);
if Found then Fn := D.Filename;
end;
Close(F);
end;
end;
until (Found) or (cA >= numFileArea);
fConfAll := False;
faUploadSearch := Found;
User^.curFileArea := A;
faLoad;
oBack(oWhereX);
end;
procedure faUpload;
const maxBatchUL = 60;
var batchUL : array[1..maxBatchUL] of String[12]; fn : String; num, z, l : Byte;
Ok, bl : Boolean; tp, rp, dp : String; numUL : Word; F : tFileRec; pD : pFileDesc;
cmd : array[1..2] of String; sr : SearchRec;
function ulBatchNum(fn : String) : Byte;
var x : Byte;
begin
for x := 1 to num do if fn = batchUL[x] then
begin
ulBatchNum := x;
Exit;
end;
ulBatchNum := 0;
end;
procedure ulGetDesc(z : Byte);
var T : Text; S : String;
begin
oDnLn(1);
Assign(T,tp+'FILEDESC.'+St(z));
{$I-}
Rewrite(T);
{$I+}
oStrLn(strCode(mStr(strFaULdescribe),1,batchUL[z]));
l := 0;
repeat
Inc(l);
oStr(strCode(mStr(strFaULdescLine),1,St(l)));
S := iReadString('',inNormal,chNormal,rsNoCR,maxDescLen);
if S <> '' then
begin
WriteLn(T,S);
oDnLn(1);
end else
begin
oMoveLeft(80);
oClrEol;
end;
until (HangUp) or (l >= maxDescLns) or (S = '');
Close(T);
if HangUp then {$I-} Erase(T); {$I+}
end;
begin
oDnLn(1);
if not acsOk(fArea^.acsUL) then
begin
oStringLn(strFaULnoAccess);
Exit;
end;
if Cfg^.allowBlind then
begin
oString(strFaULaskBlind);
bl := iYesNo(False);
oDnLn(1);
end else bl := False;
tp := fTempPath('D');
fClearDir(tp);
num := 0;
if not bl then
begin
oStrLn(strCode(mStr(strFaULenterFiles),1,St(maxBatchUL)));
oStringLn(strFaULenterToEnd);
oDnLn(1);
repeat
Inc(num);
repeat
oStr(strCode(mStr(strFaULenterFilename),1,St(num)));
fn := iReadString('',inUpper,chFilename,'',12);
if (fn <> '') and (ulBatchNum(fn) > 0) then ok := False else
if (fn <> '') and (faUploadSearch(fn)) then
begin
oStrLn(strCode(mStr(strFaULfileExists),1,fn));
Ok := False;
end else ok := True;
until (HangUp) or (ok);
batchUL[num] := fn;
until (HangUp) or (fn = '') or (num >= maxBatchUL);
Dec(num);
if num = 0 then Exit;
oDnLn(1);
cmd[1] := 'Now';
cmd[2] := 'Later';
oString(strFaULaskDescNow);
if iXprompt(cmd,2,1) = 1 then
for z := 1 to num do ulGetDesc(z);
end;
rp := fTempPath('X');
fClearDir(rp);
fCreateDir(rp,False);
if not xferReceive('',[protActive,protBatch]) then
begin
logWrite('Upload aborted');
Exit;
end;
fCreateDir(rp,False);
oDnLn(1);
numUL := 0;
FindFirst(rp+'*.*',0,sr);
while dosError = 0 do
begin
z := ulBatchNum(sr.Name);
fn := sr.Name;
if (num < maxBatchUL) and (z = 0) and (Cfg^.allowBlind) then
begin
oStrLn(strCode(mStr(strFaULfileFound),1,fn));
if faUploadSearch(fn) then oStrLn(strCode(mStr(strFaULfileExists),1,fn)) else
begin
Inc(num);
batchUL[num] := fn;
z := num;
end;
end;
if z > 0 then
begin
if faTestFile(rp+sr.Name) then
begin
dp := fTempPath('A');
if not ((fExists(dp+Cfg^.fileDesc1)) and (fCopyFile(dp+Cfg^.fileDesc1,tp+'FILEDESC.'+St(z)))) then
if not ((fExists(dp+Cfg^.fileDesc2)) and (fCopyFile(dp+Cfg^.fileDesc2,tp+'FILEDESC.'+St(z)))) then
if not fExists(tp+'FILEDESC.'+St(z)) then ulGetDesc(z);
oDnLn(1);
oStrLn(strCode(mStr(strFaULaddingFile),1,sr.Name));
with F do
begin
Filename := sr.Name;
Downloads := 0;
Size := sr.Size;
Uploader := User^.UserName;
Date := dtDatePackedString(sr.Time);
ulDate := dtDateString;
if fExists(tp+'FILEDESC.'+St(z)) then
DescLns := faLoadDescFile(tp+'FILEDESC.'+St(z),pD) else
DescLns := 0;
Valid := Cfg^.autoValidate;
filePts := Size div (Cfg^.kbPerFilePoint*1024);
faAddFile(F,pD^);
faKillDesc(F,pD);
if not fMoveFile(rp+sr.Name,fArea^.Path+sr.Name) then
logWrite('-Error moving file: '+rp+sr.Name+' to '+fArea^.Path);
Inc(Stat^.Uploads);
Inc(Stat^.UploadKb,Size div 1024);
Inc(His^.Uploads);
Inc(His^.UploadKb,Size div 1024);
if Valid then
begin
Inc(User^.Uploads);
Inc(User^.UploadKb,Size div 1024);
if (Cfg^.useFilePoints) and (Cfg^.filePtsPer > 0) then
begin
Inc(User^.filePts,filePts*Cfg^.filePtsPer div 100);
end;
end;
end;
oStrLn(strCode(strCode(mStr(strFaULfileAdded),1,sr.Name),2,St(F.DescLns)));
end;
end;
FindNext(sr);
end;
statSave;
hisSave;
userSave(User^);
oDnLn(1);
end;
procedure faSearchFile(fs : Boolean);
var Fn : String; D : tFileRec; sA, eA, cA, oA, N : Word;
all, conf, any, ok : Boolean; idx : pFileScanIdx;
begin
oDnLn(1);
oA := User^.curFileArea;
if fs then
begin
oString(strFaSearchAskFile);
Fn := iReadString('',inUpper,chFilename+['*','?'],'',12);
if (fn <> '') and (Pos('.',fn) = 0) then fn := fn+'.*';
end else
begin
oString(strFaSearchAskDesc);
Fn := upStr(iReadString('',inNormal,chNormal,'',50));
end;
if Fn = '' then Exit;
oString(strFaSearchAskAll);
all := iYesNo(True);
if all then
begin
oString(strFaSearchAskConfs);
conf := iYesNo(True);
end else conf := False;
if all then
begin
sA := 1;
eA := numFileArea;
end else
begin
sA := oA;
eA := oA;
end;
any := False;
if conf then fConfAll := True;
New(Idx);
ok := True;
for cA := sA to eA do if ok then
begin
User^.curFileArea := cA;
if (faLoad) and (faHasAccess) and (fArea^.Password = '') then
begin
oStr(strCode(mStr(strFaSearchArea),1,fArea^.Name));
if fs then n := faBuildScanIdx(idx^,'L',fn) else
n := faBuildScanIdx(idx^,'D',fn);
oDnLn(1);
if n > 0 then
begin
ok := (not HangUp) and (faListFiles(True,idx,n)) and (not (iKeypressed and (iReadKey = ' ')));
any := True;
end;
end;
end;
fConfAll := False;
Dispose(Idx);
User^.curFileArea := oA;
faLoad;
if not any then oStringLn(strFaSearchNone);
end;
end. |
2 { (c) 2002, Tom Verhoeff, TUE }
3 { 2006, Etienne van Delden, TUE}
4 { Programma om te controleren of het ingegeven ISBN een geldig ISBN is. }
5
6 var
7 input: String; // string om ISBN in te lezen
8
9 const
10 AantalCijfersInISBN = 10; // aantal ISBN-cijfers in een ISBN
11
12 type
13 CijferWaarde = 0 .. 10; // verz. waarden van ISBN-cijfers
14
15 function charToCijferWaarde ( const c: Char ): CijferWaarde;
16 // converteer karakter dat ISBN-cijfer voorstelt naar zijn waarde
17 // pre: c in [ '0' .. '9', 'X' ]
18 // ret: 0 .. 9, of 10 al naar gelang c = '0' .. '9', of 'X'
19
20 begin
21 if c in [ '0' .. '9' ] then
22 Result := ord ( c ) - ord ( '0' )
23 else { c = 'X' }
24 Result := 10
25 end; // end charToCijferWaarde
26
27 function isGeldigISBN ( const code: String ): Boolean;
28 // controleer of code een geldig ISBN is }
29 // pre: code bestaat uit precies 10 ISBN-cijfers
30 // ret: of code een geldig ISBN is, d.w.z. of
31 // (som k: 1 <= k <= 10: (11-k) code_k) een 11-voud is
32
33 var
34 s: Integer; // gewogen cijfer-som
35 i: Integer; // hulp var: teller
36
37 begin
38 s := 0; // int. var s: cijfer som
39 i := 1; // int. hulp var i:teller
40
41 // controleer of het i-de getal een X is en vervang met 10
42 // vermenigvuldig het i-de getal met i en tel dit op bij de vorige uitkomst
43
44 for i := Length( code ) downto 1 do
45 begin
46 s := s + charToCijferWaarde( code[ i ] ) * i
47 end;
48
49 Result := ( s mod 11 = 0 )
50 end; // end isGeldigISBN
51
52 procedure verwerkRegel ( const regel: String );
53 // pre: regel bevat een code met precies 10 ISBN-cijfers
54 // post: regel is geschreven,
55 // met erachter de tekst ' is een geldig ISBN' of ' is niet een geldig ISBN'
56 // al naar gelang regel een geldig ISBN bevat of niet
57
58 begin
59 write ( regel, ' is ' );
60
61 if isGeldigISBN( regel ) <> True then
62 begin
63 write( 'niet ' )
64 end;
65
66 write( 'een geldig ISBN');
67 writeln
68 end; // end verwerkRegel
69
70 begin // het uiteindelijke programma
71 readln ( input );
72
73 while input <> '.' do begin // zolang het einde niet is bereikt
74 verwerkRegel ( input );
75 readln ( input )
76 end; // end while
77
78 end. |
{*****************************************************************************
The Class tree team (see file NOTICE.txt) licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. A copy of this licence is found in the root directory of
this project in the file LICENCE.txt or alternatively 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 MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
tb_Generate: TToolButton;
pc_Main: TPageControl;
ts_Tree: TTabSheet;
ts_TextExport: TTabSheet;
TreeView: TTreeView;
MemoExport: TMemo;
tb_Export: TToolButton;
tb_CopyToClipboard: TToolButton;
procedure tb_GenerateClick(Sender: TObject);
procedure tb_ExportClick(Sender: TObject);
procedure tb_CopyToClipboardClick(Sender: TObject);
private
procedure FillTreeClasses(TreeViewClasses:TTreeView);
procedure ExportFromNode(Node: TTreeNode; Level: UInt16; OutputList: TStringList);
procedure CleanupExport(OutputList: TStringList);
public
end;
var
Form1: TForm1;
implementation
uses
Rtti;
{$R *.dfm}
procedure TForm1.FillTreeClasses(TreeViewClasses:TTreeView);
//function to get the node wich match with the TRttiType
function FindTRttiType(lType:TRttiType):TTreeNode;
var
i : integer;
Node : TTreeNode;
begin
Result:=nil;
for i:=0 to TreeViewClasses.Items.Count-1 do
begin
Node:=TreeViewClasses.Items.Item[i];
if Assigned(Node.Data) then
if lType=TRttiType(Node.Data) then
begin
Result:=Node;
exit;
end;
end;
end;
//function to get the node wich not match with the BaseType of the Parent
function FindFirstTRttiTypeOrphan:TTreeNode;
var
i : integer;
Node : TTreeNode;
lType : TRttiType;
begin
Result:=nil;
for i:=0 to TreeViewClasses.Items.Count-1 do
begin
Node :=TreeViewClasses.Items[i];
lType:=TRttiType(Node.Data);
if not Assigned(lType.BaseType) then Continue;
if lType.BaseType<>TRttiType(Node.Parent.Data) then
begin
Result:=Node;
break;
end;
end;
end;
var
ctx : TRttiContext;
TypeList : TArray<TRttiType>;
lType : TRttiType;
PNode : TTreeNode;
Node : TTreeNode;
begin
ctx := TRttiContext.Create;
TreeViewClasses.Items.BeginUpdate;
try
TreeViewClasses.Items.Clear;
//Add Root, TObject
lType:=ctx.GetType(TObject);
Node:=TreeViewClasses.Items.AddObject(nil,lType.Name,lType);
//Fill the tree with all the classes
TypeList:= ctx.GetTypes;
for lType in TypeList do
if lType.IsInstance then
begin
if Assigned(lType.BaseType) then
TreeViewClasses.Items.AddChildObject(Node,lType.Name,lType);
end;
//Sort the classes
Repeat
Node:=FindFirstTRttiTypeOrphan;
if Node=nil then break;
//get the location of the node containing the BaseType
PNode:=FindTRttiType(TRttiType(Node.Data).BaseType);
//Move the node to the new location
Node.MoveTo(PNode,naAddChild);
Until 1<>1;
finally
TreeViewClasses.Items.EndUpdate;
ctx.Free;
end;
end;
procedure TForm1.tb_GenerateClick(Sender: TObject);
begin
FillTreeClasses(TreeView);
TreeView.FullExpand;
TreeView.Select(TreeView.Items.GetFirstNode);
end;
procedure TForm1.tb_CopyToClipboardClick(Sender: TObject);
begin
MemoExport.SelectAll;
MemoExport.CopyToClipboard;
MemoExport.ClearSelection;
end;
procedure TForm1.tb_ExportClick(Sender: TObject);
var
sl : TStringList;
begin
if Assigned(TreeView.Selected) then
begin
sl := TStringList.Create;
try
MemoExport.Lines.Clear;
ExportFromNode(TreeView.Selected, 0, sl);
CleanupExport(sl);
MemoExport.Lines.BeginUpdate;
MemoExport.Lines.Assign(sl);
finally
MemoExport.Lines.EndUpdate;
sl.Free;
end;
end;
end;
procedure TForm1.ExportFromNode(Node: TTreeNode; Level: UInt16; OutputList: TStringList);
var
s : string;
Child : TTreeNode;
Sibling : TTreeNode;
Sibling2 : TTreeNode;
begin
Child := Node.getFirstChild;
Sibling := Node.getNextSibling;
Sibling2 := nil;
if Assigned(Sibling) then
Sibling2 := Sibling.getNextSibling;
for var i := 0 to Level-1 do
s := s + '│ ';
if (not Assigned(Sibling)) and (not Assigned(Sibling2)) then
begin
if (OutputList.Count > 0) and (Pos('└', OutputList[OutputList.Count-1]) <> 0) then
begin
Delete(s, 1, 2);
s := s + ' ';
end;
OutputList.Add(s + '└─' + Node.Text);
end
else
OutputList.Add(s + '├─' + Node.Text);
if Assigned(Child) then
ExportFromNode(Child, Level + 1, OutputList);
if Assigned(Sibling) then
ExportFromNode(Sibling, Level, OutputList);
end;
procedure TForm1.CleanupExport(OutputList: TStringList);
var
s: string;
begin
for var Line := 0 to OutputList.Count - 1 do
begin
for var i := 1 to Length(OutputList[Line]) do
begin
// check whether there's a preceeding └ in that column
if (OutputList[Line][i] = '│') and (Line > 0) then
begin
if (OutputList[Line - 1][i] = '└') or
(OutputList[Line - 1][i] = ' ') then
begin
s := OutputList[Line];
s[i] := ' ';
OutputList[Line] := s;
end;
end
else
if (OutputList[Line][i] = ' ') and (Line > 0) and
(OutputList[Line - 1][i] = '│') then
begin
s := OutputList[Line];
s[i] := '│';
OutputList[Line] := s;
end;
end;
end;
end;
end.
|
unit uMoney;
interface
uses
System.SysUtils;
type
TMoney = record
strict private
FMoney : integer;
FCents : array[0..3] of integer;
FFormatSettings : TFormatSettings;
procedure FillCentsArray;
function CentFactor: integer;
function GetMoney: Currency;
private
function GetIntMoney: integer;
//procedure SetMoney(const Value: Currency);
public
constructor Create(const Money : Currency); overload;
constructor Create(const IntMoney : integer); overload;
class operator Add(const a, b : TMoney): TMoney;
class operator Subtract(const a, b : TMoney): TMoney;
class operator Multiply(const a, b : TMoney): TMoney;
class operator Divide(const a, b : TMoney): TMoney;
property Money : Currency read GetMoney{ write SetMoney};
property IntMoney : integer read GetIntMoney;
end;
implementation
{ TMoney }
class operator TMoney.Add(const a, b: TMoney): TMoney;
begin
result := TMoney.Create(a.IntMoney + b.IntMoney);
end;
function TMoney.CentFactor: integer;
begin
result := FCents[FFormatSettings.CurrencyDecimals];
end;
constructor TMoney.Create(const IntMoney: integer);
begin
FillCentsArray;
FFormatSettings := TFormatSettings.Create;
FMoney := IntMoney;
end;
class operator TMoney.Divide(const a, b: TMoney): TMoney;
begin
end;
constructor TMoney.Create(const Money : Currency);
begin
FillCentsArray;
FFormatSettings := TFormatSettings.Create;
FMoney := trunc(Money * CentFactor);
end;
procedure TMoney.FillCentsArray;
begin
FCents[0] := 1;
FCents[1] := 10;
FCents[2] := 100;
FCents[3] := 1000;
end;
function TMoney.GetIntMoney: integer;
begin
result := FMoney;
end;
function TMoney.GetMoney: Currency;
begin
result := FMoney / CentFactor;
end;
class operator TMoney.Multiply(const a, b: TMoney): TMoney;
begin
result := TMoney.Create(Trunc((a.IntMoney * b.IntMoney) / CentFactor));
end;
{procedure TMoney.SetMoney(const Value: Currency);
begin
FMoney := trunc(Value * CentFactor);
end; }
class operator TMoney.Subtract(const a, b: TMoney): TMoney;
begin
result.Create(a.FMoney - b.FMoney);
end;
end.
|
unit IdCoderIMF;
interface
uses
Classes,
IdCoder,
SysUtils;
const
ConstIMFStart = 0;
ConstIMFMessageStart = 1;
ConstIMFBoundaryEnd = 2;
ConstContentType = 'content-type';
ConstContentTransferEncoding = 'content-transfer-encoding';
ConstContentDisposition = 'content-disposition';
ConstContentMD5 = 'content-md5';
ConstBoundary = 'boundary';
ConstFileName = 'filename';
ConstName = 'name';
type
TIdIMFDecoder = class(TIdCoder)
protected
FState: Byte;
FContentType, FContentTransferEncoding: string;
FDefaultContentType, FDefaultContentTransferEncoding: string;
FDefaultContentFound, FDefaultContentTypeFound,
FDefaultContentTransferEncodingFound: Boolean;
FLastContentType, FLastContentTransferEncoding: string;
FCurHeader, FTrueString: string;
FMIMEBoundary: TStringList;
FInternalDecoder: TIdCoder;
procedure CreateDecoder; virtual;
procedure Coder; override;
procedure CompleteCoding; override;
procedure IMFStart; virtual;
procedure IMFMessageStart; virtual;
procedure IMFBoundaryEnd; virtual;
procedure ProcessHeader; virtual;
procedure RenewCoder; virtual;
procedure WriteOutput(Sender: TComponent; const sOut: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Reset; override;
end;
TIdIMFUUDecoder = class(TIdIMFDecoder)
protected
procedure CreateDecoder; override;
procedure RenewCoder; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses
IdGlobal;
constructor TIdIMFDecoder.Create;
begin
FMIMEBoundary := TStringList.Create;
inherited Create(AOwner);
FState := ConstIMFStart;
FContentType := '';
FContentTransferEncoding := '';
FDefaultContentType := '';
fDefaultContentTransferEncoding := '8bit';
FDefaultContentFound := False;
FDefaultContentTypeFound := False;
FDefaultContentTransferEncodingFound := False;
FLastContentType := '';
FLastContentTransferEncoding := '';
FCurHeader := '';
FTrueString := '';
fAddCRLF := False;
CreateDecoder;
FInternalDecoder.UseEvent := True;
FInternalDecoder.OnCodedData := WriteOutput;
end;
destructor TIdIMFDecoder.Destroy;
begin
FMIMEBoundary.Free;
inherited Destroy;
end;
procedure TIdIMFDecoder.CreateDecoder;
var
CItem: TIdCoderItem;
begin
CItem := CoderCollective.GetCoderType('',
'7bit', CT_REALISATION);
FInternalDecoder := CItem.IdCoderClass.Create(Self);
end;
procedure TIdIMFDecoder.Reset;
begin
inherited;
FState := ConstIMFStart;
end;
procedure TIdIMFDecoder.RenewCoder;
var
CItem: TIdCoderItem;
exactType, exactEnc, temp: string;
begin
temp := FContentType;
exactType := Fetch(temp, ';');
temp := FContentTransferEncoding;
exactEnc := Fetch(temp, ';');
if (FContentType <> FLastContentType) or
(FContentTransferEncoding <> FLastContentTransferEncoding) then
begin
FInternalDecoder.Free;
CItem := CoderCollective.GetCoderType(exactType, exactEnc, CT_REALISATION);
FInternalDecoder := CItem.IdCoderClass.Create(Self);
FInternalDecoder.UseEvent := True;
FInternalDecoder.OnCodedData := WriteOutput;
end;
FLastContentType := exactType;
FLastContentTransferEncoding := exactEnc;
end;
procedure TIdIMFDecoder.Coder;
begin
case FState of
ConstIMFStart: IMFStart;
ConstIMFMessageStart: IMFMessageStart;
ConstIMFBoundaryEnd: IMFBoundaryEnd;
end;
end;
procedure TIdIMFDecoder.CompleteCoding;
begin
fInCompletion := True;
while FCBufferedData > 0 do
begin
InternSetBufferSize(FCBufferedData);
FCBufferedData := FCBufferSize;
Coder;
end;
FInternalDecoder.CompletedInput;
OutputNotification(CN_IMF_DATA_END, '');
FCBufferedData := 0;
end;
procedure TIdIMFDecoder.IMFStart;
var
i: LongWord;
s: string;
processLine: Boolean;
begin
if FCBufferedData = 0 then Exit;
s := Copy(FCBuffer, 1, FCBufferedData);
i := IndyPos(CR, s);
while i > 0 do
begin
FTrueString := FTrueString + Copy(s, 1, i);
if (s[1] = ' ') or (s[1] = #9) then
begin
ProcessLine := True;
while ProcessLine do
begin
if (s[1] = ' ') or (s[1] = #9) then
begin
System.Delete(s, 1, 1);
end
else
begin
ProcessLine := False;
end;
end;
i := Length(FCurHeader);
if i > 0 then
begin
if not ((FCurHeader[i] = ' ') or (FCurHeader[i] = #9)) then
begin
FCurHeader := FCurHeader + ' ';
end;
end;
i := IndyPos(CR, s);
end;
FCurHeader := FCurHeader + Copy(s, 1, i - 1);
s := Copy(s, i + 1, length(s));
if length(s) > 0 then
begin
if s[1] = LF then
begin
s := Copy(s, 2, length(s));
FTrueString := FTrueString + LF;
end;
end;
FCurHeader := Trim(FCurHeader);
if Length(FCurHeader) > 0 then
begin
if Length(s) > 0 then
begin
if (s[1] = ' ') or (s[1] = #9) then
begin
ProcessLine := False;
end
else
begin
ProcessLine := True;
end;
end
else
begin
ProcessLine := False;
end;
if ProcessLine then
begin
ProcessHeader;
end;
end
else
begin
FState := ConstIMFMessageStart;
OutputString(FTrueString);
FTrueString := '';
Break;
end;
i := IndyPos(CR, s);
end;
FDefaultContentFound := True;
if FState = ConstIMFStart then
begin
if fInCompletion then
begin
OutputString(s);
s := '';
end
else
begin
FCurHeader := FCurHeader + s;
end;
end;
FCBufferedData := LongWord(length(s));
System.Move(s[1], FCBuffer[1], FCBufferedData);
if FState = ConstIMFMessageStart then
begin
OutputString(CR + LF);
OutputNotification(CN_IMF_BODY_START, '');
RenewCoder;
IMFMessageStart;
end;
end;
procedure TIdIMFDecoder.ProcessHeader;
var
paramWork: string;
i: LongWord;
function GetQuotedPair(const AString: string): string;
var
li: LongWord;
ls: string;
testSpace: Boolean;
begin
if length(AString) = 0 then
begin
result := '';
end
else
begin
ls := AString;
if ls[1] = '"' then
begin
ls := Copy(ls, 2, length(ls));
li := IndyPos('"', ls);
if li > 0 then
begin
result := Copy(ls, 1, li - 1);
testSpace := False;
end
else
begin
testSpace := True;
end;
end
else
begin
testSpace := True;
end;
if testSpace then
begin
result := Fetch(ls, ' ');
end;
end;
end;
begin
OutputNotification(CN_IMF_HEAD_VALUE, FCurHeader);
case FCurHeader[1] of
'c', 'C':
begin
if lowercase(Copy(FCurHeader, 1, length(ConstContentTransferEncoding)))
= ConstContentTransferEncoding then
begin
Fetch(FCurHeader, ':');
FContentTransferEncoding := Trim(FCurHeader);
if not FDefaultContentFound then
begin
FDefaultContentTransferEncodingFound := True;
fDefaultContentTransferEncoding := FContentTransferEncoding;
end;
end
else
if lowercase(Copy(FCurHeader, 1, Length(ConstContentType)))
= ConstContentType then
begin
Fetch(FCurHeader, ':');
FContentType := Trim(FCurHeader);
FContentTransferEncoding := '';
if not FDefaultContentFound then
begin
FDefaultContentTypeFound := True;
FDefaultContentType := FContentType;
end;
i := IndyPos(ConstBoundary + '=', LowerCase(FContentType));
if i > 0 then
begin
paramWork := Copy(FContentType, i + 9, length(FContentType));
i := IndyPos('"', paramWork);
if i > 0 then
begin
paramWork := Copy(paramWork, i + 1, length(paramWork));
end;
i := IndyPos('"', paramWork);
if i > 0 then
begin
paramWork := Copy(paramWork, 1, i - 1);
end;
FMIMEBoundary.Insert(0, paramWork);
end;
i := IndyPos(ConstName + '=', LowerCase(FContentType));
if i > 0 then
begin
paramWork := Copy(FContentType, i + 1 + LongWord(length(ConstName)),
length(FContentType));
FFileName := GetQuotedPair(paramWork);
OutputNotification(CN_IMF_NEW_FILENAME, FFileName);
FTakesFileName := True;
end;
end
else
if lowercase(Copy(FCurHeader, 1, Length(ConstContentDisposition)))
= ConstContentDisposition then
begin
Fetch(FCurHeader, ':');
i := IndyPos(ConstFileName + '=', LowerCase(FCurHeader));
if i > 0 then
begin
FCurHeader := Copy(FCurHeader, i + LongWord(length(ConstFileName)) +
1,
length(FCurHeader));
FFileName := GetQuotedPair(FCurHeader);
OutputNotification(CN_IMF_NEW_FILENAME, FFileName);
FTakesFileName := True;
end;
end
else
begin
OutputString(FTrueString);
FTrueString := '';
end;
end;
else
begin
OutputString(FTrueString);
FTrueString := '';
end;
end;
FCurHeader := '';
end;
procedure TIdIMFDecoder.IMFMessageStart;
var
i, bPos, mPos, mIndicator: LongWord;
s, mData, mTemp: string;
begin
if FCBufferedData = 0 then Exit;
s := Copy(FCBuffer, 1, FCBufferedData);
if FMIMEBoundary.Count > 0 then
begin
mPos := LongWord(-1);
mIndicator := LongWord(-1);
for i := 0 to FMIMEBoundary.Count - 1 do
begin
bPos := IndyPos(FMIMEBoundary[i], s);
if (bPos < mPos) and (bPos <> 0) then
begin
mPos := bPos;
mIndicator := i;
end;
end;
if mIndicator <> LongWord(-1) then
begin
mData := Copy(s, 1, mPos - 1);
i := Length(mData);
if i >= 4 then
begin
mTemp := Copy(mData, length(mData) - 3, 4);
if mTemp = CR + LF + '--' then
begin
mData := Copy(mData, 1, i - 4);
i := 4;
end
else
begin
i := 5;
end;
end
else
if i >= 2 then
begin
if (mData[i] = '-') and (mData[i - 1] = '-') then
begin
mData := Copy(mData, 1, i - 2);
end;
end;
s := Copy(s, length(mData) + 1, length(s));
if length(mData) > 0 then
begin
FInternalDecoder.CodeString(mData);
FInternalDecoder.CompletedInput;
FInternalDecoder.Reset;
end
else
if (FInternalDecoder.BytesIn.L > 0) or
(FInternalDecoder.BytesIn.H > 0) then
begin
FInternalDecoder.CompletedInput;
FInternalDecoder.Reset;
end;
OutputNotification(CN_IMF_NEW_MULTIPART, FMIMEBoundary[mIndicator]);
if i >= 4 then
begin
FCurHeader := CR + LF + '--' + FMIMEBoundary[mIndicator];
end
else
if i >= 2 then
begin
FCurHeader := '--' + FMIMEBoundary[mIndicator];
end
else
begin
end;
mPos := IndyPos(FMIMEBoundary[mIndicator], s);
s := Copy(s, mPos + LongWord(length(FMIMEBoundary[mIndicator])),
length(s));
FCBufferedData := length(s);
System.Move(s[1], FCBuffer[1], FCBufferedData);
FState := ConstIMFBoundaryEnd;
end
else
begin
FInternalDecoder.CodeString(s);
FCBufferedData := 0;
end;
end
else
begin
FInternalDecoder.CodeString(s);
FCBufferedData := 0;
end;
end;
procedure TIdIMFDecoder.IMFBoundaryEnd;
var
s: string;
begin
if FCBufferedData = 0 then Exit;
if FCBufferSize < 4 then
begin
InternSetBufferSize(5);
end
else
if (FCBufferedData < 4) and fInCompletion then
begin
case FCBufferedData of
1:
begin
end;
2:
begin
end;
3:
begin
end;
end;
FCBufferedData := 0;
end
else
if FCBufferedData >= 4 then
begin
s := Copy(FCBuffer, 1, FCBufferedData);
if (s[1] = '-') and (s[2] = '-') then
begin
OutputNotification(CN_IMF_END_MULTIPART, '');
FCurHeader := FCurHeader + '--';
s := Copy(s, 3, length(s));
end;
if s[1] = '-' then
begin
FCurHeader := FCurHeader + s[1];
s := Copy(s, 2, length(s));
end;
if s[1] = CR then
begin
FCurHeader := FCurHeader + s[1];
s := Copy(s, 2, length(s));
end;
if s[1] = LF then
begin
FCurHeader := FCurHeader + s[1];
s := Copy(s, 2, length(s));
end;
if length(FCurHeader) > 0 then
begin
OutputString(FCurHeader);
FCurHeader := '';
end;
FCBufferedData := length(s);
System.Move(s[1], FCBuffer[1], FCBufferedData);
FState := ConstIMFStart;
end;
end;
procedure TIdIMFDecoder.WriteOutput;
begin
OutputString(sOut);
end;
constructor TIdIMFUUDecoder.Create;
begin
inherited Create(AOwner);
end;
destructor TIdIMFUUDecoder.Destroy;
begin
inherited;
end;
procedure TIdIMFUUDecoder.RenewCoder;
begin
end;
procedure TIdIMFUUDecoder.CreateDecoder;
var
CItem: TIdCoderItem;
begin
CItem := CoderCollective.GetCoderType('',
'x-uu', CT_REALISATION);
if CItem = nil then
begin
inherited;
end
else
begin
FInternalDecoder := CItem.IdCoderClass.Create(Self);
end;
end;
initialization
RegisterCoderClass(TIdCoder, CT_REALISATION, CP_FALLBACK,
'', '7bit');
RegisterCoderClass(TIdCoder, CT_REALISATION, CP_FALLBACK,
'', '8bit');
RegisterCoderClass(TIdCoder, CT_REALISATION, CP_FALLBACK,
'', 'binary');
RegisterCoderClass(TIdIMFDecoder, CT_REALISATION, CP_IMF or CP_STANDARD,
'text/', '8bit');
end.
|
unit uQuestionList;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.ListBox, FMX.Controls.Presentation, System.Rtti, FMX.Grid.Style, FMX.Grid,
System.Actions, FMX.ActnList, FMX.ScrollBox, uSortList, xSortInfo, xSortControl,
xQuestionInfo, uQuestionInfo, xFunction;
type
TfQuestionList = class(TForm)
pnl1: TPanel;
cbbSortList: TComboBox;
btnSortManage: TButton;
lbl1: TLabel;
strngrdQuestionList: TStringGrid;
actnlstList: TActionList;
actAdd: TAction;
actDel: TAction;
actUpdate: TAction;
actSearch: TAction;
actSearchAll: TAction;
actClearAll: TAction;
pnl2: TPanel;
btnAdd: TButton;
btnDel: TButton;
btnEdit: TButton;
btn3: TButton;
pnl3: TPanel;
btnOK: TButton;
btnCancel: TButton;
strngclmn1: TStringColumn;
strngclmn2: TStringColumn;
strngclmn3: TStringColumn;
strngclmn4: TStringColumn;
actLoadSort: TAction;
procedure actLoadSortExecute(Sender: TObject);
procedure btnSortManageClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actAddExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actDelExecute(Sender: TObject);
procedure actUpdateExecute(Sender: TObject);
procedure actClearAllExecute(Sender: TObject);
procedure cbbSortListChange(Sender: TObject);
private
{ Private declarations }
protected
FSortInfo : TSortInfo;
FFormInfo : TfQuestionInfo;
/// <summary>
/// 创建考题信息界面
/// </summary>
function CreateQuestionFrom : TfQuestionInfo; virtual;
/// <summary>
/// 加载题库考题
/// </summary>
procedure LoadSortQuestions(ASortInfo : TSortInfo);
/// <summary>
/// 刷新
/// </summary>
procedure RefurshAct;
/// <summary>
/// 添加记录
/// </summary>
procedure AddRecord(AInfo : TQuestionInfo);
/// <summary>
/// 刷新StringGrid纪录
/// </summary>
procedure RefurshGrd(nIndex : Integer);
/// <summary>
/// StringGrid 双击 单机事件
/// </summary>
procedure GridClick(Sender: TObject);
procedure GridDblClick(Sender: TObject);
public
{ Public declarations }
/// <summary>
/// 选择一个考题
/// </summary>
function SelOneQuestion : TQuestionInfo;
end;
var
fQuestionList: TfQuestionList;
implementation
{$R *.fmx}
procedure TfQuestionList.actAddExecute(Sender: TObject);
var
AInfo : TQuestionInfo;
begin
if Assigned(FFormInfo) then
begin
AInfo := TQuestionInfo.Create;
FFormInfo.ShowInfo(AInfo);
if FFormInfo.ShowModal = mrOk then
begin
FFormInfo.SaveInfo;
if Assigned(FSortInfo) then
begin
FSortInfo.AddQuestion(AInfo);
AddRecord(AInfo);
end;
strngrdQuestionList.SelectRow(strngrdQuestionList.RowCount - 1);
end
else
begin
AInfo.Free;
end;
end;
RefurshAct;
end;
procedure TfQuestionList.actClearAllExecute(Sender: TObject);
begin
if HintMessage(1, '您确定清空记录吗?', '提示', hbtYesNo) = hrtYes then
begin
strngrdQuestionList.RowCount := 0;
FSortInfo.ClearQuestion;
end;
RefurshAct;
end;
procedure TfQuestionList.actDelExecute(Sender: TObject);
var
nValue : integer;
AInfo : TQuestionInfo;
begin
nValue := strngrdQuestionList.Selected;
if nValue = -1 then
HintMessage(1, '请选择要删除的记录', '提示', hbtOk)
else
begin
if HintMessage(1, '你确定删除吗?', '提示', hbtYesNo) = hrtYes then
begin
if (strngrdQuestionList.RowCount > 0) then
begin
if strngrdQuestionList.Selected <> -1 then
begin
AInfo := FSortInfo.QuestionInfo[strngrdQuestionList.Selected];
FSortInfo.DelQuestion(AInfo.QID);
LoadSortQuestions(FSortInfo);
end;
end
else
begin
HintMessage(1, '请选择要删除的记录', '提示', hbtOk);
end;
end;
end;
RefurshAct;
end;
procedure TfQuestionList.actLoadSortExecute(Sender: TObject);
var
i : Integer;
ASortInfo : TSortInfo;
begin
cbbSortList.Items.Clear;
for i := 0 to SortControl.SortList.Count - 1 do
begin
ASortInfo := SortControl.SortInfo[i];
cbbSortList.Items.AddObject(ASortInfo.SortName, ASortInfo);
end;
if SortControl.SortList.Count > 0 then
begin
cbbSortList.ItemIndex := -1;
cbbSortList.ItemIndex := 0;
end;
end;
procedure TfQuestionList.actUpdateExecute(Sender: TObject);
var
AInfo : TQuestionInfo;
begin
if strngrdQuestionList.Selected = -1 then
HintMessage(1, '请选择要修改的记录!', '提示', hbtOk)
else
begin
AInfo := FSortInfo.QuestionInfo[strngrdQuestionList.Selected];
if Assigned(AInfo) then
begin
FFormInfo.ShowInfo(AInfo);
if FFormInfo.ShowModal = mrOk then
begin
FFormInfo.SaveInfo;
FSortInfo.EditQuestion(AInfo);
RefurshGrd(strngrdQuestionList.Selected);
end;
end
else
begin
HintMessage(1, '请选择要修改的记录!', '提示', hbtOk)
end;
end;
end;
procedure TfQuestionList.AddRecord(AInfo: TQuestionInfo);
var
nGrdRowNum : Integer;
begin
if Assigned(AInfo) and Assigned(FSortInfo) then
begin
strngrdQuestionList.RowCount := strngrdQuestionList.RowCount + 1;
nGrdRowNum := strngrdQuestionList.RowCount - 1;
with strngrdQuestionList, AInfo do
begin
Cells[0, nGrdRowNum] := IntToStr(AInfo.QID);
Cells[1, nGrdRowNum] := AInfo.QName;
Cells[2, nGrdRowNum] := AInfo.QDescribe;
Cells[3, nGrdRowNum] := AInfo.QRemark1;
end;
end;
end;
procedure TfQuestionList.btnSortManageClick(Sender: TObject);
begin
with TfSortList.Create(Self) do
begin
ShowModal;
Free;
end;
actLoadSortExecute(nil);
end;
procedure TfQuestionList.cbbSortListChange(Sender: TObject);
begin
if cbbSortList.ItemIndex <> -1 then
begin
FSortInfo := SortControl.SortInfo[cbbSortList.ItemIndex];
FSortInfo.LoadQuestion;
LoadSortQuestions(FSortInfo);
end;
RefurshAct;
end;
function TfQuestionList.CreateQuestionFrom: TfQuestionInfo;
begin
Result := TfQuestionInfo.Create(Self);
end;
procedure TfQuestionList.FormCreate(Sender: TObject);
begin
FFormInfo := CreateQuestionFrom;
strngrdQuestionList.OnDblClick := GridDblClick;
strngrdQuestionList.OnClick := GridClick;
end;
procedure TfQuestionList.FormDestroy(Sender: TObject);
begin
FFormInfo.Free;
end;
procedure TfQuestionList.FormShow(Sender: TObject);
begin
actLoadSortExecute(nil);
end;
procedure TfQuestionList.GridClick(Sender: TObject);
begin
RefurshAct;
end;
procedure TfQuestionList.GridDblClick(Sender: TObject);
begin
actUpdateExecute(nil);
end;
procedure TfQuestionList.LoadSortQuestions(ASortInfo: TSortInfo);
var
i : Integer;
begin
strngrdQuestionList.RowCount := 0;
if Assigned(ASortInfo) then
begin
for i := 0 to ASortInfo.QuestionList.Count - 1 do
AddRecord(ASortInfo.QuestionInfo[i]);
end;
end;
procedure TfQuestionList.RefurshAct;
begin
actDel.Enabled := strngrdQuestionList.Selected <> -1;
actUpdate.Enabled := strngrdQuestionList.Selected <> -1;
actClearAll.Enabled := strngrdQuestionList.RowCount > 0;
end;
procedure TfQuestionList.RefurshGrd(nIndex: Integer);
var
AInfo : TQuestionInfo;
begin
if (nIndex <> -1) and Assigned(FSortInfo) then
begin
AInfo := FSortInfo.QuestionInfo[nIndex];
if Assigned(AInfo) then
begin
with strngrdQuestionList, AInfo do
begin
Cells[0, nIndex] := IntToStr(AInfo.SortID);
Cells[1, nIndex] := AInfo.QName;
Cells[2, nIndex] := AInfo.QDescribe;
Cells[3, nIndex] := AInfo.QRemark1;
end;
strngrdQuestionList.SetFocus;
end;
end;
end;
function TfQuestionList.SelOneQuestion: TQuestionInfo;
begin
pnl2.Visible := False;
pnl3.Visible := True;
Result := nil;
if ShowModal = mrOk then
begin
if Assigned(FSortInfo) then
begin
if strngrdQuestionList.RowCount > 0 then
begin
if strngrdQuestionList.Selected <> -1 then
begin
Result := FSortInfo.QuestionInfo[strngrdQuestionList.Selected];
end;
end;
end;
end;
pnl2.Visible := True;
pnl3.Visible := False;
end;
end.
|
unit CheckListBoxImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, CheckLst;
type
TCheckListBoxX = class(TActiveXControl, ICheckListBoxX)
private
{ Private declarations }
FDelphiControl: TCheckListBox;
FEvents: ICheckListBoxXEvents;
procedure ClickCheckEvent(Sender: TObject);
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
procedure MeasureItemEvent(Control: TWinControl; Index: Integer;
var Height: Integer);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_AllowGrayed: WordBool; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_BorderStyle: TxBorderStyle; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Columns: Integer; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Flat: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_ImeMode: TxImeMode; safecall;
function Get_ImeName: WideString; safecall;
function Get_IntegralHeight: WordBool; safecall;
function Get_ItemHeight: Integer; safecall;
function Get_ItemIndex: Integer; safecall;
function Get_Items: IStrings; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_SelCount: Integer; safecall;
function Get_Sorted: WordBool; safecall;
function Get_Style: TxListBoxStyle; safecall;
function Get_TabWidth: Integer; safecall;
function Get_TopIndex: Integer; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure Clear; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_AllowGrayed(Value: WordBool); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_BorderStyle(Value: TxBorderStyle); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Columns(Value: Integer); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Flat(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_ImeMode(Value: TxImeMode); safecall;
procedure Set_ImeName(const Value: WideString); safecall;
procedure Set_IntegralHeight(Value: WordBool); safecall;
procedure Set_ItemHeight(Value: Integer); safecall;
procedure Set_ItemIndex(Value: Integer); safecall;
procedure Set_Items(const Value: IStrings); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Sorted(Value: WordBool); safecall;
procedure Set_Style(Value: TxListBoxStyle); safecall;
procedure Set_TabWidth(Value: Integer); safecall;
procedure Set_TopIndex(Value: Integer); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About5;
{ TCheckListBoxX }
procedure TCheckListBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_CheckListBoxXPage); }
end;
procedure TCheckListBoxX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as ICheckListBoxXEvents;
end;
procedure TCheckListBoxX.InitializeControl;
begin
FDelphiControl := Control as TCheckListBox;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnClickCheck := ClickCheckEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
FDelphiControl.OnMeasureItem := MeasureItemEvent;
end;
function TCheckListBoxX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TCheckListBoxX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TCheckListBoxX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TCheckListBoxX.Get_AllowGrayed: WordBool;
begin
Result := FDelphiControl.AllowGrayed;
end;
function TCheckListBoxX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TCheckListBoxX.Get_BorderStyle: TxBorderStyle;
begin
Result := Ord(FDelphiControl.BorderStyle);
end;
function TCheckListBoxX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TCheckListBoxX.Get_Columns: Integer;
begin
Result := FDelphiControl.Columns;
end;
function TCheckListBoxX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TCheckListBoxX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TCheckListBoxX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TCheckListBoxX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TCheckListBoxX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TCheckListBoxX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TCheckListBoxX.Get_Flat: WordBool;
begin
Result := FDelphiControl.Flat;
end;
function TCheckListBoxX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TCheckListBoxX.Get_ImeMode: TxImeMode;
begin
Result := Ord(FDelphiControl.ImeMode);
end;
function TCheckListBoxX.Get_ImeName: WideString;
begin
Result := WideString(FDelphiControl.ImeName);
end;
function TCheckListBoxX.Get_IntegralHeight: WordBool;
begin
Result := FDelphiControl.IntegralHeight;
end;
function TCheckListBoxX.Get_ItemHeight: Integer;
begin
Result := FDelphiControl.ItemHeight;
end;
function TCheckListBoxX.Get_ItemIndex: Integer;
begin
Result := FDelphiControl.ItemIndex;
end;
function TCheckListBoxX.Get_Items: IStrings;
begin
GetOleStrings(FDelphiControl.Items, Result);
end;
function TCheckListBoxX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TCheckListBoxX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TCheckListBoxX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TCheckListBoxX.Get_SelCount: Integer;
begin
Result := FDelphiControl.SelCount;
end;
function TCheckListBoxX.Get_Sorted: WordBool;
begin
Result := FDelphiControl.Sorted;
end;
function TCheckListBoxX.Get_Style: TxListBoxStyle;
begin
Result := Ord(FDelphiControl.Style);
end;
function TCheckListBoxX.Get_TabWidth: Integer;
begin
Result := FDelphiControl.TabWidth;
end;
function TCheckListBoxX.Get_TopIndex: Integer;
begin
Result := FDelphiControl.TopIndex;
end;
function TCheckListBoxX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TCheckListBoxX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TCheckListBoxX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TCheckListBoxX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TCheckListBoxX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TCheckListBoxX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TCheckListBoxX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TCheckListBoxX.AboutBox;
begin
ShowCheckListBoxXAbout;
end;
procedure TCheckListBoxX.Clear;
begin
FDelphiControl.Clear;
end;
procedure TCheckListBoxX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TCheckListBoxX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TCheckListBoxX.Set_AllowGrayed(Value: WordBool);
begin
FDelphiControl.AllowGrayed := Value;
end;
procedure TCheckListBoxX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TCheckListBoxX.Set_BorderStyle(Value: TxBorderStyle);
begin
FDelphiControl.BorderStyle := TBorderStyle(Value);
end;
procedure TCheckListBoxX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TCheckListBoxX.Set_Columns(Value: Integer);
begin
FDelphiControl.Columns := Value;
end;
procedure TCheckListBoxX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TCheckListBoxX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TCheckListBoxX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TCheckListBoxX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TCheckListBoxX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TCheckListBoxX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TCheckListBoxX.Set_Flat(Value: WordBool);
begin
FDelphiControl.Flat := Value;
end;
procedure TCheckListBoxX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TCheckListBoxX.Set_ImeMode(Value: TxImeMode);
begin
FDelphiControl.ImeMode := TImeMode(Value);
end;
procedure TCheckListBoxX.Set_ImeName(const Value: WideString);
begin
FDelphiControl.ImeName := TImeName(Value);
end;
procedure TCheckListBoxX.Set_IntegralHeight(Value: WordBool);
begin
FDelphiControl.IntegralHeight := Value;
end;
procedure TCheckListBoxX.Set_ItemHeight(Value: Integer);
begin
FDelphiControl.ItemHeight := Value;
end;
procedure TCheckListBoxX.Set_ItemIndex(Value: Integer);
begin
FDelphiControl.ItemIndex := Value;
end;
procedure TCheckListBoxX.Set_Items(const Value: IStrings);
begin
SetOleStrings(FDelphiControl.Items, Value);
end;
procedure TCheckListBoxX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TCheckListBoxX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TCheckListBoxX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TCheckListBoxX.Set_Sorted(Value: WordBool);
begin
FDelphiControl.Sorted := Value;
end;
procedure TCheckListBoxX.Set_Style(Value: TxListBoxStyle);
begin
FDelphiControl.Style := TListBoxStyle(Value);
end;
procedure TCheckListBoxX.Set_TabWidth(Value: Integer);
begin
FDelphiControl.TabWidth := Value;
end;
procedure TCheckListBoxX.Set_TopIndex(Value: Integer);
begin
FDelphiControl.TopIndex := Value;
end;
procedure TCheckListBoxX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TCheckListBoxX.ClickCheckEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClickCheck;
end;
procedure TCheckListBoxX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TCheckListBoxX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TCheckListBoxX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
procedure TCheckListBoxX.MeasureItemEvent(Control: TWinControl;
Index: Integer; var Height: Integer);
var
TempHeight: Integer;
begin
TempHeight := Integer(Height);
if FEvents <> nil then FEvents.OnMeasureItem(Index, TempHeight);
Height := Integer(TempHeight);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TCheckListBoxX,
TCheckListBox,
Class_CheckListBoxX,
5,
'{695CDAF6-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit unPagamento;
interface
uses
SysUtils;
type
EPagamentoException = Exception;
type
TPagamento = class
private
fFluxo: Integer;
fJuros: Double;
fAmortizacaoSaldoDevedor: Double;
fPagamento: Double;
fSaldoDevedor: Double;
procedure SetFluxo(const Value: Integer);
procedure SetJuros(const Value: Double);
procedure SetAmortizacaoSaldoDevedor(const Value: Double);
procedure SetPagamento(const Value: Double);
procedure SetSaldoDevedor(const Value: Double);
public
property Fluxo: Integer read fFluxo write SetFluxo;
property Juros: Double read fJuros write SetJuros;
property AmortizacaoSaldoDevedor: Double read fAmortizacaoSaldoDevedor write SetAmortizacaoSaldoDevedor;
property Pagamento: Double read fPagamento write SetPagamento;
property SaldoDevedor: Double read fSaldoDevedor write SetSaldoDevedor;
Constructor Create(AFluxo: Integer; AJuros: Double;
AAmortizacaoSaldoDevedor: Double; APagamento: Double; ASaldoDevedor: Double);
Destructor Destroy;
end;
TObtemJurosProduto = reference to function (AProd: TPagamento): Double;
implementation
{ TPagamento }
uses unUtils;
constructor TPagamento.Create(AFluxo: Integer; AJuros, AAmortizacaoSaldoDevedor,
APagamento, ASaldoDevedor: Double);
begin
inherited Create;
Fluxo := AFluxo;
Juros := AJuros;
AmortizacaoSaldoDevedor := AAmortizacaoSaldoDevedor;
Pagamento := APagamento;
SaldoDevedor := ASaldoDevedor;
end;
destructor TPagamento.Destroy;
begin
inherited Destroy;
end;
procedure TPagamento.SetAmortizacaoSaldoDevedor(const Value: Double);
begin
fAmortizacaoSaldoDevedor := Value;
end;
procedure TPagamento.SetPagamento(const Value: Double);
begin
fPagamento := Value;
end;
procedure TPagamento.SetSaldoDevedor(const Value: Double);
begin
fSaldoDevedor := Value;
end;
procedure TPagamento.SetFluxo(const Value: Integer);
begin
fFluxo := Value;
end;
procedure TPagamento.SetJuros(const Value: Double);
begin
fJuros := Value;
end;
end.
|
(*
Name: keymanhotkey
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 1 Aug 2006
Modified Date: 1 Aug 2006
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 01 Aug 2006 - mcdurdin - Initial version
*)
unit keymanhotkey;
interface
uses
System.Win.ComObj,
System.Classes,
Winapi.ActiveX,
internalinterfaces,
keymanapi_TLB,
KeymanContext,
keymanautoobject;
type
TKeymanHotkey = class(TKeymanAutoObject, IKeymanHotkey)
private
FValue: Integer;
FTarget: Integer;
protected
{ IKeymanHotkey }
function Get_Modifiers: TOleEnum; safecall;
procedure Set_Modifiers(Value: TOleEnum); safecall;
function Get_RawValue: Integer; safecall;
procedure Set_RawValue(Value: Integer); safecall;
function Get_Target: TOleEnum; safecall;
procedure Set_Target(Value: TOleEnum); safecall;
function Get_VirtualKey: Integer; safecall;
procedure Set_VirtualKey(Value: Integer); safecall;
procedure Clear; safecall;
function IsEmpty: WordBool; safecall;
public
constructor Create(AContext: TKeymanContext; AHotkeyValue: Integer; ATarget: KeymanHotkeyTarget);
end;
implementation
uses Windows, ComServ, ErrorControlledRegistry, RegistryKeys, SysUtils, keymanerrorcodes, Variants;
constructor TKeymanHotkey.Create(AContext: TKeymanContext;
AHotkeyValue: Integer; ATarget: KeymanHotkeyTarget);
begin
inherited Create(AContext, IKeymanHotkey);
FValue := AHotkeyValue;
FTarget := ATarget;
end;
procedure TKeymanHotkey.Clear;
begin
FValue := 0;
end;
function TKeymanHotkey.Get_Modifiers: TOleEnum;
begin
Result := FValue and (HK_ALT or HK_CTRL or HK_SHIFT);
end;
function TKeymanHotkey.Get_RawValue: Integer;
begin
Result := FValue;
end;
function TKeymanHotkey.Get_Target: TOleEnum;
begin
Result := FTarget;
end;
function TKeymanHotkey.Get_VirtualKey: Integer;
begin
Result := FValue and $FF;
end;
function TKeymanHotkey.IsEmpty: WordBool;
begin
Result := FValue = 0;
end;
procedure TKeymanHotkey.Set_Modifiers(Value: TOleEnum);
begin
FValue := (FValue and $FF) or Integer(Value);
end;
procedure TKeymanHotkey.Set_RawValue(Value: Integer);
begin
FValue := Value;
end;
procedure TKeymanHotkey.Set_Target(Value: TOleEnum);
begin
FTarget := Integer(Value);
end;
procedure TKeymanHotkey.Set_VirtualKey(Value: Integer);
begin
FValue := (FValue and (HK_ALT or HK_CTRL or HK_SHIFT)) or Value;
end;
end.
|
(* MapClass: MM, 2020-06-05 *)
(* ------ *)
(* A Unit for Mapping Operations using Hash Chaining *)
(* ========================================================================= *)
UNIT MapClass;
INTERFACE
CONST MAX = 100;
TYPE
NodePtr = ^Node;
Node = RECORD
key, value: STRING;
next: NodePtr;
END; (* Node *)
HashTable = ARRAY [0..MAX-1] OF NodePtr;
Map = ^MapObj;
MapObj = OBJECT
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
PROCEDURE Put(key, value: STRING);
PROCEDURE WriteMap;
PROCEDURE GetValue(key: STRING; VAR value: STRING);
PROCEDURE Remove(key: STRING);
FUNCTION GetSize: INTEGER;
PRIVATE
table: HashTable;
size: INTEGER;
END; (* MapObj *)
IMPLEMENTATION
FUNCTION NewNode(key, value: STRING; next: NodePtr): NodePtr;
VAR n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.key := key;
n^.value := value;
n^.next := next;
NewNode := n;
END; (* NewNode *)
PROCEDURE DisposeList(VAR l: NodePtr);
BEGIN (* DisposeList *)
IF (l <> NIL) THEN BEGIN
DisposeList(l^.next);
Dispose(l);
END; (* IF *)
END; (* DisposeList *)
FUNCTION GetHashCode(key: STRING): INTEGER;
BEGIN (* GetHashCode *)
IF (Length(key) = 0) THEN BEGIN
GetHashCode := 0;
END ELSE IF (Length(key) = 1) THEN BEGIN
GetHashCode := ((Ord(key[1]) * 7 + 1) * 17) MOD MAX;
END ELSE BEGIN
GetHashCode := ((Ord(key[1]) * 7 + Ord(key[2]) + Length(key)) * 17) MOD MAX;
END (* IF *)
END; (* GetHashCode *)
CONSTRUCTOR MapObj.Init;
VAR i: INTEGER;
BEGIN
FOR i := Low(table) TO High(table) DO BEGIN
table[i] := NIL;
END; (* FOR *)
size := 0;
END; (* MapObj.Init *)
DESTRUCTOR MapObj.Done;
VAR i: INTEGER;
BEGIN
FOR i := Low(table) TO High(table) DO BEGIN
DisposeList(table[i]);
END; (* FOR *)
END; (* MapObj.Done *)
FUNCTION Contains(table: HashTable; key: STRING): BOOLEAN;
VAR hashcode: INTEGER;
n: NodePtr;
BEGIN (* Contains *)
hashcode := GetHashCode(key);
n := table[hashcode];
WHILE ((n <> NIL) AND (n^.key <> key)) DO BEGIN
n := n^.next;
END; (* WHILE *)
Contains := n <> NIL;
END; (* Contains *)
PROCEDURE MapObj.Put(key, value: STRING);
VAR hashcode: INTEGER;
BEGIN (* MapObj.Put *)
hashcode := GetHashCode(key);
IF (Contains(table, key)) THEN
WriteLn('ERROR: Key "', key, '" is already mapped, you have to remove it first.')
ELSE BEGIN
table[hashcode] := NewNode(key, value, table[hashcode]);
Inc(size);
END; (* ELSE *)
END; (* MapObj.Put *)
PROCEDURE MapObj.WriteMap;
VAR i: INTEGER;
n: NodePtr;
BEGIN (* MapObj.Write *)
WriteLn('Map contains: --------------------------');
FOR i := 0 TO High(table) DO BEGIN
n := table[i];
IF (n <> NIL) THEN BEGIN
Write('Index ', i, ': ');
WHILE (n <> NIL) DO BEGIN
Write(n^.key, ' - ', n^.value, ' --> ');
n := n^.next;
END; (* WHILE *)
WriteLn;
END; (* IF *)
END; (* FOR *)
WriteLn('----------------------------------------');
END; (* MapObj.Write *)
PROCEDURE MapObj.GetValue(key: STRING; VAR value: STRING);
VAR hashcode: INTEGER;
n: NodePtr;
BEGIN (* MapObj.GetValue *)
hashcode := GetHashCode(key);
n := table[hashcode];
WHILE ((n <> NIL) AND (n^.key <> key)) DO BEGIN
n := n^.next;
END; (* WHILE *)
IF (n <> NIL) THEN
value := n^.value
ELSE
value := 'WARNING: Key not found!';
END; (* MapObj.GetValue *)
PROCEDURE MapObj.Remove(key: STRING);
VAR hashcode: INTEGER;
n, prev: NodePtr;
BEGIN (* MapObj.Remove *)
IF (NOT Contains(table, key)) THEN
WriteLn('ERROR: Key "', key, '" could not be found, remove unsuccessfull')
ELSE BEGIN
hashcode := GetHashCode(key);
n := table[hashcode];
prev := NIL;
WHILE ((n <> NIL) AND (n^.key <> key)) DO BEGIN
prev := n;
n := n^.next;
END; (* WHILE *)
IF (prev = NIL) THEN
table[hashcode] := n^.next
ELSE
prev^.next := n^.next;
Dispose(n);
Dec(size);
END; (* ELSE *)
END; (* MapObj.Remove *)
FUNCTION MapObj.GetSize: INTEGER;
BEGIN (* MapObj.Size *)
GetSize := SELF.size;
END; (* MapObj.Size *)
END. (* MapClass *) |
{==============================================================================|
| Project : Ararat Synapse | 001.003.000 |
|==============================================================================|
| Content: SSL support by OpenSSL and the CAPI engine |
|==============================================================================|
| Copyright (c)2018, Pepak |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Pepak (Czech Republic). |
| Portions created by Pepak are Copyright (c)2018. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
//requires OpenSSL libraries, including the CAPI engine (capi.dll)!
//recommended source: Stunnel (https://www.stunnel.org)
{:@abstract(SSL plugin for OpenSSL and the CAPI engine)
Compatibility with OpenSSL versions:
1.0.2 works fine.
1.1.x does not work properly out of the box. I was never able to get CAPI
to work with pre-built binaries or binaries that I built myself, even in
third party applications such as STunnel. The only config which works for
me involves custom-building OpenSSL with engines statically compiled into
libcrypto:
1) Install PERL (e.g. C:\PERL). Make sure the BIN subdirectory is in
the PATH (SET PATH=%PATH%;C:\PERL\BIN).
2) Download DMAKE ( https://metacpan.org/release/dmake ) and unpack it
into the Perl directory (you will get C:\PERL\DMAKE\DMAKE.EXE and
other files). Add the DMAKE directory to PATH as well.
3) Start Visual Studio Development Prompt, either 32 or 64bit. All the
following commands should be run in this prompt.
4) Install the Text::Template module by running:
cpan -i Text::Template
5) Download and unpack the OpenSSL sources into e.g. C:\SOURCE\OPENSSL.
6) Download and unpack the Zlib sources into e.g. C:\SOURCE\ZLIB.
7) Go to the ZLIB directory and run:
nmake -f win32/Makefile.msc
8) Go to the OpenSSL directory and run:
32bit:
perl Configure shared enable-static-engine enable-zlib --with-zlib-include=C:\SOURCE\ZLIB --with-zlib-lib=C:\SOURCE\ZLIB\zlib.lib VC-WIN32
64bit:
perl Configure shared enable-static-engine enable-zlib --with-zlib-include=C:\SOURCE\ZLIB --with-zlib-lib=C:\SOURCE\ZLIB\zlib.lib VC-WIN64A
Make sure to replace both instances of C:\SOURCE\ZLIB with the actual
path to the Zlib library.
9) If you want to build the OpenSSL DLLs without external dependencies
(e.g. on the Visual Studio Runtime), edit the generated makefile:
- Change the "/MD" flag in CNF_FLAGS to "/MT".
- Add "/NODEFAULTLIB:MSVCRT" to CNF_LDFLAGS.
10) In the OpenSSL directory, run:
nmake
11) When all is done, copy LIBCRYPTO-1_1*.DLL and LIBSSH-1_1*.DLL to
your application's binary directory.
OpenSSL libraries are loaded dynamically - you do not need the librares even if
you compile your application with this unit. SSL just won't work if you don't
have the OpenSSL libraries.
The plugin is built on the standard OpenSSL plugin, giving it all the features
of it. In fact, if you do not have the CAPI engine, the plugin will behave in
exactly the same way as the original plugin - the CAPI engine is completely
optional, the plugin will work without it - obviously without the support for
Windows Certificate Stores.
The windows certificate stores are supported through the following properties:
@link(TSSLOpenSSLCapi.SigningCertificate) - expects pointer to the certificate
context of the signing certificate (PCCERT_CONTENT). @br
Note that due to the limitations of OpenSSL, it is not possible to switch
between different engines (e.g. CAPI and default) on the fly - the engine is
a global setting for the whole of OpenSSL. For that reason, once the engine
is enabled (either explicitly or by using a Windows certificate for a connection),
it will stay enabled and there is no method for disabling it.
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
{$INCLUDE 'jedi.inc'}
{$DEFINE USE_ENGINE_POOL}
unit ssl_openssl_capi;
interface
uses
Windows, Crypt32, SysUtils, Classes, SyncObjs,
blcksock, ssl_openssl, ssl_openssl_lib;
type
PENGINE = Pointer;
type
TWindowsCertStoreLocation = (
wcslCurrentUser
, wcslCurrentUserGroupPolicy
, wcslUsers
, wcslCurrentService
, wcslServices
, wcslLocalMachine
, wcslLocalMachineGroupPolicy
, wcslLocalMachineEnterprise
);
type
{:@abstract(class extending the OpenSSL SSL plugin with CAPI support.)
Instance of this class will be created for each @link(TTCPBlockSocket).
You not need to create instance of this class, all is done by Synapse itself!}
TSSLOpenSSLCapi = class(TSSLOpenSSL)
private
FEngine: PENGINE;
FEngineInitialized: boolean;
FSigningCertificateLocation: TWindowsCertStoreLocation;
FSigningCertificateStore: string;
FSigningCertificateID: string;
function GetEngine: PENGINE;
protected
{:Loads a certificate context into the CAPI engine for signing/decryption.}
function LoadSigningCertificate: boolean;
{:See @inherited}
function SetSslKeys: boolean; override;
{:See @inherited}
function NeedSigningCertificate: boolean; override;
{:Returns true if the signing certificate should be used.}
function SigningCertificateSpecified: boolean;
{:Provides a cryptographic engine for OpenSSL}
property Engine: PENGINE read GetEngine;
public
{:See @inherited}
constructor Create(const Value: TTCPBlockSocket); override;
{:See @inherited}
destructor Destroy; override;
{:See @inherited}
procedure Assign(const Value: TCustomSSL); override;
{:Use this function to load the CAPI engine and/or verify that the engine
is available. The plugin will load CAPI itself when it is needed, so you
may skip this function completely, but it may be useful to perform a manual
CAPI load early during the application startup to make sure all connection
use the same cryptographic engine (and, as a result, behave the same way).}
class function InitEngine: boolean;
{:Location of the certificate store used for the communication.}
property SigningCertificateLocation: TWindowsCertStoreLocation read FSigningCertificateLocation write FSigningCertificateLocation;
{:Certificate store used for the communication. The most common is "MY",
or the user's private certificates.}
property SigningCertificateStore: string read FSigningCertificateStore write FSigningCertificateStore;
{:ID of the certificate to use. For standard CAPI, this is the friendly name
of the certificate. For the client-side SSL it is not really necessary, as
long as it is non-empty (which signifies that the CAPI engine should be
used). For the server side, it must be a substring of the SubjectName of
the certificate. The first matching certificate will be used.}
property SigningCertificateID: string read FSigningCertificateID write FSigningCertificateID;
end;
implementation
{$IFDEF SUPPORTS_REGION}{$REGION 'Support and compatibility functions'}{$ENDIF}
{==============================================================================}
{Support and compatibility functions }
{------------------------------------------------------------------------------}
function GetModuleFileNamePAS(Handle: THandle; out FileName: string): boolean;
var
FN: string;
n: integer;
begin
Result := False;
if Handle = 0 then
Exit;
SetLength(FN, MAX_PATH);
n := GetModuleFileName(Handle, @FN[1], Length(FN));
if (n > 0) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
SetLength(FN, n);
n := GetModuleFileName(Handle, @FN[1], Length(FN));
end;
if (n > 0) and (GetLastError = ERROR_SUCCESS) then
begin
SetLength(FN, n);
FileName := FN;
Result := True;
end;
end;
{$IFNDEF UNICODE}
type
PPointer = ^Pointer;
procedure RaiseLastOSError;
begin
RaiseLastWin32Error;
end;
{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$REGION 'Imported functions'}{$ENDIF}
{==============================================================================}
{Imported functions }
{------------------------------------------------------------------------------}
const
CapiEngineID = 'capi';
DLLCapiName = CapiEngineID + '.dll';
const
SSL_CTRL_OPTIONS = 32;
SSL_OP_NO_TLSv1_2 = $08000000;
const
ENGINE_METHOD_ALL = $ffff;
type
PPX509 = ^PX509;
var
FEngineCS: TCriticalSection = nil;
FEngineNeedsSHA2Workaround: boolean = False;
var
FEngineInterfaceInitialized: boolean = False;
FENGINE_cleanup: procedure; cdecl = nil;
FENGINE_load_builtin_engines: procedure; cdecl = nil;
FENGINE_by_id: function(id: PAnsiChar): PENGINE; cdecl = nil;
FENGINE_ctrl_cmd_string: function(e: PENGINE; cmd_name, arg: PAnsiChar; cmd_optional: integer): integer; cdecl = nil;
FENGINE_init: function(e: PENGINE): integer; cdecl = nil;
FENGINE_finish: function(e: PENGINE): integer; cdecl = nil;
FENGINE_free: function(e: PENGINE): integer; cdecl = nil;
FENGINE_set_default: function(e: PENGINE; flags: DWORD): integer; cdecl = nil;
FENGINE_load_private_key: function(e: PENGINE; key_id: PAnsiChar; ui_method: Pointer; callback_data: Pointer): EVP_PKEY; cdecl = nil;
FSSL_CTX_set_client_cert_engine: function(ctx: PSSL_CTX; e: PENGINE): integer; cdecl = nil;
Fd2i_X509: function(px: PPX509; data: PPointer; len: integer): PX509; cdecl = nil;
function InitEngineInterface: boolean;
var
OpenSSLFileName: string;
VerInfoSize: DWORD;
VerInfo: Pointer;
VerHandle: DWORD;
SpecVerInfo: PVsFixedFileInfo;
begin
if FEngineInterfaceInitialized then
begin
Result := True;
Exit;
end;
FEngineCS.Enter;
try
if FEngineInterfaceInitialized then
begin
Result := True;
Exit;
end;
Result := False;
if not InitSSLInterface then
Exit;
if SSLUtilHandle = 0 then
Exit;
if SSLLibHandle = 0 then
Exit;
FENGINE_cleanup := GetProcAddress(SSLUtilHandle, 'ENGINE_cleanup');
FENGINE_load_builtin_engines := GetProcAddress(SSLUtilHandle, 'ENGINE_load_builtin_engines');
FENGINE_by_id := GetProcAddress(SSLUtilHandle, 'ENGINE_by_id');
FENGINE_ctrl_cmd_string := GetProcAddress(SSLUtilHandle, 'ENGINE_ctrl_cmd_string');
FENGINE_init := GetProcAddress(SSLUtilHandle, 'ENGINE_init');
FENGINE_finish := GetProcAddress(SSLUtilHandle, 'ENGINE_finish');
FENGINE_free := GetProcAddress(SSLUtilHandle, 'ENGINE_free');
FENGINE_set_default := GetProcAddress(SSLUtilHandle, 'ENGINE_set_default');
FENGINE_load_private_key := GetProcAddress(SSLUtilHandle, 'ENGINE_load_private_key');
FSSL_CTX_set_client_cert_engine := GetProcAddress(SSLLibHandle, 'SSL_CTX_set_client_cert_engine');
Fd2i_X509 := GetProcAddress(SSLUtilHandle, 'd2i_X509');
FEngineInterfaceInitialized := True;
//---- Workaround for a CAPI engine bug ------------------------------------
// https://www.stunnel.org/pipermail/stunnel-users/2017-February/005720.html
//
// The capi ENGINE in OpenSSL 1.0.2 and earlier uses the CSP attached
// to the key for cryptographic operations. Unfortunately this means that
// SHA2 algorithms are not supported for client authentication.
//
// OpenSSL 1.1.0 adds a workaround for this issue. If you disable TLS 1.2
// in earlier versions of OpenSSL it will not use SHA2 for client auth so
// that will also work.
begin
FEngineNeedsSHA2Workaround := False;
if GetModuleFileNamePAS(SSLUtilHandle, OpenSSLFileName) then
begin
VerInfoSize := GetFileVersionInfoSize(PChar(OpenSSLFileName), VerHandle);
if VerInfoSize > 0 then
begin
GetMem(VerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(OpenSSLFileName), VerHandle, VerInfoSize, VerInfo) then
if VerQueryValue(VerInfo, '\', Pointer(SpecVerInfo), VerInfoSize) then
begin
if SpecVerInfo^.dwFileVersionMS < (65536*1 + 1) then
FEngineNeedsSHA2Workaround := True;
end;
finally
FreeMem(VerInfo);
end;
end;
end;
end;
//---- Workaround end ------------------------------------------------------
Result := True;
finally
FEngineCS.Leave;
end;
end;
procedure DestroyEngineInterface;
begin
FEngineCS.Enter;
try
if Assigned(FENGINE_cleanup) then
FENGINE_cleanup;
FENGINE_cleanup := nil;
FENGINE_load_builtin_engines := nil;
FENGINE_by_id := nil;
FENGINE_ctrl_cmd_string := nil;
FENGINE_init := nil;
FENGINE_finish := nil;
FENGINE_free := nil;
FENGINE_set_default := nil;
FENGINE_load_private_key := nil;
FSSL_CTX_set_client_cert_engine := nil;
Fd2i_X509 := nil;
FEngineInterfaceInitialized := False;
finally
FEngineCS.Leave;
end;
end;
procedure ENGINE_load_builtin_engines;
begin
if InitEngineInterface and Assigned(FENGINE_load_builtin_engines) then
FENGINE_load_builtin_engines;
end;
function ENGINE_by_id(id: PAnsiChar): PENGINE;
begin
if InitEngineInterface and Assigned(FENGINE_by_id) then
Result := FENGINE_by_id(id)
else
Result := nil;
end;
function ENGINE_ctrl_cmd_string(e: PENGINE; cmd_name, arg: PAnsiChar; cmd_optional: integer): integer;
begin
if InitEngineInterface and Assigned(FENGINE_ctrl_cmd_string) then
Result := FENGINE_ctrl_cmd_string(e, cmd_name, arg, cmd_optional)
else
Result := 0;
end;
function ENGINE_init(e: PENGINE): integer;
begin
if InitEngineInterface and Assigned(FENGINE_init) then
Result := FENGINE_init(e)
else
Result := 0;
end;
function ENGINE_finish(e: PENGINE): integer;
begin
if InitEngineInterface and Assigned(FENGINE_finish) then
Result := FENGINE_finish(e)
else
Result := 0;
end;
function ENGINE_free(e: PENGINE): integer;
begin
if InitEngineInterface and Assigned(FENGINE_free) then
Result := FENGINE_free(e)
else
Result := 0;
end;
function ENGINE_set_default(e: PENGINE; flags: DWORD): integer;
begin
if InitEngineInterface and Assigned(FENGINE_set_default) then
Result := FENGINE_set_default(e, flags)
else
Result := 0;
end;
function ENGINE_load_private_key(e: PENGINE; key_id: PAnsiChar; ui_method: Pointer; callback_data: Pointer): EVP_PKEY;
begin
if InitEngineInterface and Assigned(FENGINE_load_private_key) then
Result := FENGINE_load_private_key(e, key_id, ui_method, callback_data)
else
Result := nil;
end;
function SSL_CTX_set_client_cert_engine(ctx: PSSL_CTX; e: PENGINE): integer;
begin
if InitEngineInterface and Assigned(FSSL_CTX_set_client_cert_engine) then
Result := FSSL_CTX_set_client_cert_engine(ctx, e)
else
Result := 0;
end;
function d2i_X509(px: PPX509; data: PPointer; len: integer): PX509;
begin
if InitEngineInterface and Assigned(Fd2i_X509) then
Result := Fd2i_X509(px, data, len)
else
Result := nil;
end;
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$REGION 'CAPI engine support'}{$ENDIF}
{==============================================================================}
{CAPI engine support }
{------------------------------------------------------------------------------}
var
FGlobalEngineInitialized: boolean = False;
FGlobalEngine: PENGINE = nil;
function PrepareCapiEngine(out Engine: PENGINE): boolean;
function LoadCapiEngine(Engine: PENGINE; const FileName: string): boolean;
begin
Result := False;
if ENGINE_ctrl_cmd_string(Engine, 'SO_PATH', PAnsiChar(AnsiString(FileName)), 0) <> 0 then
if ENGINE_ctrl_cmd_string(Engine, 'LOAD', nil, 0) <> 0 then
Result := True;
end;
function LoadCapiEngineDynamic(out Engine: PENGINE): boolean;
var
OpenSSLFileName: string;
TempEngine: PENGINE;
begin
Result := False;
if not GetModuleFileNamePAS(SSLUtilHandle, OpenSSLFileName) then
Exit;
TempEngine := ENGINE_by_id('dynamic');
try
if TempEngine <> nil then
begin
if LoadCapiEngine(TempEngine, ExtractFilePath(OpenSSLFileName) + DLLCapiName) then // need a version match! Same dir suggests the versions could be the same
if ENGINE_init(TempEngine) <> 0 then
begin
Engine := TempEngine;
TempEngine := nil;
Result := True;
end;
end;
finally
if TempEngine <> nil then
begin
ENGINE_free(TempEngine);
//TempEngine := nil; // triggers a hint
end;
end;
end;
function LoadCapiEngineStatic(out Engine: PENGINE): boolean;
var
TempEngine: PENGINE;
begin
Result := False;
TempEngine := ENGINE_by_id(CapiEngineID);
try
if TempEngine <> nil then
begin
if ENGINE_init(TempEngine) <> 0 then
begin
Engine := TempEngine;
TempEngine := nil;
Result := True;
end;
end;
finally
if TempEngine <> nil then
begin
ENGINE_free(TempEngine);
//TempEngine := nil; // triggers a hint
end;
end;
end;
begin
Result := LoadCapiEngineStatic(Engine) or LoadCapiEngineDynamic(Engine);
end;
function InitCapiEngine: boolean;
var
E: PENGINE;
begin
Result := FGlobalEngine <> nil;
if FGlobalEngineInitialized then
Exit;
FEngineCS.Enter;
try
if FGlobalEngineInitialized then
Exit;
ENGINE_load_builtin_engines();
if PrepareCapiEngine(E) then
begin
if not Assigned(FSSL_CTX_set_client_cert_engine) then
begin
if ENGINE_set_default(E, ENGINE_METHOD_ALL) = 0 then
begin
ENGINE_finish(E);
ENGINE_free(E);
E := nil;
end;
end;
FGlobalEngine := E;
end;
FGlobalEngineInitialized := True;
Result := FGlobalEngine <> nil;
finally
FEngineCS.Leave;
end;
end;
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$REGION 'Pool of engines'}{$ENDIF}
{==============================================================================}
{Pool of engines, to reduce the time to get a working connection }
{------------------------------------------------------------------------------}
{$IFDEF USE_ENGINE_POOL}
type
TEnginePool = class
private
fLock: TCriticalSection;
fAvailableList: TList;
protected
procedure Lock;
procedure Unlock;
public
constructor Create;
destructor Destroy; override;
function Acquire(out Engine: PENGINE): boolean;
procedure Release(var Engine: PENGINE);
procedure Clear;
end;
var
FEnginePool: TEnginePool = nil;
{ TEnginePool }
function TEnginePool.Acquire(out Engine: PENGINE): boolean;
var
n: integer;
begin
if fAvailableList.Count > 0 then
begin
Lock;
try
for n := Pred(fAvailableList.Count) downto 0 do
begin
Engine := fAvailableList[n];
if Engine <> nil then
begin
fAvailableList.Delete(n);
Result := True;
Exit;
end;
end;
finally
Unlock;
end;
end;
Result := InitCapiEngine and PrepareCapiEngine(Engine);
end;
procedure TEnginePool.Clear;
var
i: integer;
E: PENGINE;
begin
Lock;
try
for i := 0 to Pred(fAvailableList.Count) do
begin
E := fAvailableList[i];
fAvailableList[i] := nil;
if E <> nil then
begin
ENGINE_finish(E);
ENGINE_free(E);
end;
end;
fAvailableList.Clear;
finally
Unlock;
end;
end;
constructor TEnginePool.Create;
begin
inherited Create;
fLock := TCriticalSection.Create;
fAvailableList := TList.Create;
end;
destructor TEnginePool.Destroy;
begin
Clear;
FreeAndNil(fAvailableList);
FreeAndNil(fLock);
inherited;
end;
procedure TEnginePool.Lock;
begin
fLock.Enter;
end;
procedure TEnginePool.Release(var Engine: PENGINE);
begin
if Engine = nil then
Exit;
Lock;
try
fAvailableList.Add(Engine);
Engine := nil;
finally
Unlock;
end;
end;
procedure TEnginePool.Unlock;
begin
fLock.Leave;
end;
{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$REGION 'The plugin'}{$ENDIF}
{==============================================================================}
{The plugin }
{------------------------------------------------------------------------------}
{ TSSLOpenSSLCapi }
class function TSSLOpenSSLCapi.InitEngine: boolean;
begin
Result := InitCapiEngine;
end;
procedure TSSLOpenSSLCapi.Assign(const Value: TCustomSSL);
var
CAPIValue: TSSLOpenSSLCapi;
begin
inherited;
if (Value <> nil) and (Value is TSSLOpenSSLCapi) then
begin
CAPIValue := TSSLOpenSSLCapi(Value);
Self.FSigningCertificateLocation := CAPIValue.FSigningCertificateLocation;
Self.FSigningCertificateStore := CAPIValue.FSigningCertificateStore;
Self.FSigningCertificateID := CAPIValue.FSigningCertificateID;
end;
end;
constructor TSSLOpenSSLCapi.Create(const Value: TTCPBlockSocket);
begin
inherited;
FEngine := nil;
FEngineInitialized := False;
FSigningCertificateLocation := wcslCurrentUser;
FSigningCertificateStore := 'MY';
FSigningCertificateID := '';
end;
destructor TSSLOpenSSLCapi.Destroy;
begin
if FEngine <> nil then
begin
{$IFDEF USE_ENGINE_POOL}
FEnginePool.Release(FEngine);
{$ELSE}
ENGINE_finish(FEngine);
ENGINE_free(FEngine);
{$ENDIF}
FEngineInitialized := False;
end;
inherited;
end;
function TSSLOpenSSLCapi.GetEngine: PENGINE;
begin
if not FEngineInitialized then
begin
{$IFDEF USE_ENGINE_POOL}
if not FEnginePool.Acquire(FEngine) then
FEngine := nil;
{$ELSE}
if (not InitEngine) or (not PrepareCapiEngine(FEngine)) then
FEngine := nil;
{$ENDIF}
FEngineInitialized := True;
end;
Result := FEngine;
end;
function TSSLOpenSSLCapi.LoadSigningCertificate: boolean;
var
pkey: EVP_PKEY;
pdata: Pointer;
cert: PX509;
store: HCERTSTORE;
certctx: PCCERT_CONTEXT;
flags: DWORD;
begin
Result := False;
if not SigningCertificateSpecified then
Exit;
if not InitEngine then
Exit;
if Engine = nil then
Exit;
if not Assigned(FSSL_CTX_set_client_cert_engine) then
Exit;
if SSL_CTX_set_client_cert_engine(Fctx, Engine) = 0 then
Exit;
if ENGINE_ctrl_cmd_string(Engine, 'store_name', PAnsiChar( {$IFDEF UNICODE} AnsiString {$ENDIF} (SigningCertificateStore)), 0) = 0 then
Exit;
if ENGINE_ctrl_cmd_string(Engine, 'lookup_method', '1', 0) = 0 then
Exit;
case SigningCertificateLocation of
wcslCurrentUser:
if ENGINE_ctrl_cmd_string(Engine, 'store_flags', '0', 0) = 0 then
Exit;
wcslLocalMachine:
if ENGINE_ctrl_cmd_string(Engine, 'store_flags', '1', 0) = 0 then
Exit;
else
Exit; // other store flags are not supported by the CAPI engine
end;
if Server then
begin
cert := nil;
pkey := nil;
try
// Need to find the context and the store for the certificate. Unfortunately,
// due to the CAPI engine limitations (see capi_load_privkey), I can only use
// a very limited set of criteria for finding the certificate
flags := 0;
case SigningCertificateLocation of
wcslCurrentUser:
flags := flags or CERT_SYSTEM_STORE_CURRENT_USER;
wcslLocalMachine:
flags := flags or CERT_SYSTEM_STORE_LOCAL_MACHINE;
else
Exit; // other store flags are not supported by the CAPI engine
end;
store := CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, flags, PWideChar(WideString(SigningCertificateStore)));
if store <> 0 then
begin
try
certctx := CertFindCertificateInStore(store, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_A, PAnsiChar( {$IFDEF UNICODE} AnsiString {$ENDIF} (SigningCertificateID)), nil);
if certctx = nil then
Exit;
pkey := ENGINE_load_private_key(Engine, PAnsiChar( {$IFDEF UNICODE} AnsiString {$ENDIF} (SigningCertificateID)), nil, nil);
if pkey = nil then
Exit;
pdata := certctx.pbCertEncoded;
cert := d2i_X509(nil, @pdata, certctx.cbCertEncoded);
if cert = nil then
Exit;
if SSLCTXusecertificate(Fctx, cert) <= 0 then
Exit;
if SSLCTXusePrivateKey(Fctx, pkey) <= 0 then
Exit;
Result := True;
finally
CertCloseStore(store, 0);
end;
end;
finally
if pkey <> nil then
EvpPkeyFree(pkey);
if cert <> nil then
X509free(cert);
end;
end
else
begin
Result := True;
end;
if Result then
if FEngineNeedsSHA2Workaround then
SslCtxCtrl(Fctx, SSL_CTRL_OPTIONS, SslCtxCtrl(Fctx, SSL_CTRL_OPTIONS, 0, nil) or SSL_OP_NO_TLSv1_2, nil);
end;
function TSSLOpenSSLCapi.NeedSigningCertificate: boolean;
begin
Result := SigningCertificateSpecified and inherited NeedSigningCertificate;
end;
function TSSLOpenSSLCapi.SetSslKeys: boolean;
begin
Result := False;
if not assigned(FCtx) then
Exit;
try
if SigningCertificateSpecified and InitEngine then
begin
if not LoadSigningCertificate then
Exit;
Result := True;
end;
if inherited SetSslKeys then
Result := True;
finally
SSLCheck;
end;
end;
function TSSLOpenSSLCapi.SigningCertificateSpecified: boolean;
begin
Result := (SigningCertificateID <> '');
end;
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF SUPPORTS_REGION}{$REGION 'Initialization and finalization'}{$ENDIF}
{==============================================================================}
{Initialization and finalization }
{------------------------------------------------------------------------------}
initialization
begin
FEngineCS := TCriticalSection.Create;
if InitSSLInterface and ((SSLImplementation = TSSLNone) or (SSLImplementation = TSSLOpenSSL)) then
SSLImplementation := TSSLOpenSSLCapi;
{$IFDEF USE_ENGINE_POOL}
FEnginePool := TEnginePool.Create;
{$ENDIF}
end;
finalization
begin
DestroyEngineInterface;
{$IFDEF USE_ENGINE_POOL}
FreeAndNil(FEnginePool);
{$ENDIF}
FreeAndNil(FEngineCS);
end;
{$IFDEF SUPPORTS_REGION}{$ENDREGION}{$ENDIF}
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный клас-переходник между библиотечным интерфейсом
предоставления данных для чарта (ISCInputDataCollection) и
источником данных (IStockDataSource)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.DataSourceToInputDataCollectionMediator;
{$I Compiler.inc}
interface
uses BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,FC.Definitions, StockChart.Obj;
type
//----------------------------------------------------------------------------
TEventMediator = class;
IStockDataSourceToInputDataCollectionMediator = interface
['{F10C6A71-9FFF-4137-B45A-E3B277466A90}']
procedure SetDataSource(aDS: IStockDataSource);
function GetDataSource: IStockDataSource;
end;
TStockDataSourceToInputDataCollectionMediator = class (TSCInputDataCollection_B,IStockDataSourceToInputDataCollectionMediator)
private
FDS : IStockDataSource;
FEventMediator : TEventMediator;
public
constructor Create(aDS:IStockDataSource; AOwner: ISCChangeNotifier);
destructor Destroy; override;
function ISCInputDataCollection_GetItem(Index: Integer): ISCInputData; override;
function DirectGetItem_DataDateTime(index: integer):TDateTime; override;
function DirectGetItem_DataClose(index: integer): TStockRealNumber; override;
function DirectGetItem_DataHigh(index: integer): TStockRealNumber; override;
function DirectGetItem_DataLow(index: integer): TStockRealNumber; override;
function DirectGetItem_DataOpen(index: integer): TStockRealNumber; override;
function DirectGetItem_DataVolume(index: integer): integer; override;
function Count: integer; override;
procedure SetDataSource(aDS: IStockDataSource);
function GetDataSource: IStockDataSource;
end;
TEventMediator = class (TInterfacedObject,IStockDataSourceEventHandler)
private
FEventHandlers:TInterfaceList; //ISCInputDataCollectionEventHandler
FOwner : TStockDataSourceToInputDataCollectionMediator;
public
procedure OnChangeData(const aSender: IStockDataSource; index: integer; aType: TStockDataModificationType);
constructor Create(aOwner: TStockDataSourceToInputDataCollectionMediator);
destructor Destroy; override;
end;
implementation
uses Math;
type
//----------------------------------------------------------------------------
//Класс для описания одного элемента входных данных
TDataMediator = class (TInterfacedObjectEx,ISCInputData)
private
FDS : IStockDataSource;
FIndex : integer;
protected
function _Release: Integer; override; stdcall;
public
//from ISCInputData
function GetDataClose: TStockRealNumber;
function GetDataHigh: TStockRealNumber;
function GetDataLow: TStockRealNumber;
function GetDataOpen: TStockRealNumber;
function GetDataVolume: integer;
function GetDataDateTime: TDateTime;
function IsBullish: boolean;
function IsBearish: boolean;
constructor Create(aDS: IStockDataSource; index: integer);
destructor Destroy; override;
end;
const
gReserveInputDataObjectsSize = 1024;
var
gReserveInputDataObjects : array [0..gReserveInputDataObjectsSize-1] of TDataMediator;
gReserveInputDataObjectsCounter: integer;
{ TSCInputDataMediator }
constructor TDataMediator.Create(aDS: IStockDataSource; index: integer);
begin
inherited Create;
Assert(index>=0);
Assert(index<=aDS.RecordCount);
FDS:=aDS;
FIndex:=index;
end;
function TDataMediator.GetDataOpen: TStockRealNumber;
begin
result:=FDS.GetDataOpen(FIndex);
end;
function TDataMediator.GetDataHigh: TStockRealNumber;
begin
result:=FDS.GetDataHigh(FIndex);
end;
function TDataMediator.GetDataDateTime: TDateTime;
begin
result:=FDS.GetDataDateTime(FIndex);
end;
function TDataMediator.GetDataVolume: integer;
begin
result:=FDS.GetDataVolume(FIndex);
end;
function TDataMediator.GetDataClose: TStockRealNumber;
begin
result:=FDS.GetDataClose(FIndex);
end;
function TDataMediator.GetDataLow: TStockRealNumber;
begin
result:=FDS.GetDataLow(FIndex);
end;
destructor TDataMediator.Destroy;
begin
FDS:=nil;
inherited;
end;
function TDataMediator._Release: Integer;
begin
Dec(FRefCount);
Result:=FRefCount;
ASSERT(Result >= 0);
if (Result=0) then
begin
if gReserveInputDataObjectsCounter<gReserveInputDataObjectsSize then
begin
gReserveInputDataObjects[gReserveInputDataObjectsCounter]:=self;
inc(gReserveInputDataObjectsCounter);
self.FDS:=nil;
end
else
self.free;
end;
end;
function TDataMediator.IsBullish: boolean;
begin
result:=GetDataOpen<GetDataClose;
end;
function TDataMediator.IsBearish: boolean;
begin
result:=GetDataOpen>GetDataClose;
end;
{ TStockDataSourceToInputDataCollectionMediator }
constructor TStockDataSourceToInputDataCollectionMediator.Create(aDS: IStockDataSource; AOwner: ISCChangeNotifier);
begin
inherited Create(AOwner,0.0);
FEventMediator:=TEventMediator.Create(self);
IInterface(FEventMediator)._AddRef;
SetDataSource(aDS);
end;
destructor TStockDataSourceToInputDataCollectionMediator.Destroy;
begin
inherited;
FEventMediator.FOwner:=nil;
IInterface(FEventMediator)._Release;
FEventMediator:=nil;
end;
function TStockDataSourceToInputDataCollectionMediator.Count: integer;
begin
if FDS=nil then
result:=0
else
result:=FDS.RecordCount;
end;
function TStockDataSourceToInputDataCollectionMediator.ISCInputDataCollection_GetItem(Index: Integer): ISCInputData;
begin
if gReserveInputDataObjectsCounter>0 then
begin
dec(gReserveInputDataObjectsCounter);
gReserveInputDataObjects[gReserveInputDataObjectsCounter].FDS:=FDS;
gReserveInputDataObjects[gReserveInputDataObjectsCounter].FIndex:=Index;
result:=gReserveInputDataObjects[gReserveInputDataObjectsCounter];
gReserveInputDataObjects[gReserveInputDataObjectsCounter+1]:=nil;
end
else begin
result:=TDataMediator.Create(FDS,index);
end;
end;
procedure TStockDataSourceToInputDataCollectionMediator.SetDataSource(aDS: IStockDataSource);
begin
if FDS<>aDS then
begin
if FDS<>nil then
FDS.RemoveEventHandler(FEventMediator);
FDS:=aDS;
if FDS<>nil then
begin
self.SetGradation(FDS.StockSymbol.GetTimeIntervalValue/MinsPerDay);
FDS.AddEventHandler(FEventMediator);
SetPricePrecision(FDS.GetPricePrecision);
SetPricesInPoint(FDS.GetPricesInPoint);
end;
OnItemsChanged;
end;
end;
function TStockDataSourceToInputDataCollectionMediator.GetDataSource: IStockDataSource;
begin
result:=FDS;
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataOpen(index: integer): TStockRealNumber;
begin
result:=FDS.GetDataOpen(index);
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataHigh(index: integer): TStockRealNumber;
begin
result:=FDS.GetDataHigh(index);
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataDateTime(index: integer): TDateTime;
begin
result:=FDS.GetDataDateTime(index);
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataVolume(index: integer): integer;
begin
result:=FDS.GetDataVolume(index);
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataClose(index: integer): TStockRealNumber;
begin
result:=FDS.GetDataClose(index);
end;
function TStockDataSourceToInputDataCollectionMediator.DirectGetItem_DataLow(index: integer): TStockRealNumber;
begin
result:=FDS.GetDataLow(index);
end;
procedure CleanupInputDataObjects;
var
i: integer;
begin
for i:=0 to gReserveInputDataObjectsSize-1 do
FreeAndNil(gReserveInputDataObjects[i]);
end;
{ TEventMediator }
constructor TEventMediator.Create(aOwner: TStockDataSourceToInputDataCollectionMediator);
begin
FEventHandlers := TInterfaceList.Create;
FOwner:=aOwner;
end;
destructor TEventMediator.Destroy;
begin
FreeAndNil(FEventHandlers);
FOwner:=nil;
inherited;
end;
procedure TEventMediator.OnChangeData(const aSender: IStockDataSource; index: integer; aType: TStockDataModificationType);
begin
if FOwner<>nil then
FOwner.OnItemChanged(index,aType);
end;
initialization
finalization
CleanupInputDataObjects;
end.
|
unit ltr210api;
interface
uses SysUtils, ltrapitypes, ltrapidefine, ltrapi;
const
// Размер строки с именем модуля в структуре TINFO_LTR210
LTR210_NAME_SIZE = 8;
// Размер строки с серийным номером модуля в структуре TINFO_LTR210
LTR210_SERIAL_SIZE = 16;
// Количество каналов АЦП в одном модуле
LTR210_CHANNEL_CNT = 2;
// Количество диапазонов измерения АЦП
LTR210_RANGE_CNT = 5;
// Код принятого отсчета АЦП, соответствующий максимальному напряжению заданного диапазона
LTR210_ADC_SCALE_CODE_MAX = 13000;
// Максимальное значение делителя частоты АЦП
LTR210_ADC_FREQ_DIV_MAX = 9;
// Максимальное значение коэффициента прореживания данных от АЦП
LTR210_ADC_DCM_CNT_MAX = 256;
// Частота в Герцах, относительно которой задается частота отсчетов АЦП
LTR210_ADC_FREQ_HZ = 10000000;
// Частота в Герцах, относительно которой задается частота следования кадров в режиме LTR210_SYNC_MODE_PERIODIC
LTR210_FRAME_FREQ_HZ = 1000000;
// Размер внутреннего циклического буфера модуля в отсчетах АЦП
LTR210_INTERNAL_BUFFER_SIZE = 16777216;
// Максимальный размер кадра, который можно установить в одноканальном режиме
LTR210_FRAME_SIZE_MAX = (16777216 - 512);
{ -------------- Коды ошибок, специфичные для LTR210 ------------------------}
LTR210_ERR_INVALID_SYNC_MODE = -10500; // Задан неверный код условия сбора кадра
LTR210_ERR_INVALID_GROUP_MODE = -10501; // Задан неверный код режима работы модуля в составе группы
LTR210_ERR_INVALID_ADC_FREQ_DIV = -10502; // Задано неверное значение делителя частоты АЦП
LTR210_ERR_INVALID_CH_RANGE = -10503; // Задан неверный код диапазона канала АЦП
LTR210_ERR_INVALID_CH_MODE = -10504; // Задан неверный режим измерения канала
LTR210_ERR_SYNC_LEVEL_EXCEED_RANGE = -10505; // Установленный уровень аналоговой синхронизации выходит за границы установленного диапазона
LTR210_ERR_NO_ENABLED_CHANNEL = -10506; // Ни один канал АЦП не был разрешен
LTR210_ERR_PLL_NOT_LOCKED = -10507; // Ошибка захвата PLL
LTR210_ERR_INVALID_RECV_DATA_CNTR = -10508; // Неверное значение счетчика в принятых данных
LTR210_ERR_RECV_UNEXPECTED_CMD = -10509; // Прием неподдерживаемой команды в потоке данных
LTR210_ERR_FLASH_INFO_SIGN = -10510; // Неверный признак информации о модуле во Flash-памяти
LTR210_ERR_FLASH_INFO_SIZE = -10511; // Неверный размер прочитанной из Flash-памяти информации о модуле
LTR210_ERR_FLASH_INFO_UNSUP_FORMAT = -10512; // Неподдерживаемый формат информации о модуле из Flash-памяти
LTR210_ERR_FLASH_INFO_CRC = -10513; // Ошибка проверки CRC информации о модуле из Flash-памяти
LTR210_ERR_FLASH_INFO_VERIFY = -10514; // Ошибка проверки записи информации о модуле во Flash-память
LTR210_ERR_CHANGE_PAR_ON_THE_FLY = -10515; // Часть измененнных параметров нельзя изменять на лету
LTR210_ERR_INVALID_ADC_DCM_CNT = -10516; // Задан неверный коэффициент прореживания данных АЦП
LTR210_ERR_MODE_UNSUP_ADC_FREQ = -10517; // Установленный режим не поддерживает заданную частоту АЦП
LTR210_ERR_INVALID_FRAME_SIZE = -10518; // Неверно задан размер кадра
LTR210_ERR_INVALID_HIST_SIZE = -10519; // Неверно задан размер предыстории
LTR210_ERR_INVALID_INTF_TRANSF_RATE = -10520; // Неверно задано значение скорости выдачи данных в интерфейс
LTR210_ERR_INVALID_DIG_BIT_MODE = -10321; // Неверно задан режим работы дополнительного бита
LTR210_ERR_SYNC_LEVEL_LOW_EXCEED_HIGH = -10522; // Нижний порог аналоговой синхронизации превышает верхний
LTR210_ERR_KEEPALIVE_TOUT_EXCEEDED = -10523; // Не пришло ни одного статуса от модуля за заданный интервал
LTR210_ERR_WAIT_FRAME_TIMEOUT = -10524; // Не удалось дождаться прихода кадра за заданное время */
LTR210_ERR_FRAME_STATUS = -10525; // Слово статуса в принятом кадре указывает на ошибку данных */
{ --------------- Диапаоны канала АЦП ---------------------}
LTR210_ADC_RANGE_10 = 0; // Диапазон +/- 10 В
LTR210_ADC_RANGE_5 = 1; // Диапазон +/- 5 В
LTR210_ADC_RANGE_2 = 2; // Диапазон +/- 2 В
LTR210_ADC_RANGE_1 = 3; // Диапазон +/- 1 В
LTR210_ADC_RANGE_0_5 = 4; // Диапазон +/- 0.5 В
{ --------------- Режим измерения канала АЦП -------------}
LTR210_CH_MODE_ACDC = 0; // Измерение переменной и постоянной состовляющей (открытый вход)
LTR210_CH_MODE_AC = 1; // Отсечка постоянной состовляющей (закрытый вход)
LTR210_CH_MODE_ZERO = 2; // Режим измерения собственного нуля
{ --------------- Режим запуска сбора данных -------------------}
LTR210_SYNC_MODE_INTERNAL = 0; // Режим сбора кадра по программной команде, передаваемой вызовом LTR210_FrameStart()
LTR210_SYNC_MODE_CH1_RISE = 1; // Режим сбора кадра по фронту сигнала относительно уровня синхронизации на первом аналоговом канале
LTR210_SYNC_MODE_CH1_FALL = 2; // Режим сбора кадра по спаду сигнала относительно уровня синхронизации на первом аналоговом канале
LTR210_SYNC_MODE_CH2_RISE = 3; // Режим сбора кадра по фронту сигнала относительно уровня синхронизации на втором аналоговом канале
LTR210_SYNC_MODE_CH2_FALL = 4; // Режим сбора кадра по спаду сигнала относительно уровня синхронизации на втором аналоговом канале
LTR210_SYNC_MODE_SYNC_IN_RISE = 5; // Режим сбора кадра по фронту цифрового сигнала на входе SYNC (не от другого модуля!)
LTR210_SYNC_MODE_SYNC_IN_FALL = 6; // Режим сбора кадра по спаду цифрового сигнала на входе SYNC (не от другого модуля!)
LTR210_SYNC_MODE_PERIODIC = 7; // Режим периодического сбора кадров с установленной частотой следования кадров
LTR210_SYNC_MODE_CONTINUOUS = 8; // Режим непрерывного сбора данных
{ ---------------- Режим работы модуля в группе ------------------}
LTR210_GROUP_MODE_SINGLE = 0; // Работает только один независимый модуль
LTR210_GROUP_MODE_MASTER = 1; // Режим мастера
LTR210_GROUP_MODE_SLAVE = 2; // Режим подчиненного модуля
{----------------- Коды асинхронных событий ---------------------}
LTR210_RECV_EVENT_TIMEOUT = 0; // Не пришло никакого события от модуля за указанное время
LTR210_RECV_EVENT_KEEPALIVE = 1; // Пришел корректный сигнал жизни от модуля
LTR210_RECV_EVENT_SOF = 2; // Пришло начало собранного кадра
{ ---------------- Коды, определяющие правильность принятого кадра -------}
LTR210_FRAME_RESULT_OK = 0; // Кадр принят без ошибок. Данные кадра действительны
LTR210_FRAME_RESULT_PENDING = 1; // В обрабатываемых данных не было признака конца кадра.
LTR210_FRAME_RESULT_ERROR = 2; // Кадр принят с ошибкой. Данные кадра не действительны.
{----------------- Флаги статуса ----------------------------------}
LTR210_STATUS_FLAG_PLL_LOCK = $0001; // Признак захвата PLL в момент передачи статуса
LTR210_STATUS_FLAG_PLL_LOCK_HOLD = $0002; // Признак, что захват PLL не пропадал с момента предыдущей предачи статуса.
LTR210_STATUS_FLAG_OVERLAP = $0004; // Признак, что процесс записи обогнал процесс чтения
LTR210_STATUS_FLAG_SYNC_SKIP = $0008; // Признак, что во время записи кадра возникло хотя бы одно синхрособытие, которое было пропущено.
LTR210_STATUS_FLAG_INVALID_HIST = $0010; // Признак того, что предистория принятого кадра не действительна
LTR210_STATUS_FLAG_CH1_EN = $0040; // Признак, что разрешена запись по первому каналу
LTR210_STATUS_FLAG_CH2_EN = $0080; // Признак, что разрешена запись по второму каналу
{---------------- Дополнительные флаги настроек -------------------}
// Разрешение периодической передачи статуса модуля при запущенном сборе
LTR210_CFG_FLAGS_KEEPALIVE_EN = $001;
{ Разрешение режима автоматической приостановки записи на время, пока
кадр выдается по интерфейсу в крейт. Данный режим позволяет установить
максимальный размер кадра независимо от частоты отсчетов АЦП }
LTR210_CFG_FLAGS_WRITE_AUTO_SUSP = $002;
// Включение тестого режима, в котором вместо данных передается счетчик
LTR210_CFG_FLAGS_TEST_CNTR_MODE = $100;
{ ----------------- Флаги обработки данных ------------------------}
{ Признак, что нужно перевести коды АЦП в Вольты. Если данный флаг не указан,
то будут возвращены коды АЦП. При этом код #LTR210_ADC_SCALE_CODE_MAX
соответствует максиальному напряжению для установленного диапзона. }
LTR210_PROC_FLAG_VOLT = $0001;
{ Признак, что необходимо выполнить коррекцию АЧХ на основании записанных
в модуль коэффициентов падения АЧХ }
LTR210_PROC_FLAG_AFC_COR = $0002;
{ Признак, что необходимо выполнить дополнительную коррекцию нуля с помощью
значений из State.AdcZeroOffset, которые могут быть измерены с помощью
функции LTR210_MeasAdcZeroOffset() }
LTR210_PROC_FLAG_ZERO_OFFS_COR = $0004;
{ По умолчанию LTR210_ProcessData() предпологает, что ей на обработку
передаются все принятые данные, и проверяет непрерывность счетчика не только
внутри переданного блока данных, но и между вызовами.
Если обрабатываются не все данные или одни и теже данные обрабатыаются
повторно, то нужно указать данный флаг, чтобы счетчик проверялся только
внутри блока }
LTR210_PROC_FLAG_NONCONT_DATA = $0100;
{ --------------- Скорость выдачи данных в интерфейс ----------------}
LTR210_INTF_TRANSF_RATE_500K = 0; // 500 КСлов/c
LTR210_INTF_TRANSF_RATE_200K = 1; // 200 КСлов/c
LTR210_INTF_TRANSF_RATE_100K = 2; // 100 КСлов/c
LTR210_INTF_TRANSF_RATE_50K = 3; // 50 КСлов/c
LTR210_INTF_TRANSF_RATE_25K = 4; // 25 КСлов/c
LTR210_INTF_TRANSF_RATE_10K = 5; // 10 КСлов/c
{ ---------- Режим работы дополнительного бита во входном потоке ----------}
LTR210_DIG_BIT_MODE_ZERO = 0; // Всегда нулевое значение бита
LTR210_DIG_BIT_MODE_SYNC_IN = 1; // Бит отражает состояние цифрового входа SYNC модуля
LTR210_DIG_BIT_MODE_CH1_LVL = 2; // Бит равен "1", если уровень сигнала для 1-го канала АЦП выше уровня синхронизации
LTR210_DIG_BIT_MODE_CH2_LVL = 3; // Бит равен "1", если уровень сигнала для 2-го канала АЦП выше уровня синхронизации
LTR210_DIG_BIT_MODE_INTERNAL_SYNC = 4; // Бит равен "1" для одного отсчета в момент срабатывания программной или периодической синхронизации
{$A4}
{ Калибровочные коэффициенты }
type TLTR210_CBR_COEF = record
Offset : Single; // Код смещения
Scale : Single; // Коэффициент шкалы
end;
{ Параметры БИХ-фильтра }
type TLTR210_AFC_IIR_COEF = record
R : Double; // Сопротивление эквивалентной цепи фильтра
C : Double; // Емкость эквивалентной цепи фильтра
end;
{ Информация о модуле }
TINFO_LTR210 = record
Name : Array [0..LTR210_NAME_SIZE-1] of AnsiChar; // Название модуля (оканчивающаяся нулем ASCII-строка)
Serial : Array [0..LTR210_SERIAL_SIZE-1] of AnsiChar; //Серийный номер модуля (оканчивающаяся нулем ASCII-строка)
VerFPGA : Word; // Версия прошивки ПЛИС модуля (действительна только после ее загрузки)
VerPLD : Byte; //Версия прошивки PLD
{ Заводские калибровочные коэффициенты (на канал действительны первые
#LTR210_RANGE_CNT, остальные - резерв) }
CbrCoef : Array[0..LTR210_CHANNEL_CNT-1] of Array [0..7] of TLTR210_CBR_COEF;
{ Частота в Гц, которой соответствуют корректировочные коэффициенты АЧХ }
AfcCoefFreq : Double;
{ Коэффициенты, задающие спад АЧХ модуля на частоте AfcCoefFreq. Представляют
собой отношение амплитуды измеренного синусоидального сигнала на указанной
частоте к амплитуде реально выставленного сигнала. Коэффициенты загружаются
из Flash-памяти модуля при открытии связи с ним. Могут быть использованы
для корректировки АЧХ при необходимости. На канал действительны первые
LTR210_RANGE_CNT коэффициентов, остальные - резерв. }
AfcCoef : Array[0..LTR210_CHANNEL_CNT-1] of Array [0..7] of Double;
AfcIirParam : Array[0..LTR210_CHANNEL_CNT-1] of Array [0..7] of TLTR210_AFC_IIR_COEF;
Reserved : Array[1..32] of LongWord; // Резервные поля (не должны изменяться пользователем)
end;
{ Настройки канала АЦП }
TLTR210_CHANNEL_CONFIG = record
Enabled : Boolean; // Признак, разрешен ли сбор по данному каналу
Range : Byte; // Установленный диапазон --- константа из #e_LTR210_ADC_RANGE
Mode : Byte; // Режим измерения --- константа из #e_LTR210_CH_MODE
DigBitMode : Byte; // Режим работы дополнительного бита во входном потоке данных данного канала. Константа из #e_LTR210_DIG_BIT_MODE
Reserved: Array [1..4] of Byte; //Резервные поля (не должны изменяться пользователем)
SyncLevelL : Double; //Нижний порог гистерезиса для события аналоговой синхронизации в Вольтах
SyncLevelH : Double; //Верхний порог гистерезиса для события аналоговой синхронизации в Вольтах
Reserved2: array [1..10] of LongWord; // Резервные поля (не должны изменяться пользователем)
end;
PTLTR210_CHANNEL_CONFIG = ^TLTR210_CHANNEL_CONFIG;
{ Настройки модуля }
TLTR210_CONFIG = record
Ch : array [0..LTR210_CHANNEL_CNT-1] of TLTR210_CHANNEL_CONFIG; // Настройки каналов АЦП
FrameSize : LongWord; // Размер точек на канал в кадре при покадровом сборе
{ Размер сохранной предыстории (количество точек в кадре на канал,
измеренных до возникновения события синхронизации) }
HistSize : LongWord;
// Условие сбора кадра (событие синхронизации). Одно из значений #e_LTR210_SYNC_MODE
SyncMode : Byte;
// Режим работы в составе группы модулей. Одно из значений #e_LTR210_GROUP_MODE
GroupMode : Byte;
{ Значение делителя частоты АЦП - 1. Может быть в диапазоне от 0
до #LTR210_ADC_FREQ_DIV_MAX-1 }
AdcFreqDiv : Word;
{ Значение коэфициент прореживания данных АЦП - 1. Может быть в диапазоне
от 0 до #LTR210_ADC_DCM_CNT_MAX-1.}
AdcDcmCnt : LongWord;
{ Делитель частоты запуска сбора кадров для SyncMode = #LTR210_SYNC_MODE_PERIODIC.
Частота кадров равна 10^6/(FrameFreqDiv + 1) Гц }
FrameFreqDiv : LongWord;
Flags : LongWord; // Флаги (комбинация из #e_LTR210_CFG_FLAGS)
{ Скорость выдачи данных в интерфейс (одно из значений из #e_LTR210_INTF_TRANSF_RATE).
По-умолчанию устанавливается максимальная скорость (500 КСлов/с).
Если установленная скорость превышает максимальную скорость интерфейса для крейта,
в который установлен модуль, то будет установлена максимальная скорость,
поддерживаемая данным крейтом }
IntfTransfRate : Byte;
Reserved : array [1..39] of LongWord; // Резервные поля (не должны изменяться пользователем)
end;
PTLTR210_CONFIG = ^TLTR210_CONFIG;
{ Параметры состояния модуля. }
TLTR210_STATE = record
Run : Boolean; // Признак, запущен ли сбор данных
{ Количество слов в принимаемом кадре, включая статус.
(устанавливается после вызова LTR210_SetADC()) }
RecvFrameSize : LongWord;
{ Рассчитанная частота отсчетов АЦП в Гц (устанавливается после вызова
LTR210_SetADC()) }
AdcFreq : Double;
{ Рассчитанная частота следования кадров для режима синхронизации
#LTR210_SYNC_MODE_PERIODIC (устанавливается после вызова
LTR210_SetADC()) }
FrameFreq : Double;
{ Измеренные значения смещения нуля АЦП в кодах }
AdcZeroOffset : Array [0..LTR210_CHANNEL_CNT-1] of Double;
Reserved : Array [1..4] of LongWord; // Резервные поля
end;
PTLTR210_INTARNAL = ^TLTR210_INTARNAL;
TLTR210_INTARNAL = record
end;
{ Описатель модуля }
TLTR210 = record
Size : Integer; // Размер структуры. Заполняется в LTR210_Init().
{ Структура, содержащая состояние соединения с сервером.
Не используется напрямую пользователем. }
Channel : TLTR;
{ Указатель на непрозрачную структуру с внутренними параметрами,
используемыми исключительно библиотекой и недоступными для пользователя. }
Internal : PTLTR210_INTARNAL;
{ Настройки модуля. Заполняются пользователем перед вызовом LTR210_SetADC(). }
Cfg : TLTR210_CONFIG;
{ Состояние модуля и рассчитанные параметры. Поля изменяются функциями
библиотеки. Пользовательской программой могут использоваться
только для чтения. }
State : TLTR210_STATE;
ModuleInfo : TINFO_LTR210; // Информация о модуле
end;
pTLTR210=^TLTR210;
{ Дополнительная информация о принятом отсчете }
TLTR210_DATA_INFO = record
{ Младший бит соответствует значению дополнительного бита, передаваемого
вместе с потоком данных. Что означает данный бит задается одной
из констант из #e_LTR210_DIG_BIT_MODE в поле DigBitMode на этапе конфигурации.
Остальные биты могут быть использованы в будущем, поэтому при аналезе
нужно проверять значение DigBitState and 1 }
DigBitState : Byte;
{ Номер канала, которому соответствует принятое слово (0-первый, 1 - второй) }
Ch : Byte;
Range : Byte; // Диапазон канала, установленный во время преобразования
Reserved : Byte; // Резервные поля (не должны изменяться пользователем)
end;
PTLTR210_DATA_INFO = ^TLTR210_DATA_INFO;
{ Информация о статусе обработанного кадра }
TLTR210_FRAME_STATUS = record
{ Код результата обработки кадра (одно из значений #e_LTR210_FRAME_RESULT).
Позволяет определить, найден ли был конец кадра и действительны
ли данные в кадре }
Result : Byte;
{ Резервное поле (всегда равно 0) }
Reserved : Byte;
{ Дополнительные флаги из #e_LTR210_STATUS_FLAGS,
представляющие собой информацию о статусе самого
модуля и принятого кадра. Может быть несколько флагов,
объединенных через логическое ИЛИ }
Flags : Word;
end;
PTLTR210_FRAME_STATUS = ^TLTR210_FRAME_STATUS;
{ Тип функции для индикации процесса загрузки ПЛИС }
type TLTR210_LOAD_PROGR_CB = procedure(cb_data : Pointer; var hnd: TLTR210; done_size: LongWord; full_size : LongWord); {$I ltrapi_callconvention};
type PTLTR210_LOAD_PROGR_CB = ^TLTR210_LOAD_PROGR_CB;
{$A+}
// Инициализация описателя модуля
Function LTR210_Init(out hnd: TLTR210) : Integer;
// Установить соединение с модулем.
Function LTR210_Open(var hnd: TLTR210; net_addr : LongWord; net_port : LongWord;
csn: string; slot: Word): Integer;
// Закрытие соединения с модулем
Function LTR210_Close(var hnd: TLTR210) : Integer;
// Проверка, открыто ли соединение с модулем.
Function LTR210_IsOpened(var hnd: TLTR210) : Integer;
// Проверка, загружена ли прошивка ПЛИС модуля.
Function LTR210_FPGAIsLoaded(var hnd: TLTR210) : Integer;
// Загрузка прошивки ПЛИС модуля.
Function LTR210_LoadFPGA(var hnd: TLTR210; filename : string; progr_cb : TLTR210_LOAD_PROGR_CB; cb_data: Pointer) : Integer;
Function LTR210_LoadFPGA(var hnd: TLTR210; filename : string) : Integer; overload;
// Запись настроек в модуль
Function LTR210_SetADC(var hnd: TLTR210) : Integer;
Function LTR210_FillAdcFreq(var cfg: TLTR210_CONFIG; freq : double; flags : LongWord; out set_freq : double) : Integer; overload;
Function LTR210_FillAdcFreq(var cfg: TLTR210_CONFIG; freq : double; flags : LongWord) : Integer; overload;
Function LTR210_FillFrameFreq(var cfg: TLTR210_CONFIG; freq : double; out set_freq : double) : Integer; overload;
Function LTR210_FillFrameFreq(var cfg: TLTR210_CONFIG; freq : double) : Integer; overload;
// Перевод в режим сбора данных
Function LTR210_Start(var hnd: TLTR210) : Integer;
// Останов режима сбора данных
Function LTR210_Stop(var hnd: TLTR210) : Integer;
// Програмный запуск сбора кадра
Function LTR210_FrameStart(var hnd: TLTR210) : Integer;
// Ожидание асинхронного события от модуля
Function LTR210_WaitEvent(var hnd: TLTR210; out evt: LongWord; out status: LongWord; tout: LongWord) : Integer; overload;
Function LTR210_WaitEvent(var hnd: TLTR210; out evt: LongWord; tout: LongWord) : Integer; overload;
// Прием данных от модуля
Function LTR210_Recv(var hnd: TLTR210; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
Function LTR210_Recv(var hnd: TLTR210; out data : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
// Обработка принятых от модуля слов
Function LTR210_ProcessData(var hnd: TLTR210; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS; out data_info: array of TLTR210_DATA_INFO): LongInt; overload;
Function LTR210_ProcessData(var hnd: TLTR210; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS): LongInt; overload;
// Измерение смещения нуля
Function LTR210_MeasAdcZeroOffset(var hnd: TLTR210; flags : LongWord) : Integer;
// Получение прошедшего интервала с момента приема последнего слова
Function LTR210_GetLastWordInterval(var hnd: TLTR210; out interval: LongWord) : Integer;
// Получение сообщения об ошибке.
Function LTR210_GetErrorString(err: Integer) : string;
implementation
Function _init(out hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Init';
Function _open(var hnd: TLTR210; net_addr : LongWord; net_port : LongWord; csn: PAnsiChar; slot: Word) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Open';
Function _close(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Close';
Function _is_opened(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_IsOpened';
Function _fpga_is_loaded(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_FPGAIsLoaded';
Function _load_fpga(var hnd: TLTR210; filename : PAnsiChar; progr_cb : TLTR210_LOAD_PROGR_CB; cb_data: Pointer) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_LoadFPGA';
Function _set_adc(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_SetADC';
Function _fill_adc_freq(var cfg: TLTR210_CONFIG; freq : double; flags : LongWord; out set_freq : double) : Integer; {$I ltrapi_callconvention};external 'ltr210api' name 'LTR210_FillAdcFreq';
Function _fill_frame_freq(var cfg: TLTR210_CONFIG; freq : double; out set_freq : double) : Integer; {$I ltrapi_callconvention};external 'ltr210api' name 'LTR210_FillFrameFreq';
Function _start(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Start';
Function _stop(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Stop';
Function _frame_start(var hnd: TLTR210) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_FrameStart';
Function _wait_event(var hnd: TLTR210; out evt: LongWord; out status: LongWord; tout: LongWord) : Integer; {$I ltrapi_callconvention}; overload; external 'ltr210api' name 'LTR210_WaitEvent';
Function _recv(var hnd: TLTR210; out data; out tmark; size: LongWord; tout : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_Recv';
Function _process_data(var hnd: TLTR210; var src; out dest; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS; out data_info): LongInt; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_ProcessData'; overload;
//Function _process_data(var hnd: TLTR210; var src; out dest; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS; data_info : Pointer): LongInt; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_ProcessData'; overload;
Function _meas_adc_zero_offset(var hnd: TLTR210; flags : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_MeasAdcZeroOffset';
Function _get_last_word_interval(var hnd: TLTR210; out interval: LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_GetLastWordInterval';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr210api' name 'LTR210_GetErrorString';
Function LTR210_Init(out hnd: TLTR210) : Integer;
begin
LTR210_Init:=_init(hnd);
end;
Function LTR210_Open(var hnd: TLTR210; net_addr : LongWord; net_port : LongWord; csn: string; slot: Word): Integer;
begin
LTR210_Open:=_open(hnd, net_addr, net_port, PAnsiChar(AnsiString(csn)), slot);
end;
Function LTR210_Close(var hnd: TLTR210) : Integer;
begin
LTR210_Close:=_close(hnd);
end;
Function LTR210_IsOpened(var hnd: TLTR210) : Integer;
begin
LTR210_IsOpened:=_is_opened(hnd);
end;
Function LTR210_FPGAIsLoaded(var hnd: TLTR210) : Integer;
begin
LTR210_FPGAIsLoaded:=_fpga_is_loaded(hnd);
end;
Function LTR210_LoadFPGA(var hnd: TLTR210; filename : string; progr_cb : TLTR210_LOAD_PROGR_CB; cb_data: Pointer) : Integer;
begin
LTR210_LoadFPGA:=_load_fpga(hnd, PAnsiChar(AnsiString(filename)), progr_cb, cb_data);
end;
Function LTR210_LoadFPGA(var hnd: TLTR210; filename : string) : Integer;
begin
LTR210_LoadFPGA:=LTR210_LoadFPGA(hnd, PAnsiChar(AnsiString(filename)), nil, nil);
end;
Function LTR210_SetADC(var hnd: TLTR210) : Integer;
begin
LTR210_SetADC:=_set_adc(hnd);
end;
Function LTR210_FillAdcFreq(var cfg: TLTR210_CONFIG; freq : double; flags : LongWord; out set_freq : double) : Integer; overload;
begin
LTR210_FillAdcFreq:=_fill_adc_freq(cfg, freq, flags, set_freq);
end;
Function LTR210_FillAdcFreq(var cfg: TLTR210_CONFIG; freq : double; flags : LongWord) : Integer;
begin
LTR210_FillAdcFreq:=LTR210_FillAdcFreq(cfg, freq, flags, PDouble(nil)^);
end;
Function LTR210_FillFrameFreq(var cfg: TLTR210_CONFIG; freq : double; out set_freq : double) : Integer; overload;
begin
LTR210_FillFrameFreq:=_fill_frame_freq(cfg, freq, set_freq);
end;
Function LTR210_FillFrameFreq(var cfg: TLTR210_CONFIG; freq : double) : Integer;
begin
LTR210_FillFrameFreq:=LTR210_FillFrameFreq(cfg, freq, PDouble(nil)^);
end;
Function LTR210_Start(var hnd: TLTR210) : Integer;
begin
LTR210_Start:=_start(hnd);
end;
Function LTR210_Stop(var hnd: TLTR210) : Integer;
begin
LTR210_Stop:=_stop(hnd);
end;
Function LTR210_FrameStart(var hnd: TLTR210) : Integer;
begin
LTR210_FrameStart:=_frame_start(hnd);
end;
Function LTR210_WaitEvent(var hnd: TLTR210; out evt: LongWord; out status: LongWord; tout: LongWord) : Integer; overload;
begin
LTR210_WaitEvent:=_wait_event(hnd, evt, status, tout);
end;
Function LTR210_WaitEvent(var hnd: TLTR210; out evt: LongWord; tout: LongWord) : Integer; overload;
begin
LTR210_WaitEvent:=LTR210_WaitEvent(hnd, evt, PLongWord(nil)^, tout);
end;
Function LTR210_Recv(var hnd: TLTR210; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR210_Recv:=_recv(hnd, data, tmark, size, tout);
end;
Function LTR210_Recv(var hnd: TLTR210; out data : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR210_Recv:=_recv(hnd, data, PLongWord(nil)^, size, tout);
end;
Function LTR210_ProcessData(var hnd: TLTR210; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS; out data_info: array of
TLTR210_DATA_INFO): LongInt;
begin
LTR210_ProcessData:=_process_data(hnd, src, dest, size, flags, frame_status, data_info);
end;
Function LTR210_ProcessData(var hnd: TLTR210; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out frame_status: TLTR210_FRAME_STATUS): LongInt;
begin
LTR210_ProcessData:=_process_data(hnd, src, dest, size, flags, frame_status, PTLTR210_DATA_INFO(nil)^);
end;
Function LTR210_MeasAdcZeroOffset(var hnd: TLTR210; flags : LongWord) : Integer;
begin
LTR210_MeasAdcZeroOffset:=_meas_adc_zero_offset(hnd, flags);
end;
Function LTR210_GetLastWordInterval(var hnd: TLTR210; out interval: LongWord) : Integer;
begin
LTR210_GetLastWordInterval:=_get_last_word_interval(hnd, interval);
end;
function LTR210_GetErrorString(err: Integer) : string;
begin
LTR210_GetErrorString:=string(_get_err_str(err));
end;
end.
|
unit Whirl512;
{Whirlpool - 512 bit Secure Hash Function}
interface
(*************************************************************************
DESCRIPTION : Whirlpool - 512 bit Secure Hash Function
REQUIREMENTS : TP6/7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : about 8KB tables in data segment
DISPLAY MODE : ---
REMARKS : Message bit length is limited to "only" 2^128
REFERENCES : [1] Whirlpool.c Version 3.0 (2003.03.12) by
Paulo S.L.M. Barreto / Vincent Rijmen available in
http://www.larc.usp.br/~pbarreto/whirlpool.zip
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 08.12.05 W.Ehrhardt Initial BP7 using SHA512 layout
0.11 08.12.05 we ISO_WHIRLPOOL: switch between V3.0 and ISO-Draft(=V2.1)
0.12 08.12.05 we TP5-6
0.13 09.12.05 we Tables C0...C7
0.14 09.12.05 we Tables C0L, C0H, ... C7H,C7H
0.15 09.12.05 we Tables CxL as absolute aliases
0.16 09.12.05 we Transform now global proc
0.17 09.12.05 we Byte access in 16 Bit Transform
0.18 09.12.05 we Tables: CxH -> Cx, CxL -> Cy (y=x+4 mod 8)
0.19 09.12.05 we BIT16: local copy in Transform, 20% faster
0.20 10.12.05 we const ISO_Whirl, BASM16
0.21 10.12.05 we BASM16: combine L[2x], L[2x+1] calculations
0.22 11.12.05 we BASM16: XorBlock
0.23 11.12.05 we Whirl_is_ISO, Whirl_UpdateXL interfaced if WIN32
0.24 11.12.05 we Force $I- in Whirl_File
0.25 17.12.05 we $ifdef DOUBLE_ROUNDS
0.26 22.12.05 we Keep only Final V3.0, no INC for tables
0.27 15.01.06 we uses Hash unit and THashDesc
0.28 15.01.06 we THState8
0.29 18.01.06 we Descriptor fields HAlgNum, HSig
0.30 22.01.06 we Removed HSelfTest from descriptor
0.31 11.02.06 we Descriptor as typed const
0.32 07.08.06 we $ifdef BIT32: (const fname: shortstring...)
0.33 21.01.07 we Bugfix for message bit lengths >= 2^32 (reported by Nicola Lugato)
0.34 22.02.07 we values for OID vector
0.35 30.06.07 we Use conditional define FPC_ProcVar
0.36 04.10.07 we FPC: {$asmmode intel}
0.37 03.05.08 we Bit-API: Whirl_FinalBits/Ex
0.38 05.05.08 we THashDesc constant with HFinalBit field
0.39 07.05.08 we Selftest; 1 Zero bit from nessie-test-vectors.txt
0.40 12.11.08 we uses BTypes, Ptr2Inc and/or Str255/Str127
0.41 18.12.10 we Updated link
0.42 26.12.12 we D17 and PurePascal
0.43 27.12.12 we Removed symbols DOUBLE_ROUNDS and USE_SHR
0.44 16.08.15 we Removed $ifdef DLL / stdcall
0.45 15.05.17 we adjust OID to new MaxOIDLen
0.46 29.11.17 we Whirl_File - fname: string
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2005-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
{$ifdef BIT64}
{$ifndef PurePascal}
{$define PurePascal}
{$endif}
{$endif}
{$ifdef PurePascal}
{$define UseInt64}
{$else}
{$ifdef D4Plus}
{$define UseInt64}
{$endif}
{$ifdef FPC}
{$define UseInt64}
{$endif}
{$endif}
uses
BTypes,Hash;
procedure Whirl_Init(var Context: THashContext);
{-initialize context}
procedure Whirl_Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
procedure Whirl_UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
procedure Whirl_Final(var Context: THashContext; var Digest: TWhirlDigest);
{-finalize Whirlpool calculation, clear context}
procedure Whirl_FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize Whirlpool calculation, clear context}
procedure Whirl_FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize Whirlpool calculation with bitlen bits from BData (big-endian), clear context}
procedure Whirl_FinalBits(var Context: THashContext; var Digest: TWhirlDigest; BData: byte; bitlen: integer);
{-finalize Whirlpool calculation with bitlen bits from BData (big-endian), clear context}
function Whirl_SelfTest: boolean;
{-self test for strings from Whirlpool distribution}
procedure Whirl_Full(var Digest: TWhirlDigest; Msg: pointer; Len: word);
{-Whirlpool hash-code of Msg with init/update/final}
procedure Whirl_FullXL(var Digest: TWhirlDigest; Msg: pointer; Len: longint);
{-Whirlpool hash-code of Msg with init/update/final}
procedure Whirl_File({$ifdef CONST} const {$endif} fname: string;
var Digest: TWhirlDigest; var buf; bsize: word; var Err: word);
{-Whirlpool hash-code of file, buf: buffer with at least bsize bytes}
implementation
{$ifdef BIT16}
{$F-}
{$endif}
const
Whirl_BlockLen = 64;
type
TWhirlTab = array[0..255] of longint;
THState8 = array[0..sizeof(THashState)-1] of byte;
PHashState = ^THashState;
{1.0.10118.3.0.55}
{iso(1) standard(0) hash-functions(10118) part3(3) algorithm(0) whirlpool(55)}
const
Whirl_OID : TOID_Vec = (1,0,10118,3,0,55,-1,-1,-1,-1,-1); {Len=6}
{$ifndef VER5X}
const
Whirl_Desc: THashDesc = (
HSig : C_HashSig;
HDSize : sizeof(THashDesc);
HDVersion : C_HashVers;
HBlockLen : Whirl_BlockLen;
HDigestlen: sizeof(TWhirlDigest);
{$ifdef FPC_ProcVar}
HInit : @Whirl_Init;
HFinal : @Whirl_FinalEx;
HUpdateXL : @Whirl_UpdateXL;
{$else}
HInit : Whirl_Init;
HFinal : Whirl_FinalEx;
HUpdateXL : Whirl_UpdateXL;
{$endif}
HAlgNum : longint(_Whirlpool);
HName : 'Whirlpool';
HPtrOID : @Whirl_OID;
HLenOID : 6;
HFill : 0;
{$ifdef FPC_ProcVar}
HFinalBit : @Whirl_FinalBitsEx;
{$else}
HFinalBit : Whirl_FinalBitsEx;
{$endif}
HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
);
{$else}
var
Whirl_Desc: THashDesc;
{$endif}
{Though Whirlpool is endianness-neutral, the encryption tables are listed}
{in Little-Endian format, which is adopted throughout this implementation}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
const
{Round constants in Little-Endian format high, low, high, low, ...}
RC: array[0..19] of longint = (
$e8c62318, $4f01b887, $f5d2a636, $52916f79, $8e9bbc60, $357b0ca3, $c2d7e01d,
$57fe4b2e, $e5377715, $da4af09f, $0a29c958, $856ba0b1, $f4105dbd, $67053ecb,
$8b4127e4, $d8957da7, $667ceefb, $9e4717dd, $07bf2dca, $33835aad);
{Whirlpool Version 3.0 encryption tables (highest 32 bits)}
C0: TWhirlTab = (
$18601818, $238c2323, $c63fc6c6, $e887e8e8, $87268787, $b8dab8b8, $01040101, $4f214f4f,
$36d83636, $a6a2a6a6, $d26fd2d2, $f5f3f5f5, $79f97979, $6fa16f6f, $917e9191, $52555252,
$609d6060, $bccabcbc, $9b569b9b, $8e028e8e, $a3b6a3a3, $0c300c0c, $7bf17b7b, $35d43535,
$1d741d1d, $e0a7e0e0, $d77bd7d7, $c22fc2c2, $2eb82e2e, $4b314b4b, $fedffefe, $57415757,
$15541515, $77c17777, $37dc3737, $e5b3e5e5, $9f469f9f, $f0e7f0f0, $4a354a4a, $da4fdada,
$587d5858, $c903c9c9, $29a42929, $0a280a0a, $b1feb1b1, $a0baa0a0, $6bb16b6b, $852e8585,
$bdcebdbd, $5d695d5d, $10401010, $f4f7f4f4, $cb0bcbcb, $3ef83e3e, $05140505, $67816767,
$e4b7e4e4, $279c2727, $41194141, $8b168b8b, $a7a6a7a7, $7de97d7d, $956e9595, $d847d8d8,
$fbcbfbfb, $ee9feeee, $7ced7c7c, $66856666, $dd53dddd, $175c1717, $47014747, $9e429e9e,
$ca0fcaca, $2db42d2d, $bfc6bfbf, $071c0707, $ad8eadad, $5a755a5a, $83368383, $33cc3333,
$63916363, $02080202, $aa92aaaa, $71d97171, $c807c8c8, $19641919, $49394949, $d943d9d9,
$f2eff2f2, $e3abe3e3, $5b715b5b, $881a8888, $9a529a9a, $26982626, $32c83232, $b0fab0b0,
$e983e9e9, $0f3c0f0f, $d573d5d5, $803a8080, $bec2bebe, $cd13cdcd, $34d03434, $483d4848,
$ffdbffff, $7af57a7a, $907a9090, $5f615f5f, $20802020, $68bd6868, $1a681a1a, $ae82aeae,
$b4eab4b4, $544d5454, $93769393, $22882222, $648d6464, $f1e3f1f1, $73d17373, $12481212,
$401d4040, $08200808, $c32bc3c3, $ec97ecec, $db4bdbdb, $a1bea1a1, $8d0e8d8d, $3df43d3d,
$97669797, $00000000, $cf1bcfcf, $2bac2b2b, $76c57676, $82328282, $d67fd6d6, $1b6c1b1b,
$b5eeb5b5, $af86afaf, $6ab56a6a, $505d5050, $45094545, $f3ebf3f3, $30c03030, $ef9befef,
$3ffc3f3f, $55495555, $a2b2a2a2, $ea8feaea, $65896565, $bad2baba, $2fbc2f2f, $c027c0c0,
$de5fdede, $1c701c1c, $fdd3fdfd, $4d294d4d, $92729292, $75c97575, $06180606, $8a128a8a,
$b2f2b2b2, $e6bfe6e6, $0e380e0e, $1f7c1f1f, $62956262, $d477d4d4, $a89aa8a8, $96629696,
$f9c3f9f9, $c533c5c5, $25942525, $59795959, $842a8484, $72d57272, $39e43939, $4c2d4c4c,
$5e655e5e, $78fd7878, $38e03838, $8c0a8c8c, $d163d1d1, $a5aea5a5, $e2afe2e2, $61996161,
$b3f6b3b3, $21842121, $9c4a9c9c, $1e781e1e, $43114343, $c73bc7c7, $fcd7fcfc, $04100404,
$51595151, $995e9999, $6da96d6d, $0d340d0d, $facffafa, $df5bdfdf, $7ee57e7e, $24902424,
$3bec3b3b, $ab96abab, $ce1fcece, $11441111, $8f068f8f, $4e254e4e, $b7e6b7b7, $eb8bebeb,
$3cf03c3c, $813e8181, $946a9494, $f7fbf7f7, $b9deb9b9, $134c1313, $2cb02c2c, $d36bd3d3,
$e7bbe7e7, $6ea56e6e, $c437c4c4, $030c0303, $56455656, $440d4444, $7fe17f7f, $a99ea9a9,
$2aa82a2a, $bbd6bbbb, $c123c1c1, $53515353, $dc57dcdc, $0b2c0b0b, $9d4e9d9d, $6cad6c6c,
$31c43131, $74cd7474, $f6fff6f6, $46054646, $ac8aacac, $891e8989, $14501414, $e1a3e1e1,
$16581616, $3ae83a3a, $69b96969, $09240909, $70dd7070, $b6e2b6b6, $d067d0d0, $ed93eded,
$cc17cccc, $42154242, $985a9898, $a4aaa4a4, $28a02828, $5c6d5c5c, $f8c7f8f8, $86228686) ;
C1: TWhirlTab = (
$601818d8, $8c232326, $3fc6c6b8, $87e8e8fb, $268787cb, $dab8b811, $04010109, $214f4f0d,
$d836369b, $a2a6a6ff, $6fd2d20c, $f3f5f50e, $f9797996, $a16f6f30, $7e91916d, $555252f8,
$9d606047, $cabcbc35, $569b9b37, $028e8e8a, $b6a3a3d2, $300c0c6c, $f17b7b84, $d4353580,
$741d1df5, $a7e0e0b3, $7bd7d721, $2fc2c29c, $b82e2e43, $314b4b29, $dffefe5d, $415757d5,
$541515bd, $c17777e8, $dc373792, $b3e5e59e, $469f9f13, $e7f0f023, $354a4a20, $4fdada44,
$7d5858a2, $03c9c9cf, $a429297c, $280a0a5a, $feb1b150, $baa0a0c9, $b16b6b14, $2e8585d9,
$cebdbd3c, $695d5d8f, $40101090, $f7f4f407, $0bcbcbdd, $f83e3ed3, $1405052d, $81676778,
$b7e4e497, $9c272702, $19414173, $168b8ba7, $a6a7a7f6, $e97d7db2, $6e959549, $47d8d856,
$cbfbfb70, $9feeeecd, $ed7c7cbb, $85666671, $53dddd7b, $5c1717af, $01474745, $429e9e1a,
$0fcacad4, $b42d2d58, $c6bfbf2e, $1c07073f, $8eadadac, $755a5ab0, $368383ef, $cc3333b6,
$9163635c, $08020212, $92aaaa93, $d97171de, $07c8c8c6, $641919d1, $3949493b, $43d9d95f,
$eff2f231, $abe3e3a8, $715b5bb9, $1a8888bc, $529a9a3e, $9826260b, $c83232bf, $fab0b059,
$83e9e9f2, $3c0f0f77, $73d5d533, $3a8080f4, $c2bebe27, $13cdcdeb, $d0343489, $3d484832,
$dbffff54, $f57a7a8d, $7a909064, $615f5f9d, $8020203d, $bd68680f, $681a1aca, $82aeaeb7,
$eab4b47d, $4d5454ce, $7693937f, $8822222f, $8d646463, $e3f1f12a, $d17373cc, $48121282,
$1d40407a, $20080848, $2bc3c395, $97ececdf, $4bdbdb4d, $bea1a1c0, $0e8d8d91, $f43d3dc8,
$6697975b, $00000000, $1bcfcff9, $ac2b2b6e, $c57676e1, $328282e6, $7fd6d628, $6c1b1bc3,
$eeb5b574, $86afafbe, $b56a6a1d, $5d5050ea, $09454557, $ebf3f338, $c03030ad, $9befefc4,
$fc3f3fda, $495555c7, $b2a2a2db, $8feaeae9, $8965656a, $d2baba03, $bc2f2f4a, $27c0c08e,
$5fdede60, $701c1cfc, $d3fdfd46, $294d4d1f, $72929276, $c97575fa, $18060636, $128a8aae,
$f2b2b24b, $bfe6e685, $380e0e7e, $7c1f1fe7, $95626255, $77d4d43a, $9aa8a881, $62969652,
$c3f9f962, $33c5c5a3, $94252510, $795959ab, $2a8484d0, $d57272c5, $e43939ec, $2d4c4c16,
$655e5e94, $fd78789f, $e03838e5, $0a8c8c98, $63d1d117, $aea5a5e4, $afe2e2a1, $9961614e,
$f6b3b342, $84212134, $4a9c9c08, $781e1eee, $11434361, $3bc7c7b1, $d7fcfc4f, $10040424,
$595151e3, $5e999925, $a96d6d22, $340d0d65, $cffafa79, $5bdfdf69, $e57e7ea9, $90242419,
$ec3b3bfe, $96abab9a, $1fcecef0, $44111199, $068f8f83, $254e4e04, $e6b7b766, $8bebebe0,
$f03c3cc1, $3e8181fd, $6a949440, $fbf7f71c, $deb9b918, $4c13138b, $b02c2c51, $6bd3d305,
$bbe7e78c, $a56e6e39, $37c4c4aa, $0c03031b, $455656dc, $0d44445e, $e17f7fa0, $9ea9a988,
$a82a2a67, $d6bbbb0a, $23c1c187, $515353f1, $57dcdc72, $2c0b0b53, $4e9d9d01, $ad6c6c2b,
$c43131a4, $cd7474f3, $fff6f615, $0546464c, $8aacaca5, $1e8989b5, $501414b4, $a3e1e1ba,
$581616a6, $e83a3af7, $b9696906, $24090941, $dd7070d7, $e2b6b66f, $67d0d01e, $93ededd6,
$17cccce2, $15424268, $5a98982c, $aaa4a4ed, $a0282875, $6d5c5c86, $c7f8f86b, $228686c2);
C2: TWhirlTab = (
$1818d830, $23232646, $c6c6b891, $e8e8fbcd, $8787cb13, $b8b8116d, $01010902, $4f4f0d9e,
$36369b6c, $a6a6ff51, $d2d20cb9, $f5f50ef7, $797996f2, $6f6f30de, $91916d3f, $5252f8a4,
$606047c0, $bcbc3565, $9b9b372b, $8e8e8a01, $a3a3d25b, $0c0c6c18, $7b7b84f6, $3535806a,
$1d1df53a, $e0e0b3dd, $d7d721b3, $c2c29c99, $2e2e435c, $4b4b2996, $fefe5de1, $5757d5ae,
$1515bd2a, $7777e8ee, $3737926e, $e5e59ed7, $9f9f1323, $f0f023fd, $4a4a2094, $dada44a9,
$5858a2b0, $c9c9cf8f, $29297c52, $0a0a5a14, $b1b1507f, $a0a0c95d, $6b6b14d6, $8585d917,
$bdbd3c67, $5d5d8fba, $10109020, $f4f407f5, $cbcbdd8b, $3e3ed37c, $05052d0a, $676778ce,
$e4e497d5, $2727024e, $41417382, $8b8ba70b, $a7a7f653, $7d7db2fa, $95954937, $d8d856ad,
$fbfb70eb, $eeeecdc1, $7c7cbbf8, $666671cc, $dddd7ba7, $1717af2e, $4747458e, $9e9e1a21,
$cacad489, $2d2d585a, $bfbf2e63, $07073f0e, $adadac47, $5a5ab0b4, $8383ef1b, $3333b666,
$63635cc6, $02021204, $aaaa9349, $7171dee2, $c8c8c68d, $1919d132, $49493b92, $d9d95faf,
$f2f231f9, $e3e3a8db, $5b5bb9b6, $8888bc0d, $9a9a3e29, $26260b4c, $3232bf64, $b0b0597d,
$e9e9f2cf, $0f0f771e, $d5d533b7, $8080f41d, $bebe2761, $cdcdeb87, $34348968, $48483290,
$ffff54e3, $7a7a8df4, $9090643d, $5f5f9dbe, $20203d40, $68680fd0, $1a1aca34, $aeaeb741,
$b4b47d75, $5454cea8, $93937f3b, $22222f44, $646463c8, $f1f12aff, $7373cce6, $12128224,
$40407a80, $08084810, $c3c3959b, $ececdfc5, $dbdb4dab, $a1a1c05f, $8d8d9107, $3d3dc87a,
$97975b33, $00000000, $cfcff983, $2b2b6e56, $7676e1ec, $8282e619, $d6d628b1, $1b1bc336,
$b5b57477, $afafbe43, $6a6a1dd4, $5050eaa0, $4545578a, $f3f338fb, $3030ad60, $efefc4c3,
$3f3fda7e, $5555c7aa, $a2a2db59, $eaeae9c9, $65656aca, $baba0369, $2f2f4a5e, $c0c08e9d,
$dede60a1, $1c1cfc38, $fdfd46e7, $4d4d1f9a, $92927639, $7575faea, $0606360c, $8a8aae09,
$b2b24b79, $e6e685d1, $0e0e7e1c, $1f1fe73e, $626255c4, $d4d43ab5, $a8a8814d, $96965231,
$f9f962ef, $c5c5a397, $2525104a, $5959abb2, $8484d015, $7272c5e4, $3939ec72, $4c4c1698,
$5e5e94bc, $78789ff0, $3838e570, $8c8c9805, $d1d117bf, $a5a5e457, $e2e2a1d9, $61614ec2,
$b3b3427b, $21213442, $9c9c0825, $1e1eee3c, $43436186, $c7c7b193, $fcfc4fe5, $04042408,
$5151e3a2, $9999252f, $6d6d22da, $0d0d651a, $fafa79e9, $dfdf69a3, $7e7ea9fc, $24241948,
$3b3bfe76, $abab9a4b, $cecef081, $11119922, $8f8f8303, $4e4e049c, $b7b76673, $ebebe0cb,
$3c3cc178, $8181fd1f, $94944035, $f7f71cf3, $b9b9186f, $13138b26, $2c2c5158, $d3d305bb,
$e7e78cd3, $6e6e39dc, $c4c4aa95, $03031b06, $5656dcac, $44445e88, $7f7fa0fe, $a9a9884f,
$2a2a6754, $bbbb0a6b, $c1c1879f, $5353f1a6, $dcdc72a5, $0b0b5316, $9d9d0127, $6c6c2bd8,
$3131a462, $7474f3e8, $f6f615f1, $46464c8c, $acaca545, $8989b50f, $1414b428, $e1e1badf,
$1616a62c, $3a3af774, $696906d2, $09094112, $7070d7e0, $b6b66f71, $d0d01ebd, $ededd6c7,
$cccce285, $42426884, $98982c2d, $a4a4ed55, $28287550, $5c5c86b8, $f8f86bed, $8686c211);
C3: TWhirlTab = (
$18d83078, $232646af, $c6b891f9, $e8fbcd6f, $87cb13a1, $b8116d62, $01090205, $4f0d9e6e,
$369b6cee, $a6ff5104, $d20cb9bd, $f50ef706, $7996f280, $6f30dece, $916d3fef, $52f8a407,
$6047c0fd, $bc356576, $9b372bcd, $8e8a018c, $a3d25b15, $0c6c183c, $7b84f68a, $35806ae1,
$1df53a69, $e0b3dd47, $d721b3ac, $c29c99ed, $2e435c96, $4b29967a, $fe5de121, $57d5ae16,
$15bd2a41, $77e8eeb6, $37926eeb, $e59ed756, $9f1323d9, $f023fd17, $4a20947f, $da44a995,
$58a2b025, $c9cf8fca, $297c528d, $0a5a1422, $b1507f4f, $a0c95d1a, $6b14d6da, $85d917ab,
$bd3c6773, $5d8fba34, $10902050, $f407f503, $cbdd8bc0, $3ed37cc6, $052d0a11, $6778cee6,
$e497d553, $27024ebb, $41738258, $8ba70b9d, $a7f65301, $7db2fa94, $954937fb, $d856ad9f,
$fb70eb30, $eecdc171, $7cbbf891, $6671cce3, $dd7ba78e, $17af2e4b, $47458e46, $9e1a21dc,
$cad489c5, $2d585a99, $bf2e6379, $073f0e1b, $adac4723, $5ab0b42f, $83ef1bb5, $33b666ff,
$635cc6f2, $0212040a, $aa934938, $71dee2a8, $c8c68dcf, $19d1327d, $493b9270, $d95faf9a,
$f231f91d, $e3a8db48, $5bb9b62a, $88bc0d92, $9a3e29c8, $260b4cbe, $32bf64fa, $b0597d4a,
$e9f2cf6a, $0f771e33, $d533b7a6, $80f41dba, $be27617c, $cdeb87de, $348968e4, $48329075,
$ff54e324, $7a8df48f, $90643dea, $5f9dbe3e, $203d40a0, $680fd0d5, $1aca3472, $aeb7412c,
$b47d755e, $54cea819, $937f3be5, $222f44aa, $6463c8e9, $f12aff12, $73cce6a2, $1282245a,
$407a805d, $08481028, $c3959be8, $ecdfc57b, $db4dab90, $a1c05f1f, $8d910783, $3dc87ac9,
$975b33f1, $00000000, $cff983d4, $2b6e5687, $76e1ecb3, $82e619b0, $d628b1a9, $1bc33677,
$b574775b, $afbe4329, $6a1dd4df, $50eaa00d, $45578a4c, $f338fb18, $30ad60f0, $efc4c374,
$3fda7ec3, $55c7aa1c, $a2db5910, $eae9c965, $656acaec, $ba036968, $2f4a5e93, $c08e9de7,
$de60a181, $1cfc386c, $fd46e72e, $4d1f9a64, $927639e0, $75faeabc, $06360c1e, $8aae0998,
$b24b7940, $e685d159, $0e7e1c36, $1fe73e63, $6255c4f7, $d43ab5a3, $a8814d32, $965231f4,
$f962ef3a, $c5a397f6, $25104ab1, $59abb220, $84d015ae, $72c5e4a7, $39ec72dd, $4c169861,
$5e94bc3b, $789ff085, $38e570d8, $8c980586, $d117bfb2, $a5e4570b, $e2a1d94d, $614ec2f8,
$b3427b45, $213442a5, $9c0825d6, $1eee3c66, $43618652, $c7b193fc, $fc4fe52b, $04240814,
$51e3a208, $99252fc7, $6d22dac4, $0d651a39, $fa79e935, $df69a384, $7ea9fc9b, $241948b4,
$3bfe76d7, $ab9a4b3d, $cef081d1, $11992255, $8f830389, $4e049c6b, $b7667351, $ebe0cb60,
$3cc178cc, $81fd1fbf, $944035fe, $f71cf30c, $b9186f67, $138b265f, $2c51589c, $d305bbb8,
$e78cd35c, $6e39dccb, $c4aa95f3, $031b060f, $56dcac13, $445e8849, $7fa0fe9e, $a9884f37,
$2a675482, $bb0a6b6d, $c1879fe2, $53f1a602, $dc72a58b, $0b531627, $9d0127d3, $6c2bd8c1,
$31a462f5, $74f3e8b9, $f615f109, $464c8c43, $aca54526, $89b50f97, $14b42844, $e1badf42,
$16a62c4e, $3af774d2, $6906d2d0, $0941122d, $70d7e0ad, $b66f7154, $d01ebdb7, $edd6c77e,
$cce285db, $42688457, $982c2dc2, $a4ed550e, $28755088, $5c86b831, $f86bed3f, $86c211a4);
C4: TWhirlTab = (
$d83078c0, $2646af05, $b891f97e, $fbcd6f13, $cb13a14c, $116d62a9, $09020508, $0d9e6e42,
$9b6ceead, $ff510459, $0cb9bdde, $0ef706fb, $96f280ef, $30dece5f, $6d3feffc, $f8a407aa,
$47c0fd27, $35657689, $372bcdac, $8a018c04, $d25b1571, $6c183c60, $84f68aff, $806ae1b5,
$f53a69e8, $b3dd4753, $21b3acf6, $9c99ed5e, $435c966d, $29967a62, $5de121a3, $d5ae1682,
$bd2a41a8, $e8eeb69f, $926eeba5, $9ed7567b, $1323d98c, $23fd17d3, $20947f6a, $44a9959e,
$a2b025fa, $cf8fca06, $7c528d55, $5a142250, $507f4fe1, $c95d1a69, $14d6da7f, $d917ab5c,
$3c677381, $8fba34d2, $90205080, $07f503f3, $dd8bc016, $d37cc6ed, $2d0a1128, $78cee61f,
$97d55373, $024ebb25, $73825832, $a70b9d2c, $f6530151, $b2fa94cf, $4937fbdc, $56ad9f8e,
$70eb308b, $cdc17123, $bbf891c7, $71cce317, $7ba78ea6, $af2e4bb8, $458e4602, $1a21dc84,
$d489c51e, $585a9975, $2e637991, $3f0e1b38, $ac472301, $b0b42fea, $ef1bb56c, $b666ff85,
$5cc6f23f, $12040a10, $93493839, $dee2a8af, $c68dcf0e, $d1327dc8, $3b927072, $5faf9a86,
$31f91dc3, $a8db484b, $b9b62ae2, $bc0d9234, $3e29c8a4, $0b4cbe2d, $bf64fa8d, $597d4ae9,
$f2cf6a1b, $771e3378, $33b7a6e6, $f41dba74, $27617c99, $eb87de26, $8968e4bd, $3290757a,
$54e324ab, $8df48ff7, $643deaf4, $9dbe3ec2, $3d40a01d, $0fd0d567, $ca3472d0, $b7412c19,
$7d755ec9, $cea8199a, $7f3be5ec, $2f44aa0d, $63c8e907, $2aff12db, $cce6a2bf, $82245a90,
$7a805d3a, $48102840, $959be856, $dfc57b33, $4dab9096, $c05f1f61, $9107831c, $c87ac9f5,
$5b33f1cc, $00000000, $f983d436, $6e568745, $e1ecb397, $e619b064, $28b1a9fe, $c33677d8,
$74775bc1, $be432911, $1dd4df77, $eaa00dba, $578a4c12, $38fb18cb, $ad60f09d, $c4c3742b,
$da7ec3e5, $c7aa1c92, $db591079, $e9c96503, $6acaec0f, $036968b9, $4a5e9365, $8e9de74e,
$60a181be, $fc386ce0, $46e72ebb, $1f9a6452, $7639e0e4, $faeabc8f, $360c1e30, $ae099824,
$4b7940f9, $85d15963, $7e1c3670, $e73e63f8, $55c4f737, $3ab5a3ee, $814d3229, $5231f4c4,
$62ef3a9b, $a397f666, $104ab135, $abb220f2, $d015ae54, $c5e4a7b7, $ec72ddd5, $1698615a,
$94bc3bca, $9ff085e7, $e570d8dd, $98058614, $17bfb2c6, $e4570b41, $a1d94d43, $4ec2f82f,
$427b45f1, $3442a515, $0825d694, $ee3c66f0, $61865222, $b193fc76, $4fe52bb3, $24081420,
$e3a208b2, $252fc7bc, $22dac44f, $651a3968, $79e93583, $69a384b6, $a9fc9bd7, $1948b43d,
$fe76d7c5, $9a4b3d31, $f081d13e, $99225588, $8303890c, $049c6b4a, $667351d1, $e0cb600b,
$c178ccfd, $fd1fbf7c, $4035fed4, $1cf30ceb, $186f67a1, $8b265f98, $51589c7d, $05bbb8d6,
$8cd35c6b, $39dccb57, $aa95f36e, $1b060f18, $dcac138a, $5e88491a, $a0fe9edf, $884f3721,
$6754824d, $0a6b6db1, $879fe246, $f1a602a2, $72a58bae, $53162758, $0127d39c, $2bd8c147,
$a462f595, $f3e8b987, $15f109e3, $4c8c430a, $a5452609, $b50f973c, $b42844a0, $badf425b,
$a62c4eb0, $f774d2cd, $06d2d06f, $41122d48, $d7e0ada7, $6f7154d9, $1ebdb7ce, $d6c77e3b,
$e285db2e, $6884572a, $2c2dc2b4, $ed550e49, $7550885d, $86b831da, $6bed3f93, $c211a444);
C5: TWhirlTab = (
$3078c018, $46af0523, $91f97ec6, $cd6f13e8, $13a14c87, $6d62a9b8, $02050801, $9e6e424f,
$6ceead36, $510459a6, $b9bdded2, $f706fbf5, $f280ef79, $dece5f6f, $3feffc91, $a407aa52,
$c0fd2760, $657689bc, $2bcdac9b, $018c048e, $5b1571a3, $183c600c, $f68aff7b, $6ae1b535,
$3a69e81d, $dd4753e0, $b3acf6d7, $99ed5ec2, $5c966d2e, $967a624b, $e121a3fe, $ae168257,
$2a41a815, $eeb69f77, $6eeba537, $d7567be5, $23d98c9f, $fd17d3f0, $947f6a4a, $a9959eda,
$b025fa58, $8fca06c9, $528d5529, $1422500a, $7f4fe1b1, $5d1a69a0, $d6da7f6b, $17ab5c85,
$677381bd, $ba34d25d, $20508010, $f503f3f4, $8bc016cb, $7cc6ed3e, $0a112805, $cee61f67,
$d55373e4, $4ebb2527, $82583241, $0b9d2c8b, $530151a7, $fa94cf7d, $37fbdc95, $ad9f8ed8,
$eb308bfb, $c17123ee, $f891c77c, $cce31766, $a78ea6dd, $2e4bb817, $8e460247, $21dc849e,
$89c51eca, $5a99752d, $637991bf, $0e1b3807, $472301ad, $b42fea5a, $1bb56c83, $66ff8533,
$c6f23f63, $040a1002, $493839aa, $e2a8af71, $8dcf0ec8, $327dc819, $92707249, $af9a86d9,
$f91dc3f2, $db484be3, $b62ae25b, $0d923488, $29c8a49a, $4cbe2d26, $64fa8d32, $7d4ae9b0,
$cf6a1be9, $1e33780f, $b7a6e6d5, $1dba7480, $617c99be, $87de26cd, $68e4bd34, $90757a48,
$e324abff, $f48ff77a, $3deaf490, $be3ec25f, $40a01d20, $d0d56768, $3472d01a, $412c19ae,
$755ec9b4, $a8199a54, $3be5ec93, $44aa0d22, $c8e90764, $ff12dbf1, $e6a2bf73, $245a9012,
$805d3a40, $10284008, $9be856c3, $c57b33ec, $ab9096db, $5f1f61a1, $07831c8d, $7ac9f53d,
$33f1cc97, $00000000, $83d436cf, $5687452b, $ecb39776, $19b06482, $b1a9fed6, $3677d81b,
$775bc1b5, $432911af, $d4df776a, $a00dba50, $8a4c1245, $fb18cbf3, $60f09d30, $c3742bef,
$7ec3e53f, $aa1c9255, $591079a2, $c96503ea, $caec0f65, $6968b9ba, $5e93652f, $9de74ec0,
$a181bede, $386ce01c, $e72ebbfd, $9a64524d, $39e0e492, $eabc8f75, $0c1e3006, $0998248a,
$7940f9b2, $d15963e6, $1c36700e, $3e63f81f, $c4f73762, $b5a3eed4, $4d3229a8, $31f4c496,
$ef3a9bf9, $97f666c5, $4ab13525, $b220f259, $15ae5484, $e4a7b772, $72ddd539, $98615a4c,
$bc3bca5e, $f085e778, $70d8dd38, $0586148c, $bfb2c6d1, $570b41a5, $d94d43e2, $c2f82f61,
$7b45f1b3, $42a51521, $25d6949c, $3c66f01e, $86522243, $93fc76c7, $e52bb3fc, $08142004,
$a208b251, $2fc7bc99, $dac44f6d, $1a39680d, $e93583fa, $a384b6df, $fc9bd77e, $48b43d24,
$76d7c53b, $4b3d31ab, $81d13ece, $22558811, $03890c8f, $9c6b4a4e, $7351d1b7, $cb600beb,
$78ccfd3c, $1fbf7c81, $35fed494, $f30cebf7, $6f67a1b9, $265f9813, $589c7d2c, $bbb8d6d3,
$d35c6be7, $dccb576e, $95f36ec4, $060f1803, $ac138a56, $88491a44, $fe9edf7f, $4f3721a9,
$54824d2a, $6b6db1bb, $9fe246c1, $a602a253, $a58baedc, $1627580b, $27d39c9d, $d8c1476c,
$62f59531, $e8b98774, $f109e3f6, $8c430a46, $452609ac, $0f973c89, $2844a014, $df425be1,
$2c4eb016, $74d2cd3a, $d2d06f69, $122d4809, $e0ada770, $7154d9b6, $bdb7ced0, $c77e3bed,
$85db2ecc, $84572a42, $2dc2b498, $550e49a4, $50885d28, $b831da5c, $ed3f93f8, $11a44486);
C6: TWhirlTab = (
$78c01860, $af05238c, $f97ec63f, $6f13e887, $a14c8726, $62a9b8da, $05080104, $6e424f21,
$eead36d8, $0459a6a2, $bdded26f, $06fbf5f3, $80ef79f9, $ce5f6fa1, $effc917e, $07aa5255,
$fd27609d, $7689bcca, $cdac9b56, $8c048e02, $1571a3b6, $3c600c30, $8aff7bf1, $e1b535d4,
$69e81d74, $4753e0a7, $acf6d77b, $ed5ec22f, $966d2eb8, $7a624b31, $21a3fedf, $16825741,
$41a81554, $b69f77c1, $eba537dc, $567be5b3, $d98c9f46, $17d3f0e7, $7f6a4a35, $959eda4f,
$25fa587d, $ca06c903, $8d5529a4, $22500a28, $4fe1b1fe, $1a69a0ba, $da7f6bb1, $ab5c852e,
$7381bdce, $34d25d69, $50801040, $03f3f4f7, $c016cb0b, $c6ed3ef8, $11280514, $e61f6781,
$5373e4b7, $bb25279c, $58324119, $9d2c8b16, $0151a7a6, $94cf7de9, $fbdc956e, $9f8ed847,
$308bfbcb, $7123ee9f, $91c77ced, $e3176685, $8ea6dd53, $4bb8175c, $46024701, $dc849e42,
$c51eca0f, $99752db4, $7991bfc6, $1b38071c, $2301ad8e, $2fea5a75, $b56c8336, $ff8533cc,
$f23f6391, $0a100208, $3839aa92, $a8af71d9, $cf0ec807, $7dc81964, $70724939, $9a86d943,
$1dc3f2ef, $484be3ab, $2ae25b71, $9234881a, $c8a49a52, $be2d2698, $fa8d32c8, $4ae9b0fa,
$6a1be983, $33780f3c, $a6e6d573, $ba74803a, $7c99bec2, $de26cd13, $e4bd34d0, $757a483d,
$24abffdb, $8ff77af5, $eaf4907a, $3ec25f61, $a01d2080, $d56768bd, $72d01a68, $2c19ae82,
$5ec9b4ea, $199a544d, $e5ec9376, $aa0d2288, $e907648d, $12dbf1e3, $a2bf73d1, $5a901248,
$5d3a401d, $28400820, $e856c32b, $7b33ec97, $9096db4b, $1f61a1be, $831c8d0e, $c9f53df4,
$f1cc9766, $00000000, $d436cf1b, $87452bac, $b39776c5, $b0648232, $a9fed67f, $77d81b6c,
$5bc1b5ee, $2911af86, $df776ab5, $0dba505d, $4c124509, $18cbf3eb, $f09d30c0, $742bef9b,
$c3e53ffc, $1c925549, $1079a2b2, $6503ea8f, $ec0f6589, $68b9bad2, $93652fbc, $e74ec027,
$81bede5f, $6ce01c70, $2ebbfdd3, $64524d29, $e0e49272, $bc8f75c9, $1e300618, $98248a12,
$40f9b2f2, $5963e6bf, $36700e38, $63f81f7c, $f7376295, $a3eed477, $3229a89a, $f4c49662,
$3a9bf9c3, $f666c533, $b1352594, $20f25979, $ae54842a, $a7b772d5, $ddd539e4, $615a4c2d,
$3bca5e65, $85e778fd, $d8dd38e0, $86148c0a, $b2c6d163, $0b41a5ae, $4d43e2af, $f82f6199,
$45f1b3f6, $a5152184, $d6949c4a, $66f01e78, $52224311, $fc76c73b, $2bb3fcd7, $14200410,
$08b25159, $c7bc995e, $c44f6da9, $39680d34, $3583facf, $84b6df5b, $9bd77ee5, $b43d2490,
$d7c53bec, $3d31ab96, $d13ece1f, $55881144, $890c8f06, $6b4a4e25, $51d1b7e6, $600beb8b,
$ccfd3cf0, $bf7c813e, $fed4946a, $0cebf7fb, $67a1b9de, $5f98134c, $9c7d2cb0, $b8d6d36b,
$5c6be7bb, $cb576ea5, $f36ec437, $0f18030c, $138a5645, $491a440d, $9edf7fe1, $3721a99e,
$824d2aa8, $6db1bbd6, $e246c123, $02a25351, $8baedc57, $27580b2c, $d39c9d4e, $c1476cad,
$f59531c4, $b98774cd, $09e3f6ff, $430a4605, $2609ac8a, $973c891e, $44a01450, $425be1a3,
$4eb01658, $d2cd3ae8, $d06f69b9, $2d480924, $ada770dd, $54d9b6e2, $b7ced067, $7e3bed93,
$db2ecc17, $572a4215, $c2b4985a, $0e49a4aa, $885d28a0, $31da5c6d, $3f93f8c7, $a4448622);
C7: TWhirlTab = (
$c0186018, $05238c23, $7ec63fc6, $13e887e8, $4c872687, $a9b8dab8, $08010401, $424f214f,
$ad36d836, $59a6a2a6, $ded26fd2, $fbf5f3f5, $ef79f979, $5f6fa16f, $fc917e91, $aa525552,
$27609d60, $89bccabc, $ac9b569b, $048e028e, $71a3b6a3, $600c300c, $ff7bf17b, $b535d435,
$e81d741d, $53e0a7e0, $f6d77bd7, $5ec22fc2, $6d2eb82e, $624b314b, $a3fedffe, $82574157,
$a8155415, $9f77c177, $a537dc37, $7be5b3e5, $8c9f469f, $d3f0e7f0, $6a4a354a, $9eda4fda,
$fa587d58, $06c903c9, $5529a429, $500a280a, $e1b1feb1, $69a0baa0, $7f6bb16b, $5c852e85,
$81bdcebd, $d25d695d, $80104010, $f3f4f7f4, $16cb0bcb, $ed3ef83e, $28051405, $1f678167,
$73e4b7e4, $25279c27, $32411941, $2c8b168b, $51a7a6a7, $cf7de97d, $dc956e95, $8ed847d8,
$8bfbcbfb, $23ee9fee, $c77ced7c, $17668566, $a6dd53dd, $b8175c17, $02470147, $849e429e,
$1eca0fca, $752db42d, $91bfc6bf, $38071c07, $01ad8ead, $ea5a755a, $6c833683, $8533cc33,
$3f639163, $10020802, $39aa92aa, $af71d971, $0ec807c8, $c8196419, $72493949, $86d943d9,
$c3f2eff2, $4be3abe3, $e25b715b, $34881a88, $a49a529a, $2d269826, $8d32c832, $e9b0fab0,
$1be983e9, $780f3c0f, $e6d573d5, $74803a80, $99bec2be, $26cd13cd, $bd34d034, $7a483d48,
$abffdbff, $f77af57a, $f4907a90, $c25f615f, $1d208020, $6768bd68, $d01a681a, $19ae82ae,
$c9b4eab4, $9a544d54, $ec937693, $0d228822, $07648d64, $dbf1e3f1, $bf73d173, $90124812,
$3a401d40, $40082008, $56c32bc3, $33ec97ec, $96db4bdb, $61a1bea1, $1c8d0e8d, $f53df43d,
$cc976697, $00000000, $36cf1bcf, $452bac2b, $9776c576, $64823282, $fed67fd6, $d81b6c1b,
$c1b5eeb5, $11af86af, $776ab56a, $ba505d50, $12450945, $cbf3ebf3, $9d30c030, $2bef9bef,
$e53ffc3f, $92554955, $79a2b2a2, $03ea8fea, $0f658965, $b9bad2ba, $652fbc2f, $4ec027c0,
$bede5fde, $e01c701c, $bbfdd3fd, $524d294d, $e4927292, $8f75c975, $30061806, $248a128a,
$f9b2f2b2, $63e6bfe6, $700e380e, $f81f7c1f, $37629562, $eed477d4, $29a89aa8, $c4966296,
$9bf9c3f9, $66c533c5, $35259425, $f2597959, $54842a84, $b772d572, $d539e439, $5a4c2d4c,
$ca5e655e, $e778fd78, $dd38e038, $148c0a8c, $c6d163d1, $41a5aea5, $43e2afe2, $2f619961,
$f1b3f6b3, $15218421, $949c4a9c, $f01e781e, $22431143, $76c73bc7, $b3fcd7fc, $20041004,
$b2515951, $bc995e99, $4f6da96d, $680d340d, $83facffa, $b6df5bdf, $d77ee57e, $3d249024,
$c53bec3b, $31ab96ab, $3ece1fce, $88114411, $0c8f068f, $4a4e254e, $d1b7e6b7, $0beb8beb,
$fd3cf03c, $7c813e81, $d4946a94, $ebf7fbf7, $a1b9deb9, $98134c13, $7d2cb02c, $d6d36bd3,
$6be7bbe7, $576ea56e, $6ec437c4, $18030c03, $8a564556, $1a440d44, $df7fe17f, $21a99ea9,
$4d2aa82a, $b1bbd6bb, $46c123c1, $a2535153, $aedc57dc, $580b2c0b, $9c9d4e9d, $476cad6c,
$9531c431, $8774cd74, $e3f6fff6, $0a460546, $09ac8aac, $3c891e89, $a0145014, $5be1a3e1,
$b0165816, $cd3ae83a, $6f69b969, $48092409, $a770dd70, $d9b6e2b6, $ced067d0, $3bed93ed,
$2ecc17cc, $2a421542, $b4985a98, $49a4aaa4, $5d28a028, $da5c6d5c, $93f8c7f8, $44862286);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
{Internal types for type casting}
type
TW64 = packed record
L,H: longint;
end;
{$ifndef BIT16}
{$ifdef PurePascal}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler;
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{$ifndef UseInt64}
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; const X: TW64); assembler;
{-Inc a 64 bit integer}
asm
{$ifdef LoadArgs}
mov eax,[Z]
mov edx,[X]
{$endif}
mov ecx, [edx]
add [eax], ecx
mov ecx, [edx+4]
adc [eax+4],ecx
end;
{$endif}
{$endif}
{$else}
{*** 16 bit ***}
(**** TP5-7/Delphi1 for 386+ *****)
{$ifndef BASM16}
(*** TP 5/5.5 ***)
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; var X: TW64);
{-Inc a 64 bit integer}
inline(
$8C/$DF/ {mov di,ds }
$5E/ {pop si }
$1F/ {pop ds }
$8B/$04/ {mov ax,[si] }
$8B/$5C/$02/ {mov bx,[si+02]}
$8B/$4C/$04/ {mov cx,[si+04]}
$8B/$54/$06/ {mov dx,[si+06]}
$5E/ {pop si }
$1F/ {pop ds }
$01/$04/ {add [si],ax }
$11/$5C/$02/ {adc [si+02],bx}
$11/$4C/$04/ {adc [si+04],cx}
$11/$54/$06/ {adc [si+06],dx}
$8E/$DF); {mov ds,di }
{$else}
(**** TP 6/7/Delphi1 for 386+ *****)
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; {$ifdef CONST} const {$else} var {$endif} X: TW64);
{-Inc a 64 bit integer}
inline(
$8C/$D9/ {mov cx,ds }
$5B/ {pop bx }
$1F/ {pop ds }
$66/$8B/$07/ {mov eax,[bx] }
$66/$8B/$57/$04/ {mov edx,[bx+04]}
$5B/ {pop bx }
$1F/ {pop ds }
$66/$03/$07/ {add eax,[bx] }
$66/$13/$57/$04/ {adc edx,[bx+04]}
$66/$89/$07/ {mov [bx],eax }
$66/$89/$57/$04/ {mov [bx+04],edx}
$8E/$D9); {mov ds,cx }
{$endif BASM16}
{$endif BIT16}
{---------------------------------------------------------------------------}
procedure XorBlock({$ifdef CONST} const {$else} var {$endif} b1,b2: THashState; var b3: THashState);
{-xor two Whirlpool hash blocks}
begin
{$ifdef BASM16}
asm
mov di,ds
lds si,[b1]
db $66; mov ax,[si+00]
db $66; mov bx,[si+04]
db $66; mov cx,[si+08]
db $66; mov dx,[si+12]
lds si,[b2]
db $66; xor ax,[si+00]
db $66; xor bx,[si+04]
db $66; xor cx,[si+08]
db $66; xor dx,[si+12]
lds si,[b3]
db $66; mov [si+00],ax
db $66; mov [si+04],bx
db $66; mov [si+08],cx
db $66; mov [si+12],dx
lds si,[b1]
db $66; mov ax,[si+16]
db $66; mov bx,[si+20]
db $66; mov cx,[si+24]
db $66; mov dx,[si+28]
lds si,[b2]
db $66; xor ax,[si+16]
db $66; xor bx,[si+20]
db $66; xor cx,[si+24]
db $66; xor dx,[si+28]
lds si,[b3]
db $66; mov [si+16],ax
db $66; mov [si+20],bx
db $66; mov [si+24],cx
db $66; mov [si+28],dx
lds si,[b1]
db $66; mov ax,[si+32]
db $66; mov bx,[si+36]
db $66; mov cx,[si+40]
db $66; mov dx,[si+44]
lds si,[b2]
db $66; xor ax,[si+32]
db $66; xor bx,[si+36]
db $66; xor cx,[si+40]
db $66; xor dx,[si+44]
lds si,[b3]
db $66; mov [si+32],ax
db $66; mov [si+36],bx
db $66; mov [si+40],cx
db $66; mov [si+44],dx
lds si,[b1]
db $66; mov ax,[si+48]
db $66; mov bx,[si+52]
db $66; mov cx,[si+56]
db $66; mov dx,[si+60]
lds si,[b2]
db $66; xor ax,[si+48]
db $66; xor bx,[si+52]
db $66; xor cx,[si+56]
db $66; xor dx,[si+60]
lds si,[b3]
db $66; mov [si+48],ax
db $66; mov [si+52],bx
db $66; mov [si+56],cx
db $66; mov [si+60],dx
mov ds,di
end;
{$else}
b3[00] := b1[00] xor b2[00];
b3[01] := b1[01] xor b2[01];
b3[02] := b1[02] xor b2[02];
b3[03] := b1[03] xor b2[03];
b3[04] := b1[04] xor b2[04];
b3[05] := b1[05] xor b2[05];
b3[06] := b1[06] xor b2[06];
b3[07] := b1[07] xor b2[07];
b3[08] := b1[08] xor b2[08];
b3[09] := b1[09] xor b2[09];
b3[10] := b1[10] xor b2[10];
b3[11] := b1[11] xor b2[11];
b3[12] := b1[12] xor b2[12];
b3[13] := b1[13] xor b2[13];
b3[14] := b1[14] xor b2[14];
b3[15] := b1[15] xor b2[15];
{$endif}
end;
{$ifdef BASM16}
{---------------------------------------------------------------------------}
procedure Transform({$ifdef CONST} const {$else} var {$endif} KK: THashState; var L: THashState);
{-perform transformation L = theta(pi(gamma(KK)))}
var
K: THState8;
begin
asm
{dest = K}
mov dx, ds
mov ax, ss
mov es, ax
lea di, [K]
{src = KK}
mov dx, ds
lds si, [KK]
{move words, movsd is slower!}
mov cx, 32
cld
rep movsw
{restore ds}
mov ds,dx
{es:di -> L}
les di, [L]
{L[00]:= C0[K[00]] xor C1[K[57]] xor C2[K[50]] xor C3[K[43]] xor
C4[K[36]] xor C5[K[29]] xor C6[K[22]] xor C7[K[15]]}
{L[01]:= C4[K[00]] xor C5[K[57]] xor C6[K[50]] xor C7[K[43]] xor
C0[K[36]] xor C1[K[29]] xor C2[K[22]] xor C3[K[15]]}
sub bh, bh
mov bl, byte ptr K[00]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[57]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[50]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[43]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[36]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[29]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[22]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[15]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[02]:= C0[K[08]] xor C1[K[01]] xor C2[K[58]] xor C3[K[51]] xor
C4[K[44]] xor C5[K[37]] xor C6[K[30]] xor C7[K[23]]}
{L[03]:= C4[K[08]] xor C5[K[01]] xor C6[K[58]] xor C7[K[51]] xor
C0[K[44]] xor C1[K[37]] xor C2[K[30]] xor C3[K[23]]}
sub bh, bh
mov bl, byte ptr K[08]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[01]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[58]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[51]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[44]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[37]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[30]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[23]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[04]:= C0[K[16]] xor C1[K[09]] xor C2[K[02]] xor C3[K[59]] xor
C4[K[52]] xor C5[K[45]] xor C6[K[38]] xor C7[K[31]]}
{L[05]:= C4[K[16]] xor C5[K[09]] xor C6[K[02]] xor C7[K[59]] xor
C0[K[52]] xor C1[K[45]] xor C2[K[38]] xor C3[K[31]]}
sub bh, bh
mov bl, byte ptr K[16]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[09]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[02]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[59]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[52]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[45]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[38]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[31]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[06]:= C0[K[24]] xor C1[K[17]] xor C2[K[10]] xor C3[K[03]] xor
C4[K[60]] xor C5[K[53]] xor C6[K[46]] xor C7[K[39]]}
{L[07]:= C4[K[24]] xor C5[K[17]] xor C6[K[10]] xor C7[K[03]] xor
C0[K[60]] xor C1[K[53]] xor C2[K[46]] xor C3[K[39]]}
sub bh, bh
mov bl, byte ptr K[24]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[17]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[10]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[03]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[60]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[53]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[46]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[39]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[08]:= C0[K[32]] xor C1[K[25]] xor C2[K[18]] xor C3[K[11]] xor
C4[K[04]] xor C5[K[61]] xor C6[K[54]] xor C7[K[47]]}
{L[09]:= C4[K[32]] xor C5[K[25]] xor C6[K[18]] xor C7[K[11]] xor
C0[K[04]] xor C1[K[61]] xor C2[K[54]] xor C3[K[47]]}
sub bh, bh
mov bl, byte ptr K[32]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[25]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[18]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[11]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[04]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[61]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[54]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[47]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[10]:= C0[K[40]] xor C1[K[33]] xor C2[K[26]] xor C3[K[19]] xor
C4[K[12]] xor C5[K[05]] xor C6[K[62]] xor C7[K[55]]}
{L[11]:= C4[K[40]] xor C5[K[33]] xor C6[K[26]] xor C7[K[19]] xor
C0[K[12]] xor C1[K[05]] xor C2[K[62]] xor C3[K[55]]}
sub bh, bh
mov bl, byte ptr K[40]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[33]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[26]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[19]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[12]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[05]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[62]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[55]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[12]:= C0[K[48]] xor C1[K[41]] xor C2[K[34]] xor C3[K[27]] xor
C4[K[20]] xor C5[K[13]] xor C6[K[06]] xor C7[K[63]]}
{L[13]:= C4[K[48]] xor C5[K[41]] xor C6[K[34]] xor C7[K[27]] xor
C0[K[20]] xor C1[K[13]] xor C2[K[06]] xor C3[K[63]]}
sub bh, bh
mov bl, byte ptr K[48]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[41]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[34]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[27]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[20]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[13]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[06]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[63]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
add di,8
{L[14]:= C0[K[56]] xor C1[K[49]] xor C2[K[42]] xor C3[K[35]] xor
C4[K[28]] xor C5[K[21]] xor C6[K[14]] xor C7[K[07]]}
{L[15]:= C4[K[56]] xor C5[K[49]] xor C6[K[42]] xor C7[K[35]] xor
C0[K[28]] xor C1[K[21]] xor C2[K[14]] xor C3[K[07]]}
sub bh, bh
mov bl, byte ptr K[56]
shl bx, 2
db $66; mov ax, word ptr C0[bx]
db $66; mov dx, word ptr C4[bx]
sub bh, bh
mov bl, byte ptr K[49]
shl bx, 2
db $66; xor ax, word ptr C1[bx]
db $66; xor dx, word ptr C5[bx]
sub bh, bh
mov bl, byte ptr K[42]
shl bx, 2
db $66; xor ax, word ptr C2[bx]
db $66; xor dx, word ptr C6[bx]
sub bh, bh
mov bl, byte ptr K[35]
shl bx, 2
db $66; xor ax, word ptr C3[bx]
db $66; xor dx, word ptr C7[bx]
sub bh, bh
mov bl, byte ptr K[28]
shl bx, 2
db $66; xor ax, word ptr C4[bx]
db $66; xor dx, word ptr C0[bx]
sub bh, bh
mov bl, byte ptr K[21]
shl bx, 2
db $66; xor ax, word ptr C5[bx]
db $66; xor dx, word ptr C1[bx]
sub bh, bh
mov bl, byte ptr K[14]
shl bx, 2
db $66; xor ax, word ptr C6[bx]
db $66; xor dx, word ptr C2[bx]
sub bh, bh
mov bl, byte ptr K[07]
shl bx, 2
db $66; xor ax, word ptr C7[bx]
db $66; xor dx, word ptr C3[bx]
db $66; mov es:[di],ax
db $66; mov es:[di+4],dx
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure Transform({$ifdef CONST} const {$else} var {$endif} KK: THashState; var L: THashState);
{-perform transformation L = theta(pi(gamma(KK)))}
var
K: THState8 {$ifndef BIT16} absolute KK {$endif};
begin
{$ifdef BIT16}
{For 16 bit compilers copy KK to stack segment: about 20% faster.}
{For 32 bit compilers with flat address space copying slows down!}
K := THState8(KK);
{$endif}
L[00] := C0[K[00]] xor C1[K[57]] xor C2[K[50]] xor C3[K[43]] xor C4[K[36]] xor C5[K[29]] xor C6[K[22]] xor C7[K[15]];
L[02] := C0[K[08]] xor C1[K[01]] xor C2[K[58]] xor C3[K[51]] xor C4[K[44]] xor C5[K[37]] xor C6[K[30]] xor C7[K[23]];
L[04] := C0[K[16]] xor C1[K[09]] xor C2[K[02]] xor C3[K[59]] xor C4[K[52]] xor C5[K[45]] xor C6[K[38]] xor C7[K[31]];
L[06] := C0[K[24]] xor C1[K[17]] xor C2[K[10]] xor C3[K[03]] xor C4[K[60]] xor C5[K[53]] xor C6[K[46]] xor C7[K[39]];
L[08] := C0[K[32]] xor C1[K[25]] xor C2[K[18]] xor C3[K[11]] xor C4[K[04]] xor C5[K[61]] xor C6[K[54]] xor C7[K[47]];
L[10] := C0[K[40]] xor C1[K[33]] xor C2[K[26]] xor C3[K[19]] xor C4[K[12]] xor C5[K[05]] xor C6[K[62]] xor C7[K[55]];
L[12] := C0[K[48]] xor C1[K[41]] xor C2[K[34]] xor C3[K[27]] xor C4[K[20]] xor C5[K[13]] xor C6[K[06]] xor C7[K[63]];
L[14] := C0[K[56]] xor C1[K[49]] xor C2[K[42]] xor C3[K[35]] xor C4[K[28]] xor C5[K[21]] xor C6[K[14]] xor C7[K[07]];
{Use special properties of circulant matrices: the lower 32 bit}
{tables Cx(low) are the tables Cy(high) with y = x + 4 (mod 8) }
L[01] := C4[K[00]] xor C5[K[57]] xor C6[K[50]] xor C7[K[43]] xor C0[K[36]] xor C1[K[29]] xor C2[K[22]] xor C3[K[15]];
L[03] := C4[K[08]] xor C5[K[01]] xor C6[K[58]] xor C7[K[51]] xor C0[K[44]] xor C1[K[37]] xor C2[K[30]] xor C3[K[23]];
L[05] := C4[K[16]] xor C5[K[09]] xor C6[K[02]] xor C7[K[59]] xor C0[K[52]] xor C1[K[45]] xor C2[K[38]] xor C3[K[31]];
L[07] := C4[K[24]] xor C5[K[17]] xor C6[K[10]] xor C7[K[03]] xor C0[K[60]] xor C1[K[53]] xor C2[K[46]] xor C3[K[39]];
L[09] := C4[K[32]] xor C5[K[25]] xor C6[K[18]] xor C7[K[11]] xor C0[K[04]] xor C1[K[61]] xor C2[K[54]] xor C3[K[47]];
L[11] := C4[K[40]] xor C5[K[33]] xor C6[K[26]] xor C7[K[19]] xor C0[K[12]] xor C1[K[05]] xor C2[K[62]] xor C3[K[55]];
L[13] := C4[K[48]] xor C5[K[41]] xor C6[K[34]] xor C7[K[27]] xor C0[K[20]] xor C1[K[13]] xor C2[K[06]] xor C3[K[63]];
L[15] := C4[K[56]] xor C5[K[49]] xor C6[K[42]] xor C7[K[35]] xor C0[K[28]] xor C1[K[21]] xor C2[K[14]] xor C3[K[07]];
end;
{$endif BASM16}
{---------------------------------------------------------------------------}
procedure Whirl_Compress(var Data: THashContext);
{-The core Whirlpool compression function, using double rounds}
var
r,r4: integer;
L,K: THashState; {even/odd round keys}
S: THashState; {cipher state}
begin
{compute and apply K^0 to the cipher state}
K := Data.Hash;
XorBlock(Data.Hash, PHashState(@Data.Buffer)^, S);
for r:=0 to 4 do begin
{compression is done in five double rounds}
r4 := r shl 2;
{compute next round key (=L)}
Transform(K,L);
L[0] := L[0] xor RC[r4 ];
L[1] := L[1] xor RC[r4+1];
{apply the round transformation}
Transform(S,K);
XorBlock(L, K, S);
{compute next round key (=K)}
Transform(L,K);
K[0] := K[0] xor RC[r4+2];
K[1] := K[1] xor RC[r4+3];
{apply the round transformation}
Transform(S,L);
XorBlock(K, L, S);
end;
{apply the Miyaguchi-Preneel compression function}
XorBlock(S, PHashState(@Data.Buffer)^, S);
XorBlock(S, Data.Hash, Data.Hash);
end;
{$ifdef UseInt64}
{---------------------------------------------------------------------------}
procedure UpdateLen(var Context: THashContext; Len: longint; IsByteLen: boolean);
{-Update 128 bit message bit length, Len = byte length if IsByteLen}
var
t0,t1: TW64;
i: integer;
begin
if IsByteLen then int64(t0) := 8*int64(Len)
else int64(t0) := int64(Len);
t1.L := Context.MLen[0];
t1.H := 0;
Inc(int64(t0),int64(t1));
Context.MLen[0] := t0.L;
for i:=1 to 3 do begin
if t0.H=0 then exit;
t1.L := Context.MLen[i];
t0.L := t0.H;
t0.H := 0;
Inc(int64(t0),int64(t1));
Context.MLen[i] := t0.L;
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure UpdateLen(var Context: THashContext; Len: longint; IsByteLen: boolean);
{-Update 128 bit message bit length, Len = byte length if IsByteLen}
var
t0,t1: TW64;
i: integer;
begin
if IsByteLen then begin
{Calculate bit length increment = 8*Len}
if Len<=$0FFFFFFF then begin
{safe to multiply without overflow}
t0.L := 8*Len;
t0.H := 0;
end
else begin
t0.L := Len;
t0.H := 0;
Inc64(t0,t0);
Inc64(t0,t0);
Inc64(t0,t0);
end;
end
else begin
t0.L := Len;
t0.H := 0;
end;
{Update 128 bit length}
t1.L := Context.MLen[0];
t1.H := 0;
Inc64(t0,t1);
Context.MLen[0] := t0.L;
for i:=1 to 3 do begin
{propagate carry into higher bits}
if t0.H=0 then exit;
t1.L := Context.MLen[i];
t0.L := t0.H;
t0.H := 0;
Inc64(t0,t1);
Context.MLen[i] := t0.L;
end;
end;
{$endif}
{---------------------------------------------------------------------------}
procedure Whirl_Init(var Context: THashContext);
{-initialize context}
begin
{Clear context, buffer=0!, InitIV=0!}
fillchar(Context,sizeof(Context),0);
end;
{---------------------------------------------------------------------------}
procedure Whirl_UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
begin
{Update message bit length}
UpdateLen(Context, Len, true);
while Len > 0 do begin
{fill block with msg data}
Context.Buffer[Context.Index]:= pByte(Msg)^;
inc(Ptr2Inc(Msg));
inc(Context.Index);
dec(Len);
if Context.Index=Whirl_BlockLen then begin
{If 512 bit transferred, compress a block}
Context.Index:= 0;
Whirl_Compress(Context);
while Len>=Whirl_BlockLen do begin
move(Msg^,Context.Buffer,Whirl_BlockLen);
Whirl_Compress(Context);
inc(Ptr2Inc(Msg),Whirl_BlockLen);
dec(Len,Whirl_BlockLen);
end;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure Whirl_Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
begin
Whirl_UpdateXL(Context, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure Whirl_FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize Whirlpool calculation with bitlen bits from BData (big-endian), clear context}
var
i: integer;
begin
{Message padding}
{append bits from BData and a single '1' bit}
if (bitlen>0) and (bitlen<=7) then begin
Context.Buffer[Context.Index]:= (BData and BitAPI_Mask[bitlen]) or BitAPI_PBit[bitlen];
UpdateLen(Context, bitlen, false);
end
else Context.Buffer[Context.Index]:= $80;
for i:=Context.Index+1 to pred(sizeof(Context.Buffer)) do Context.Buffer[i] := 0;
{2. Compress if more than 256 bits}
if Context.Index>=Whirl_BlockLen-32 then begin
Whirl_Compress(Context);
fillchar(Context.Buffer,sizeof(Context.Buffer),0);
end;
{Write 128 bit msg length into the last bits of the last block}
{(in big endian format) and do a final compress}
THashBuf32(Context.Buffer)[12]:= RB(Context.MLen[3]);
THashBuf32(Context.Buffer)[13]:= RB(Context.MLen[2]);
THashBuf32(Context.Buffer)[14]:= RB(Context.MLen[1]);
THashBuf32(Context.Buffer)[15]:= RB(Context.MLen[0]);
Whirl_Compress(Context);
{Hash -> Digest (note: Hash is little endian format)}
move(Context.Hash, Digest, sizeof(Digest));
{Clear context}
fillchar(Context,sizeof(Context),0);
end;
{---------------------------------------------------------------------------}
procedure Whirl_FinalBits(var Context: THashContext; var Digest: TWhirlDigest; BData: byte; bitlen: integer);
{-finalize Whirlpool calculation with bitlen bits from BData (big-endian), clear context}
var
tmp: THashDigest;
begin
Whirl_FinalBitsEx(Context, tmp, BData, bitlen);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
procedure Whirl_FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize Whirlpool calculation, clear context}
begin
Whirl_FinalBitsEx(Context,Digest,0,0);
end;
{---------------------------------------------------------------------------}
procedure Whirl_Final(var Context: THashContext; var Digest: TWhirlDigest);
{-finalize Whirlpool calculation, clear context}
var
tmp: THashDigest;
begin
Whirl_FinalBitsEx(Context, tmp, 0, 0);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
function Whirl_SelfTest: boolean;
{-self test for strings from Whirlpool distribution}
const
sex3: string[03] = 'abc';
sex7: string[80] = '12345678901234567890123456789012345678901234567890123456789012345678901234567890';
const
{Whirlpool Version 3 test vectors} {abc'}
DEX3: TWhirlDigest = ($4e,$24,$48,$a4,$c6,$f4,$86,$bb,
$16,$b6,$56,$2c,$73,$b4,$02,$0b,
$f3,$04,$3e,$3a,$73,$1b,$ce,$72,
$1a,$e1,$b3,$03,$d9,$7e,$6d,$4c,
$71,$81,$ee,$bd,$b6,$c5,$7e,$27,
$7d,$0e,$34,$95,$71,$14,$cb,$d6,
$c7,$97,$fc,$9d,$95,$d8,$b5,$82,
$d2,$25,$29,$20,$76,$d4,$ee,$f5);
{'12345678901234567890123456789012345678901234567890123456789012345678901234567890'}
DEX7: TWhirlDigest = ($46,$6e,$f1,$8b,$ab,$b0,$15,$4d,
$25,$b9,$d3,$8a,$64,$14,$f5,$c0,
$87,$84,$37,$2b,$cc,$b2,$04,$d6,
$54,$9c,$4a,$fa,$db,$60,$14,$29,
$4d,$5b,$d8,$df,$2a,$6c,$44,$e5,
$38,$cd,$04,$7b,$26,$81,$a5,$1a,
$2c,$60,$48,$1e,$88,$c5,$a2,$0b,
$2c,$2a,$80,$cf,$3a,$9a,$08,$3b);
{nessie-test-vectors.txt, L=1}
D3: TWhirlDigest = ($e3,$84,$d5,$40,$e0,$bd,$fd,$28,
$c8,$52,$91,$77,$34,$3b,$31,$18,
$3f,$b4,$0c,$20,$f9,$60,$b0,$bc,
$dc,$e0,$51,$3a,$38,$2f,$96,$a3,
$83,$20,$99,$eb,$b6,$aa,$bd,$b7,
$1b,$0e,$a2,$e3,$01,$77,$f6,$98,
$ea,$70,$3d,$e5,$1f,$93,$cf,$3c,
$fe,$a6,$d3,$17,$1b,$95,$53,$83);
var
Context: THashContext;
Digest : TWhirlDigest;
function SingleTest(s: Str127; TDig: TWhirlDigest): boolean;
{-do a single test, const not allowed for VER<7}
{ Two sub tests: 1. whole string, 2. one update per char}
var
i: integer;
begin
SingleTest := false;
{1. Hash complete string}
Whirl_Full(Digest, @s[1],length(s));
{Compare with known value}
if not HashSameDigest(@Whirl_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
{2. one update call for all chars}
Whirl_Init(Context);
for i:=1 to length(s) do Whirl_Update(Context,@s[i],1);
Whirl_Final(Context,Digest);
{Compare with known value}
if not HashSameDigest(@Whirl_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
SingleTest := true;
end;
begin
Whirl_SelfTest := false;
{1 Zero bit from nessie-test-vectors.txt}
Whirl_Init(Context);
Whirl_FinalBits(Context,Digest,0,1);
if not HashSameDigest(@Whirl_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit;
{exmaple xx strings from iso-test-vectors.txt}
Whirl_SelfTest := SingleTest(sex3, DEX3) and SingleTest(sex7, DEX7)
end;
{---------------------------------------------------------------------------}
procedure Whirl_FullXL(var Digest: TWhirlDigest; Msg: pointer; Len: longint);
{-Whirlpool hash-code of Msg with init/update/final}
var
Context: THashContext;
begin
Whirl_Init(Context);
Whirl_UpdateXL(Context, Msg, Len);
Whirl_Final(Context, Digest);
end;
{---------------------------------------------------------------------------}
procedure Whirl_Full(var Digest: TWhirlDigest; Msg: pointer; Len: word);
{-Whirlpool hash-code of Msg with init/update/final}
begin
Whirl_FullXL(Digest, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure Whirl_File({$ifdef CONST} const {$endif} fname: string;
var Digest: TWhirlDigest; var buf; bsize: word; var Err: word);
{-Whirlpool hash-code of file, buf: buffer with at least bsize bytes}
var
tmp: THashDigest;
begin
HashFile(fname, @Whirl_Desc, tmp, buf, bsize, Err);
move(tmp, Digest, sizeof(Digest));
end;
begin
{$ifdef VER5X}
fillchar(Whirl_Desc, sizeof(Whirl_Desc), 0);
with Whirl_Desc do begin
HSig := C_HashSig;
HDSize := sizeof(THashDesc);
HDVersion := C_HashVers;
HBlockLen := Whirl_BlockLen;
HDigestlen:= sizeof(TWhirlDigest);
HInit := Whirl_Init;
HFinal := Whirl_FinalEx;
HUpdateXL := Whirl_UpdateXL;
HAlgNum := longint(_Whirlpool);
HName := 'Whirlpool';
HPtrOID := @Whirl_OID;
HLenOID := 6;
HFinalBit := Whirl_FinalBitsEx;
end;
{$endif}
RegisterHash(_Whirlpool, @Whirl_Desc);
end.
|
unit FHIR.Cache.PackageClient;
interface
uses
SysUtils, Classes,
FHIR.Support.Base, FHIR.Support.Utilities, FHIR.Support.Json;
type
TFHIRPackageInfo = class (TFslObject)
private
FId : String;
FVersion : String;
FFhirVersion : String;
FDescription : String;
FUrl : String;
public
constructor Create(id, version, fhirVersion, description, url : String);
property id : String read FId;
property version : String read FVersion;
property fhirVersion : String read FFhirVersion;
property description : String read FDescription;
property url : String read FUrl;
end;
TFHIRPackageClient = class (TFslObject)
private
FAddress : String;
public
constructor Create(address : String);
property address : String read FAddress;
function exists(id, ver : String) : boolean;
function fetch(id, ver : String) : TBytes; overload;
function fetch(info : TFHIRPackageInfo) : TBytes; overload;
function fetchNpm(id, ver : String) : TBytes;
function getVersions(id : String) : TFslList<TFHIRPackageInfo>;
function search(name, canonical, fhirVersion : String; preRelease : boolean) : TFslList<TFHIRPackageInfo>; overload;
function search(lastCalled : TFslDateTime; packages : TFslList<TFHIRPackageInfo>) : TFslDateTime; overload;
function url(id, v : String) : string;
end;
implementation
{ TFHIRPackageClient }
constructor TFHIRPackageClient.Create(address: String);
begin
end;
function TFHIRPackageClient.exists(id, ver: String): boolean;
begin
result := false;
end;
function TFHIRPackageClient.fetch(info: TFHIRPackageInfo): TBytes;
begin
end;
function TFHIRPackageClient.fetch(id, ver: String): TBytes;
begin
end;
function TFHIRPackageClient.fetchNpm(id, ver: String): TBytes;
begin
end;
function TFHIRPackageClient.getVersions(id: String): TFslList<TFHIRPackageInfo>;
begin
result := nil;
end;
function TFHIRPackageClient.search(lastCalled: TFslDateTime;
packages: TFslList<TFHIRPackageInfo>): TFslDateTime;
begin
end;
function TFHIRPackageClient.search(name, canonical, fhirVersion: String;
preRelease: boolean): TFslList<TFHIRPackageInfo>;
begin
result := nil;
end;
function TFHIRPackageClient.url(id, v: String): string;
begin
end;
{ TFHIRPackageInfo }
constructor TFHIRPackageInfo.Create(id, version, fhirVersion, description, url: String);
begin
end;
end.
|
unit CurrencyEdit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, FileUtil, StdCtrls, LCLType;
type
{ TCurrencyEdit }
TCurrencyEdit = class(TEdit)
private
constructor Create(AOwner: TEdit);
protected
{ Protected declarations }
public
procedure CreateParams(var Params: TCreateParams); override;
procedure KeyPress(var Key: Char); override;
procedure Change; override;
procedure SetValue(val: currency);
function GetValue: currency;
published
property Value: Currency read GetValue write SetValue;
end;
procedure Register;
implementation
constructor TCurrencyEdit.Create(AOwner: TEdit);
begin
inherited Create(AOwner);
end;
procedure TCurrencyEdit.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Text:='0'; // задаём начальное значение
//SelStart:=Length(Text); // перевод курсора в конец строки
end;
procedure TCurrencyEdit.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
//
if (Key='/') or (Key='?') or (Key='<') then Key:='.';
if (SysToUTF8(key)='б') or (SysToUTF8(key)='Б') or (SysToUTF8(key)='ю') or (SysToUTF8(key)='Ю') then Key:='.';
// фильтрация вводимых символов
case Key of
// разрешаем ввод цифр
'0'..'9': key:=key;
// разрешаем ввод всего, что похоже на десятичный разделитель
'.', ',': //with (Owner as TEdit) do
begin
// запрещаем ввод более 1 десятичного разделителя
if (Pos('.', Text)=0) and (Pos(',', Text)=0)
then key:='.'
else key:=#0;
end;
// разрешаем использование клавиш BackSpace и Delete
#8: key:=key;
// "гасим" все прочие клавиши
else key:=#0;
end; // case
end;
procedure TCurrencyEdit.Change;
var
val: currency;
begin
inherited Change;
// проверка входящего значения
if TryStrToCurr(Text, val)=false then text:='0';
// при попытке полностью очистить поле - заполняем его нулём
if Length(Text)<=0 then
begin
Text:='0';
SelStart:=Length(Text); // перевод курсора в конец строки
end
else
// убираем ведущие нули (если сразу после них нет десятичного разделителя)
if (Length(Text)>1) and (Text[1]='0') and ((Text[2]<>'.')) then
begin
Text:=Copy(Text, 2, Length(text));
SelStart:=Length(Text); // перевод курсора в конец строки
end
else if (Length(Text)=1) then SelStart:=Length(Text);
end;
procedure TCurrencyEdit.SetValue(val: currency);
var
fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
Text:= CurrToStr(val, fs);// FValue;
end;
function TCurrencyEdit.GetValue: currency;
var
val: currency;
begin
if TryStrToCurr(Text, val)=true then Result:=StrToCurr(Text)
else
begin
text:='0';
Result:=0;
end;
end;
procedure Register;
begin
{$I CurrencyEdit_icon.lrs}
RegisterComponents('BookTools',[TCurrencyEdit]);
end;
end.
|
unit UnFabricaDeDominios;
interface
uses SysUtils, Classes, DB, DBClient, Provider, SqlExpr,
{ helsonsant }
Util, DataUtil, UnModelo, Dominio, FMTBcd;
type
FabricaDeDominio = class of TFabricaDeDominio;
TFabricaDeDominio = class(TDataModule)
private
class procedure ConstruirDataSet(const DataSet: TDataSet;
const Sql: string; const Campos: TCampos);
class function CopiarCampo(const CampoOrigem, CampoDestino: TField;
const DataSet: TDataSet): TField;
class function DuplicarCampo(const CampoOrigem: TField; const DataSet: TDataSet;
const Modelo: TModelo = nil): Boolean;
class procedure ConstruirDataSetDetalhe(const Modelo: TModelo;
const EntidadeMestre, EntidadeDetalhe: TDominio;
const MasterSqlDataSet: TSqlDataSet;
const MasterClientDataSet: TClientDataSet);
public
class function Conexao(const Conexao: TSQLConnection): FabricaDeDominio;
class procedure FabricarDominio(const Dominio: TDominio; const Modelo: TModelo);
end;
var
FConexao: TSQLConnection;
FSqlProcessor: TSQLDataSet;
implementation
{$R *.dfm}
class procedure TFabricaDeDominio.FabricarDominio(const Dominio: TDominio;
const Modelo: TModelo);
var
_i: Integer;
_ds: TSQLDataSet;
_dsp: TDataSetProvider;
_cds: TClientDataSet;
_dsr: TDataSource;
begin
// configura SqlDataSet com conexão, comando Sql e cria seus campos
_ds := Modelo.ds;
_ds.SQLConnection := FConexao;
_ds.CommandText := Dominio.Sql.ObterSql;
Self.ConstruirDataSet(_ds, Dominio.Sql.ObterSqlMetadados, Dominio.Campos);
// configua DataSetProvider com seu SqlDataSet, opções de
_dsp := Modelo.dsp;
_dsp.DataSet := _ds;
_dsp.Options := [] + [poCascadeDeletes] + [poCascadeUpdates] +
[poAllowCommandText];
_dsp.UpdateMode := upWhereKeyOnly;
_cds := Modelo.cds;
// configura ClientDataSet
_cds.ProviderName := 'dsp';
if Assigned(Dominio.EventoAntesDePostarRegistro) then
_cds.BeforePost := Dominio.EventoAntesDePostarRegistro;
Self.ConstruirDataSet(_cds, Dominio.Sql.ObterSqlMetadados, Dominio.Campos);
_dsr := Modelo.dsr;
_dsr.DataSet := _cds;
// Construir Detail
for _i := 0 to Dominio.Detalhes.Count-1 do
Self.ConstruirDataSetDetalhe(Modelo, Dominio,
Dominio.Detalhes.Objects[_i] as TDominio, _ds, _cds);
end;
class function TFabricaDeDominio.Conexao(
const Conexao: TSQLConnection): FabricaDeDominio;
begin
// Armazena referência à conexão ao banco de dados e configura
// SqlProcessor com esta conexão.
FConexao := Conexao;
if FSqlProcessor = nil then
begin
FSqlProcessor := TSQLDataSet.Create(nil);
FSqlProcessor.SQLConnection := Conexao;
end;
Result := Self;
end;
class function TFabricaDeDominio.DuplicarCampo(const CampoOrigem: TField;
const DataSet: TDataSet; const Modelo: TModelo = nil): Boolean;
var
_campoDestino: TField;
begin
// cria um novo campo _campoDestino para espelhar CampoOrigem
_campoDestino := nil;
case CampoOrigem.DataType of
ftString: _campoDestino := TStringField.Create(Modelo);
ftSmallint: _campoDestino := TSmallintField.Create(Modelo);
ftInteger: _campoDestino := TIntegerField.Create(Modelo);
ftWord: _campoDestino := TWordField.Create(Modelo);
ftFloat: _campoDestino := TFloatField.Create(Modelo);
ftCurrency: _campoDestino := TCurrencyField.Create(Modelo);
ftBCD: _campoDestino := TBCDField.Create(Modelo);
ftDate: _campoDestino := TDateField.Create(Modelo);
ftTime: _campoDestino := TTimeField.Create(Modelo);
ftDateTime: _campoDestino := TDateTimeField.Create(Modelo);
ftAutoInc: _campoDestino := TAutoIncField.Create(Modelo);
ftWideString: _campoDestino := TWideStringField.Create(Modelo);
ftLargeint: _campoDestino := TLargeIntField.Create(Modelo);
ftTimeStamp: _campoDestino := TSQLTimesTampField.Create(Modelo);
ftFMTBcd: _campoDestino := TFMTBCDField.Create(Modelo);
end;
// copia atributos de CampoOrigem em _campoDestino;
if _campoDestino <> nil then
Self.CopiarCampo(CampoOrigem, _campoDestino, DataSet);
Result := _campoDestino <> nil;
end;
class function TFabricaDeDominio.CopiarCampo(const CampoOrigem, CampoDestino: TField;
const DataSet: TDataSet): TField;
begin
// copia atributos de CampoOrigem em CampoDestino;
CampoDestino.Name := CampoOrigem.Name;
CampoDestino.FieldName := CampoOrigem.FieldName;
CampoDestino.Alignment := CampoOrigem.Alignment;
CampoDestino.DefaultExpression := CampoOrigem.DefaultExpression;
CampoDestino.DisplayLabel := CampoOrigem.DisplayLabel;
CampoDestino.DisplayWidth := CampoOrigem.DisplayWidth;
CampoDestino.FieldKind := CampoOrigem.FieldKind;
CampoDestino.Tag := CampoOrigem.Tag;
CampoDestino.Size := CampoOrigem.Size;
// todos os campos são inicialmente invisíveis
CampoDestino.Visible := False;
CampoDestino.ProviderFlags := CampoOrigem.ProviderFlags;
CampoDestino.Index := CampoOrigem.Index;
// precisão de campos numéricos
if CampoOrigem is TBCDField then
(CampoDestino as TBCDField).Precision := (CampoOrigem as TBCDField).Precision;
if CampoOrigem is TFMTBCDField then
(CampoDestino as TFMTBCDField).Precision := (CampoOrigem as TFMTBCDField).Precision;
// configura DataSet
CampoDestino.DataSet := DataSet;
Result := CampoDestino;
end;
class procedure TFabricaDeDominio.ConstruirDataSet(const DataSet: TDataSet;
const Sql: string; const Campos: TCampos);
var
_i: Integer;
_campo: TCampo;
_campoDS: TField;
begin
// executa comando Sql para recuperar campos
FSqlProcessor.Active := False;
FSqlProcessor.CommandText := Sql;
FSqlProcessor.Open;
// cria cópia dos campos no DataSet de destino
for _i := 0 to FSqlProcessor.FieldCount-1 do
Self.DuplicarCampo(FSqlProcessor.Fields[_i], DataSet, DataSet.Owner as TModelo);
FSqlProcessor.Active := False;
// configura campos de acordo com as regras do Domínio
for _i := 0 to Campos.Count-1 do
begin
_campo := Campos.Objects[_i] as TCampo;
_campoDS := DataSet.FindField(_campo.ObterNome);
_campoDS.DisplayLabel := _campo.ObterDescricao;
if _campo.ObterTamanho <> 0 then
_campoDS.DisplayWidth := _campo.ObterTamanho;
_campoDS.ProviderFlags := [];
if _campo.EhChave then
_campoDS.ProviderFlags := _campoDS.ProviderFlags + [pfInKey];
if _campo.EhAtualizavel then
_campoDS.ProviderFlags := _campoDS.ProviderFlags + [pfInUpdate];
_campoDS.Required := _campo.EhObrigatorio;
_campoDS.Visible := _campo.EhVisivel;
// formato de campos numéricos, data e hora
if (_campoDS is TBCDField) and (_campo.ObterFormato <> '') then
(_campoDS as TBCDField).DisplayFormat := _campo.ObterFormato;
if (_campoDS is TFMTBCDField) and (_campo.ObterFormato <> '') then
(_campoDS as TFMTBCDField).DisplayFormat := _campo.ObterFormato;
if (_campoDS is TDateField) and (_campo.ObterFormato <> '') then
(_campoDS as TDateField).DisplayFormat := _campo.ObterFormato;
if (_campoDS is TDateTimeField) and (_campo.ObterFormato <> '') then
(_campoDS as TDateTimeField).DisplayFormat := _campo.ObterFormato;
if (_campoDS is TTimeField) and (_campo.ObterFormato <> '') then
(_campoDS as TTimeField).DisplayFormat := _campo.ObterFormato;
if (_campoDS is TSQLTimestampField) and (_campo.ObterFormato <> '') then
(_campoDS as TSQLTimestampField).DisplayFormat := _campo.ObterFormato;
end;
end;
class procedure TFabricaDeDominio.ConstruirDataSetDetalhe(const Modelo: TModelo;
const EntidadeMestre, EntidadeDetalhe: TDominio;
const MasterSqlDataSet: TSqlDataSet;
const MasterClientDataSet: TClientDataSet);
var
_i: Integer;
_ds: TSQLDataSet;
_ds_dsr: TDataSource;
_cds: TClientDataSet;
_dsr: TDataSource;
_campoDeLigacao: TDataSetField;
begin
// DataSource que liga o MasterDS ao DetailDS
_ds_dsr := TDataSource.Create(Modelo);
_ds_dsr.DataSet := MasterSqlDataSet;
_ds_dsr.Name := 'ds_' +
EntidadeMestre.Entidade + '_' + EntidadeDetalhe.Entidade;
MasterSqlDataSet.Active := True;
// DetailDS
_ds := TSQLDataSet.Create(Modelo);
_ds.SQLConnection := FConexao;
_ds.Name := 'ds_' + EntidadeDetalhe.Entidade;
_ds.CommandText := EntidadeDetalhe.Sql.ObterSqlComCondicaoDeJuncao;
_ds.DataSource := _ds_dsr;
Self.ConstruirDataSet(_ds,
EntidadeDetalhe.Sql.ObterSqlMetadados,
EntidadeDetalhe.Campos);
// DataSetField que liga MasterClientDataSet ao DetailClientDataSet
_campoDeLigacao := TDataSetField.Create(Modelo);
_campoDeLigacao.Name := MasterSqlDataSet.Name + _ds.Name;
_campoDeLigacao.FieldName := _ds.Name;
_campoDeLigacao.DataSet := MasterClientDataSet;
// DetailClientDataSet
_cds := TClientDataSet.Create(Modelo);
_cds.Name := 'cds_' + EntidadeDetalhe.Entidade;
_cds.DataSetField := _campoDeLigacao;
Self.ConstruirDataSet(_cds,
EntidadeDetalhe.Sql.ObterSql,
EntidadeDetalhe.Campos);
// DetailDataSource
_dsr := TDataSource.Create(Modelo);
_dsr.Name := 'dsr_' + EntidadeDetalhe.Entidade;
_dsr.DataSet := _cds;
for _i := 0 to EntidadeDetalhe.Detalhes.Count-1 do
Self.ConstruirDataSetDetalhe(Modelo,
EntidadeDetalhe,
EntidadeDetalhe.Detalhes.Objects[_i] as TDominio,
_ds,
_cds);
MasterSqlDataSet.Active := False;
end;
end.
|
{*******************************************************}
{ }
{ NetView Version 2.3 }
{ }
{ }
{ Copyright (c) 1999-2004 Vadim Crits }
{ }
{*******************************************************}
unit NvMain;
{$WARN SYMBOL_DEPRECATED OFF}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ToolWin, Menus, ImgList, ActnList, ExtCtrls, StdCtrls, Registry;
type
TResourceType = (rtComputer, rtSharedFolder, rtSharedPrinter);
TMainForm = class(TForm)
StatusBar: TStatusBar;
ListView: TListView;
ImageList: TImageList;
CoolBar: TCoolBar;
Animate: TAnimate;
ActionList: TActionList;
actSave: TAction;
actSaveAs: TAction;
actExit: TAction;
actToolBar: TAction;
actStatusBar: TAction;
actRefresh: TAction;
actFind: TAction;
actPing: TAction;
actAbout: TAction;
Splitter: TSplitter;
psMenuBar: TPageScroller;
MenuBar: TToolBar;
btnFile: TToolButton;
btnView: TToolButton;
btnResource: TToolButton;
btnHelp: TToolButton;
PopupMenu: TPopupMenu;
actGridLines: TAction;
actHotTrack: TAction;
actRowSelect: TAction;
piGridLines: TMenuItem;
piHotTrack: TMenuItem;
piRowSelect: TMenuItem;
psToolBar: TPageScroller;
ToolBar: TToolBar;
btnSave: TToolButton;
ToolButton1: TToolButton;
btnStop: TToolButton;
btnRefresh: TToolButton;
ToolButton2: TToolButton;
btnFind: TToolButton;
btnPing: TToolButton;
actStop: TAction;
ResourceBar: TToolBar;
cboResource: TComboBox;
btnGo: TToolButton;
actGo: TAction;
actResourceBar: TAction;
TbrImages: TImageList;
TbrHotImages: TImageList;
MainMenu: TMainMenu;
miFile: TMenuItem;
miView: TMenuItem;
miResource: TMenuItem;
miHelp: TMenuItem;
miSave: TMenuItem;
miSaveAs: TMenuItem;
N1: TMenuItem;
miExit: TMenuItem;
miToolbars: TMenuItem;
miStatusBar: TMenuItem;
N2: TMenuItem;
miGridLines: TMenuItem;
miHotTrack: TMenuItem;
miRowSelect: TMenuItem;
N3: TMenuItem;
miGo: TMenuItem;
miStop: TMenuItem;
miRefresh: TMenuItem;
miStandardButtons: TMenuItem;
miResourceBar: TMenuItem;
miFind: TMenuItem;
miPing: TMenuItem;
miAbout: TMenuItem;
actOpen: TAction;
btnOpen: TToolButton;
ProgressBar: TProgressBar;
miOpen: TMenuItem;
actMessage: TAction;
btnMessage: TToolButton;
miMessage: TMenuItem;
piOpen: TMenuItem;
piPing: TMenuItem;
piMessage: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListViewColumnClick(Sender: TObject; Column: TListColumn);
procedure ListViewCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure ListViewDblClick(Sender: TObject);
procedure ListViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure StatusBarResize(Sender: TObject);
procedure StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
procedure cboResourceKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboResourceDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure SplitterCanResize(Sender: TObject; var NewSize: Integer;
var Accept: Boolean);
procedure ResourceBarResize(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure actSaveAsExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actToolBarExecute(Sender: TObject);
procedure actResourceBarExecute(Sender: TObject);
procedure actStatusBarExecute(Sender: TObject);
procedure actGoExecute(Sender: TObject);
procedure actStopExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure actFindExecute(Sender: TObject);
procedure actOpenExecute(Sender: TObject);
procedure actPingExecute(Sender: TObject);
procedure actMessageExecute(Sender: TObject);
procedure actAboutExecute(Sender: TObject);
procedure actGridLinesExecute(Sender: TObject);
procedure actHotTrackExecute(Sender: TObject);
procedure actRowSelectExecute(Sender: TObject);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure PopupMenuPopup(Sender: TObject);
private
{ Private declarations }
FRegistry: TRegistry;
FResType: TResourceType;
FSortCol: Integer;
FAscending: Boolean;
FFileName: string;
procedure ThreadDone(Sender: TObject);
procedure MkFile(const FileName: string; CreationFlag: Boolean);
public
{ Public declarations }
property Registry: TRegistry read FRegistry;
end;
TItemData = packed record
ImageIndex: Integer;
Caption : string;
SubItem0: string;
SubItem1: string;
SubItem2: string;
SubItem3: string;
end;
TChildThread = class(TThread)
private
FResType: TResourceType;
FValue: Integer;
FCurItem: TItemData;
procedure SetMax;
procedure SetPosition;
procedure AddItem;
protected
procedure Execute; override;
public
constructor Create(ResType: TResourceType);
end;
var
MainForm: TMainForm;
ChildThread: TChildThread;
implementation
uses NvFind, NvPing, NvMsg, NvAbout, NvConst, WinSock, Nb30, MMSystem, ShellAPI;
{$R *.dfm}
var
ProviderName: array[0..255] of Char;
LanaEnum: TLanaEnum;
function GetLana(var LanaEnum: TLanaEnum): Boolean;
var
NCB: TNCB;
begin
FillChar(LanaEnum, SizeOf(LanaEnum), 0);
FillChar(NCB, SizeOf(NCB), 0);
with NCB do
begin
ncb_command := Char(NCBENUM);
ncb_buffer := PChar(@LanaEnum);
ncb_length := SizeOf(TLanaEnum);
Netbios(@NCB);
Result := (ncb_retcode = Char(NRC_GOODRET)) and (Byte(LanaEnum.length) > 0);
end;
end;
function NBReset(const LanaNum: Char): Boolean;
var
NCB: TNCB;
begin
FillChar(NCB, SizeOf(NCB), 0);
with NCB do
begin
ncb_command := Char(NCBRESET);
ncb_lana_num := LanaNum;
Netbios(@NCB);
Result := (ncb_retcode = Char(NRC_GOODRET));
end;
end;
function GetMacAddress(const LanaNum: Char; Name: PChar): string;
var
NCB: TNCB;
AdapterStatus: PAdapterStatus;
begin
Result := '';
FillChar(NCB, SizeOf(TNCB), 0);
FillChar(AdapterStatus, SizeOf(AdapterStatus), 0);
NCB.ncb_length := SizeOf(TAdapterStatus) + 255 * SizeOf(TNameBuffer);
GetMem(AdapterStatus, NCB.ncb_length);
try
with NCB do
begin
ncb_command := Char(NCBASTAT);
ncb_buffer := PChar(AdapterStatus);
StrCopy(ncb_callname, Name);
ncb_lana_num := LanaNum;
Netbios(@NCB);
if ncb_retcode = Char(NRC_GOODRET) then
Result := Format('%2.2x-%2.2x-%2.2x-%2.2x-%2.2x-%2.2x', [
Byte(AdapterStatus^.adapter_address[0]),
Byte(AdapterStatus^.adapter_address[1]),
Byte(AdapterStatus^.adapter_address[2]),
Byte(AdapterStatus^.adapter_address[3]),
Byte(AdapterStatus^.adapter_address[4]),
Byte(AdapterStatus^.adapter_address[5])]);
end;
finally
FreeMem(AdapterStatus);
end;
end;
{ TChildThread }
constructor TChildThread.Create(ResType: TResourceType);
begin
inherited Create(False);
FResType := ResType;
end;
procedure TChildThread.AddItem;
begin
with MainForm do
begin
with ListView.Items.Add do
begin
ImageIndex := FCurItem.ImageIndex;
Caption := FCurItem.Caption;
SubItems.Add(FCurItem.SubItem0);
SubItems.Add(FCurItem.SubItem1);
if FResType = rtComputer then
begin
SubItems.Add(FCurItem.SubItem2);
SubItems.Add(FCurItem.SubItem3);
end;
end;
if FSortCol <> -1 then
ListView.CustomSort(nil, FSortCol - 1);
end;
Application.ProcessMessages;
end;
procedure TChildThread.SetMax;
begin
MainForm.ProgressBar.Max := FValue;
end;
procedure TChildThread.SetPosition;
begin
MainForm.ProgressBar.Position := FValue;
end;
procedure TChildThread.Execute;
const
ENUM_COUNT = 512;
MAX_ENTRIES = DWORD(-1);
var
hEnum: THandle;
NetGroups, NetComps, NetShares: array[0..ENUM_COUNT - 1] of TNetResource;
BufferSize, GroupCount, CompCount, ShareCount: DWORD;
i, j, k: Integer;
ComputerName: string;
HostEnt: PHostEnt;
NBBuffer: array[0..NCBNAMSZ - 1] of Char;
begin
BufferSize := SizeOf(TNetResource) * ENUM_COUNT;
NetGroups[0].lpProvider := ProviderName;
if WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
RESOURCEUSAGE_CONTAINER, @NetGroups[0], hEnum) <> NO_ERROR then
begin
ReturnValue := -1;
RaiseLastWin32Error;
end;
GroupCount := MAX_ENTRIES;
FillChar(NetGroups, BufferSize, 0);
try
if WNetEnumResource(hEnum, GroupCount, @NetGroups, BufferSize) <> NO_ERROR then
begin
ReturnValue := -1;
RaiseLastWin32Error;
end;
finally
WNetCloseEnum(hEnum);
end;
FValue := GroupCount - 1;
Synchronize(SetMax);
for i := 0 to GroupCount - 1 do
begin
FValue := i;
Synchronize(SetPosition);
if Terminated then
begin
ReturnValue := -1;
Exit;
end;
if WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
RESOURCEUSAGE_CONTAINER, @NetGroups[i], hEnum) <> NO_ERROR then
Continue;
CompCount := MAX_ENTRIES;
FillChar(NetComps, BufferSize, 0);
try
if WNetEnumResource(hEnum, CompCount, @NetComps, BufferSize) <> NO_ERROR then
Continue;
finally
WNetCloseEnum(hEnum);
end;
for j := 0 to CompCount - 1 do
begin
if Terminated then
begin
ReturnValue := -1;
Exit;
end;
case FResType of
rtComputer:
with FCurItem do
begin
ImageIndex := Ord(FResType);
Caption := NetComps[j].lpRemoteName;
SubItem0 := NetGroups[i].lpRemoteName;
SubItem1 := NetComps[j].lpComment;
ComputerName := Copy(Caption, 3, MaxInt);
HostEnt := gethostbyname(PChar(ComputerName));
if Assigned(HostEnt) then
SubItem2 := inet_ntoa(TInAddr(PLongint(HostEnt^.h_addr_list^)^))
else
SubItem2 := '?.?.?.?';
for k := 0 to Byte(LanaEnum.length) - 1 do
begin
if Terminated then
begin
ReturnValue := -1;
Exit;
end;
FillChar(NBBuffer, NCBNAMSZ, ' ');
CopyMemory(@NBBuffer, PChar(ComputerName), Length(ComputerName));
SubItem3 := GetMacAddress(LanaEnum.lana[k], NBBuffer);
if SubItem3 <> '' then
Break;
end;
if SubItem3 = '' then
SubItem3 := '?-?-?-?-?-?';
if (Pos('?', SubItem2) > 0) or (Pos('?', SubItem3) > 0) then
ImageIndex := 3;
Synchronize(AddItem);
end;
rtSharedFolder, rtSharedPrinter:
begin
if WNetOpenEnum(RESOURCE_GLOBALNET, Ord(FResType),
RESOURCEUSAGE_CONNECTABLE, @NetComps[j], hEnum) <> NO_ERROR then
Continue;
ShareCount := MAX_ENTRIES;
FillChar(NetShares, BufferSize, 0);
try
if WNetEnumResource(hEnum, ShareCount, @NetShares, BufferSize) <> NO_ERROR then
Continue;
finally
WNetCloseEnum(hEnum);
end;
for k := 0 to ShareCount - 1 do
begin
if Terminated then
begin
ReturnValue := -1;
Exit;
end;
with FCurItem do
begin
ImageIndex := Ord(FResType);
Caption := NetShares[k].lpRemoteName;
SubItem0 := NetGroups[i].lpRemoteName;
SubItem1 := NetShares[k].lpComment;
end;
Synchronize(AddItem);
end;
end;
end;
end;
end;
end;
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
procedure FatalError(const ErrMsg: string);
begin
with Application do
begin
MessageBox(PChar(ErrMsg), PChar(Title), MB_OK or MB_ICONERROR);
ShowMainForm := False;
Terminate;
end;
end;
var
BufferSize: Cardinal;
WSAData: TWSAData;
i: Integer;
Position: TRect;
begin
BufferSize := SizeOf(ProviderName);
if WNetGetProviderName(WNNC_NET_LANMAN, @ProviderName, BufferSize) <> NO_ERROR then
FatalError(SysErrorMessage(GetLastError));
if WSAStartup($0101, WSAData) <> 0 then
FatalError(SWinSockErr);
if not GetLana(LanaEnum) then
FatalError(SProblemWithNA);
if Win32Platform = VER_PLATFORM_WIN32_NT then
for i := 0 to Byte(LanaEnum.length) - 1 do
if not NBReset(LanaEnum.lana[i]) then
FatalError(SResetLanaErr);
Animate.ResName := 'FINDCOMP';
with cboResource do
begin
for i := 0 to High(NetResNames) do
Items.Add(NetResNames[i]);
ItemIndex := 0;
end;
with ProgressBar do
begin
Parent := StatusBar;
Top := 2;
Height := StatusBar.Height - 2;
end;
FRegistry := TRegistry.Create;
with FRegistry do
if OpenKey(INIT_KEY, False) then
try
if ValueExists(SPosition) then
begin
ReadBinaryData(SPosition, Position, SizeOf(Position));
BoundsRect := Position;
end;
if ValueExists(SWindowState) then
if ReadInteger(SWindowState) = Ord(wsMaximized) then
WindowState := wsMaximized;
if ValueExists(SResourceType) then
cboResource.ItemIndex := ReadInteger(SResourceType);
if ValueExists(SShowToolBar) then
psToolBar.Visible := ReadBool(SShowToolBar);
if ValueExists(SShowResourceBar) then
ResourceBar.Visible := ReadBool(SShowResourceBar);
if ValueExists(SShowStatusBar) then
StatusBar.Visible := ReadBool(SShowStatusBar);
with ListView do
begin
if ValueExists(SShowGridLines) then
GridLines := ReadBool(SShowGridLines);
if ValueExists(SShowHotTrack) then
if ReadBool(SShowHotTrack) then
actHotTrack.Execute;
if ValueExists(SShowRowSelect) then
RowSelect := ReadBool(SShowRowSelect);
end;
finally
CloseKey;
end;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
actGo.Execute;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
var
Position: TRect;
begin
with FRegistry do
begin
RootKey := HKEY_CLASSES_ROOT;
if not KeyExists(NN_KEY) then
if OpenKey(NN_KEY, True) then
try
WriteString('', SScanWithNetView);
CloseKey;
OpenKey(NN_KEY + 'command', True);
WriteString('', Application.ExeName + ' "%1"');
finally
CloseKey;
end;
RootKey := HKEY_CURRENT_USER;
if OpenKey(INIT_KEY, True) then
try
if WindowState = wsNormal then
begin
Position := BoundsRect;
WriteBinaryData(SPosition, Position, SizeOf(Position));
end;
WriteInteger(SWindowState, Ord(WindowState));
WriteInteger(SResourceType, Ord(FResType));
WriteBool(SShowToolBar, psToolBar.Visible);
WriteBool(SShowResourceBar, ResourceBar.Visible);
WriteBool(SShowStatusBar, StatusBar.Visible);
WriteBool(SShowGridLines, actGridLines.Checked);
WriteBool(SShowHotTrack, actHotTrack.Checked);
WriteBool(SShowRowSelect, actRowSelect.Checked);
finally
CloseKey;
end;
Free;
end;
actStop.Execute;
WSACleanup;
end;
procedure TMainForm.ListViewColumnClick(Sender: TObject;
Column: TListColumn);
begin
FAscending := not FAscending;
if (FSortCol <> -1) and (FSortCol <> Column.Index) then
begin
FAscending := True;
ListView.Columns[FSortCol].ImageIndex := -1;
end;
if FAscending then
Column.ImageIndex := 4
else
Column.ImageIndex := 5;
FSortCol := Column.Index;
ListView.CustomSort(nil, FSortCol - 1);
end;
procedure TMainForm.ListViewCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
function AlignIpAddress(const IpAddress: string): string;
var
P, Start: PChar;
S: string;
begin
Result := '';
P := PChar(IpAddress);
while P^ <> #0 do
begin
Start := P;
while not (P^ in [#0, '.']) do Inc(P);
SetString(S, Start, P - Start);
Result := Result + Format('%3s', [S]);
if P^ <> #0 then
begin
Result := Result + '.';
Inc(P);
end;
end;
end;
var
SortFlag: Integer;
begin
if FAscending then SortFlag := 1 else SortFlag := -1;
case Data of
-1: Compare := SortFlag * AnsiCompareText(Item1.Caption, Item2.Caption);
0,1,3: Compare := SortFlag * AnsiCompareText(Item1.SubItems[Data],
Item2.SubItems[Data]);
2: Compare := SortFlag * AnsiCompareText(AlignIpAddress(Item1.SubItems[Data]),
AlignIpAddress(Item2.SubItems[Data]))
end;
end;
procedure TMainForm.ListViewDblClick(Sender: TObject);
begin
if actOpen.Enabled then actOpen.Execute;
end;
procedure TMainForm.ListViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then ListViewDblClick(Sender);
end;
procedure TMainForm.StatusBarResize(Sender: TObject);
const
W = 150;
begin
with Sender as TStatusBar do
begin
if ClientWidth >= Panels[2].Width + W then
begin
Panels[0].Width := ClientWidth - Panels[1].Width - Panels[2].Width;
if Panels[1].Width <= W then Panels[1].Width := W;
end
else
begin
Panels[0].Width := 1;
Panels[1].Width := ClientWidth - Panels[2].Width;
if ClientWidth <= Panels[2].Width then Panels[1].Width := 0;
end;
with ProgressBar do
begin
Left := Panels[0].Width + 2;
Width := Panels[1].Width - 2;
end;
end;
end;
procedure TMainForm.StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
begin
with StatusBar do
if Panel.Index = 0 then
begin
ImageList.Draw(Canvas, Rect.Left + 1, Rect.Top, 6);
Canvas.TextOut(Rect.Left + 21, Rect.Top + 1, SUpdating);
end
else
begin
ImageList.Draw(Canvas, Rect.Left + 1, Rect.Top, 7);
Canvas.TextOut(Rect.Left + 21, Rect.Top + 1, SLocalInet);
end;
end;
procedure TMainForm.cboResourceKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then actGo.Execute;
end;
procedure TMainForm.cboResourceDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
OldRect: TRect;
DrawingStyle: TDrawingStyle;
begin
with Control as TComboBox do
begin
OldRect := Rect;
if odFocused in State then
DrawingStyle := dsSelected
else
DrawingStyle := dsNormal;
ImageList.Draw(Canvas, Rect.Left, Rect.Top, Index, DrawingStyle, itImage);
Rect.Right := Rect.Left + Canvas.TextWidth(Items[Index]) + 3;
OffsetRect(Rect, ImageList.Width + 2, 0);
Canvas.FillRect(Rect);
Canvas.TextOut(Rect.Left + 1, Rect.Top + 2, Items[Index]);
if odFocused in State then
begin
Canvas.DrawFocusRect(OldRect);
Canvas.DrawFocusRect(Rect);
end;
end;
end;
procedure TMainForm.SplitterCanResize(Sender: TObject;
var NewSize: Integer; var Accept: Boolean);
var
i: Integer;
begin
with CoolBar do
if NewSize < Height then
begin
for i := Bands.Count - 1 downto 0 do
if Bands[i].Break = True then
if NewSize <= Height - Bands[i].Height then
begin
Bands[i].Break := False;
Accept := True;
end;
end
else
begin
for i := Bands.Count - 1 downto 0 do
if (Bands[i].Break = False) and (not Bands[i].FixedSize) then
if NewSize >= Height + Bands[i].Height then
begin
Bands[i].Break := True;
Accept := True;
end;
end;
end;
procedure TMainForm.ResourceBarResize(Sender: TObject);
begin
cboResource.Width := ResourceBar.Width - ResourceBar.ButtonWidth - 2;
end;
procedure TMainForm.actSaveExecute(Sender: TObject);
begin
if FFileName = '' then
actSaveAs.Execute
else
MkFile(FFileName, False);
end;
procedure TMainForm.actSaveAsExecute(Sender: TObject);
var
FileExt: string;
begin
Application.ProcessMessages;
with TSaveDialog.Create(Self) do
try
Options := [ofHideReadOnly, ofEnableSizing, ofOverwritePrompt];
if FFileName = '' then FileName := '*' + SDefExt
else
FileName := FFileName;
Filter := SFilter;
if Execute then
begin
FFileName := FileName;
FileExt := ExtractFileExt(FFileName);
if AnsiLowerCase(FileExt) <> SDefExt then
begin
Delete(FFileName, Pos('.', FFileName), Length(FileExt));
FFileName := FFileName + SDefExt;
end;
MkFile(FFileName, True);
end;
finally
Free;
end;
end;
procedure TMainForm.actExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMainForm.actToolBarExecute(Sender: TObject);
begin
psToolBar.Visible := not psToolBar.Visible;
end;
procedure TMainForm.actResourceBarExecute(Sender: TObject);
begin
with CoolBar.Bands.FindBand(ResourceBar) do Visible := not Visible;
end;
procedure TMainForm.actStatusBarExecute(Sender: TObject);
begin
StatusBar.Visible := not StatusBar.Visible;
end;
procedure TMainForm.actGoExecute(Sender: TObject);
var
ResType: TResourceType;
i: Integer;
begin
actStop.Execute;
Screen.Cursor := crAppStart;
Animate.Active := True;
StatusBar.Panels[0].Style := psOwnerDraw;
ResType := TResourceType(cboResource.ItemIndex);
with ListView do
begin
Items.BeginUpdate;
Items.Clear;
Items.EndUpdate;
if (ResType <> FResType) or (Columns.Count = 0) then
begin
Columns.BeginUpdate;
Columns.Clear;
Columns.EndUpdate;
for i := 0 to High(ColumnNames) do
begin
with Columns.Add do
begin
Caption := ColumnNames[i];
Width := 110;
end;
if (ResType <> rtComputer) and (Columns.Count > 2) then
Break;
end;
FAscending := False;
FSortCol := -1;
end;
end;
ChildThread := TChildThread.Create(ResType);
ChildThread.OnTerminate := ThreadDone;
FResType := ResType;
end;
procedure TMainForm.actStopExecute(Sender: TObject);
begin
Application.ProcessMessages;
if Assigned(ChildThread) then
with ChildThread do
begin
Terminate;
WaitFor;
FreeAndNil(ChildThread);
end;
end;
procedure TMainForm.actRefreshExecute(Sender: TObject);
begin
actGo.Execute;
end;
procedure TMainForm.actFindExecute(Sender: TObject);
begin
ShowFindDialog(Self);
end;
procedure TMainForm.actOpenExecute(Sender: TObject);
begin
ShellExecute(Handle, 'open', PChar(ListView.Selected.Caption), nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.actPingExecute(Sender: TObject);
begin
with ListView.Selected do
ShowPingDialog(Self, Copy(Caption, 3, MaxInt), SubItems[2]);
end;
procedure TMainForm.actMessageExecute(Sender: TObject);
begin
ShowMessageDialog(Self, Copy(ListView.Selected.Caption, 3, MaxInt));
end;
procedure TMainForm.actAboutExecute(Sender: TObject);
begin
ShowAboutBox(Self);
end;
procedure TMainForm.actGridLinesExecute(Sender: TObject);
begin
with ListView do
begin
GridLines := not GridLines;
Invalidate;
end;
end;
procedure TMainForm.actHotTrackExecute(Sender: TObject);
begin
with ListView do
begin
HotTrack := not HotTrack;
if HotTrack then
begin
OnDblClick := nil;
OnClick := ListViewDblClick;
HotTrackStyles := [htHandPoint, htUnderlineCold, htUnderlineHot];
end
else
begin
OnClick := nil;
OnDblClick := ListViewDblClick;
HotTrackStyles := [];
end;
Invalidate;
end;
end;
procedure TMainForm.actRowSelectExecute(Sender: TObject);
begin
with ListView do
begin
RowSelect := not RowSelect;
Invalidate;
end;
end;
procedure TMainForm.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
actSave.Enabled := not Animate.Active;
actSaveAs.Enabled := actSave.Enabled;
actToolBar.Checked := psToolBar.Visible;
actResourceBar.Checked := ResourceBar.Visible;
actStatusBar.Checked := StatusBar.Visible;
with ListView do
begin
actFind.Enabled := Items.Count > 0;
actMessage.Visible := Win32Platform = VER_PLATFORM_WIN32_NT;
if Assigned(Selected) then
begin
actOpen.Enabled := Selected.ImageIndex in [0, 1];
actPing.Enabled := Selected.ImageIndex = 0;
actMessage.Enabled := actMessage.Visible and actPing.Enabled;
end
else
begin
actOpen.Enabled := False;
actPing.Enabled := False;
actMessage.Enabled := False;
end;
actGridLines.Checked := GridLines;
actHotTrack.Checked := HotTrack;
actRowSelect.Checked := RowSelect;
end;
end;
procedure TMainForm.PopupMenuPopup(Sender: TObject);
begin
actOpen.Update;
piOpen.Visible := actOpen.Enabled;
piPing.Visible := actPing.Enabled;
piMessage.Visible := actMessage.Enabled;
piGridLines.Visible := not Assigned(ListView.Selected);
piHotTrack.Visible := piGridLines.Visible;
piRowSelect.Visible := piGridLines.Visible;
end;
procedure TMainForm.ThreadDone(Sender: TObject);
begin
with ChildThread do
if Assigned(FatalException) then
Application.ShowException(Exception(FatalException));
ProgressBar.Position := 0;
StatusBar.Panels[0].Style := psText;
StatusBar.Panels[0].Text := Format(SStatusText, [ListView.Items.Count,
NetResNames[Ord(FResType)]]);
if ChildThread.ReturnValue = 0 then
sndPlaySound(PChar('JP'), SND_RESOURCE);
Animate.Active := False;
Screen.Cursor := crDefault;
end;
procedure TMainForm.MkFile(const FileName: string; CreationFlag: Boolean);
var
F: TextFile;
SaveCursor: TCursor;
FmtStr: string;
i: Integer;
begin
AssignFile(F, FileName);
if CreationFlag then Rewrite(F) else Reset(F);
SaveCursor := Screen.Cursor;
try
Screen.Cursor := crAppStart;
Append(F);
Writeln(F, Format(#13#10'*** %s (%s) ***'#13#10, [NetResNames[Ord(FResType)],
FormatDateTime(ShortDateFormat +
' ' + LongTimeFormat, Now)]));
with ListView do
if FResType = rtComputer then
begin
FmtStr := '%-17s %-15s %-48s %-15s %-17s';
Writeln(F, Format(FmtStr, [Columns[0].Caption,
Columns[1].Caption,
Columns[2].Caption,
Columns[3].Caption,
Columns[4].Caption]));
Writeln(F, Format('%s %s %s %s %s', ['=================',
'===============',
'================================================',
'===============',
'=================']));
for i := 0 to Items.Count - 1 do
Writeln(F, Format(FmtStr, [Items[i].Caption,
Items[i].SubItems[0],
Items[i].SubItems[1],
Items[i].SubItems[2],
Items[i].SubItems[3]]));
end
else
begin
FmtStr := '%-48s %-15s %-48s';
Writeln(F, Format(FmtStr, [Columns[0].Caption,
Columns[1].Caption,
Columns[2].Caption]));
Writeln(F, Format('%s %s %s', ['================================================',
'===============',
'================================================']));
for i := 0 to Items.Count - 1 do
Writeln(F, Format(FmtStr, [Items[i].Caption,
Items[i].SubItems[0],
Items[i].SubItems[1]]));
end;
finally
CloseFile(F);
Screen.Cursor := SaveCursor;
end;
end;
end.
|
program LinkedList;
type
Nd = ^Node;
Node = record
Info : integer;
Next : Nd;
end;
procedure Print(var Start : Nd);
var
i : integer;
L : Nd;
begin
L := Start;
i := 0;
while L <> nil do
begin
writeln(i, ' : ', L^.Info);
L := L^.Next;
i := i + 1;
end;
end;
procedure AddNToAppend(N : integer; var Start : Nd);
var
i : integer;
L : Nd;
Prev : Nd;
begin
Prev := Start;
for i := 1 to N do
begin
new(L);
Prev^.Next := L;
Prev := L;
L^.Info := i;
end;
end;
function AddNToBeginning(N : integer; var Start : Nd) : Nd;
var
L, Prev : Nd;
begin
Prev := Start;
while N >= 0 do
begin
new(L);
L^.Info := N;
L^.Next := Prev;
Prev := L;
N := N - 1;
end;
AddNToBeginning := Prev;
end;
procedure AddAfter(var L, Q : Nd);
begin
Q^.Next := L^.Next;
L^.Next := Q;
end;
procedure AddBefore(var L, Q : Nd);
var
tmp : integer;
begin
Q^.Next := L^.Next;
L^.Next := Q;
tmp := L^.Info;
L^.Info := Q^.Info;
Q^.Info := tmp;
end;
procedure RemoveAfter(var L : Nd);
begin
if L^.Next <> nil then
L^.Next := L^.Next^.Next;
end;
procedure Remove(var L : Nd);
begin
if L^.Next <> nil then
begin
L^.Info := L^.Next^.Info;
L^.Next := L^.Next^.Next;
end;
end;
procedure RemoveByInfo(var Start : Nd; info : integer);
var
C, Prev : Nd;
begin
C := Start;
while C <> nil do
begin
if C^.Info = info then
begin
if Prev <> nil then
Prev^.Next := C^.Next;
C := nil;
end
else
begin
Prev := C;
C := C^.Next;
end;
end;
end;
procedure RemoveByInfo2(var Start : Nd; info : integer);
var
C, Prev : Nd;
begin
Prev := Start;
C := Start;
while C <> nil do
begin
if C^.Info = info then
begin
if Prev <> nil then
Prev^.Next := C^.Next;
end
else
Prev := C;
C := C^.Next;
end;
end;
procedure RemoveAllAfter(var Start : Nd);
var
C, Prev : Nd;
begin
C := Start^.Next^.Next;
while C <> nil do
begin
if Prev <> nil then
Dispose(Prev);
Prev := C;
C := C^.Next;
end;
Dispose(C);
Start^.Next := nil;
end;
function Reverse(var Start : Nd) : Nd;
var
L, C, Following : Nd;
begin
Following := nil;
L := Start;
while L <> nil do
begin
new(C);
C^.Info := L^.Info;
C^.Next := Following;
Following := C;
Reverse := C;
L := L^.Next;
end;
end;
function FindInIncreasingOrderLinkedList(var Start : Nd; Info : integer) : integer;
var
i : integer;
C : Nd;
begin
i := 0;
C := Start;
FindInIncreasingOrderLinkedList := -1;
while C <> nil do
begin
if C^.Info = Info then
begin
FindInIncreasingOrderLinkedList := i;
C := nil;
end
else if Info < C^.Info then
C := nil
else
C := C^.Next;
i := i + 1;
end;
end;
var
First : Nd;
L : Nd;
begin
new(First);
First^.Info := 5;
First := AddNToBeginning(10, First);
L := Reverse(First);
RemoveByInfo(First, 3);
Print(First);
writeln('---');
Print(L);
writeln('---');
writeln(FindInIncreasingOrderLinkedList(First, 5));
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
//GLS
GLObjects, GLScene, GLVectorGeometry, GLCadencer, GLWin32Viewer,
GLGeomObjects, GLCrossPlatform, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
DCSphere: TGLDummyCube;
ArrowLine: TGLArrowLine;
GLLightSource1: TGLLightSource;
Sphere: TGLSphere;
DCArrow: TGLDummyCube;
GLCadencer1: TGLCadencer;
Disk1: TGLDisk;
Disk2: TGLDisk;
Lines1: TGLLines;
Plane1: TGLPlane;
Lines2: TGLLines;
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
// Make the blue sphere turn and ride a sin
DCSphere.Turn(deltaTime*30);
Sphere.Position.Y:=Sin(DegToRad(newTime*50))*3;
// Make the arrow turn
DCArrow.Turn(-deltaTime*15);
// Make the arrow point toward the sphere, using Y as up reference
ArrowLine.PointTo(Sphere, YHmgVector);
end;
end.
|
unit js_tokens;
interface
uses fw_utils,fw_vm_constants;
const
// Los tokens de control del lexer
jst_Root =255;
jst_None =254;
jst_Error =253;
jst_Eof =252;
jst_vars =251;
jst_Functions =250;
jst_CodeDef =249;
jst_FuncDef =248;
jst_CodeDef2 =247;
jst_ObjectDef =246;
jst_ArrayDef =245;
jst_Unassigned =244;
jst_Internal =240;
// Los tokens de simbolos
jst_Begin =060;
jst_End =059;
jst_OpenPar =058;
jst_ClosePar =057;
jst_OpenB =056;
jst_CloseB =055;
jst_PComma =054;
jst_Dot =053;
jst_Comma =052;
jst_2Puntos =051;
jst_ExpGroup =050;
// Los tokens de palabras clave
jst_GCopy =040;
jst_if =039;
jst_else =038;
jst_while =037;
jst_try =036;
jst_catch =035;
jst_finally =034;
jst_Return =033;
jst_Function =032;
jst_Var =031;
jst_Throw =030;
jst_Param =029;
jst_ExtValue =028;
jst_IndParam =027;
jst_IndVar =026;
jst_LinkCopy =025;
jst_For =024;
jst_Break =023;
jst_Continue =022;
jst_BreakHelper=021;
jst_Do =020;
jst_ForIn =019;
jst_ForEachIn =018;
jst_Each =017;
jst_This =016;
jst_Null =015;
jst_Undefined =014;
jst_Getter =013; // Es un get dentro de la definicion de un Objeto
jst_Setter =012; // Es un set dentro de la definicion de un Objeto
jst_GetSet =011;
// Los tokens de elementos
jst_pchar =001;
jst_float =002;
jst_bool =003;
jst_ident =004;
jst_true =005;
jst_false =006;
jst_integer =007;
jst_pchar2 =009;
// Los operadores unarios que van antes
jst_New =101;
jst_PreInc =102;
jst_PreDec =103;
// Operadores binarios
jst_Not =OP_NOT;
jst_bnot =105;
jst_Positive =106;
jst_Negative =107;
jst_TypeOf =OP_TYPEOF;
jst_delete =110;
jst_Void =111;
// Los unarios posteriores
jst_member =112;
jst_fcall =113;
jst_PostInc =114;
jst_PostDec =115;
jst_Index =116;
// Los operadores binarios despues
jst_Times =OP_TIMES;
jst_Div =OP_DIV;
jst_Mod =OP_MOD;
jst_Add =OP_ADD;
jst_Minus =OP_MINUS;
jst_shiftl =OP_SHIFTL;
jst_shiftr =OP_SHIFTR;
jst_shiftrz =OP_SHIFTRZ;
jst_instance =OP_INSTANCE;
jst_Equals =160;
jst_Diff =161;
jst_strictEq =162;
jst_strictDif =163;
jst_Less =164;
jst_LessEq =165;
jst_Big =166;
jst_BigEq =167;
jst_In =168;
jst_Min_BoolOp =jst_Equals;
jst_Max_BoolOp =jst_In;
jst_bAnd =169;
jst_bXOr =170;
jst_bOr =171;
jst_And =172;
jst_Or =173;
// El operador Ternario condicional If
jst_CondIf =174;
// Aqui van los operadores de asignacion (con menos prioridad)
jst_Assign =175;
jst_AsgnAdd =176;
jst_AsgnMinus =177;
jst_AsgnTimes =178;
jst_AsgnDiv =179;
jst_AsgnMod =180;
jst_AsgnLeft =181;
jst_AsgnRight =182;
jst_AsgnZRight =183;
jst_AsgnAnd =184;
jst_AsgnXor =185;
jst_AsgnOr =186;
function js_token2str(k:cardinal):string;
function js_maxBinOp:integer;
function js_minBinOp:integer;
function js_maxPreOp:integer;
function js_minPreOp:integer;
// Normalmente un token se corresponde con un operador
// pero hay algunos que afectan a mas de uno:
// + (Signo Positivo / Suma) o - (Signo Negativo / Resta)
// ++ (PreInc / PostInc) o -- (PreDec/PostDec)
//
// Por eficiencia todos operadores BINARIOS coinciden con su token
function js_tokenIsBinOp(token,ope:cardinal):boolean;
// Esta funcion resuelve las ambiguedades de los tokens unarios
function js_token2UnaryOp(token:cardinal;pre:boolean):cardinal;
// Nos dice si un token es unario (pre o post)
function js_tokenIsUnaryPreOp(token:cardinal):boolean;
function js_tokenIsUnaryPostOp(token:cardinal):boolean;
function js_tokenIsLoop(token:cardinal):boolean;
function js_keyword(h:cardinal):cardinal;
// Nos dice si Kind es un operador binario
function js_kindIsBinOp(k:cardinal):boolean;
// Nos dice si un operador se evalua IZ->DER o DER-IZ
function js_tokenEvalLeft(ope:cardinal):boolean;
// Nos dice si un operador afecta a los flags (pej. operadores de comparacion)
function js_flaggedOp(k:cardinal):boolean;
// Nos dice si un operador debe copiar el resultado en el primer operando (pej. a+=b)
function js_IsAssignOp(k:cardinal):boolean;
implementation
type TJs_KeyWord=record hash,value:cardinal;end;
const JS_NKEYWORDS =21; // Cuantas Keywords tenemos
var JS_KeyWords: array[0..JS_NKEYWORDS] of TJS_KeyWord; // Palabras clave
// PRE: new, ++ -- ! ~ + - typeof void delete CLASS_NAME
JS_Op_Pre: array[0..9] of byte=(jst_New,jst_PreInc,jst_PreDec,jst_Not,jst_bnot,jst_Positive,jst_Negative,jst_TypeOf,jst_void,jst_delete);
// POST -> EXTENDIDOS . [] () y SIN EXTENDER ++ --
JS_Op_Pos: array[0..4] of byte=(jst_member,jst_index,jst_fcall,jst_PostInc,jst_PostDec);
// binarios * / % + - << >> >>>
// < <= > >= in instanceof == !=
// === !== & ^ | && || =
// += -= *= /= %= <<= >>= >>>= &= ^= |=
JS_Op_Bin: array[0..35] of byte=(jst_Times,jst_Div,jst_Mod,jst_Minus,jst_Add,jst_shiftl,jst_shiftr,jst_shiftrz,
jst_Less,jst_LessEq,jst_Big,jst_BigEq,jst_In,jst_instance,jst_Equals,jst_Diff,
jst_strictEq,jst_strictDif,jst_bAnd,jst_bXOr,jst_bOr,jst_And,jst_Or,
jst_CondIf,
jst_Assign,jst_AsgnAdd,jst_AsgnMinus,jst_AsgnTimes,jst_AsgnDiv,jst_AsgnMod,
jst_AsgnLeft,jst_AsgnRight,jst_AsgnZRight,jst_AsgnAnd,jst_AsgnXor,jst_AsgnOr);
// Nos dejamos estos ya que al ser unicos los gestionamos directamente desde el parser
// trinarios ?:
// multiples ,
function js_maxBinOp:integer;
begin
result:=high(JS_Op_Bin);
end;
function js_minBinOp:integer;
begin
result:=low(JS_Op_Bin);
end;
function js_tokenIsLoop(token:cardinal):boolean;
begin
result:=token in [jst_For,jst_while,jst_Do,jst_ForEachIn,jst_ForIn];
end;
function js_flaggedOp(k:cardinal):boolean;
begin
result:=k in [jst_Less,jst_LessEq,jst_Big,jst_BigEq,jst_In,jst_Equals,jst_Diff];
end;
function js_IsAssignOp(k:cardinal):boolean;
begin
result:=k in [jst_AsgnAdd,jst_AsgnMinus,jst_AsgnTimes,jst_AsgnDiv,jst_AsgnMod,jst_AsgnLeft,jst_AsgnRight,jst_AsgnZRight,jst_AsgnAnd,jst_AsgnXor,jst_AsgnOr];
end;
function js_maxPreOp:integer;
begin
result:=high(JS_Op_Pre);
end;
function js_minPreOp:integer;
begin
result:=low(JS_Op_Pre);
end;
function js_tokenIsBinOp(token,ope:cardinal):boolean;
begin
if (ope<=High(JS_Op_Bin)) then result:=token=JS_Op_Bin[ope] else result:=false;
end;
function js_kindIsBinOp(k:cardinal):boolean;
var i:longint;
begin
result:=false;i:=low(JS_Op_Bin);
while (result=false) and (i<=High(JS_Op_Bin)) do begin result:=JS_Op_Bin[i]=k;i:=i+1;end;
end;
function js_tokenEvalLeft(ope:cardinal):boolean;
begin
if (ope<=High(JS_Op_Bin)) then result:=JS_Op_Bin[ope]<>jst_Assign else result:=true;
end;
function js_token2UnaryOp(token:cardinal;pre:boolean):cardinal;
begin
result:=token;
case token of
jst_Dot: if not pre then result:=jst_Member;
jst_OpenPar: if not pre then result:=jst_fcall;
jst_OpenB: if not pre then result:=jst_index;
jst_PostInc: if pre then result:=jst_PreInc else result:=jst_PostInc;
jst_PostDec: if pre then result:=jst_PreDec else result:=jst_PostDec;
jst_Add: if pre then result:=jst_Positive;
jst_Minus: if pre then result:=jst_Negative;
end;
end;
function js_tokenIsUnaryPreOp(token:cardinal):boolean;
var i:longint;
begin
result:=false;i:=js_minPreOp;
while (result=false) and (i<=js_maxPreOp) do begin result:=JS_Op_Pre[i]=token;i:=i+1;end;
end;
function js_tokenIsUnaryPostOp(token:cardinal):boolean;
var i:longint;
begin
result:=false;i:=low(JS_Op_Pos);
while (result=false) and (i<=high(JS_Op_Pos)) do begin result:=JS_Op_Pos[i]=token;i:=i+1;end;
end;
function js_token2str(k:cardinal):string;
begin
case k of
jst_Throw: result:='[THROW]';
jst_TypeOf: result:='[TYPE_OF]';
jst_This: result:='[THIS]';
jst_ExpGroup: result:='[EXP_GROUP]';
jst_Getter: result:='[GETTER]';
jst_Setter: result:='[SETTER]';
jst_Positive: result:='[POSITIVE]';
jst_Null: result:='[null]';
jst_Negative: result:='[NEGATIVE]';
jst_fCall: result:='[call]';
jst_root: result:='[ROOT]';
jst_None: result:='[NONE]';
jst_vars: result:='[VARS]';
jst_Eof: result:='[EOF]';
jst_Begin: result:='[BEGIN]';
jst_IndParam: result:='[IND_PARAM]';
jst_IndVar: result:='[IND_VAR]';
jst_LinkCopy: result:='[LINKCOPY]';
jst_End: result:='[END]';
jst_ExtValue: result:='[EXTVALUE]';
jst_OpenPar: result:='[OPENPAR]';
jst_ClosePar: result:='[CLOSEPAR]';
jst_OpenB: result:='[OPENB]';
jst_CloseB: result:='[CLOSEB]';
jst_PComma: result:='[PCOMMA]';
jst_if: result:='[IF]';
jst_While: result:='[WHILE]';
jst_For: result:='[FOR]';
jst_ForIn: result:='[FOR IN]';
jst_New: result:='[NEW]';
jst_ForEachIn: result:='[FOR EACH IN]';
jst_Break: result:='[BREAK]';
jst_Do: result:='[DO]';
jst_BreakHelper:result:='[BREAK_HELPER]';
jst_Continue: result:='[CONTINUE]';
jst_Index: result:='[INDEX]';
jst_integer: result:='integer';
jst_pchar: result:='pchar';
jst_float: result:='float';
jst_bool: result:='bool';
jst_ident: result:='ident';
jst_Add: result:='[add]';
jst_AsgnAdd: result:='[add_asign]';
jst_AsgnMinus: result:='[minus_asign]';
jst_Dot: result:='[dot]';
jst_Comma: result:='[comma]';
jst_Assign: result:='[assign]';
jst_AsgnAnd: result:='[assign_and]';
jst_Try: result:='[try]';
jst_Catch: result:='[catch]';
jst_Finally: result:='[finally]';
jst_ObjectDef: result:='[object]';
jst_ArrayDef: result:='[array]';
jst_2Puntos: result:='[:]';
jst_AsgnOr: result:='[assign_or]';
jst_Diff: result:='[diff]';
jst_Var: result:='[var]';
jst_Equals: result:='[equals]';
jst_Less: result:='[less]';
jst_Return: result:='[return]';
jst_LessEq: result:='[less_eq]';
jst_In: result:='[in]';
jst_Big: result:='[bigger]';
jst_BigEq: result:='[bigger_eq]';
jst_Minus: result:='[minus]';
jst_Times: result:='[times]';
jst_Div: result:='[div]';
jst_Undefined: result:='[undefined]';
jst_Mod: result:='[mod]';
jst_shiftl: result:='[shiftl]';
jst_shiftr: result:='[shiftr]';
jst_And: result:='[and]';
jst_Or: result:='[or]';
jst_PreInc: result:='[pre_inc]';
jst_PreDec: result:='[pre_dec]';
jst_Not: result:='[not]';
jst_CondIf: result:='[if_operator]';
jst_instance: result:='[instance]';
jst_Param: result:='[param]';
jst_PostInc: result:='[post_inc]';
jst_Functions: result:='[functions]';
jst_GetSet: result:='[getset]';
jst_PostDec: result:='[post_dec]';
jst_GCopy: result:='[GCOPY]';
//jst_CallParams: result:='[c_params]';
jst_CodeDef: result:='[code]'; // Define un bloque de codigo (pej. una funcion fuera de una expresion)
jst_CodeDef2: result:='[code_2]'; // Se trata del nodo anterior tras haber sido procesado por el Generador de Codigo
jst_FuncDef: result:='[def_func]'; // Define una funcion dentro de una expresion
jst_member: result:='[property]';
else result:='-E:'+s_i2s(k);
end;
end;
function js_keyword(h:cardinal):cardinal;
var i:cardinal;
begin
result:=jst_ident;i:=low(JS_KeyWords);
while (result=jst_ident) and (i<=JS_NKEYWORDS) do if JS_KeyWords[i].hash=h then result:=JS_KeyWords[i].value else i:=i+1;
end;
procedure Init_Tokens;
begin
JS_KeyWords[0].hash :=s_Hash('if'); JS_KeyWords[0].value :=jst_If;
JS_KeyWords[1].hash :=s_Hash('else'); JS_KeyWords[1].value :=jst_Else;
JS_KeyWords[2].hash :=s_Hash('while'); JS_KeyWords[2].value :=jst_While;
JS_KeyWords[3].hash:=s_Hash('typeof'); JS_KeyWords[3].value:=jst_TypeOf;
JS_KeyWords[4].hash:=s_Hash('function'); JS_KeyWords[4].value:=jst_Function;
JS_KeyWords[5].hash:=s_Hash('var'); JS_KeyWords[5].value:=jst_Var;
JS_KeyWords[6].hash:=s_Hash('return'); JS_KeyWords[6].value:=jst_Return;
JS_KeyWords[7].hash:=s_Hash('new'); JS_KeyWords[7].value:=jst_New;
JS_KeyWords[8].hash:=s_hash('this'); Js_KeyWords[8].value:=jst_This;
JS_KeyWords[9].hash:=s_Hash('instanceof'); JS_KeyWords[9].value:=jst_Instance;
JS_KeyWords[10].hash:=s_Hash('true'); JS_KeyWords[10].value:=jst_True;
JS_KeyWords[11].hash:=s_Hash('false'); JS_KeyWords[11].value:=jst_False;
JS_KeyWords[12].hash:=s_Hash('try'); JS_KeyWords[12].value:=jst_Try;
JS_KeyWords[13].hash:=s_Hash('catch'); JS_KeyWords[13].value:=jst_Catch;
JS_KeyWords[14].hash:=s_Hash('finally'); JS_KeyWords[14].value:=jst_Finally;
JS_KeyWords[15].hash:=s_Hash('throw'); JS_KeyWords[15].value:=jst_Throw;
JS_KeyWords[16].hash:=s_hash('for'); Js_KeyWords[16].value:=jst_For;
JS_KeyWords[17].hash:=s_hash('break'); Js_KeyWords[17].value:=jst_Break;
JS_KeyWords[18].hash:=s_hash('continue'); Js_KeyWords[18].value:=jst_Continue;
JS_KeyWords[19].hash:=s_hash('each'); Js_KeyWords[19].value:=jst_Each;
JS_KeyWords[20].hash:=s_hash('in'); Js_KeyWords[20].value:=jst_In;
JS_KeyWords[21].hash:=s_hash('null'); Js_KeyWords[21].value:=jst_Null; // Null es un KeyWord
// JS_KeyWords[22].hash:=s_hash('undefined'); Js_KeyWords[22].value:=jst_Undefined; // Undefined NO y NaN tampoco
end;
initialization
Init_Tokens;
end.
|
{
Лабораторная работа № 2 Отношения и их свойства
Бинарное отношение R на конечном множестве A2 задано списком упорядоченных пар вида (a,b), где a,bA. Программа должна определять свойства данного отношения: рефлексивность, симметричность, антисимметричность, транзитивность (по материалам лекции 2).
Работа программы должна происходить следующим образом:
1. На вход подается множество A из n элементов, список упорядоченных пар, задающий отношение R (ввод с клавиатуры).
2. Результаты выводятся на экран (с необходимыми пояснениями) в следующем виде:
а) матрица бинарного отношения размера nn;
б) список свойств данного отношения.
Дополнительно: после вывода результатов предусмотреть возможность изменения списка пар, определяющих отношение. Например, вывести на экран список пар (с номерами) и по команде пользователя изменить что-либо в этом списке (удалить какую-то пару, добавить новую, изменить имеющуюся), после чего повторить вычисления.
}
program lab2;
uses
Crt;
const
Nmax = 15; { Макс. количество элементов множества A }
type
T = Char; { Тип элементов множества A }
TPair = Record
a, b: T;
end;
TSet = Array[1..Nmax] of T;
TMatrix = Array[1..Nmax, 1..Nmax] of Byte;
{ Сортировка выбором по неубыванию }
procedure Sort(var A: TSet; const N: Integer);
var
i, j, k: Integer;
tmp: T;
begin
for i := 1 to N - 1 do begin
k := i;
for j := i + 1 to N do
if A[j] < A[k] then k := j;
tmp := A[i];
A[i] := A[k];
A[k] := tmp;
end;
end;
{ Возвращает индекс элемента x в A. Если такого элемента нет, то возвращает -1 }
function Search(const x: T; const A: TSet; const N: Integer): Integer;
var
i: Integer;
begin
for i := 1 to N do
if x = A[i] then begin
Search := i;
Exit;
end;
Search := -1;
end;
{ Проверка на рефлексивность }
function Reflex(const M: TMatrix; const N: Integer): Boolean;
var
i: Integer;
begin
Reflex := False;
for i := 1 to N do
if M[i, i] = 0 then Exit;
Reflex := True;
end;
{ Проверка на симметричность }
function Symmetry(const M: TMatrix; const N: Integer): Boolean;
var
i, j: Integer;
begin
Symmetry := False;
for i := 1 to N - 1 do
for j := i + 1 to N do
if M[i, j] <> M[j, i] then Exit;
Symmetry := True;
end;
{ Проверка на антисимметричность }
function Antisymmetry(const M: TMatrix; const N: Integer): Boolean;
var
i, j: Integer;
begin
Antisymmetry := False;
for i := 1 to N do
for j := 1 to N do
if (i <> j) and (M[i, j] * M[j, i] <> 0) then Exit;
Antisymmetry := True;
end;
{ Проверка на транзитивность }
function Transit(const M: TMatrix; const N: Integer): Boolean;
var
i, j, k: Integer;
S: TMatrix;
begin
Transit := False;
for i := 1 to N do
for j := 1 to N do begin
S[i, j] := 0;
for k := 1 to N do
S[i, j] := S[i, j] or M[i, k] and M[k, j];
end;
for i := 1 to N do
for j := 1 to N do
if M[i, j] < S[i, j] then Exit;
Transit := True;
end;
{ Вывод списка клавиш управления }
procedure Keys;
begin
ClrScr;
WriteLn('Выберите действие.');
WriteLn;
WriteLn('1 - показать список элементов множества A');
WriteLn('2 - показать список пар бинарного отношения');
WriteLn('3 - показать матрицу бинарного отношения');
WriteLn('4 - показать свойства бинарного отношения');
WriteLn('5 - измененть одну пару бинарного отношения');
WriteLn('6 - удалить одну пару бинарного отношения');
WriteLn('7 - добавить новую пару бинарного отношения');
WriteLn('0 - очистить экран');
WriteLn('Esc - завершить работу');
WriteLn
end;
var
i, j, N, k, z: Integer;
x, y: T;
A: TSet;
M: TMatrix;
P: Array[1..Nmax] of TPair;
F: Boolean;
v: Char;
begin
ClrScr;
WriteLn('Введите множество A (набор элементов через пробел)');
N := 0;
while not SeekEoLn do begin
Inc(N);
Read(A[N]);
end;
Sort(A, N);
F := False;
i := 1;
while i < N do begin
if A[i] = A[i + 1] then begin
F := True;
Dec(N);
for j := i to N do
A[j] := A[j + 1];
end
else
Inc(i);
end;
if F then WriteLn('Повторяющиеся элементы были удалены.');
for i := 1 to Nmax do
for j := 1 to Nmax do
M[i, j] := 0;
WriteLn;
WriteLn('Введите список пар. Каждую пару в новой строке, элементы пары - через пробел.');
WriteLn('Для завершения ввода, вместо ввода пары нажмите Enter.');
Reset(Input);
k := 0;
while not SeekEoLn do begin
Read(x);
if SeekEoLn then Reset(Input);
ReadLn(y);
if (Search(x, A, N) = -1) or (Search(y, A, N) = -1) then begin
WriteLn('Элементы должны быть из множества A. Эта пара будет пропущена.');
Continue;
end;
F := False;
for i := 1 to k do
if (P[i].a = x) and (P[i].b = y) then begin
WriteLn('Эта пара уже была. Пропущено.');
F := True;
Break;
end;
if F then Continue;
M[Search(x, A, N), Search(y, A, N)] := 1;
Inc(k);
P[k].a := x;
P[k].b := y;
end;
Keys;
repeat
v := ReadKey;
case v of
'1':
begin
WriteLn('Элементы множества A:');
for i := 1 to N do
Write(A[i], ' ');
WriteLn;
end;
'2':
begin
WriteLn('Список пар бинарного отношения:');
for i := 1 to k do
WriteLn(i, '. (', P[i].a, ', ', P[i].b, ')');
end;
'3':
begin
WriteLn('Матрица бинарного отношения:');
Write(' ');
for i := 1 to N do
Write(A[i]:3, ' ');
WriteLn;
for i := 1 to N do
begin
Write(A[i]:3, ' ');
for j := 1 to N do
Write(M[i, j]:3, ' ');
WriteLn;
end;
end;
'4':
begin
WriteLn('Введённое отношение');
if Symmetry(M, N) then WriteLn('- симметрично') else WriteLn('- не симметрично ');
if Antisymmetry(M, N) then WriteLn('- антисимметрично') else WriteLn('- не антисимметрично');
if Reflex(M, N) then WriteLn('- рефлексивно') else WriteLn('- не рефлексивно');
if Transit(M, N) then WriteLn('- транзитивно') else WriteLn('- не транзитивно');
end;
'5':
begin
WriteLn('Введите номер пары, которую хотите изменить.');
{$I-}
ReadLn(z);
{$I+}
while IOResult <> 0 do begin
WriteLn('Введено неверно. Введите заново.');
{$I-}
ReadLn(z);
{$I+}
end;
if (z > k) or (z < 1) then
WriteLn('Нет такой пары.')
else begin
WriteLn('Введите новое значение пары (два элемента через пробел).');
Reset(Input);
Read(x);
if SeekEoLn then Reset(Input);
ReadLn(y);
if (Search(x, A, N) = -1) or (Search(y, A, N) = -1) then
WriteLn('Значения должны быть из множества A. Изменение не произведено.')
else begin
F := False;
for i := 1 to k do
if (P[i].a = x) and (P[i].b = y) then begin
WriteLn('Эта пара уже была. Пропущено.');
F := True;
Break;
end;
if not F then begin
M[Search(P[z].a, A, N), Search(P[z].b, A, N)] := 0;
P[z].a := x;
P[z].b := y;
M[Search(x, A, N), Search(y, A, N)] := 1;
WriteLn('Изменено.');
end;
end;
end;
end;
'6':
begin
WriteLn('Введите номер пары для удаления');
{$I-}
ReadLn(z);
{$I+}
while IOResult <> 0 do begin
WriteLn('Введено неверно. Введите заново.');
{$I-}
ReadLn(z);
{$I+}
end;
if (z > k) or (z < 1) then
WriteLn('Нет такой пары')
else begin
M[Search(P[z].a, A, N), Search(P[z].b, A, N)] := 0; { Удаляем пару из матрицы }
Dec(k);
for i := z to k do { Удаляем пару из списка P }
P[i] := P[i + 1];
WriteLn('Удалено.');
end;
end;
'7':
begin
WriteLn('Введите пару (два элемента через пробел)');
Reset(Input);
Read(x);
if SeekEoLn then Reset(Input);
ReadLn(y);
if (Search(x, A, N) = -1) or (Search(y, A, N) = -1) then
WriteLn('Значения должны быть из множества A. Добавление не произведено.')
else begin
F := False;
for i := 1 to k do
if (P[i].a = x) and (P[i].b = y) then begin
WriteLn('Эта пара уже есть. Пропущено.');
F := True;
Break;
end;
if not F then begin
Inc(k);
P[k].a := x;
P[k].b := y;;
M[Search(P[k].a, A, N), Search(P[k].b, A, N)] := 1;
end;
end;
if not F then WriteLn('Добавлено.');
end;
'0': Keys;
end;
until v = #27;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls,
//GLScene
GLScene, GLObjects, GLParticles, GLBehaviours, GLVectorGeometry, GLCadencer,
GLWin32Viewer, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLUtils;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLParticles1: TGLParticles;
Sprite1: TGLSprite;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
procedure GLParticles1ActivateParticle(Sender: TObject;
particle: TGLBaseSceneObject);
procedure Sprite1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
I : Integer;
MediaPath : String;
begin
SetGLSceneMediaDir;
MediaPath := GetCurrentDir + '\';
Sprite1.Material.Texture.Image.LoadFromFile(MediaPath+'Flare1.bmp');
// if we don't do this, our random won't look like random
Randomize;
end;
procedure TForm1.GLParticles1ActivateParticle(Sender: TObject;
particle: TGLBaseSceneObject);
begin
// this event is called when a particle is activated,
// ie. just before it will be rendered
with TGLSprite(particle) do begin
with Material.FrontProperties do begin
// we pick a random color
Emission.Color:=PointMake(Random, Random, Random);
// our halo starts transparent
Diffuse.Alpha:=0;
end;
// this is our "birth time"
TagFloat:=GLCadencer1.CurrentTime;
end;
end;
procedure TForm1.Sprite1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
life : Double;
begin
with TGLSprite(Sender) do begin
// calculate for how long we've been living
life:=(newTime-TagFloat);
if life>10 then
// old particle to kill
GLParticles1.KillParticle(TGLSprite(Sender))
else if life<1 then
// baby particles become brighter in their 1st second of life...
Material.FrontProperties.Diffuse.Alpha:=life
else // ...and slowly disappear in the darkness
Material.FrontProperties.Diffuse.Alpha:=(9-life)/9;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// every timer, we create a particle at a random position
with TGLSprite(GLParticles1.CreateParticle).Position do begin
X:=3*(Random-0.5);
Y:=3*(Random-0.5);
Z:=3*(Random-0.5);
end;
// infos for the user
Caption:='Particles - '+Format('%d particles, %.1f FPS',
[GLParticles1.Count-1, GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
// change focal so the view will shrink and not just get clipped
GLCamera1.FocalLength:=50*Width/280;
end;
end.
|
program MemDeviceMappedInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
procedure GetMemDeviceMappedInfo;
Var
SMBios: TSMBios;
LMemDevMappedAddress: TMemoryDeviceMappedAddressInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Memory Device Mapped Address Information');
WriteLn('----------------------------------------');
if SMBios.HasMemoryDeviceMappedAddressInfo then
for LMemDevMappedAddress in SMBios.MemoryDeviceMappedAddressInformation do
begin
WriteLn(Format('Starting Address %.8x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.StartingAddress]));
WriteLn(Format('Ending Address %.8x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.EndingAddress]));
WriteLn(Format('Memory Device Handle %.4x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.MemoryDeviceHandle]));
WriteLn(Format('Memory Array Mapped Address Handle %.4x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.MemoryArrayMappedAddressHandle]));
WriteLn(Format('Partition Row Position %d',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.PartitionRowPosition]));
WriteLn(Format('Interleave Position %d',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.InterleavePosition]));
WriteLn(Format('Interleaved Data Depth %d',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.InterleavedDataDepth]));
if SMBios.SmbiosVersion>='2.7' then
begin
WriteLn(Format('Extended Starting Address %x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.ExtendedStartingAddress]));
WriteLn(Format('Extended Ending Address %x',[LMemDevMappedAddress.RAWMemoryDeviceMappedAddressInfo^.ExtendedEndingAddress]));
end;
WriteLn;
end
else
Writeln('No Memory Device Mapped Address Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetMemDeviceMappedInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
unit shared;
interface
uses ComCtrls, SysUtils, Windows;
function CustomSortProc(Item1, Item2: TListItem; SortColumn: Integer): Integer; stdcall;
function findindex(item : string):integer;
type
TCustomSortStyle = (cssAlphaNum, cssNumeric, cssDateTime);
TUser = record
name : string[50];
id_no : string[20];
end;
TCategory = record
name : string[100];
id : integer;
end;
var
CurrentUser: TUser;
users: array of TUser;
categories: array of TCategory;
main_form_state, riv_form_state, ticket_form_state : String;
riv_id, ticket_id : integer;
riv_no, riv_rights, riv_description : string;
ftype : string;
loginas, loginaspass, loginasrights, loginasuserid : string;
{ variable to hold the sort style }
LvSortStyle: TCustomSortStyle;
{ array to hold the sort order }
LvSortOrder: array[0..10] of Boolean; // High[LvSortOrder] = Number of Lv Columns
implementation
function findIndex(item : string):integer;
var i : integer;
begin
for i := Low(users) to High(users) do begin
if AnsiSameText(item, users[i].id_no) then begin
Result := i;
Break;
end;
end;
end;
function CustomSortProc(Item1, Item2: TListItem; SortColumn: Integer): Integer; stdcall;
var
s1, s2: string;
i1, i2: Integer;
r1, r2: Boolean;
d1, d2: TDateTime;
{ Helper functions }
function IsValidNumber(AString : string; var AInteger : Integer): Boolean;
var
Code: Integer;
begin
Val(AString, AInteger, Code);
Result := (Code = 0);
end;
function IsValidDate(AString : string; var ADateTime : TDateTime): Boolean;
begin
Result := True;
try
ADateTime := StrToDateTime(AString);
except
ADateTime := 0;
Result := False;
end;
end;
function CompareDates(dt1, dt2: TDateTime): Integer;
begin
if (dt1 > dt2) then Result := 1
else
if (dt1 = dt2) then Result := 0
else
Result := -1;
end;
function CompareNumeric(AInt1, AInt2: Integer): Integer;
begin
if AInt1 > AInt2 then Result := 1
else
if AInt1 = AInt2 then Result := 0
else
Result := -1;
end;
begin
Result := 0;
if (Item1 = nil) or (Item2 = nil) then Exit;
case SortColumn of
-1 :
{ Compare Captions }
begin
s1 := Item1.Caption;
s2 := Item2.Caption;
end;
else
{ Compare Subitems }
begin
s1 := '';
s2 := '';
{ Check Range }
if (SortColumn < Item1.SubItems.Count) then
s1 := Item1.SubItems[SortColumn];
if (SortColumn < Item2.SubItems.Count) then
s2 := Item2.SubItems[SortColumn]
end;
end;
{ Sort styles }
case LvSortStyle of
cssAlphaNum : Result := lstrcmp(PChar(s1), PChar(s2));
cssNumeric : begin
r1 := IsValidNumber(s1, i1);
r2 := IsValidNumber(s2, i2);
Result := ord(r1 or r2);
if Result <> 0 then
Result := CompareNumeric(i2, i1);
end;
cssDateTime : begin
r1 := IsValidDate(s1, d1);
r2 := IsValidDate(s2, d2);
Result := ord(r1 or r2);
if Result <> 0 then
Result := CompareDates(d1, d2);
end;
end;
{ Sort direction }
if LvSortOrder[SortColumn + 1] then
Result := - Result;
end;
end.
|
// dws2Classes
{: DelphiWebScriptII symbol creation for base Delphi classes.<p>
<b>History : </b><font size=-1><ul>
<li>27/04/2004 - SG - Creation
</ul></font>
}
unit dws2Classes;
interface
uses
Classes, SysUtils,
dws2Exprs, dws2Symbols, dws2Comp, dws2CompStrings, dws2Stack,
dws2Functions, dws2HelperFunc;
type
Tdws2ClassesUnit = class(Tdws2UnitComponent)
private
procedure AddClassTPersistent(SymbolTable : TSymbolTable);
procedure AddClassTComponent(SymbolTable : TSymbolTable);
protected
procedure AddUnitSymbols(SymbolTable: TSymbolTable); override;
public
constructor Create(AOwner: TComponent); override;
end;
procedure Register;
implementation
// ----------
// ---------- Internal class method class declarations ----------
// ----------
type
// TPersitent
TPersistentAssignMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TPersistentGetNamePathMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
// TComponent
TComponentCreateMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentSetTagMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetTagMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentSetNameMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetNameMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetOwnerMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentSetComponentIndexMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetComponentIndexMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetComponentCountMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetComponentMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentFindComponentMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentFreeNotificationMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentRemoveFreeNotificationMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetParentComponentMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentGetNamePathMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
TComponentHasParentMethod = class(TInternalMethod)
public
procedure Execute(var ExternalObject: TObject); override;
end;
// ----------
// ---------- Internal class method execute procedures ----------
// ----------
// TPersistent internal class methods
// TPersistent.Assign
procedure TPersistentAssignMethod.Execute(var ExternalObject: TObject);
var
Source : TObject;
begin
ValidateExternalObject(ExternalObject, TPersistent);
Source:=Info.GetExternalObjForVar('Source');
if not Assigned(Source) then raise Exception.Create('Source parameter is unassigned.');
if not (Source is TPersistent) then Exception.Create('Source parameter is not inheriting from TPersistent.');
TPersistent(ExternalObject).Assign(TPersistent(Source));
end;
// TPersistent.GetNamePath
procedure TPersistentGetNamePathMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TPersistent);
Info.Result.Value:=TPersistent(ExternalObject).GetNamePath;
end;
// TComponent internal class method execute procedures
// TComponent.Create
procedure TComponentCreateMethod.Execute(var ExternalObject: TObject);
var
AOwner : TComponent;
begin
AOwner:=TComponent(Info.GetExternalObjForVar('AOwner'));
ExternalObject:=TComponent.Create(AOwner);
end;
// TComponent.SetTag
procedure TComponentSetTagMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
TComponent(ExternalObject).Tag:=Info['Value'];
end;
// TComponent.GetTag
procedure TComponentGetTagMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).Tag;
end;
// TComponent.SetName
procedure TComponentSetNameMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
TComponent(ExternalObject).Name:=Info['Value'];
end;
// TComponent.GetName
procedure TComponentGetNameMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).Name;
end;
// TComponent.GetOwner
procedure TComponentGetOwnerMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=Info.RegisterExternalObject(TComponent(ExternalObject).Owner, False, False);
end;
// TComponent.SetComponentIndex
procedure TComponentSetComponentIndexMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
TComponent(ExternalObject).ComponentIndex:=Info['Value'];
end;
// TComponent.GetComponentIndex
procedure TComponentGetComponentIndexMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).ComponentIndex;
end;
// TComponent.GetComponentCount
procedure TComponentGetComponentCountMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).ComponentCount;
end;
// TComponent.GetComponent
procedure TComponentGetComponentMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=Info.RegisterExternalObject(TComponent(ExternalObject).Components[Info['Index']], False, False);
end;
// TComponent.FindComponent
procedure TComponentFindComponentMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=Info.RegisterExternalObject(TComponent(ExternalObject).FindComponent(Info['AName']), False, False);
end;
// TComponent.FreeNotification
procedure TComponentFreeNotificationMethod.Execute(var ExternalObject: TObject);
var
AComponent : TComponent;
begin
ValidateExternalObject(ExternalObject, TComponent);
AComponent:=TComponent(Info.GetExternalObjForVar('AComponent'));
if Assigned(AComponent) then
TComponent(ExternalObject).FreeNotification(AComponent);
end;
// TComponent.RemoveFreeNotification
procedure TComponentRemoveFreeNotificationMethod.Execute(var ExternalObject: TObject);
var
AComponent : TComponent;
begin
ValidateExternalObject(ExternalObject, TComponent);
AComponent:=TComponent(Info.GetExternalObjForVar('AComponent'));
if Assigned(AComponent) then
TComponent(ExternalObject).RemoveFreeNotification(AComponent);
end;
// TComponent.GetParentComponent
procedure TComponentGetParentComponentMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=Info.RegisterExternalObject(TComponent(ExternalObject).GetParentComponent, False, False);
end;
// TComponent.GetNamePath
procedure TComponentGetNamePathMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).GetNamePath;
end;
// TComponent.HasParent
procedure TComponentHasParentMethod.Execute(var ExternalObject: TObject);
begin
ValidateExternalObject(ExternalObject, TComponent);
Info.Result:=TComponent(ExternalObject).HasParent;
end;
// ----------
// ---------- Global procedures/functions ----------
// ----------
procedure Register;
begin
RegisterComponents('GLScene DWS2', [Tdws2ClassesUnit]);
end;
// ----------
// ---------- Tdws2ClassesUnit ----------
// ----------
// Create
//
constructor Tdws2ClassesUnit.Create(AOwner: TComponent);
begin
inherited;
FUnitName:='Classes';
end;
// AddClassTPersistent
//
procedure Tdws2ClassesUnit.AddClassTPersistent(SymbolTable: TSymbolTable);
var
ClassSym : TClassSymbol;
begin
ClassSym:=TClassSymbol(AddClassSymbol(SymbolTable, 'TPersistent', 'TObject'));
if not Assigned(ClassSym.Members.FindLocal('Assign')) then
TPersistentAssignMethod.Create(mkProcedure, [maVirtual], 0, 'Assign', ['Source', 'TPersistent'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetNamePath')) then
TPersistentGetNamePathMethod.Create(mkFunction, [maVirtual], 0, 'GetNamePath', [], 'String', ClassSym, SymbolTable);
end;
// AddClassTComponent
//
procedure Tdws2ClassesUnit.AddClassTComponent(SymbolTable: TSymbolTable);
var
ClassSym : TClassSymbol;
begin
ClassSym:=TClassSymbol(AddClassSymbol(SymbolTable, 'TComponent', 'TPersistent'));
// Methods
if not Assigned(ClassSym.Members.FindLocal('Create')) then
TComponentCreateMethod.Create(mkConstructor, [maVirtual], 0, 'Create', ['AOwner', 'TComponent'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('SetTag')) then
TComponentSetTagMethod.Create(mkProcedure, [], 0, 'SetTag', ['Value', 'Integer'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetTag')) then
TComponentGetTagMethod.Create(mkFunction, [], 0, 'GetTag', [], 'Integer', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('SetName')) then
TComponentSetNameMethod.Create(mkProcedure, [], 0, 'SetName', ['Value', 'String'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetName')) then
TComponentGetNameMethod.Create(mkFunction, [], 0, 'GetName', [], 'String', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetOwner')) then
TComponentGetOwnerMethod.Create(mkFunction, [], 0, 'GetOwner', [], 'TComponent', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('SetComponentIndex')) then
TComponentSetComponentIndexMethod.Create(mkProcedure, [], 0, 'SetComponentIndex', ['Value', 'Integer'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetComponentIndex')) then
TComponentGetComponentIndexMethod.Create(mkFunction, [], 0, 'GetComponentIndex', [], 'Integer', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetComponentCount')) then
TComponentGetComponentCountMethod.Create(mkFunction, [], 0, 'GetComponentCount', [], 'Integer', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetComponent')) then
TComponentGetComponentMethod.Create(mkFunction, [], 0, 'GetComponent', ['Index', 'Integer'], 'TComponent', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('FindComponent')) then
TComponentFindComponentMethod.Create(mkFunction, [], 0, 'FindComponent', ['AName', 'String'], 'TComponent', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('FreeNotification')) then
TComponentFreeNotificationMethod.Create(mkProcedure, [], 0, 'FreeNotification', ['AComponent', 'TComponent'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('RemoveFreeNotification')) then
TComponentRemoveFreeNotificationMethod.Create(mkProcedure, [], 0, 'RemoveFreeNotification', ['AComponent', 'TComponent'], '', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetParentComponent')) then
TComponentGetParentComponentMethod.Create(mkFunction, [maVirtual], 0, 'GetParentComponent', [], 'TComponent', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('GetNamePath')) then
TComponentGetNamePathMethod.Create(mkFunction, [maOverride], 0, 'GetNamePath', [], 'String', ClassSym, SymbolTable);
if not Assigned(ClassSym.Members.FindLocal('HasParent')) then
TComponentHasParentMethod.Create(mkFunction, [maVirtual], 0, 'HasParent', [], 'Boolean', ClassSym, SymbolTable);
// Properties
AddPropertyToClass('Tag', 'Integer', 'GetTag', 'SetTag', '', False, ClassSym, SymbolTable);
AddPropertyToClass('Name', 'String', 'GetName', 'SetName', '', False, ClassSym, SymbolTable);
AddPropertyToClass('Owner', 'TComponent', 'GetOwner', '', '', False, ClassSym, SymbolTable);
AddPropertyToClass('ComponentIndex', 'Integer', 'GetComponentIndex', 'SetComponentIndex', '', False, ClassSym, SymbolTable);
AddPropertyToClass('Components', 'TComponent', 'GetComponent', 'SetComponent', 'Integer', True, ClassSym, SymbolTable);
end;
// AddUnitSymbols
//
procedure Tdws2ClassesUnit.AddUnitSymbols(SymbolTable: TSymbolTable);
begin
// Forward class declaration
AddForwardDeclaration('TPersistent', SymbolTable);
AddForwardDeclaration('TComponent', SymbolTable);
// Class types
AddClassTPersistent(SymbolTable);
AddClassTComponent(SymbolTable);
end;
end.
|
unit ScriptRunner;
interface
uses
Windows, SysUtils, Classes, GMGlobals, FlexBase, JvInterpreter, h_GMClient;
type
TPasScriptAction = (psaCompile, psaRun);
TPasScriptActionSet = set of TPasScriptAction;
TScriptRunner = class
private
FScript: TStrings;
FLastError: string;
FStartTick: int64;
hcPasScript: TJvInterpreterProgram;
procedure HandlePasScriptLine(Sender: TObject);
procedure FindObjects(Sender: TObject; Identifier: string; var Value: Variant; Args: TJvInterpreterArgs; var Done: Boolean);
procedure Prepare;
function DoAction(action: TPasScriptActionSet): bool;
function FindObjectInControl(control: TFlexControl; const Identifier: string; var Value: Variant): bool;
public
ParentPanel: TFlexPanel;
TimeOut: int;
ParentObject: TObject;
property LastError: string read FLastError;
property Script: TStrings read FScript;
constructor Create();
destructor Destroy; override;
function Run(): bool;
function Compile(): bool;
class function RunScript(script: string; panel: TFlexPanel; owner: TFlexControl = nil): bool;
end;
implementation
{ TScriptRunner }
function TScriptRunner.FindObjectInControl(control: TFlexControl; const Identifier: string; var Value: Variant): bool;
var i: int;
begin
Result := AnsiSameText(Identifier, control.Name);
if Result then
begin
Value := O2V(control);
Exit;
end;
for i := 0 to control.Count - 1 do
begin
Result := FindObjectInControl(control[i], Identifier, Value);
if Result then Exit;
end;
end;
procedure TScriptRunner.FindObjects(Sender: TObject; Identifier: string; var Value: Variant; Args: TJvInterpreterArgs; var Done: Boolean);
begin
if AnsiSameText(Identifier, 'System') then
begin
Value := O2V(ParentPanel);
Done := true;
Exit;
end;
if AnsiSameText(Identifier, 'Owner') then
begin
Value := O2V(ParentObject);
Done := true;
Exit;
end;
if AnsiSameText(Identifier, 'GlobalArray') then
begin
Value := true;
Value := O2V(TGlobalArrayContainer.GetInstance());
Done := true;
Exit;
end;
if ParentPanel = nil then Exit;
Done := FindObjectInControl(ParentPanel.Schemes, Identifier, Value);
end;
constructor TScriptRunner.Create;
begin
FScript := TStringList.Create();
hcPasScript := TJvInterpreterProgram.Create(nil);
hcPasScript.OnGetValue := FindObjects;
hcPasScript.OnStatement := HandlePasScriptLine;
TimeOut := 2000;
FLastError := '';
ParentPanel := nil;
ParentObject := nil;
end;
destructor TScriptRunner.Destroy;
begin
FScript.Free();
hcPasScript.Free();
inherited;
end;
procedure TScriptRunner.HandlePasScriptLine(Sender: TObject);
begin
if (ParentPanel <> nil) and ParentPanel.ModalDialogMode then
begin
FStartTick := GetTickCount();
ParentPanel.ModalDialogMode := false;
end;
{$ifndef DEBUG}
if Abs(int64(GetTickCount()) - FStartTick) > TimeOut then
raise Exception.Create('Execution timeout expired');
{$endif}
end;
procedure TScriptRunner.Prepare();
begin
FLastError := '';
hcPasScript.Pas.Assign(Script);
end;
function TScriptRunner.DoAction(action: TPasScriptActionSet): bool;
begin
Result := true;
Prepare();
if Script.IsEmpty() then Exit;
try
if psaCompile in action then
hcPasScript.Compile();
if psaRun in action then
begin
FStartTick := GeTTickCount();
hcPasScript.Run();
end;
except
on e: Exception do
begin
Result := false;
FLastError := e.Message;
end;
end;
end;
function TScriptRunner.Compile: bool;
begin
Result := DoAction([psaCompile]);
end;
function TScriptRunner.Run(): bool;
begin
Result := DoAction([psaCompile, psaRun]);
end;
class function TScriptRunner.RunScript(script: string; panel: TFlexPanel; owner: TFlexControl = nil): bool;
var runner: TScriptRunner;
begin
runner := TScriptRunner.Create();
runner.Script.Text := script;
runner.ParentPanel := panel;
runner.ParentObject := owner;
runner.TimeOut := 1000;
try
Result := runner.Run();
finally
runner.Free();
panel.Refresh();
end;
end;
end.
|
unit SimpleSQL;
interface
uses
SimpleInterface;
Type
TSimpleSQL<T : class, constructor> = class(TInterfacedObject, iSimpleSQL<T>)
private
FInstance : T;
FFields : String;
FWhere : String;
FOrderBy : String;
FGroupBy : String;
FJoin : String;
public
constructor Create(aInstance : T);
destructor Destroy; override;
class function New(aInstance : T) : iSimpleSQL<T>;
function Insert (var aSQL : String) : iSimpleSQL<T>;
function Update (var aSQL : String) : iSimpleSQL<T>;
function Delete (var aSQL : String) : iSimpleSQL<T>;
function Select (var aSQL : String) : iSimpleSQL<T>;
function SelectId(var aSQL: String): iSimpleSQL<T>;
function Fields (aSQL : String) : iSimpleSQL<T>;
function Where (aSQL : String) : iSimpleSQL<T>;
function OrderBy (aSQL : String) : iSimpleSQL<T>;
function GroupBy (aSQL : String) : iSimpleSQL<T>;
function Join (aSQL : String) : iSimpleSQL<T>;
function LastID (var aSQL : String) : iSimpleSQL<T>;
function LastRecord (var aSQL : String) : iSimpleSQL<T>;
end;
implementation
uses
SimpleRTTI, System.Generics.Collections, System.SysUtils;
{ TSimpleSQL<T> }
constructor TSimpleSQL<T>.Create(aInstance : T);
begin
FInstance := aInstance;
end;
function TSimpleSQL<T>.Delete(var aSQL: String): iSimpleSQL<T>;
var
aClassName, aWhere : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.TableName(aClassName)
.Where(aWhere);
aSQL := aSQL + 'DELETE FROM ' + aClassName;
aSQL := aSQL + ' WHERE ' + aWhere;
end;
destructor TSimpleSQL<T>.Destroy;
begin
inherited;
end;
function TSimpleSQL<T>.Fields(aSQL: String): iSimpleSQL<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FFields := aSQL;
end;
function TSimpleSQL<T>.GroupBy(aSQL: String): iSimpleSQL<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FGroupBy := aSQL;
end;
function TSimpleSQL<T>.Insert(var aSQL: String): iSimpleSQL<T>;
var
aClassName, aFields, aParam : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.TableName(aClassName)
.FieldsInsert(aFields)
.Param(aParam);
aSQL := aSQL + 'INSERT INTO ' + aClassName;
aSQL := aSQL + ' (' + aFields + ') ';
aSQL := aSQL + ' VALUES (' + aParam + ');';
end;
function TSimpleSQL<T>.Join(aSQL: String): iSimpleSQL<T>;
begin
Result := Self;
FJoin := aSQL;
end;
function TSimpleSQL<T>.LastID(var aSQL: String): iSimpleSQL<T>;
var
aClassName, aPK, aFields : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.TableName(aClassName)
.PrimaryKey(aPK);
aSQL := aSQL + 'select first(1) ' + aPK;
aSQL := aSQL + ' from '+ aClassName;
aSQL := aSQL + ' order by ' + aPK + ' desc';
end;
function TSimpleSQL<T>.LastRecord(var aSQL: String): iSimpleSQL<T>;
var
aClassName, aPK, aFields : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.TableName(aClassName)
.Fields(aFields)
.PrimaryKey(aPK);
aSQL := aSQL + 'select first(1) '+aFields;
aSQL := aSQL + ' from '+ aClassName;
aSQL := aSQL + ' order by ' + aPK + ' desc';
end;
class function TSimpleSQL<T>.New(aInstance : T): iSimpleSQL<T>;
begin
Result := Self.Create(aInstance);
end;
function TSimpleSQL<T>.OrderBy(aSQL: String): iSimpleSQL<T>;
begin
Result := Self;
FOrderBy := aSQL;
end;
function TSimpleSQL<T>.Select (var aSQL : String) : iSimpleSQL<T>;
var
aFields, aClassName : String;
begin
Result := Self;
TSimpleRTTI<T>.New(nil)
.Fields(aFields)
.TableName(aClassName);
if Trim(FFields) <> '' then
aSQL := aSQL + ' SELECT ' + FFields
else
aSQL := aSQL + ' SELECT ' + aFields;
aSQL := aSQL + ' FROM ' + aClassName;
if Trim(FJoin) <> '' then
aSQL := aSQL + ' ' + FJoin + ' ';
if Trim(FWhere) <> '' then
aSQL := aSQL + ' WHERE ' + FWhere;
if Trim(FGroupBy) <> '' then
aSQL := aSQL + ' GROUP BY ' + FGroupBy;
if Trim(FOrderBy) <> '' then
aSQL := aSQL + ' ORDER BY ' + FOrderBy;
end;
function TSimpleSQL<T>.SelectId(var aSQL: String): iSimpleSQL<T>;
var
aFields, aClassName, aWhere : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.Fields(aFields)
.TableName(aClassName)
.Where(aWhere);
if Trim(FWhere) <> '' then
aSQL := aSQL + ' WHERE ' + FWhere;
aSQL := aSQL + ' SELECT ' + aFields;
aSQL := aSQL + ' FROM ' + aClassName;
aSQL := aSQL + ' WHERE ' + aWhere;
end;
function TSimpleSQL<T>.Update(var aSQL: String): iSimpleSQL<T>;
var
ClassName, aUpdate, aWhere : String;
begin
Result := Self;
TSimpleRTTI<T>.New(FInstance)
.TableName(ClassName)
.Update(aUpdate)
.Where(aWhere);
aSQL := aSQL + 'UPDATE ' + ClassName;
aSQL := aSQL + ' SET ' + aUpdate;
aSQL := aSQL + ' WHERE ' + aWhere;
end;
function TSimpleSQL<T>.Where(aSQL: String): iSimpleSQL<T>;
begin
Result := Self;
FWhere := aSQL;
end;
end.
|
unit SerialThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, synaser, StdCtrls, ExtCtrls, LCLIntf;
type
{ TSerialThread }
TSerialThread = class (TThread)
private
ser:TBlockSerial;
Log:TMemo;
GroupBox1:TGroupBox;
CheckGroup1: TRadioGroup;
Data : string;
RequestReset : Boolean;
RequestSuspended : Boolean;
Send:String;
FAutoscroll : boolean;
baud,bit,parity,stop:string;
procedure ToLog;
procedure OnException;
procedure FindSerial;
procedure Connect;
protected
procedure Execute; override;
public
constructor Create(m:TMemo; gb:TGroupBox; cb: TRadioGroup); overload;
destructor Destroy; override;
procedure Reset(const xbaud,xbit,xparity,xstop:string);
procedure SendString(const xsend:string);
procedure pause;
property Autoscroll:boolean read FAutoscroll write FAutoscroll;
end;
implementation
const
cNoneConn = 'Connected: none';
{ TSerialThread }
procedure TSerialThread.ToLog();
var
p :TPoint;
begin
if data<>'' then begin
log.Lines.BeginUpdate;
try
p := log.CaretPos;
Log.Lines.Add(data);
if not(Autoscroll)
then log.CaretPos := p;
finally
log.Lines.EndUpdate;
end;
end;
end;
procedure TSerialThread.OnException;
begin
if Assigned(ser)
then ser.RaiseExcept:=false;
GroupBox1.Caption:=cNoneConn;
FreeAndNil(ser);
ToLog;
end;
procedure TSerialThread.FindSerial;
var
s:string;
t:TStringList;
i, x:integer;
begin
s:=GetSerialPortNames;
t := TStringList.Create;
try
t.CommaText:=',';
t.DelimitedText:=GetSerialPortNames+',';
i:=0;
while(i<t.Count)
do begin
s := t.Strings[i];
x := CheckGroup1.Items.IndexOf(s);
if (s<>'') and (x =-1)
then begin
x := CheckGroup1.Items.add(t.Strings[i]);
if CheckGroup1.Items.Count=1 then CheckGroup1.ItemIndex:=0;
end;
inc(i);
end;
finally
t.free;
end;
end;
procedure TSerialThread.Connect;
var
s : String;
begin
if CheckGroup1.ItemIndex>-1
then begin
try
s := CheckGroup1.Items.Strings[CheckGroup1.ItemIndex];
ser:=TBlockserial.Create;
ser.RaiseExcept:=true;
ser.LinuxLock:=false;
ser.Connect(s);
ser.Config(StrToInt(baud),StrToInt(bit),parity[1],StrToInt(stop),false,false);
GroupBox1.Caption:='Connected: '+s;
except
GroupBox1.Caption:=cNoneConn;
freeandnil(ser);
end;
end;
end;
procedure TSerialThread.Execute;
var
time : DWord;
begin
time:=GetTickCount;
while (not Terminated)
do try
if RequestSuspended
then begin
RequestSuspended := false;
data := '';
Synchronize(@OnException);
Suspend;
end;
if RequestReset
then begin
FreeAndNil(ser);
RequestReset:=false;
end;
if Assigned(ser)
then begin
if (send <> '')
then begin
ser.SendString(Send);
Send:='';
Sleep(100);
end;
if ser.CanRead(100)
then begin
data := Trim(ser.RecvPacket(1000));
Synchronize(@ToLog);
end
else
begin
if (GetTickCount-time>5000)
then begin
Synchronize(@FindSerial);
time := GetTickCount;
end;
end;
end
else begin
Synchronize(@FindSerial);
Synchronize(@Connect);
Sleep(1000);
end;
except
on E : Exception do begin
data := e.Message;
Synchronize(@OnException);
end;
end;
end;
constructor TSerialThread.Create(m:TMemo; gb:TGroupBox; cb: TRadioGroup);
begin
Priority:=tpIdle;
FreeOnTerminate:=true;
Log := m;
GroupBox1 := gb;
CheckGroup1 := cb;
RequestSuspended := False;
RequestReset:=false;
Send := '';
autoscroll := true;
inherited Create(true);
end;
destructor TSerialThread.Destroy;
begin
FreeAndNil(ser);
inherited Destroy;
end;
procedure TSerialThread.Reset(const xbaud, xbit, xparity, xstop: string);
begin
baud := xbaud;
bit := xbit;
parity := xparity;
stop := xstop;
RequestReset:=true;
end;
procedure TSerialThread.SendString(const xsend: string);
begin
Send:= xsend;
end;
procedure TSerialThread.pause;
begin
RequestSuspended:=true;
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1998 Master-Bank }
{ }
{*******************************************************}
unit rxSelDSFrm;
{$I RX.INC}
interface
{$IFDEF DCS}
uses
Windows, SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs, DB, StdCtrls,
{$IFDEF RX_D6} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF}; // Polaris
type
{ TSelectDataSetForm }
TSelectDataSetForm = class(TForm)
GroupBox: TGroupBox;
DataSetList: TListBox;
OkBtn: TButton;
CancelBtn: TButton;
procedure DataSetListDblClick(Sender: TObject);
procedure DataSetListKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
{$IFDEF RX_D6} // Polaris
FDesigner: IDesigner;
{$ELSE}
FDesigner: IFormDesigner;
{$ENDIF}
FExclude: string;
procedure FillDataSetList(ExcludeDataSet: TDataSet);
procedure AddDataSet(const S: string);
public
{ Public declarations }
end;
{ TMemDataSetEditor }
TMemDataSetEditor = class(TComponentEditor)
private
function UniqueName(Field: TField): string;
procedure BorrowStructure;
protected
function CopyStructure(Source, Dest: TDataSet): Boolean; virtual; abstract;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{$IFDEF RX_D6} // Polaris
function SelectDataSet(ADesigner: IDesigner; const ACaption: string;
ExcludeDataSet: TDataSet): TDataSet;
{$ELSE}
function SelectDataSet(ADesigner: IFormDesigner; const ACaption: string;
ExcludeDataSet: TDataSet): TDataSet;
{$ENDIF}
{$ENDIF DCS}
implementation
{$IFDEF DCS}
uses
DbConsts, TypInfo, rxVclUtils, {StrUtils,} RxLConst, // Polaris
{$IFDEF RX_D3}{$IFDEF RX_D5} DsnDbCst, {$ELSE} BdeConst, {$ENDIF}{$ENDIF}
DSDesign;
{$R *.DFM}
{$IFDEF RX_D6} // Polaris
function SelectDataSet(ADesigner: IDesigner; const ACaption: string;
ExcludeDataSet: TDataSet): TDataSet;
{$ELSE}
function SelectDataSet(ADesigner: IFormDesigner; const ACaption: string;
ExcludeDataSet: TDataSet): TDataSet;
{$ENDIF}
begin
Result := nil;
with TSelectDataSetForm.Create(Application) do
try
if ACaption <> '' then Caption := ACaption;
FDesigner := ADesigner;
FillDataSetList(ExcludeDataSet);
if ShowModal = mrOk then
if DataSetList.ItemIndex >= 0 then begin
with DataSetList do
Result := FDesigner.GetComponent(Items[ItemIndex]) as TDataSet;
end;
finally
Free;
end;
end;
{ TMemDataSetEditor }
procedure TMemDataSetEditor.BorrowStructure;
var
DataSet: TDataSet;
I: Integer;
Caption: string;
begin
Caption := Component.Name;
if (Component.Owner <> nil) and (Component.Owner.Name <> '') then
Caption := Format({$IFDEF CBUILDER} '%s->%s' {$ELSE} '%s.%s' {$ENDIF},
[Component.Owner.Name, Caption]);
DataSet := SelectDataSet(Designer, Caption, TDataSet(Component));
if DataSet <> nil then begin
StartWait;
try
if not CopyStructure(DataSet, Component as TDataSet) then Exit;
with TDataSet(Component) do begin
for I := 0 to FieldCount - 1 do
if Fields[I].Name = '' then
Fields[I].Name := UniqueName(Fields[I]);
end;
finally
StopWait;
end;
Designer.Modified;
end;
end;
function TMemDataSetEditor.UniqueName(Field: TField): string;
const
AlphaNumeric = ['A'..'Z', 'a'..'z', '_'] + ['0'..'9'];
var
Temp: string;
Comp: TComponent;
I: Integer;
begin
Result := '';
if (Field <> nil) then begin
Temp := Field.FieldName;
for I := Length(Temp) downto 1 do
if not (Temp[I] in AlphaNumeric) then System.Delete(Temp, I, 1);
if (Temp = '') or not IsValidIdent(Temp) then begin
Temp := Field.ClassName;
if (UpCase(Temp[1]) = 'T') and (Length(Temp) > 1) then
System.Delete(Temp, 1, 1);
end;
end
else Exit;
Temp := Component.Name + Temp;
Comp := Designer.GetComponent(Temp);
if (Comp = nil) or (Comp = Field) then Result := Temp
else Result := Designer.UniqueName(Temp);
end;
procedure TMemDataSetEditor.ExecuteVerb(Index: Integer);
begin
case Index of
{$IFDEF RX_D5}
0: ShowFieldsEditor(Designer, TDataSet(Component), TDSDesigner);
{$ELSE}
0: ShowDatasetDesigner(Designer, TDataSet(Component));
{$ENDIF}
1: BorrowStructure;
end;
end;
function TMemDataSetEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := ResStr(SDatasetDesigner);
1: Result := LoadStr(srBorrowStructure);
end;
end;
function TMemDataSetEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TSelectDataSetForm }
procedure TSelectDataSetForm.AddDataSet(const S: string);
begin
if (S <> '') and (S <> FExclude) then DataSetList.Items.Add(S);
end;
procedure TSelectDataSetForm.FillDataSetList(ExcludeDataSet: TDataSet);
begin
DataSetList.Items.BeginUpdate;
try
DataSetList.Clear;
FExclude := '';
if ExcludeDataSet <> nil then FExclude := ExcludeDataSet.Name;
FDesigner.GetComponentNames(GetTypeData(TypeInfo(TDataSet)), AddDataSet);
with DataSetList do begin
if Items.Count > 0 then ItemIndex := 0;
Enabled := Items.Count > 0;
OkBtn.Enabled := (ItemIndex >= 0);
end;
finally
DataSetList.Items.EndUpdate;
end;
end;
procedure TSelectDataSetForm.DataSetListDblClick(Sender: TObject);
begin
if DataSetList.ItemIndex >= 0 then ModalResult := mrOk;
end;
procedure TSelectDataSetForm.DataSetListKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = #13) and (DataSetList.ItemIndex >= 0) then
ModalResult := mrOk;
end;
{$ENDIF DCS}
end. |
UNIT MapStuff;
{ needed by cartog2.pas }
{$N+,E+}
interface
USES
CRT,
MathLib0,
Graph;
CONST
NotVisible : INTEGER = -32767; { Flag for point visibility }
TYPE
Float = SINGLE;
RenderTypes = (DoGrid, DoMap);
RenderSet = SET OF RenderTypes;
MapTypes = (NoMap, Merc, Equi, Sino, Hamr, Orth);
MapRec = RECORD
Choice : RenderSet;
MapType : MapTypes;
Phi1, Lambda0 : FLOAT;
END;
PROCEDURE ProJect( Map : MapRec;
Long, Lat, Radius: FLOAT;
VAR X, Y : FLOAT);
{ Return screen coordinates according to map coordinates }
{ and projection type }
(* ============================================================== *)
implementation
{ -------------------------------------------------------------}
FUNCTION ArcCos(X: FLOAT): FLOAT;
BEGIN
IF ABS(X) < 1 THEN ArcCos:= ARCTAN(SQRT(1-SQR(X))/X)
ELSE IF X = 1 THEN ArcCos:= 0
ELSE IF X =-1 THEN ArcCos:= PI;
END; { ArcCos. }
{ -------------------------------------------------------------}
FUNCTION ArcSin(X: FLOAT): FLOAT;
BEGIN
IF ABS(X) < 1 THEN ArcSin:= ARCTAN(X/SQRT(1-SQR(X)))
ELSE IF X = 1 THEN ArcSin:= HalfPI
ELSE IF X =-1 THEN ArcSin:=-HalfPI;
END; { ArcSin. }
{ -------------------------------------------------------------}
FUNCTION ArcTanH(X : Real): Real;
CONST
fudge = 0.999999; { ArcTanH(1.0) is undefined }
VAR A,T : FLOAT;
BEGIN
T:=ABS(X);
IF NOT (T < 1) THEN
T := fudge; { should never happen }
A := 0.5 * LN((1 + T)/(1 - T));
IF X < 0 THEN ArcTanH := -A ELSE ArcTanH :=A;
END; { ArcTanH. }
{ -------------------------------------------------------------}
FUNCTION Meridian(Lambda, Lambda0: FLOAT):FLOAT;
{ Returns difference between current longitude and map center. }
VAR DelLam : FLOAT;
BEGIN
DelLam := Lambda - Lambda0;
IF DelLam < -PI THEN DelLam := DelLam + TwoPI
ELSE
IF DelLam > PI THEN DelLam := DelLam - TwoPI;
Meridian:=DelLam;
END; { Meridian. }
{ -------------------------------------------------------------}
PROCEDURE Mercator(Lambda, Lambda0, Phi, R : FLOAT; VAR X, Y : FLOAT);
{ For R = 1: -Pi <= X <= Pi, -Pi/2 <= Y <= Pi/2. }
CONST
MaxLat : FLOAT = 1.483; { in radians }
{ 1.397;} {~80 degrees. }
{ 1.483; ~85 degrees. }
{ 1.571; ~90 degrees. }
BEGIN
(* arbitrarily constrain the max. latitude displayed since *)
(* higest latitudes go exponential with this projection *)
IF Phi > MaxLat THEN
Phi := MaxLat
ELSE IF Phi < -MaxLat THEN
Phi := -MaxLat;
Lambda := Meridian(Lambda, Lambda0);
X := R * Lambda;
Y := R * ArcTanH(SIN(Phi));
END; { Mercator. }
{ -------------------------------------------------------------}
PROCEDURE EquiCyl(Lambda, Lambda0, Phi, Phi1, R : FLOAT; VAR X, Y : FLOAT);
{ For R = 1: -Pi <= X <= Pi, -Pi/2 <= Y <= Pi/2. }
VAR
offset : FLOAT;
BEGIN
Lambda := Meridian(Lambda, Lambda0);
X := R * Lambda;
Y := R * Phi;
END; { EquiCyl. }
{ -------------------------------------------------------------}
PROCEDURE Sinusoidal(Lambda, Lambda0, Phi, R : FLOAT; VAR X, Y : FLOAT);
{ For R = 1: -Pi <= X <= Pi and -Pi/2 <= Y <= Pi/2. }
BEGIN
Lambda := Meridian(Lambda, Lambda0);
X := R * Cos(Phi) * Lambda ;
Y := R * Phi;
END; { Sinusoidal. }
{ -------------------------------------------------------------}
PROCEDURE Hammer(Lambda, Lambda0, Phi, R : FLOAT; VAR X, Y : FLOAT);
{ For R = 1: -2û2 <= X <=2û2 and - û2 <= Y <= û2. }
VAR K, CosPhi, HalfLambda : FLOAT;
BEGIN
HalfLambda := 0.5*Meridian(Lambda, Lambda0);
CosPhi:=COS(Phi);
K := R * SQRT2 / SQRT(1 +CosPhi * COS(HalfLambda));
X := 2 * K * CosPhi * (SIN(HalfLambda));
Y := K * SIN(Phi);
END; { Hammer. }
{ -------------------------------------------------------------}
PROCEDURE Orthographic(Lambda, Lambda0, Phi, Phi1, R: FLOAT; VAR X, Y : FLOAT);
{ For R = 1: -2 <= X,Y <= 2. }
VAR CosC, CosL, SinPhi1, CosPhi1, SinPhi, CosPhi, R2 : Real;
BEGIN
Lambda :=Meridian(Lambda, Lambda0); R2:=R+R;
CosPhi1:=COS(Phi1); SinPhi1:=SIN(Phi1);
CosPhi :=COS(Phi); SinPhi:= SIN(Phi);
CosL :=COS(Lambda)*CosPhi;
CosC :=SinPhi1 * SinPhi + CosPhi1 * COSL;
IF CosC >= 0 THEN
BEGIN
X :=R2 * CosPhi * SIN(Lambda);
Y :=R2 * (CosPhi1 * SinPhi - SinPhi1 * COSL);
END ELSE X:= NotVisible;
END; { Orthographic. }
(* ----------------------------------------------------- *)
PROCEDURE ProJect( Map : MapRec;
Long, Lat, Radius: FLOAT;
VAR X, Y : FLOAT);
BEGIN
WITH Map DO
BEGIN
CASE MapType OF
Merc: MERCATOR( Long, Lambda0, Lat, Radius, X, Y);
Equi: EQUICYL( Long, Lambda0, Lat, Phi1, Radius, X, Y);
Sino: SINUSOIDAL( Long, Lambda0, Lat, Radius, X, Y);
Hamr: HAMMER( Long, Lambda0, Lat, Radius, X, Y);
Orth: ORTHOGRAPHIC( Long, Lambda0, Lat, Phi1, Radius, X, Y);
ELSE
BEGIN
X := 0; Y := 0;
END;
END; { CASE...}
END {WITH};
END {ProJect};
(* ----------------------------------------------------- *)
END {MapStuff}.
|
unit optnfrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtDlgs,
ExtCtrls, Grids, wwDataInspector, StdCtrls, ComCtrls, wwriched, fcCombo;
type
TOptionsForm = class(TForm)
Panel1: TPanel;
btnSave: TButton;
btnRestore: TButton;
btnOk: TButton;
Inspector: TwwDataInspector;
btnCancel: TButton;
edtMemo: TwwDBRichEdit;
btnEdit: TButton;
procedure LoadData(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SaveData(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure getFileName(Sender: TwwDataInspector;
Item: TwwInspectorItem);
procedure getPictureName(Sender: TwwDataInspector;
Item: TwwInspectorItem);
procedure edtMemoEnter(Sender: TObject);
procedure EditData(Sender: TObject);
procedure InspectorAfterSelectCell(Sender: TwwDataInspector;
ObjItem: TwwInspectorItem);
procedure getColor(Sender: TwwDataInspector; Item: TwwInspectorItem);
private
function getInspectorItem(id:string; Items:TwwInspectorCollection):TwwInspectorItem;
procedure readInspectorItems(Items:TwwInspectorCollection);
procedure writeInspectorItems(items:TwwInspectorCollection; id:string='');
public
end;
implementation
uses config,basefrm;
{$R *.DFM}
procedure TOptionsForm.FormCreate(Sender: TObject);
var
i:integer;
text,key:string;
begin
i:=0;
while true do begin
key:='queries.query'+IntToStr(i);
text:=CurrentConfig.getString(key);
if text='' then break;
with getInspectorItem(key+'.sql',Inspector.Items) do begin
WordWrap:=false;
CustomControlAlwaysPaints:=false;
CustomControl:=edtMemo;
Resizeable:=true;
CellHeight:=48;
tag:=1;
end;
inc(i);
end;
readInspectorItems(Inspector.Items);
end;
procedure TOptionsForm.FormDestroy(Sender: TObject);
begin
//
end;
function TOptionsForm.getInspectorItem(id:string; items:TwwInspectorCollection):TwwInspectorItem;
var
index,i:integer;
str:pchar;
key:string;
append:boolean;
first:boolean;
begin
index:=1;
str:=pchar(id);
result:=nil;
first:=true;
append:=false;
while index>0 do begin
index:=pos('.',str);
if index>0 then begin
key:=copy(str,0,index-1);
str:=@(str[index]);
end else begin
key:=str;
end;
if first then begin
first := false;
if key = 'forms' then append := true;
end;
if result<>nil then items:=result.items;
result:=nil;
for i:=0 to items.Count-1 do if items[i].TagString=key then begin
result:=items[i];
break;
end;
if result=nil then begin
if append then begin
result:=items.Add;
result.Caption:=key;
result.tagString:=key;
end else begin
break;
end;
end;
end;
end;
procedure TOptionsForm.readInspectorItems(items:TwwInspectorCollection);
var
i:integer;
id:string;
item:TwwInspectorItem;
begin
if CurrentConfig=nil then exit;
for i:=0 to CurrentConfig.Items.count-1 do begin
id:=CurrentConfig.Items.Names[i];
item:=getInspectorItem(id,Items);
if item<>nil then begin
if item.tag>0 then item.EditText:=CurrentConfig.getMem(id)
else item.EditText:=CurrentConfig.getString(id);
end;
end;
end;
procedure TOptionsForm.writeInspectorItems(items:TwwInspectorCollection; id:string='');
var
i:integer;
id2,value:string;
begin
for i:=0 to items.Count-1 do begin
if id='' then id2:=items[i].TagString else id2:=id+'.'+items[i].TagString;
value:=items[i].EditText;
if items[i].tag>0 then CurrentConfig.setMem(id2,value) else CurrentConfig.setString(id2,value);
if items[i].Items.Count<>0 then writeInspectorItems(items[i].Items,id2);
end;
Update;
end;
procedure TOptionsForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if Modalresult=mrOk then begin
writeInspectorItems(Inspector.Items);
TBaseForm.appEventPost(nil,appConfig);
end;
end;
procedure TOptionsForm.LoadData(Sender: TObject);
begin
CurrentConfig.load;
readInspectorItems(Inspector.Items);
Inspector.Invalidate;
end;
procedure TOptionsForm.SaveData(Sender: TObject);
begin
writeInspectorItems(Inspector.Items);
TBaseForm.appEventPost(nil,appConfig);
CurrentConfig.save;
LoadData(Sender);
end;
procedure TOptionsForm.getFileName(Sender: TwwDataInspector;
Item: TwwInspectorItem);
begin
with TOpenDialog.Create(nil) do try
FileName:=Item.EditText;
if Execute then TEdit(Inspector.ActiveEdit).Text:=FileName;
finally
Destroy;
end;
end;
procedure TOptionsForm.getPictureName(Sender: TwwDataInspector;
Item: TwwInspectorItem);
begin
with TOpenPictureDialog.Create(nil) do try
FileName:=Item.EditText;
if Execute then TEdit(Inspector.ActiveEdit).Text:=FileName;
finally
Destroy;
end;
end;
procedure TOptionsForm.getColor(Sender: TwwDataInspector;
Item: TwwInspectorItem);
begin
with TColorDialog.Create(nil) do try
Color:=clWindow;
Options:=[cdFullOpen,cdPreventFullOpen,cdAnyColor];
if Item.EditText<>'' then try Color:=StrToInt(Item.EditText) except end;
if Execute then TEdit(Inspector.ActiveEdit).Text:=IntToStr(Color);
finally
Destroy;
end;
end;
procedure TOptionsForm.edtMemoEnter(Sender: TObject);
begin
edtMemo.Text:=Inspector.ActiveItem.DisplayText;
end;
procedure TOptionsForm.EditData(Sender: TObject);
begin
edtMemo.EditorCaption:=Inspector.ActiveItem.Caption;
if edtMemo.Execute then Inspector.ActiveItem.EditText:=edtMemo.Text;
Inspector.SetFocus;
end;
procedure TOptionsForm.InspectorAfterSelectCell(Sender: TwwDataInspector;
ObjItem: TwwInspectorItem);
begin
btnEdit.visible:=ObjItem.CustomControl=edtMemo;
end;
end.
|
{ Subroutine GUI_TICKS_MAKE (VMIN, VMAX, WID, HORIZ, MEM, FIRST_P)
*
* Create a set of tick marks for labeling the displayed value range from VMIN
* to VMAX. WID is the displayed length of the VMIN to VMAX range in the
* RENDlib TXDRAW coordinate space. The current RENDlib text parameters must
* be set as they will be when the tick mark labels are drawn. FIRST_P will be
* returned pointing to the start of the newly created chain of tick mark
* descriptors. The tick mark descriptors will be allocated statically from
* the MEM memory context. HORIZ is TRUE if the labels will be written next to
* each other horizontally, and FALSE if the labels will be written above/below
* each other vertically.
*
* This routine finds the major tick mark sequence that maximizes the number of
* labels without cramming them too close. Only major tick marks (level 0) are
* labeled. Major tick sequences are always one of the following relative
* values within each power of 10.
*
* 1, 2, 3, 4, ...
* 2, 4, 8, 10, ...
* 5, 10, 15, 20, ...
*
* The ticks chain is always in minor to major tick marks order. This is to
* facilitate drawing and minimize color switching.
}
module gui_ticks_make;
define gui_ticks_make;
%include 'gui2.ins.pas';
const
space_k = 1.0; {min char cell space between adjacent labels}
nseq_k = 3; {number of sequences within each power of 10}
var
seq_inc_ar: {list of sequence increments within pow of 10}
array[1..nseq_k] of sys_int_machine_t := [
1, 2, 5];
procedure gui_ticks_make ( {create tick marks with proper spacing}
in vmin, vmax: real; {range of axis values to make tick marks for}
in wid: real; {RENDlib TXDRAW space VMIN to VMAX distance}
in horiz: boolean; {TRUE = labels side by side, not stacked}
in out mem: util_mem_context_t; {parent context for any new memory}
out first_p: gui_tick_p_t); {will point to start of new tick marks chain}
val_param;
var
tp: rend_text_parms_t; {RENDlib text control parameters}
tw: real; {standard char cell width}
th: real; {standard char cell height}
space: real; {min space required between labels}
maxsum: real; {max sum of adjacent label widths for fit}
ii: sys_int_machine_t; {scratch integer}
r: real; {scratch floating point number}
ran: real; {size of values range}
scale: real; {mult factor to convert data values to X}
dmaj: real; {delta for each major tick}
log10: sys_int_machine_t; {power of 10 major tick sequence within}
seqi: sys_int_machine_t; {sequence index within curr power of 10}
sinc: sys_int_machine_t; {sequence increment within power of 10}
seqm: sys_int_machine_t; {sequence increment multiplier}
seqmi, seqml: sys_int_machine_t; {initial and last SEQ multiplier value}
seq: real; {sequence increment}
delta: real; {delta for being equal to VMIN or VMAX}
logm: real; {sequence power of 10 multiplier}
tv: real; {tick value}
prevw: real; {width of previous label}
lwid: real; {width of this label}
ntick: sys_int_machine_t; {number of ticks}
bv, up, ll: vect_2d_t; {string metrics returned by RENDlib}
tick_p: gui_tick_p_t; {pointer to tick descriptor}
minsig: sys_int_machine_t; {min required significant digits}
s, s2: string_var32_t; {scratch strings for number conversion}
label
loop_find_maj;
{
****************************************
*
* Local subroutine MAKE_STRING (S, V)
*
* Set S to the label string to draw for the value V.
}
procedure make_string ( {make label string from value}
in out s: univ string_var_arg_t; {the returned string}
in v: real); {label numeric value}
val_param; internal;
var
mn: string_var4_t; {factor of 1000 multiplier name}
begin
mn.max := size_char(mn.str); {init local var string}
string_f_fp_eng ( {make string in engineering notation}
s, {output string}
v, {input value}
minsig, {min required significant digits}
mn); {factor of 1000 multiplier name}
string_append (s, mn); {add multiplier name immediately after number}
end;
{
****************************************
*
* Start of main routine.
}
begin
s.max := size_char(s.str); {init local var strings}
s2.max := size_char(s2.str);
first_p := nil; {init to no ticks list created}
ran := vmax - vmin; {set size of values range}
if ran < 1.0e-30 then return; {too small a values range to work with ?}
scale := wid / ran; {mult factor from data values to X scale}
delta := (vmax - vmin) / 10000.0; {delta for being equal to VMIN or VMAX}
rend_get.text_parms^ (tp); {get current text control parameters}
tw := tp.size * tp.width; {make standard char cell width}
th := tp.size * tp.height; {make standard char cell height}
if horiz
then begin {labels will abutt horizontally}
space := tw * space_k; {make min space required between labels}
ii := {can't possibly exceed this many labels}
trunc(wid / (tw * 0.5 + space) + 2.0);
end
else begin {labels will abutt vertically}
space := tp.size * tp.lspace; {make min space required between labels}
ii := {can't possibly exceed this many labels}
trunc(wid / (th + space) + 2.0);
lwid := th; {"width" of label string}
end
;
ii := max(10, ii); {set min number of labels to start with}
dmaj := ran / ii; {init major tick delta to a bit too small}
r := math_log10(dmaj); {get Log10 of starting major delta}
log10 := trunc(r + 100.0) - 100; {find starting base power of 10}
seqi := 1; {init sequence index within this power of 10}
{
* Back here to check each new major sequence for fit. LOG10 is the power of
* 10 we are within, and SEQI is the index of the sequence to try. The
* sequence is accepted if all labels can be written next to each other with
* the minimum space in between. If a sequence fails, the next larger sequence
* is tried. This reduces the number of labels required, until eventually all
* labels should fit.
}
loop_find_maj:
logm := 10.0 ** log10; {make base power of 10 multiplier}
sinc := seq_inc_ar[seqi]; {get increment value for this sequence}
seq := logm * sinc; {sequence value increment}
seqm := trunc(vmin / seq); {make initial sequence multiplier}
tv := seq * seqm; {make initial tick value}
maxsum := (seq * scale - space) * 2.0; {max sum of adjacent label widths for fit}
{
* Find the min and max ticks in this series. SEQMI will be set to the SEQ
* multiplier for the first tick, and SEQML for the last tick.
}
while tv < (vmin - delta) do begin {loop until tick value up into range}
seqm := seqm + 1; {go one tick value up}
tv := seq * seqm;
end;
seqmi := seqm; {save multiplier for first tick}
seqml := seqmi; {init multiplier for last tick}
while true do begin {loop to find last tick that fits range}
tv := seq * (seqml + 1); {make value of next tick}
if tv > (vmax + delta) then exit; {this tick would be past range ?}
seqml := seqml + 1; {no, update last tick multiplier}
end;
ntick := seqml - seqmi + 1; {number of ticks within this range}
{
* Find MINSIG, which is the the minimum number of significant digits
* required to show this progression. SEQML is the SEQ multiplier for the
* last tick.
}
tv := (seqml - 1) * seq; {make value of next to last tick}
minsig := 0; {init min required significant digits}
while true do begin {loop until enough sig digits for rel delta}
minsig := minsig + 1; {make significant digits for this try}
make_string (s, seq * (seqml - 1)); {make reference label string}
make_string (s2, seq * seqml); {make next label string}
if string_equal (s2, s) then next; {not different ?}
make_string (s2, seq * (seqml - 2)); {make previous label string}
if string_equal (s2, s) then next; {not different ?}
exit; {prev and next strings different, good enough}
end;
{
* Loop thru this sequence of ticks to see if the label strings fit. If not,
* go back and try with next sequence.
}
prevw := -10.0; {init to previous label won't cause squish}
for seqm := seqmi to seqml do begin {loop over each label}
tv := seq * seqm; {make value of this label}
if horiz then begin {label strings in a line horizontally}
make_string (s, tv); {make label string for this tick}
rend_get.txbox_txdraw^ ( {measure the label string}
s.str, s.len, {string and string length}
bv, up, ll); {returned string metrics}
lwid := bv.x; {get width of this label string}
end;
if (prevw + lwid) > maxsum then begin {labels don't fit together ?}
seqi := seqi + 1; {advance to next sequence in this power of 10}
if seqi > nseq_k then begin {wrap to next power of ten ?}
seqi := 1;
log10 := log10 + 1;
end;
goto loop_find_maj; {back to try with this new sequence}
end;
prevw := lwid; {current width becomes previous width}
end; {back to check out this new tick value}
{
* A sequence was found for which all the labels fit next to each other. NTICK
* is the number of ticks. SEQMI to SEQML are the SEQ multipliers for the
* first and last ticks.
}
for seqm := seqmi to seqml do begin {once for each tick descriptor to create}
tv := seq * seqm; {make data value of this tick}
util_mem_grab ( {allocate memory for new tick descriptor}
sizeof(tick_p^), mem, false, tick_p);
tick_p^.next_p := first_p; {link new tick to front of chain}
first_p := tick_p;
tick_p^.val := tv; {set tick data value}
tick_p^.level := 0; {this is a major tick}
tick_p^.lab.max := size_char(tick_p^.lab.str);
make_string (tick_p^.lab, tv); {set label string for this tick}
end; {back to create next tick descriptor}
end;
|
unit UObjComm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
peoutlookbtn, StdCtrls, ExtCtrls, pegradpanl, kpaylib, OnScheme;
type
TObjCommForm = class(TForm)
Label5: TLabel;
SF_Main: TOnSchemeForm;
Pa_Title: TPeJeonGrdPanel;
E_e1ObjComment: TMemo;
B_Save: TPeJeonOutLookBtn;
procedure B_SaveClick(Sender: TObject);
procedure Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure E_e1ObjCommentKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
SendProgID, SendEmpno, RcveEmpno, MailSubject, MailBody, ReceiveYN : String;
Function Send_WebHint(SendProgID, SendEmpno, RcveEmpno, MailSubject, MailBody, ReceiveYN : String) : Boolean;
public
{ Public declarations }
Lrabasdate : string;
Lempno : string;
end;
var
ObjCommForm: TObjCommForm;
implementation
uses HMainForm;
{$R *.DFM}
procedure TObjCommForm.B_SaveClick(Sender: TObject);
var SqlText : string;
begin
if B_Save.Caption = ' 반려사유 저장 ' then
begin
SqlText := 'UPDATE peactfile '+
' SET rvalconyn = ''N'', '+
' rvalcondate = Null , '+
' e1valconyn = ''R'', '+
' e1valcondate = TO_CHAR(SYSDATE,''YYYYMMDD'') , '+
' e1ObjComment = '''+ trim(E_e1ObjComment.Text) +''', '+
' Writeemp = '''+ FM_Main.pempno +''', '+
' Writetime = TO_CHAR(SYSDATE,''YYYYMMDDHH24MISS'') '+
' WHERE RABASYM = '''+ FM_Main.LRabasYM +''' '+ //01월로 지정하여
' AND empno = '''+ FM_Main.ED_empno.Text +''' ';
FM_Main.Cupd_SQL := Sqltext;
FM_Main.Cupd_Exec;
if not FM_Main.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
MessageDlg('반려사유를 저장하였습니다.',mtinformation,[mbOK],0);
//////////////////////////////////////////////////////////////////////////////
//EAI 연동을 통한 Web Hint로 메일 발송을 위하여 PZHMAIL 테이블에 Insert...
SendProgID := 'PEK1030A';
SendEmpno := FM_Main.Le1empno;
RcveEmpno := FM_Main.ed_empno.Text;
MailSubject := '[팀장 Action Contract]을 반려하였습니다.';
MailBody := '팀장 Action Contract을 반려하였습니다.'+#13+#13+
'내용 수정후 결재상신 하시기 바랍니다.'+#13+#13+
'[화면위치 안내] : 종합인사시스템 - 평가 - Action Contract - 팀장Action Contract 등록/결재 ';
ReceiveYN := 'N';
if not Send_WebHint(SendProgID, SendEmpno, RcveEmpno, MailSubject, MailBody, ReceiveYN) then
begin
MessageDlg(' 결재상신 메일전송이 실패 하였습니다...',mtError, [mbOk], 0);
exit;
end
else MessageDlg(' 결재상신 메일전송을 성공 하였습니다...',mtError, [mbOk], 0);
//////////////////////////////////////////////////////////////////////////////
close;
end
else
Close;
end;
procedure TObjCommForm.Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssleft in shift then
begin
Releasecapture;
Self.Perform(WM_SYSCOMMAND, $F012, 0);
end;
end;
procedure TObjCommForm.E_e1ObjCommentKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var i : word;
ViewText : string;
begin
i := 222;
if key = i then
begin
Messagedlg('작은따옴표는 입력하실 수 없습니다.',mtError,[mbOK],0);
ViewText := copy(TMemo(Sender).text, 1, Length(TMemo(Sender).text)-1);
TMemo(Sender).Clear;
TMemo(Sender).Lines.Append(ViewText);
end;
end;
Function TObjCommForm.Send_WebHint(SendProgID, SendEmpno, RcveEmpno, MailSubject, MailBody, ReceiveYN : String) : Boolean;
begin
with FM_Main.TMaxDML_HInsa do
begin
ServiceName := 'PIT1030A_DML';
Close;
SQL.Clear;
SQL.Add('insert into PZHMAIL ');
SQL.Add('values (to_char(sysdate,''YYYYMMDDHHMISS''),'); //SENDTIME 메일발송 작업시간
SQL.Add(' '''+ SendProgID +''', '); //SENDPROG 발송프로그램 ID
SQL.Add(' '''+ SendEmpno +''', '); //SEND_PER 발신자 사번
SQL.Add(' '''+ RcveEmpno +''', '); //RCVR_PER, 수신자 사번
SQL.Add(' '''' , '); //REFR_PER 불필요(종합인사)
SQL.Add(' '''+ MailSubject +''', '); //SUBJECT 메일제목
SQL.Add(' '''' , '); //HEADER1 불필요(종합인사)
SQL.Add(' '''+ MailBody +''', '); //BODY1 메일내용
SQL.Add(' '''' , '); //TAIL1 불필요(종합인사)
SQL.Add(' '''+ ReceiveYN +''', '); //RECEIVEYN 'Y' 일경우 메일 읽었을경우 송신자에게 수신확인 메일 보내주기
SQL.Add(' ''N'' , '); //EAI_FLAG
SQL.Add(' '''' ) '); //EAI_DATE
try
Execute;
except
Result := false;
exit;
end;
Result := True;
end;
end;
end.
|
unit uDown;
interface
uses
windows,sysutils,strutils,classes,urlmon,Messages,uLog;
Const
WM_DOWN_FILE = WM_USER+1002;
DOWN_STAT_STOP=0;
DOWN_STAT_PAUSE=1;
DOWN_STAT_IDLE=2;
DOWN_STAT_WORKING=3;
var
idx,mState:integer;//下载序号
bDownFiles,bPause:boolean;//下载工作线程变量;
mDowns:tstrings;
mForm:HWND;
//mPage,mPageIdx,mSite,mProtocol,mPort,mWorkDir:string;//主页URL ,站点URL, 协议(http://,https://),工作目录
mWorkDir:string;//主页URL ,站点URL, 协议(http://,https://),工作目录
function DownloadToFile(Source, Dest: string): Boolean; //uses urlmon;
//procedure downloadfile(url:string);overload; //下载指定链接的文件
function downloadfile(url:string):string;
function url2file(url:string):string;//链接转换为本地文件路径
function getSite(url:string):string;//获取主站地址;
procedure downloadFilesThread();//下载子线程;
procedure setWorkDir(workDir:string);
function getPort(url:string):string;
//--------------------------------------------------------------------------------------------
procedure stop();
procedure pause();
procedure start();overload;
procedure start(workdir:string;hForm:HWND);overload;
procedure addUrl(url:string);
procedure clear;
function getState():integer;
implementation
//------------------------------------------启动,暂停,停止区---------------------------------
function getState():integer;
begin
result:=mState;
end;
procedure stop();
begin
bDownFiles:=false;
mState:=DOWN_STAT_STOP;
end;
procedure pause();
begin
bPause:=true;
mState:=DOWN_STAT_PAUSE;
end;
procedure start(workdir:string;hForm:HWND);
begin
mworkdir:=workdir;
mForm:=hForm;
start();
end;
procedure start();
begin
bPause:=false;
downloadFilesThread();
end;
procedure clear();
begin
idx:=0;
mDowns.Clear;
end;
procedure addUrl(url:string);
begin
if(pos(url,mdowns.Text)<=0)then
mDowns.Add(url);
end;
procedure setWorkDir(workDir:string);
begin
mWorkDir:=workDir;
end;
//------------------------------------------下载线程区------------------------------------------
function ThreadProc(param: LPVOID): DWORD; stdcall;
var
url:string;
begin
idx:=0;
while bDownFiles do begin
if(idx>=mDowns.Count)then begin sleep(1000); mState:=DOWN_STAT_IDLE;continue;end;
if(bPause)then begin sleep(1000);mState:=DOWN_STAT_PAUSE;continue;end;
url:=mDowns[idx];
if(url='')then continue;
mState:=DOWN_STAT_WORKING;
if(downloadfile(url)='')then
PostMessage(mForm, WM_DOWN_FILE,0,idx)
else
PostMessage(mForm, WM_DOWN_FILE,1,idx);
idx:=idx+1;
end;
//PostMessage(mForm, WM_DOWN_FILE,1,idx);
Result := 0;
end;
procedure downloadFilesThread();
var
threadId: TThreadID;
begin
if(bDownFiles)then exit;
bDownFiles:=true;
CreateThread(nil, 0, @ThreadProc, nil, 0, threadId);
end;
//------------------------------------------公共函数区----------------------------------------------
//uses urlmon;
function DownloadToFile(Source, Dest: string): Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;
//下载指定链接的文件
function downloadfile(url:string):string;
var
localpath:string;
begin
localpath:=url2file(url);
result:=localpath;
if(fileexists(localpath))then exit;
if(DownloadToFile(url,localpath))then begin
//Log('suc:'+remotepath+#13#10+localpath);
result:=localpath;
end else begin
//Log('fal:'+remotepath+#13#10+localpath);
result:='';
end;
end;
//链接转换为本地文件路径
function url2file(url:string):string;
var
p,i:integer;
s,dir,fullDir:string; //forcedirectories(mWorkDir);
begin
s:=url;
fullDir:=mworkdir; //程序工作目录;
if(rightstr(s,1)='/')then s:=s+'index.htm';
p:=pos('/',s);
if(p>0)then
dir:=leftstr(s,p-1);
if(dir='http:')then s:=rightstr(s,length(s)-7); //去除http头部
if(dir='https:')then s:=rightstr(s,length(s)-8); //去除https头部
if pos(':',s)>0 then s:=replacestr(s,':','/');
p:=pos('/',s);
while p>0 do begin
dir:=leftstr(s,p-1);
fullDir:=fullDir+'\'+dir;
if(not directoryexists(fullDir))then forcedirectories(fullDir); //创建本地文件目录
s:=rightstr(s,length(s)-length(dir)-1);
p:=pos('/',s);
end;
p:=pos('?',s); //排除链接里面?后面的内容;
if(p>0)then s:=replacestr(s,'?','$');
//if(p>0)then s:=leftstr(s,p-1);
//p:=pos('&',s); //排除链接里面?后面的内容;
//if(p>0)then s:=replacestr(s,'&','-');
//p:=pos('=',s); //排除链接里面?后面的内容;
//if(p>0)then s:=replacestr(s,'=','-');
//if(p>0)then s:=leftstr(s,p-1);
//p:=pos('#',s); //排除链接里面?后面的内容;
//if(p>0)then s:=leftstr(s,p-1);
result:=fullDir+'\'+s;
end;
//获取主站地址;
function getSite(url:string):string;
var
dir,s:string;
p:integer;
begin
s:=url;
p:=pos('/',s);
if(p<=0)then begin result:=url;exit;end;
dir:=leftstr(s,p-1);
if(dir='http:')then s:=rightstr(s,length(s)-7);
if(dir='https:')then s:=rightstr(s,length(s)-8);
p:=pos('/',s);
if(p<=0)then begin result:=url;exit;end;
s:=leftstr(s,p-1);
result:=s;
end;
//获取主站地址;
function getPort(url:string):string;
var
dir,s:string;
p:integer;
begin
s:=url;
p:=pos('/',s);
if(p<=0)then begin result:=url;exit;end;
dir:=leftstr(s,p-1);
if(dir='http:')then s:=rightstr(s,length(s)-7);
if(dir='https:')then s:=rightstr(s,length(s)-8);
p:=pos('/',s);
if(p<=0)then begin result:=url;exit;end;
s:=leftstr(s,p-1);
p:=pos(':',s);
if(p>0)then s:=rightstr(s,length(s)-p) else s:='';
result:=s;
end;
initialization
if not assigned(mDowns) then mDowns:=tstringlist.Create;
finalization
if assigned(mDowns) then begin
mDowns.Clear;
mDowns.Free;
end;
{
//下载指定链接的文件
procedure downloadfile(url:string);
var
localpath,remotepath:string;
begin
remotepath:=url;
if(rightstr(remotepath,1)='/')then remotepath:=remotepath+'index.htm';
localpath:=url2file(remotepath);
if(fileexists(localpath))then exit;
if(DownloadToFile(remotepath,localpath))then
Log('suc:'+remotepath+#13#10+localpath)
else
Log('fal:'+remotepath+#13#10+localpath);
end;
}
end.
|
{$R-}
{$Q-}
unit ncEncMisty1;
// To disable as much of RTTI as possible (Delphi 2009/2010),
// Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ENDIF}
interface
uses
System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers;
const
NUMROUNDS = 8;
type
TncEnc_misty1 = class(TncEnc_blockcipher64)
protected
KeyData: array [0 .. 31] of DWord;
function FI(const FI_IN, FI_KEY: DWord): DWord;
function FO(const FO_IN: DWord; const k: longword): DWord;
function FL(const FL_IN: DWord; const k: longword): DWord;
function FLINV(const FL_IN: DWord; const k: longword): DWord;
procedure InitKey(const Key; Size: longword); override;
public
class function GetAlgorithm: string; override;
class function GetMaxKeySize: integer; override;
class function SelfTest: boolean; override;
procedure Burn; override;
procedure EncryptECB(const InData; var OutData); override;
procedure DecryptECB(const InData; var OutData); override;
end;
{ ****************************************************************************** }
{ ****************************************************************************** }
implementation
uses ncEncryption;
const
S7TABLE: array [0 .. $7F] of byte = ($1B, $32, $33, $5A, $3B, $10, $17, $54, $5B, $1A, $72, $73, $6B, $2C, $66, $49, $1F, $24, $13, $6C, $37, $2E, $3F, $4A,
$5D, $0F, $40, $56, $25, $51, $1C, $04, $0B, $46, $20, $0D, $7B, $35, $44, $42, $2B, $1E, $41, $14, $4B, $79, $15, $6F, $0E, $55, $09, $36, $74, $0C, $67,
$53, $28, $0A, $7E, $38, $02, $07, $60, $29, $19, $12, $65, $2F, $30, $39, $08, $68, $5F, $78, $2A, $4C, $64, $45, $75, $3D, $59, $48, $03, $57, $7C, $4F,
$62, $3C, $1D, $21, $5E, $27, $6A, $70, $4D, $3A, $01, $6D, $6E, $63, $18, $77, $23, $05, $26, $76, $00, $31, $2D, $7A, $7F, $61, $50, $22, $11, $06, $47,
$16, $52, $4E, $71, $3E, $69, $43, $34, $5C, $58, $7D);
S9TABLE: array [0 .. $1FF] of DWord = ($1C3, $0CB, $153, $19F, $1E3, $0E9, $0FB, $035, $181, $0B9, $117, $1EB, $133, $009, $02D, $0D3, $0C7, $14A, $037, $07E,
$0EB, $164, $193, $1D8, $0A3, $11E, $055, $02C, $01D, $1A2, $163, $118, $14B, $152, $1D2, $00F, $02B, $030, $13A, $0E5, $111, $138, $18E, $063, $0E3, $0C8,
$1F4, $01B, $001, $09D, $0F8, $1A0, $16D, $1F3, $01C, $146, $07D, $0D1, $082, $1EA, $183, $12D, $0F4, $19E, $1D3, $0DD, $1E2, $128, $1E0, $0EC, $059, $091,
$011, $12F, $026, $0DC, $0B0, $18C, $10F, $1F7, $0E7, $16C, $0B6, $0F9, $0D8, $151, $101, $14C, $103, $0B8, $154, $12B, $1AE, $017, $071, $00C, $047, $058,
$07F, $1A4, $134, $129, $084, $15D, $19D, $1B2, $1A3, $048, $07C, $051, $1CA, $023, $13D, $1A7, $165, $03B, $042, $0DA, $192, $0CE, $0C1, $06B, $09F, $1F1,
$12C, $184, $0FA, $196, $1E1, $169, $17D, $031, $180, $10A, $094, $1DA, $186, $13E, $11C, $060, $175, $1CF, $067, $119, $065, $068, $099, $150, $008, $007,
$17C, $0B7, $024, $019, $0DE, $127, $0DB, $0E4, $1A9, $052, $109, $090, $19C, $1C1, $028, $1B3, $135, $16A, $176, $0DF, $1E5, $188, $0C5, $16E, $1DE, $1B1,
$0C3, $1DF, $036, $0EE, $1EE, $0F0, $093, $049, $09A, $1B6, $069, $081, $125, $00B, $05E, $0B4, $149, $1C7, $174, $03E, $13B, $1B7, $08E, $1C6, $0AE, $010,
$095, $1EF, $04E, $0F2, $1FD, $085, $0FD, $0F6, $0A0, $16F, $083, $08A, $156, $09B, $13C, $107, $167, $098, $1D0, $1E9, $003, $1FE, $0BD, $122, $089, $0D2,
$18F, $012, $033, $06A, $142, $0ED, $170, $11B, $0E2, $14F, $158, $131, $147, $05D, $113, $1CD, $079, $161, $1A5, $179, $09E, $1B4, $0CC, $022, $132, $01A,
$0E8, $004, $187, $1ED, $197, $039, $1BF, $1D7, $027, $18B, $0C6, $09C, $0D0, $14E, $06C, $034, $1F2, $06E, $0CA, $025, $0BA, $191, $0FE, $013, $106, $02F,
$1AD, $172, $1DB, $0C0, $10B, $1D6, $0F5, $1EC, $10D, $076, $114, $1AB, $075, $10C, $1E4, $159, $054, $11F, $04B, $0C4, $1BE, $0F7, $029, $0A4, $00E, $1F0,
$077, $04D, $17A, $086, $08B, $0B3, $171, $0BF, $10E, $104, $097, $15B, $160, $168, $0D7, $0BB, $066, $1CE, $0FC, $092, $1C5, $06F, $016, $04A, $0A1, $139,
$0AF, $0F1, $190, $00A, $1AA, $143, $17B, $056, $18D, $166, $0D4, $1FB, $14D, $194, $19A, $087, $1F8, $123, $0A7, $1B8, $141, $03C, $1F9, $140, $02A, $155,
$11A, $1A1, $198, $0D5, $126, $1AF, $061, $12E, $157, $1DC, $072, $18A, $0AA, $096, $115, $0EF, $045, $07B, $08D, $145, $053, $05F, $178, $0B2, $02E, $020,
$1D5, $03F, $1C9, $1E7, $1AC, $044, $038, $014, $0B1, $16B, $0AB, $0B5, $05A, $182, $1C8, $1D4, $018, $177, $064, $0CF, $06D, $100, $199, $130, $15A, $005,
$120, $1BB, $1BD, $0E0, $04F, $0D6, $13F, $1C4, $12A, $015, $006, $0FF, $19B, $0A6, $043, $088, $050, $15F, $1E8, $121, $073, $17E, $0BC, $0C2, $0C9, $173,
$189, $1F5, $074, $1CC, $1E6, $1A8, $195, $01F, $041, $00D, $1BA, $032, $03D, $1D1, $080, $0A8, $057, $1B9, $162, $148, $0D9, $105, $062, $07A, $021, $1FF,
$112, $108, $1C0, $0A9, $11D, $1B0, $1A6, $0CD, $0F3, $05C, $102, $05B, $1D9, $144, $1F6, $0AD, $0A5, $03A, $1CB, $136, $17F, $046, $0E1, $01E, $1DD, $0E6,
$137, $1FA, $185, $08C, $08F, $040, $1B5, $0BE, $078, $000, $0AC, $110, $15E, $124, $002, $1BC, $0A2, $0EA, $070, $1FC, $116, $15C, $04C, $1C2);
function SwapDword(a: DWord): DWord;
begin
Result := ((a and $FF) shl 24) or ((a and $FF00) shl 8) or ((a and $FF0000) shr 8) or ((a and $FF000000) shr 24);
end;
class function TncEnc_misty1.GetAlgorithm: string;
begin
Result := 'Misty1';
end;
class function TncEnc_misty1.GetMaxKeySize: integer;
begin
Result := 128;
end;
class function TncEnc_misty1.SelfTest: boolean;
const
Key: array [0 .. 15] of byte = ($00, $11, $22, $33, $44, $55, $66, $77, $88, $99, $AA, $BB, $CC, $DD, $EE, $FF);
Plain1: array [0 .. 7] of byte = ($01, $23, $45, $67, $89, $AB, $CD, $EF);
Plain2: array [0 .. 7] of byte = ($FE, $DC, $BA, $98, $76, $54, $32, $10);
Cipher1: array [0 .. 7] of byte = ($8B, $1D, $A5, $F5, $6A, $B3, $D0, $7C);
Cipher2: array [0 .. 7] of byte = ($04, $B6, $82, $40, $B1, $3B, $E9, $5D);
var
Cipher: TncEnc_misty1;
Block: array [0 .. 7] of byte;
begin
Cipher := TncEnc_misty1.Create(nil);
Cipher.Init(Key, Sizeof(Key) * 8, nil);
Cipher.EncryptECB(Plain1, Block);
Result := CompareMem(@Cipher1, @Block, Sizeof(Block));
Cipher.DecryptECB(Block, Block);
Result := Result and CompareMem(@Plain1, @Block, Sizeof(Block));
Cipher.EncryptECB(Plain2, Block);
Result := Result and CompareMem(@Cipher2, @Block, Sizeof(Block));
Cipher.DecryptECB(Block, Block);
Result := Result and CompareMem(@Plain2, @Block, Sizeof(Block));
Cipher.Burn;
Cipher.Free;
end;
function TncEnc_misty1.FI(const FI_IN, FI_KEY: DWord): DWord;
var
d7, d9: DWord;
begin
d9 := (FI_IN shr 7) and $1FF;
d7 := FI_IN and $7F;
d9 := S9TABLE[d9] xor d7;
d7 := (S7TABLE[d7] xor d9) and $7F;
d7 := d7 xor ((FI_KEY shr 9) and $7F);
d9 := d9 xor (FI_KEY and $1FF);
d9 := S9TABLE[d9] xor d7;
Result := (d7 shl 9) or d9;
end;
function TncEnc_misty1.FO(const FO_IN: DWord; const k: longword): DWord;
var
t0, t1: DWord;
begin
t0 := FO_IN shr 16;
t1 := FO_IN and $FFFF;
t0 := t0 xor KeyData[k];
t0 := FI(t0, KeyData[((k + 5) mod 8) + 8]);
t0 := t0 xor t1;
t1 := t1 xor KeyData[(k + 2) mod 8];
t1 := FI(t1, KeyData[((k + 1) mod 8) + 8]);
t1 := t1 xor t0;
t0 := t0 xor KeyData[(k + 7) mod 8];
t0 := FI(t0, KeyData[((k + 3) mod 8) + 8]);
t0 := t0 xor t1;
t1 := t1 xor KeyData[(k + 4) mod 8];
Result := (t1 shl 16) or t0;
end;
function TncEnc_misty1.FL(const FL_IN: DWord; const k: longword): DWord;
var
d0, d1: DWord;
t: byte;
begin
d0 := FL_IN shr 16;
d1 := FL_IN and $FFFF;
if (k mod 2) <> 0 then
begin
t := (k - 1) div 2;
d1 := d1 xor (d0 and KeyData[((t + 2) mod 8) + 8]);
d0 := d0 xor (d1 or KeyData[(t + 4) mod 8]);
end
else
begin
t := k div 2;
d1 := d1 xor (d0 and KeyData[t]);
d0 := d0 xor (d1 or KeyData[((t + 6) mod 8) + 8]);
end;
Result := (d0 shl 16) or d1;
end;
function TncEnc_misty1.FLINV(const FL_IN: DWord; const k: longword): DWord;
var
d0, d1: DWord;
t: byte;
begin
d0 := FL_IN shr 16;
d1 := FL_IN and $FFFF;
if (k mod 2) <> 0 then
begin
t := (k - 1) div 2;
d0 := d0 xor (d1 or KeyData[(t + 4) mod 8]);
d1 := d1 xor (d0 and KeyData[((t + 2) mod 8) + 8]);
end
else
begin
t := k div 2;
d0 := d0 xor (d1 or KeyData[((t + 6) mod 8) + 8]);
d1 := d1 xor (d0 and KeyData[t]);
end;
Result := (d0 shl 16) or d1;
end;
procedure TncEnc_misty1.InitKey(const Key; Size: longword);
var
KeyB: array [0 .. 15] of byte;
i: longword;
begin
FillChar(KeyB, Sizeof(KeyB), 0);
Move(Key, KeyB, Size div 8);
for i := 0 to 7 do
KeyData[i] := (KeyB[i * 2] * 256) + KeyB[i * 2 + 1];
for i := 0 to 7 do
begin
KeyData[i + 8] := FI(KeyData[i], KeyData[(i + 1) mod 8]);
KeyData[i + 16] := KeyData[i + 8] and $1FF;
KeyData[i + 24] := KeyData[i + 8] shr 9;
end;
end;
procedure TncEnc_misty1.Burn;
begin
FillChar(KeyData, Sizeof(KeyData), 0);
inherited Burn;
end;
procedure TncEnc_misty1.EncryptECB(const InData; var OutData);
var
d0, d1: DWord;
i: longword;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
d0 := SwapDword(PDWord(@InData)^);
d1 := SwapDword(PDWord(longword(@InData) + 4)^);
for i := 0 to NUMROUNDS - 1 do
begin
if (i mod 2) = 0 then
begin
d0 := FL(d0, i);
d1 := FL(d1, i + 1);
d1 := d1 xor FO(d0, i);
end
else
d0 := d0 xor FO(d1, i);
end;
d0 := FL(d0, NUMROUNDS);
d1 := FL(d1, NUMROUNDS + 1);
PDWord(@OutData)^ := SwapDword(d1);
PDWord(longword(@OutData) + 4)^ := SwapDword(d0);
end;
procedure TncEnc_misty1.DecryptECB(const InData; var OutData);
var
d0, d1: DWord;
i: longword;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
d1 := SwapDword(PDWord(@InData)^);
d0 := SwapDword(PDWord(longword(@InData) + 4)^);
d1 := FLINV(d1, NUMROUNDS + 1);
d0 := FLINV(d0, NUMROUNDS);
for i := NUMROUNDS - 1 downto 0 do
begin
if (i mod 2) = 0 then
begin
d1 := d1 xor FO(d0, i);
d0 := FLINV(d0, i);
d1 := FLINV(d1, i + 1);
end
else
d0 := d0 xor FO(d1, i);
end;
PDWord(@OutData)^ := SwapDword(d0);
PDWord(longword(@OutData) + 4)^ := SwapDword(d1);
end;
end.
|
unit UnLancarCreditoView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, DB, JvExStdCtrls, JvEdit, JvValidateEdit,
{ Fluente }
Util, SearchUtil, UnComandaModelo, Pagamentos, UnTeclado;
type
TLancarCreditoView = class(TForm)
Label1: TLabel;
EdtValor: TJvValidateEdit;
btnOk: TPanel;
Label2: TLabel;
EdtCartaoCredito: TEdit;
pnlCartaoCreditoPesquisa: TPanel;
procedure btnOkClick(Sender: TObject);
procedure EdtValorEnter(Sender: TObject);
procedure EdtValorExit(Sender: TObject);
private
FCartaoCreditoPesquisa: TPesquisa;
FModelo: IPagamentoCartaoDeCredito;
FTeclado: TTeclado;
public
function Modelo(
const Modelo: IPagamentoCartaoDeCredito): TLancarCreditoView;
function Descarregar: TLancarCreditoView;
function Preparar: TLancarCreditoView;
procedure ProcessarSelecaoCartaoCredito(Sender: TObject);
end;
var
LancarCreditoView: TLancarCreditoView;
implementation
{$R *.dfm}
procedure TLancarCreditoView.btnOkClick(Sender: TObject);
var
_dataSet: TDataSet;
begin
_dataSet := Self.FCartaoCreditoPesquisa.Modelo.DataSet;
Self.FModelo.RegistrarPagamentoCartaoDeCredito(
TMap.Create
.Gravar('cart_oid', _dataSet.FieldByName('cart_oid').AsString)
.Gravar('cart_cod', _dataSet.FieldByName('cart_cod').AsString)
.Gravar('valor', Self.EdtValor.AsCurrency)
);
Self.ModalResult := mrOk;
end;
function TLancarCreditoView.Modelo(
const Modelo: IPagamentoCartaoDeCredito): TLancarCreditoView;
begin
Self.FModelo := Modelo;
Result := Self;
end;
function TLancarCreditoView.Descarregar: TLancarCreditoView;
begin
Self.FModelo := nil;
Result := Self;
end;
procedure TLancarCreditoView.EdtValorEnter(Sender: TObject);
begin
if Self.FTeclado = nil then
begin
Self.FTeclado := TTeclado.Create(nil);
Self.FTeclado.Top := Self.Height - Self.FTeclado.Height;
Self.FTeclado.Parent := Self;
Self.FTeclado.ControleDeEdicao(Sender as TCustomEdit);
end;
Self.FTeclado.Visible := True;
end;
procedure TLancarCreditoView.EdtValorExit(Sender: TObject);
begin
if Self.FTeclado <> nil then
Self.FTeclado.Visible := True;
end;
function TLancarCreditoView.Preparar: TLancarCreditoView;
begin
Self.EdtValor.Value := Self.FModelo.Parametros.Ler('total').ComoDecimal;
Self.FCartaoCreditoPesquisa := TConstrutorDePesquisas
.Formulario(Self)
.ControleDeEdicao(Self.EdtCartaoCredito)
.PainelDePesquisa(Self.pnlCartaoCreditoPesquisa)
.Modelo('CartaoCreditoModeloPesquisa')
.AcaoAposSelecao(Self.ProcessarSelecaoCartaoCredito)
.Construir;
Result := Self;
end;
procedure TLancarCreditoView.ProcessarSelecaoCartaoCredito(Sender: TObject);
var
_event: TNotifyEvent;
_dataSet: TDataSet;
begin
_event := Self.EdtCartaoCredito.OnChange;
Self.EdtCartaoCredito.OnChange := nil;
_dataSet := Self.FCartaoCreditoPesquisa.Modelo.DataSet;
Self.EdtCartaoCredito.Text := _dataSet.FieldByName('cart_cod').AsString;
Self.EdtCartaoCredito.OnChange := _event;
end;
end.
|
unit uDMNXDontShut;
interface
uses
SysUtils, Classes, SyncObjs, Windows,
nxllTransport,
nxllSimpleCommandHandler, nxdb, nxllComponent, nxptBasePooledTransport,
nxtwWinsockTransport, nxllSimpleSession;
type
Tdm = class(TDataModule)
nxSession: TnxSimpleSession;
nxTCPIP: TnxWinsockTransport;
nxCmdH: TnxSimpleCommandHandler;
private
{ Private declarations }
public
{ Public declarations }
end;
TThreadDontShut = class ( TThread )
protected
procedure Execute; override;
end;
function GetQtd: Integer;
procedure IncQtd;
procedure DecQtd;
var
NumTh: Integer;
CS : TCriticalSection = nil;
dm: Tdm;
serv : String = '127.0.0.1';
implementation
{$R *.dfm}
{ TThreadDontShut }
procedure ProcessMessages;
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure TThreadDontShut.Execute;
var
d: TDM;
begin
IncQtd;
try
try
D := Tdm.Create(nil);
try
D.nxTCPIP.Active := True;
D.nxSession.Active := True;
Sleep(random(5000));
finally
D.free;
end;
except
end;
finally
DecQtd;
end;
end;
function GetQtd: Integer;
begin
CS.Enter;
try
Result := NumTh;
finally
CS.Leave;
end;
end;
procedure IncQtd;
begin
CS.Enter;
try
Inc(NumTh);
finally
CS.Leave;
end;
end;
procedure DecQtd;
begin
CS.Enter;
try
Dec(NumTh);
finally
CS.Leave;
end;
end;
initialization
NumTh := 0;
CS := TCriticalSection.Create;
Randomize;
finalization
CS.Free;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConfig.PublicPaths;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
Data.Bind.Controls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts,
FMX.DialogService, RSConfig.NameValueFrame, FMX.TabControl, FMX.ListBox,
RSConfig.ListControlFrame;
type
TPublicPathsFrame = class(TFrame)
ListControlFrame1: TListControlFrame;
TabControl: TTabControl;
ListItem: TTabItem;
EditItem: TTabItem;
Layout72: TLayout;
SaveButton: TButton;
CancelButton: TButton;
Layout2: TLayout;
PathEdit: TEdit;
Label2: TLabel;
Layout3: TLayout;
Label3: TLabel;
Layout4: TLayout;
Label4: TLabel;
Layout5: TLayout;
DirectoryEdit: TEdit;
Label5: TLabel;
Layout6: TLayout;
DefaultEdit: TEdit;
Label6: TLabel;
ExtensionsLB: TListBox;
MimesLB: TListBox;
VertScrollBox2: TVertScrollBox;
Layout7: TLayout;
Layout8: TLayout;
RemoveExtButton: TButton;
AddExtButton: TButton;
RemoveMimesButton: TButton;
AddMimesButton: TButton;
ConfigButton: TButton;
ListBox1: TListBox;
Layout1: TLayout;
CharsetEdit: TEdit;
Label1: TLabel;
procedure AddExtButtonClick(Sender: TObject);
procedure RemoveExtButtonClick(Sender: TObject);
procedure RemoveMimesButtonClick(Sender: TObject);
procedure AddMimesButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure ConfigButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ActiveFrame: TNameValueFrame;
constructor Create(AOwner: TComponent); override;
procedure Callback(Sender: TObject);
procedure LoadSectionList;
procedure SaveSectionList;
procedure ClearFields;
procedure Reset;
end;
implementation
{$R *.fmx}
uses
RSConsole.FormConfig, RSConfig.ConfigDM, RSConfig.Consts;
constructor TPublicPathsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ListControlFrame1.HelpButton.Hint := strPublicPathsHelp;
end;
procedure TPublicPathsFrame.Reset;
begin
if TabControl.ActiveTab = EditItem then
CancelButtonClick(Self);
end;
procedure TPublicPathsFrame.AddExtButtonClick(Sender: TObject);
begin
TDialogService.InputQuery(strFileExtInputQuery, [strFileExtPrompt], [''],
procedure(const AResult: TModalResult; const Values: array of string)
begin
if AResult = mrOk then
ExtensionsLB.Items.Add(Values[0]);
end);
end;
procedure TPublicPathsFrame.AddMimesButtonClick(Sender: TObject);
begin
TDialogService.InputQuery(strMimeInputQuery, [strMimePrompt], [''],
procedure(const AResult: TModalResult; const Values: array of string)
begin
if AResult = mrOk then
MimesLB.Items.Add(Values[0]);
end);
end;
procedure TPublicPathsFrame.Callback(Sender: TObject);
var
LPublicPathsItem: TPublicPathsItem;
LIndex: Integer;
begin
ActiveFrame := TNameValueFrame(Sender);
if Assigned(ActiveFrame) then
begin
if ActiveFrame.ValueEdit.Text <> '' then
begin
LPublicPathsItem := TPublicPathsItem.FromJson(ActiveFrame.ValueEdit.Text);
try
DefaultEdit.Text := LPublicPathsItem.Default;
DirectoryEdit.Text := LPublicPathsItem.Directory;
for LIndex := Low(LPublicPathsItem.Extensions) to High(LPublicPathsItem.Extensions) do
ExtensionsLB.Items.Add(LPublicPathsItem.Extensions[LIndex]);
for LIndex := Low(LPublicPathsItem.Mimes) to High(LPublicPathsItem.Mimes) do
MimesLB.Items.Add(LPublicPathsItem.Mimes[LIndex]);
PathEdit.Text := LPublicPathsItem.Path;
CharsetEdit.Text := LPublicPathsItem.Charset;
finally
LPublicPathsItem.Free;
end;
end;
TabControl.ActiveTab := EditItem;
ConfigForm.SaveLayout.Visible := False;
end;
end;
procedure TPublicPathsFrame.CancelButtonClick(Sender: TObject);
begin
ClearFields;
TabControl.ActiveTab := ListItem;
ConfigForm.SaveLayout.Visible := True;
end;
procedure TPublicPathsFrame.LoadSectionList;
begin
ListControlFrame1.SetFrameType(PUBLICPATHS_FRAME);
ListControlFrame1.SetListBox(ListBox1);
ListControlFrame1.SetCallback(Callback);
ConfigDM.LoadSectionList(strServerPublicPaths, ListBox1, Callback);
end;
procedure TPublicPathsFrame.RemoveExtButtonClick(Sender: TObject);
begin
if ExtensionsLB.ItemIndex > -1 then
ExtensionsLB.Items.Delete(ExtensionsLB.ItemIndex);
end;
procedure TPublicPathsFrame.RemoveMimesButtonClick(Sender: TObject);
begin
if MimesLB.ItemIndex > -1 then
MimesLB.Items.Delete(MimesLB.ItemIndex);
end;
procedure TPublicPathsFrame.SaveButtonClick(Sender: TObject);
var
LPublicPathsItem: TPublicPathsItem;
LIndex: Integer;
begin
if Assigned(ActiveFrame) then
begin
LPublicPathsItem := TPublicPathsItem.Create;
try
LPublicPathsItem.Default := DefaultEdit.Text;
LPublicPathsItem.Directory := DirectoryEdit.Text;
for LIndex := 0 to ExtensionsLB.Items.Count - 1 do
LPublicPathsItem.Extensions := LPublicPathsItem.Extensions +
[ExtensionsLB.Items[LIndex]];
for LIndex := 0 to MimesLB.Items.Count - 1 do
LPublicPathsItem.Mimes := LPublicPathsItem.Mimes +
[MimesLB.Items[LIndex]];
LPublicPathsItem.Path := PathEdit.Text;
LPublicPathsItem.Charset := CharsetEdit.Text;
ActiveFrame.ValueEdit.Text := LPublicPathsItem.ToJson;
finally
LPublicPathsItem.Free;
end;
ClearFields;
ActiveFrame := nil;
end;
TabControl.ActiveTab := ListItem;
ConfigForm.SaveLayout.Visible := True;
end;
procedure TPublicPathsFrame.ClearFields;
begin
DefaultEdit.Text := '';
DirectoryEdit.Text := '';
ExtensionsLB.Items.Clear;
MimesLB.Items.Clear;
PathEdit.Text := '';
end;
procedure TPublicPathsFrame.ConfigButtonClick(Sender: TObject);
var
LRoot: string;
LDirectory: string;
begin
if DirectoryEdit.Text <> '' then
LDirectory := DirectoryEdit.Text
else
LDirectory := GetCurrentDir;
LRoot := '';
if SelectDirectory(strSelectDirPrompt, LRoot, LDirectory) then
DirectoryEdit.Text := LDirectory;
end;
procedure TPublicPathsFrame.SaveSectionList;
begin
ConfigDM.SaveSectionList(strServerPublicPaths, ListBox1);
end;
end.
|
{*******************************************************}
{ }
{ FMX UI Toast 自动消失提示组件 }
{ }
{ 版权所有 (C) 2016 YangYxd }
{ }
{*******************************************************}
unit UI.Toast;
interface
uses
UI.Base,
{$IFNDEF ANDROID}
UI.Toast.AndroidLike,
{$ENDIF}
System.SysUtils,
System.Classes;
type
TToastLength = (LongToast, ShortToast);
type
[ComponentPlatformsAttribute(AllCurrentPlatforms)]
TToastManager = class(TComponent)
private
{$IFNDEF ANDROID}
FToast: TToast;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Toast(const Msg: string);
end;
procedure Toast(const Msg: string; Duration: TToastLength = ShortToast);
implementation
{$IFDEF ANDROID}
uses
UI.Toast.Android;
{$ELSE}
var
[Weak] LToast: TToast = nil;
{$ENDIF}
{$IFDEF ANDROID}
procedure Toast(const Msg: string; Duration: TToastLength = ShortToast);
begin
UI.Toast.Android.Toast(Msg, Duration);
end;
{$ENDIF}
{$IFNDEF ANDROID}
procedure Toast(const Msg: string; Duration: TToastLength = ShortToast);
begin
if (LToast <> nil) and (Msg <> '') then
LToast.ShowToast(Msg);
end;
{$ENDIF}
{ TToastManager }
constructor TToastManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$IFNDEF ANDROID}
if not (csDesigning in ComponentState) then begin
FToast := TToast.Create(AOwner);
if LToast = nil then
LToast := FToast;
end;
{$ENDIF}
end;
destructor TToastManager.Destroy;
begin
{$IFNDEF ANDROID}
FToast := nil;
{$ENDIF}
inherited;
end;
procedure TToastManager.Toast(const Msg: string);
begin
{$IFNDEF ANDROID}
if Msg <> '' then
FToast.ShowToast(Msg);
{$ELSE}
UI.Toast.Android.Toast(Msg, ShortToast);
{$ENDIF}
end;
initialization
finalization
end.
|
program MemArrayMappedInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
procedure GetMemArrayMappedInfo;
Var
SMBios: TSMBios;
LMemArrMappedAddress: TMemoryArrayMappedAddressInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Memory Array Mapped Address Information');
WriteLn('---------------------------------------');
if SMBios.HasMemoryArrayMappedAddressInfo then
for LMemArrMappedAddress in SMBios.MemoryArrayMappedAddressInformation do
begin
WriteLn(Format('Starting Address %.8x ',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.StartingAddress]));
WriteLn(Format('Ending Address %.8x ',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.EndingAddress]));
WriteLn(Format('Memory Array Handle %.4x ',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.MemoryArrayHandle]));
WriteLn(Format('Partition Width %d ',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.PartitionWidth]));
if SMBios.SmbiosVersion>='2.7' then
begin
WriteLn(Format('Extended Starting Address %x',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.ExtendedStartingAddress]));
WriteLn(Format('Extended Ending Address %x',[LMemArrMappedAddress.RAWMemoryArrayMappedAddressInfo^.ExtendedEndingAddress]));
end;
WriteLn;
end
else
Writeln('No Memory Array Mapped Address Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetMemArrayMappedInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSGenerics<p>
GLScene cross IDE generic classes collection.<p>
<b>History : </b><font size=-1><ul>
<li>10/11/12 - PW - Added CPP compatibility: redeclared FOnChange: TNotifyEvent;
<li>06/10/10 - Yar - Creation
</ul></font>
}
unit GLSGenerics;
interface
{$I GLScene.inc}
uses
SysUtils,
Classes,
SyncObjs,
GLCrossPlatform;
const
MaxListSize = Maxint div 16;
type
// GList
//
{$IFDEF GLS_GENERIC_PREFIX}
generic
{$ENDIF}
GList<T> = class(TObject)
public
type
TListChangeEvent = procedure(Sender: TObject; const Item: T;
Action: TListNotification) of object;
// var
private
FItems: array of T;
FCount: Integer;
FCapacity: Integer;
// FOnChange: TListChangeEvent;
FOnChange: TNotifyEvent;
protected
procedure SetCapacity(Value: Integer);
procedure SetCount(Value: Integer);
function GetItem(Index: Integer): T;
procedure SetItem(Index: Integer; const Value: T);
function GetItemAddress(Index: Integer): Pointer;
procedure Grow;
protected
procedure Notify(const Item: T; Action: TListNotification); virtual;
public
destructor Destroy; override;
procedure Clear;
function Add(AItem: T): Integer;
procedure Delete(Index: Integer);
procedure Extract(AItem: T);
function Remove(AItem: T): Integer;
function IndexOf(AItem: T): Integer;
procedure Insert(Index: Integer; AItem: T);
procedure Exchange(Index1, Index2: Integer);
function First: T;
function Last: T;
property Items[Index: Integer]: T read GetItem write SetItem; default;
property ItemAddress[Index: Integer]: Pointer read GetItemAddress;
property Capacity: Integer read FCapacity write SetCapacity;
property Count: Integer read FCount write SetCount;
// property OnChange: TListChangeEvent read FOnChange write FOnChange;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
// GThreadList
//
{$IFDEF GLS_GENERIC_PREFIX}
generic
{$ENDIF}
GThreadList<T> = class
public
type
TLockableList = {$IFDEF GLS_GENERIC_PREFIX} specialize {$ENDIF} GList<T>;
var
private
FList: TLockableList;
FLock: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Add(AItem: T);
procedure Clear;
function LockList: TLockableList;
procedure Remove(AItem: T);
procedure UnlockList;
end;
// GOrderedList
//
{$IFDEF GLS_GENERIC_PREFIX}
generic
{$ENDIF}
GOrderedList<T> = class(TObject)
private
type
TOrderedList = {$IFDEF GLS_GENERIC_PREFIX} specialize {$ENDIF} GList<T>;
var
FList: TOrderedList;
protected
procedure PushItem(AItem: T); virtual; abstract;
function PopItem: T; virtual;
function PeekItem: T; virtual;
property List: TOrderedList read FList;
public
constructor Create; virtual;
destructor Destroy; override;
function Count: Integer;
function AtLeast(ACount: Integer): Boolean;
function Push(const AItem: T): T;
function Pop: T;
function Peek: T;
end;
// GStack
//
{$IFDEF GLS_GENERIC_PREFIX}
generic
{$ENDIF}
GStack<T> = class({$IFDEF GLS_GENERIC_PREFIX} specialize {$ENDIF} GOrderedList<T>)
protected
procedure PushItem(AItem: T); override;
end;
// GQueue
//
{$IFDEF GLS_GENERIC_PREFIX}
generic
{$ENDIF}
GQueue<T> = class(GOrderedList<T>)
protected
procedure PushItem(AItem: T); override;
end;
implementation
{$REGION 'GList'}
destructor GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Destroy;
begin
Clear;
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Clear;
begin
SetCount(0);
SetCapacity(0);
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.SetCapacity(Value: Integer);
begin
{$IFOPT R+}
Assert(not (Value < FCount) or (Value > MaxListSize));
{$ENDIF}
if Value <> FCapacity then
begin
SetLength(FItems, Value);
FCapacity := Value;
end;
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.SetCount(Value: Integer);
var
I: Integer;
begin
{$IFOPT R+}
Assert(not (Value < 0) or (Value > MaxListSize));
{$ENDIF}
if Value > FCapacity then
SetCapacity(Value);
if Value <= FCount then
for I := FCount - 1 downto Value do
Delete(I);
FCount := Value;
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Add(AItem: T): Integer;
begin
Result := FCount;
if Result = FCapacity then
Grow;
FItems[Result] := AItem;
Inc(FCount);
Notify(AItem, lnAdded);
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Delete(Index: Integer);
var
Temp: T;
begin
{$IFOPT R+}
Assert(Index < FCount);
{$ENDIF}
Temp := FItems[Index];
Dec(FCount);
if Index < FCount then
Move(FItems[Index + 1], FItems[Index],
(FCount - Index) * SizeOf(T));
Notify(Temp, lnDeleted);
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Extract(AItem: T);
var
I: Integer;
begin
I := IndexOf(AItem);
if I >= 0 then
begin
Delete(I);
Notify(AItem, lnExtracted);
end;
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.First: T;
begin
Result := GetItem(0);
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.GetItem(Index: Integer): T;
begin
{$IFOPT R+}
Assert(Index < FCount);
{$ENDIF}
Result := FItems[Index];
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.GetItemAddress(Index: Integer): Pointer;
begin
{$IFOPT R+}
Assert(Index < FCount);
{$ENDIF}
Result := @FItems[Index];
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.IndexOf(AItem: T): Integer;
begin
for Result := 0 to FCount - 1 do
if CompareMem(@FItems[Result], @AItem, SizeOf(T)) then
exit;
Result := -1;
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Insert(Index: Integer; AItem: T);
begin
{$IFOPT R+}
Assert(Index < FCount);
{$ENDIF}
if FCount = FCapacity then
Grow;
if Index < FCount then
Move(FItems[Index], FItems[Index + 1],
(FCount - Index) * SizeOf(T));
FItems[Index] := AItem;
Inc(FCount);
Notify(AItem, lnAdded);
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Exchange(Index1, Index2: Integer);
var
Item: T;
begin
{$IFOPT R+}
Assert(Index1 < FCount);
Assert(Index2 < FCount);
{$ENDIF}
Item := FItems[Index1];
FItems[Index1] := FItems[Index2];
FItems[Index2] := Item;
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Last: T;
begin
if FCount > 0 then
Result := FItems[FCount-1];
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Notify(const Item: T; Action: TListNotification);
begin
// if Assigned(FOnChange) then FOnChange(Self, Item, Action);
if Assigned(FOnChange) then FOnChange(Self);
end;
function GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Remove(AItem: T): Integer;
begin
Result := IndexOf(AItem);
if Result >= 0 then
Delete(Result);
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.SetItem(Index: Integer; const Value: T);
begin
FItems[Index] := Value;
end;
procedure GList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Grow;
var
Delta: Integer;
begin
if FCapacity > 64 then
Delta := FCapacity div 4
else
if FCapacity > 8 then
Delta := 16
else
Delta := 4;
SetCapacity(FCapacity + Delta);
end;
{$ENDREGION}
{$REGION 'GThreadList'}
constructor GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Create;
begin
inherited Create;
FLock := TCriticalSection.Create;
FList := TLockableList.Create;
end;
destructor GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Destroy;
begin
LockList;
try
FList.Free;
inherited Destroy;
finally
UnlockList;
FLock.Free;
end;
end;
procedure GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Add(AItem: T);
begin
LockList;
try
FList.Add(AItem)
finally
UnlockList;
end;
end;
procedure GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Clear;
begin
LockList;
try
FList.Clear;
finally
UnlockList;
end;
end;
function GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.LockList: TLockableList;
begin
FLock.Enter;
Result := FList;
end;
procedure GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Remove(AItem: T);
begin
LockList;
try
FList.Remove(AItem);
finally
UnlockList;
end;
end;
procedure GThreadList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.UnlockList;
begin
FLock.Leave;
end;
{$ENDREGION 'GThreadList'}
{$REGION 'GOrderedList'}
constructor GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Create;
begin
FList := TOrderedList.Create;
end;
destructor GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Destroy;
begin
FList.Free;
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.AtLeast(ACount: Integer): Boolean;
begin
Result := List.Count >= ACount;
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.PeekItem: T;
begin
Result := List[List.Count-1];
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.PopItem: T;
begin
Result := PeekItem;
List.Delete(List.Count-1);
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Peek: T;
begin
Result := PeekItem;
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Pop: T;
begin
Result := PopItem;
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Push(const AItem: T): T;
begin
PushItem(AItem);
Result := AItem;
end;
function GOrderedList{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.Count: Integer;
begin
Result := List.Count;
end;
{$ENDREGION}
{$REGION 'GStack'}
procedure GStack{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.PushItem(AItem: T);
begin
List.Add(AItem);
end;
{$ENDREGION 'GStack'}
{$REGION 'GQueue'}
procedure GQueue{$IFNDEF GLS_GENERIC_PREFIX}<T>{$ENDIF}.PushItem(AItem: T);
begin
List.Insert(0, AItem);
end;
{$ENDREGION 'GQueue'}
end.
|
unit _IniFiles;
interface
uses
SysUtils, Forms, IniFiles;
type
TMyIni = class
private
public
Constructor Create;
Destructor Free;
function Read(Section,Ident:String; Default:String=''):String;
procedure Write(Section,Ident,Value:String);
end;
implementation
var
vIni: TIniFile;
constructor TMyIni.Create;
begin
vIni:= TIniFile.Create(ExtractFilePath(Application.ExeName)+'\config.ini');
end;
destructor TMyIni.Free;
begin
vIni.Free;
end;
function TMyIni.Read(Section,Ident:String; Default:String=''):String;
begin
Result:= vIni.ReadString(Section, Ident, Default);
end;
procedure TMyIni.Write(Section,Ident,Value:String);
begin
vIni.WriteString(Section, Ident, Value);
end;
end.
|
unit USchema;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, pFIBMetaData, FIBDatabase, pFIBDatabase, StdCtrls, DB, FIBDataSet,
pFIBDataSet, Grids, DBGrids, FIBQuery, pFIBQuery, RefreshDB;
type
TFRefreshDB = class(TForm)
SourceFDB: TEdit;
Source: TButton;
TargetFDB: TEdit;
Target: TButton;
OpenDialog: TOpenDialog;
Script: TMemo;
RefreshDB: TButton;
Demo: TCheckBox;
procedure SourceClick(Sender: TObject);
procedure TargetClick(Sender: TObject);
procedure RefreshDBClick(Sender: TObject);
procedure SourceFDBChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FRefreshDB: TFRefreshDB;
implementation
{$R *.dfm}
procedure TFRefreshDB.RefreshDBClick(Sender: TObject);
var OK : boolean;
begin
RefreshDM.ExecuteScript := not Demo.Checked;
OK := RefreshDM.RefreshDataBase(SourceFDB.Text, TargetFDB.Text);
Script.Lines.Assign(RefreshDM.Scripter.Script);
if not OK then
ShowMessage('RefreshDataBase failed!');
end;
procedure TFRefreshDB.SourceClick(Sender: TObject);
begin
if OpenDialog.Execute then
SourceFDB.Text := OpenDialog.Filename;
end;
procedure TFRefreshDB.SourceFDBChange(Sender: TObject);
begin
RefreshDB.Enabled := FileExists(SourceFDB.Text) and FileExists(TargetFDB.Text);
end;
procedure TFRefreshDB.TargetClick(Sender: TObject);
begin
if OpenDialog.Execute then
TargetFDB.Text := OpenDialog.Filename;
end;
end.
|
unit fUserData;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ToolWin, ActnList, ImgList, Ex_Grid, Ex_Inspector,
FlexBase, FlexProps,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox,
dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar,
cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup,
cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView,
cxImage;
type
TfmUserData = class(TForm)
imgToolIcons: TImageList;
tbrMain: TToolBar;
tbNew: TToolButton;
tbDelete: TToolButton;
tbDelim: TToolButton;
tbMoveUp: TToolButton;
tbMoveDown: TToolButton;
grUserProps: TExInspector;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tbNewClick(Sender: TObject);
procedure tbDeleteClick(Sender: TObject);
procedure tbMoveUpClick(Sender: TObject);
procedure tbMoveDownClick(Sender: TObject);
procedure grUserPropsGetCellText(Sender: TObject; Cell: TGridCell;
var Value: String);
procedure grUserPropsSetEditText(Sender: TObject; Cell: TGridCell;
var Value: String);
procedure grUserPropsChange(Sender: TObject; Cell: TGridCell;
Selected: Boolean);
private
{ Private declarations }
FActiveFlex: TFlexPanel;
FLastControl: TFlexControl;
procedure CheckTools;
procedure SetActiveFlex(const Value: TFlexPanel);
function GetSelControl: TFlexControl;
procedure DrawCell(Sender: TObject; Cell: TGridCell;
var Rect: TRect; var DefaultDrawing: Boolean);
public
{ Public declarations }
property ActiveFlex: TFlexPanel read FActiveFlex write SetActiveFlex;
property SelControl: TFlexControl read GetSelControl;
procedure UpdateData;
end;
var
fmUserData: TfmUserData;
implementation
{$R *.DFM}
uses
ToolMngr;
procedure TfmUserData.FormCreate(Sender: TObject);
begin
RegisterToolForm(Self);
with grUserProps do begin
Columns[0].ReadOnly := False;
Columns[0].TabStop := True;
Columns[0].Width := 80;
Fixed.Count := 0;
OnDrawCell := DrawCell;
//AlwaysEdit := false;
end;
CheckTools;
end;
procedure TfmUserData.FormDestroy(Sender: TObject);
begin
UnRegisterToolForm(Self);
fmUserData := Nil;
end;
procedure TfmUserData.CheckTools;
var DataExists: boolean;
Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control)
then DataExists := Control.UserData.LinesCount > 0
else DataExists := False;
tbNew.Enabled := Assigned(Control);
tbDelete.Enabled := DataExists;
if DataExists then begin
tbMoveUp.Enabled := grUserProps.CellFocused.Row > 0;
tbMoveDown.Enabled :=
grUserProps.CellFocused.Row < Control.UserData.LinesCount-1;
end else begin
tbMoveUp.Enabled := False;
tbMoveDown.Enabled := False;
end;
end;
procedure TfmUserData.UpdateData;
var Control: TFlexControl;
begin
Control := SelControl;
with grUserProps do begin
if Assigned(FLastControl) and (FLastControl <> Control) then Editing := False;
if Assigned(Control) then begin
Rows.Count := Control.UserData.LinesCount;
if Editing then Edit.Text := Cells[EditCell.Col, EditCell.Row];
if EditCell.Row >= 0 then begin
AlwaysEdit := False;
Editing := False;
AlwaysEdit := True;
end;
end else begin
Rows.Count := 0;
AlwaysEdit := False;
Editing := False;
AlwaysEdit := True;
end;
Invalidate;
end;
CheckTools;
FLastControl := Control;
end;
function TfmUserData.GetSelControl: TFlexControl;
begin
if Assigned(FActiveFlex) and (FActiveFlex.SelectedCount = 1)
then Result := FActiveFlex.Selected[0]
else Result := Nil;
end;
procedure TfmUserData.SetActiveFlex(const Value: TFlexPanel);
begin
if Value = FActiveFlex then exit;
if not Assigned(Value) then FLastControl := Nil;
FActiveFlex := Value;
UpdateData;
end;
procedure TfmUserData.DrawCell(Sender: TObject; Cell: TGridCell;
var Rect: TRect; var DefaultDrawing: Boolean);
begin
DefaultDrawing := true;
if Cell.Col = 0 then with TGridView(grUserProps).Canvas do begin
Pen.Color := clBtnShadow;
Pen.Width := 1;
MoveTo(Rect.Right - 2, Rect.Top - 1);
LineTo(Rect.Right - 2, Rect.Bottom);
Pen.Color := clBtnHighlight;
MoveTo(Rect.Right - 1, Rect.Bottom - 1);
LineTo(Rect.Right - 1, Rect.Top - 1);
dec(Rect.Right, 2);
end;
end;
procedure TfmUserData.grUserPropsGetCellText(Sender: TObject;
Cell: TGridCell; var Value: String);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then
case Cell.Col of
0: Value := Control.UserData.Names[Cell.Row];
1: Value := Control.UserData.ValuesByIndex[Cell.Row];
end;
end;
procedure TfmUserData.grUserPropsSetEditText(Sender: TObject;
Cell: TGridCell; var Value: String);
begin
if Assigned(FLastControl) then
if Cell.Col = 0
then FLastControl.UserData.Names[Cell.Row] := Value
else FLastControl.UserData.ValuesByIndex[Cell.Row] := Value;
grUserProps.InvalidateCell(Cell);
end;
procedure TfmUserData.grUserPropsChange(Sender: TObject; Cell: TGridCell;
Selected: Boolean);
begin
CheckTools;
end;
procedure TfmUserData.tbNewClick(Sender: TObject);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then begin
grUserProps.Editing := False;
Control.UserData.Add('');
UpdateData;
grUserProps.CellFocused := GridCell(0, grUserProps.Rows.Count-1);
end;
end;
procedure TfmUserData.tbDeleteClick(Sender: TObject);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then begin
Control.UserData.Delete(grUserProps.CellFocused.Row);
UpdateData;
end;
end;
procedure TfmUserData.tbMoveUpClick(Sender: TObject);
var Control: TFlexControl;
s1, s2: string;
begin
Control := SelControl;
if Assigned(Control) then with Control.UserData, grUserProps do begin
Editing := False;
s1 := Lines[CellFocused.Row-1];
s2 := Lines[CellFocused.Row];
Lines[CellFocused.Row-1] := s2;
Lines[CellFocused.Row] := s1;
UpdateData;
CellFocused := GridCell(CellFocused.Col, CellFocused.Row-1);
end;
end;
procedure TfmUserData.tbMoveDownClick(Sender: TObject);
var Control: TFlexControl;
s1, s2: string;
begin
Control := SelControl;
if Assigned(Control) then with Control.UserData, grUserProps do begin
Editing := False;
s1 := Lines[CellFocused.Row];
s2 := Lines[CellFocused.Row+1];
Lines[CellFocused.Row] := s2;
Lines[CellFocused.Row+1] := s1;
UpdateData;
CellFocused := GridCell(CellFocused.Col, CellFocused.Row+1);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_Forms;
{$I FMX_Defines.inc}
{$MINENUMSIZE 4}
{$H+}
{$IFDEF MSWINDOWS}
{$HPPEMIT '#pragma link "d3d10.lib"'}
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages,
{$ENDIF}
TypInfo, Math, Classes, SysUtils, Types, UITypes, FMX_Types, FMX_Types3D;
{$SCOPEDENUMS ON}
type
TCommonCustomForm = class;
{ Application }
TExceptionEvent = procedure(Sender: TObject; E: Exception) of object;
TIdleEvent = procedure(Sender: TObject; var Done: Boolean) of object;
TCreateFormRec = record
InstanceClass: TComponentClass;
Reference: Pointer;
end;
{ TApplication }
TApplication = class(TComponent)
private
FOnException: TExceptionEvent;
FRunning: Boolean;
FTerminate: Boolean;
FOnIdle: TIdleEvent;
FTitle: WideString;
FMainForm: TCommonCustomForm;
FCreateForms: array of TCreateFormRec;
FBiDiMode: TBiDiMode;
FApplicationMenuItems: IItemsContainer;
FStyleFileName: WideString;
FDefaultStyles: TFmxObject;
procedure Idle;
procedure SetStyleFileName(const Value: WideString);
procedure DestroyStyles;
protected
public
MainFormOnTaskBar: Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FormDestroyed(AForm: TCommonCustomForm);
procedure RealCreateForms;
procedure CreateForm(InstanceClass: TComponentClass; var Reference);
procedure ProcessMessages;
function DefaultStyles: TFmxObject;
procedure DoIdle(var Done: Boolean);
function HandleMessage: Boolean;
procedure Run;
procedure Terminate;
procedure Initialize;
procedure HandleException(Sender: TObject);
procedure ShowException(E: Exception);
property BiDiMode: TBiDiMode read FBiDiMode write FBiDiMode default bdLeftToRight;
property Terminated: Boolean read FTerminate write FTerminate;
property OnIdle: TIdleEvent read FOnIdle write FOnIdle;
property StyleFileName: WideString read FStyleFileName write SetStyleFileName;
property MainForm: TCommonCustomForm read FMainForm write FMainform;
property Title: WideString read FTitle write FTitle; // deprecated
property OnException: TExceptionEvent read FOnException write FOnException;
property ApplicationMenuItems: IItemsContainer read FApplicationMenuItems write FApplicationMenuItems;
end;
{ IDesignerHook }
{$IFDEF MSWINDOWS}
IDesignerHook = interface(IDesignerNotify)
['{7A314BFB-1AD5-476A-AD08-944B9F3444A6}']
function IsDesignMsg(Sender: TFmxObject; var Message: TMessage): Boolean;
procedure UpdateBorder;
procedure PaintGrid;
procedure ValidateRename(AComponent: TComponent;
const CurName, NewName: String);
function UniqueName(const BaseName: WideString): WideString;
function GetRoot: TComponent;
end;
{$ELSE}
IDesignerHook = interface
end;
{$ENDIF}
{ Forms }
TCloseEvent = procedure(Sender: TObject; var Action: TCloseAction) of object;
TCloseQueryEvent = procedure(Sender: TObject; var CanClose: Boolean) of object;
TFmxFormBorderStyle = (bsNone, bsSingle, bsSizeable, bsToolWindow, bsSizeToolWin);
TFmxFormState = (fsRecreating, fsModal);
TFmxFormStates = set of TFmxFormState;
TFormPosition = (poDesigned, poDefault, poDefaultPosOnly, poDefaultSizeOnly,
poScreenCenter, poDesktopCenter, poMainFormCenter, poOwnerFormCenter);
{ TCommonCustomForm }
TCommonCustomForm = class(TFmxObject, IRoot, IContainerObject, IAlignRoot)
private
FDesigner: IDesignerHook;
FCaption: WideString;
FLeft: Integer;
FTop: Integer;
FOnClose: TCloseEvent;
FOnCloseQuery: TCloseQueryEvent;
FTransparency: Boolean;
FHandle: TFmxHandle;
FContextHandle: THandle;
FBorderStyle: TFmxFormBorderStyle;
FBorderIcons: TBorderIcons;
FVisible: Boolean;
FTopMost: Boolean;
FOnActivate: TNotifyEvent;
FOnDeactivate: TNotifyEvent;
FShowActivated: Boolean;
FModalResult: TModalResult;
FFormState: TFmxFormStates;
FStaysOpen: Boolean;
FBiDiMode: TBiDiMode;
FActive: Boolean;
FOnCreate: TNotifyEvent;
FOnDestroy: TNotifyEvent;
FOnResize: TNotifyEvent;
FTarget: IControl;
FHovered, FCaptured, FFocused: IControl;
FMousePos, FDownPos, FResizeSize, FDownSize: TPointF;
FDragging, FResizing: Boolean;
FActiveControl: TStyledControl;
FHeight: Integer;
FWidth: Integer;
FCursor: TCursor;
FPosition: TFormPosition;
FWindowState: TWindowState;
FLastWidth, FLastHeight: single;
FDisableAlign: Boolean;
FMargins: TBounds;
FUpdating: Integer;
FOnMouseDown: TMouseEvent;
FOnMouseMove: TMouseMoveEvent;
FOnMouseUp: TMouseEvent;
FOnMouseWheel: TMouseWheelEvent;
FOnKeyDown: TKeyEvent;
FOnKeyUp: TKeyEvent;
procedure SetDesigner(ADesigner: IDesignerHook);
procedure SetLeft(const Value: Integer);
procedure SetTop(const Value: Integer);
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
procedure SetCaption(const Value: WideString);
function GetClientHeight: Integer;
function GetClientWidth: Integer;
procedure SetTransparency(const Value: Boolean);
procedure SetBorderStyle(const Value: TFmxFormBorderStyle);
procedure SetBorderIcons(const Value: TBorderIcons);
procedure SetVisible(const Value: Boolean);
procedure SetTopMost(const Value: Boolean);
procedure SetClientHeight(const Value: Integer);
procedure SetClientWidth(const Value: Integer);
procedure SetBiDiMode(const Value: TBiDiMode);
procedure SetCursor(const Value: TCursor);
procedure SetPosition(const Value: TFormPosition);
procedure SetWindowState(const Value: TWindowState);
function GetLeft: Integer;
function GetTop: Integer;
procedure MarginsChanged(Sender: TObject);
protected
function GetBackIndex: Integer; override;
procedure InvalidateRect(R: TRectF);
procedure Realign; virtual;
procedure Recreate; virtual;
procedure MouseCapture;
procedure ReleaseCapture;
procedure SetActive(const Value: Boolean); virtual;
procedure DefineProperties(Filer: TFiler); override;
function FindTarget(P: TPointF; const Data: TDragObject): IControl; virtual;
{$IFNDEF FPC}
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; override;
{$ENDIF}
{ Handle }
procedure CreateHandle; virtual;
procedure DestroyHandle; virtual;
procedure ResizeHandle; virtual;
{ IRoot }
function GetObject: TFmxObject;
function GetActiveControl: TStyledControl;
procedure SetActiveControl(AControl: TStyledControl);
procedure SetCaptured(const Value: IControl);
procedure SetFocused(const Value: IControl);
function GetCaptured: IControl;
function GetFocused: IControl;
function GetBiDiMode: TBiDiMode;
procedure BeginInternalDrag(Source: TObject; ABitmap: TBitmap);
{ TFmxObject }
procedure FreeNotification(AObject: TObject); override;
{ TComponent }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ValidateRename(AComponent: TComponent; const CurName, NewName: String); override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
{ IContainerObject }
function GetContainerWidth: Single;
function GetContainerHeight: Single;
public
constructor Create(AOwner: TComponent); override;
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); virtual;
destructor Destroy; override;
procedure InitializeNewForm; virtual;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure AddObject(AObject: TFmxObject); override;
{ children }
function ObjectAtPoint(P: TPointF): IControl; virtual;
procedure PaintRects(const UpdateRects: array of TRectF); virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual;
procedure MouseMove(Shift: TShiftState; X, Y: Single); virtual;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); virtual;
procedure MouseLeave; virtual;
procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); virtual;
procedure KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); virtual;
// function GetImeWindowRect: TRectF; virtual;
procedure Activate;
procedure Deactivate;
procedure DragEnter(const Data: TDragObject; const Point: TPointF); virtual;
procedure DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); virtual;
procedure DragDrop(const Data: TDragObject; const Point: TPointF); virtual;
procedure DragLeave; virtual;
procedure EnterMenuLoop;
{ manully start }
procedure StartWindowDrag; virtual;
procedure StartWindowResize; virtual;
{ settings }
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); virtual;
function ClientToScreen(const Point: TPointF): TPointF;
function ScreenToClient(const Point: TPointF): TPointF;
function CloseQuery: Boolean; virtual;
function ClientRect: TRectF;
procedure Release;
procedure Close;
procedure Show;
procedure Hide;
function ShowModal: TModalResult;
procedure CloseModal;
procedure Invalidate;
procedure BeginUpdate;
procedure EndUpdate;
property Handle: TFmxHandle read FHandle write FHandle;
property ContextHandle: THandle read FContextHandle write FContextHandle;
property ModalResult: TModalResult read FModalResult write FModalResult;
property FormState: TFmxFormStates read FFormState;
property Designer: IDesignerHook read FDesigner write SetDesigner;
{ IRoot }
property Captured: IControl read FCaptured;
property Focused: IControl read FFocused write SetFocused;
property Hovered: IControl read FHovered;
property Active: Boolean read FActive;
property BiDiMode: TBiDiMode read GetBiDiMode write SetBiDiMode default bdLeftToRight;
property Caption: WideString read FCaption write SetCaption;
property Cursor: TCursor read FCursor write SetCursor default crDefault;
property BorderStyle: TFmxFormBorderStyle read FBorderStyle write SetBorderStyle
default TFmxFormBorderStyle.bsSizeable;
property BorderIcons: TBorderIcons read FBorderIcons write SetBorderIcons
default [TBorderIcon.biSystemMenu, TBorderIcon.biMinimize, TBorderIcon.biMaximize];
property ClientHeight: Integer read GetClientHeight write SetClientHeight;
property ClientWidth: Integer read GetClientWidth write SetClientWidth;
property Margins: TBounds read FMargins write FMargins;
property Position: TFormPosition read FPosition write SetPosition default TFormPosition.poDefaultPosOnly;
property Width: Integer read FWidth write SetWidth stored False;
property Height: Integer read FHeight write SetHeight stored False;
property ShowActivated: Boolean read FShowActivated write FShowActivated default True;
property StaysOpen: Boolean read FStaysOpen write FStaysOpen default True;
property Transparency: Boolean read FTransparency write SetTransparency default False;
property TopMost: Boolean read FTopMost write SetTopMost default False;
property Visible: Boolean read FVisible write SetVisible default True;
property WindowState: TWindowState read FWindowState write SetWindowState default TWindowState.wsNormal;
property OnCreate: TNotifyEvent read FOnCreate write FOnCreate;
property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy;
property OnClose: TCloseEvent read FOnClose write FOnClose;
property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery write FOnCloseQuery;
property OnActivate: TNotifyEvent read FOnActivate write FOnActivate;
property OnDeactivate: TNotifyEvent read FOnDeactivate write FOnDeactivate;
property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown;
property OnKeyUp: TKeyEvent read FOnKeyUp write FOnKeyUp;
property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown;
property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove;
property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp;
property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
published
property Left: Integer read GetLeft write SetLeft;
property Top: Integer read GetTop write SetTop;
end;
{ TCustomForm }
TCustomForm = class(TCommonCustomForm, IScene)
private
FCanvas: TCanvas;
FFill: TBrush;
FDrawing: Boolean;
FStyleBook: TStyleBook;
FUpdateRects: array of TRectF;
FStyleLookup: WideString;
FNeedStyleLookup: Boolean;
FResourceLink: TControl;
FOnPaint: TOnPaintEvent;
procedure SetFill(const Value: TBrush);
procedure FillChanged(Sender: TObject);
{ IScene }
function GetCanvas: TCanvas;
function GetUpdateRectsCount: Integer;
function GetUpdateRect(const Index: Integer): TRectF;
function GetTransparency: Boolean;
function GetStyleBook: TStyleBook;
procedure SetStyleBook(const Value: TStyleBook);
function GetAnimatedCaret: Boolean;
function LocalToScreen(P: TPointF): TPointF;
function ScreenToLocal(P: TPointF): TPointF;
procedure SetStyleLookup(const Value: WideString);
procedure AddUpdateRect(R: TRectF);
protected
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{ TForm }
procedure ApplyStyleLookup; virtual;
{ }
procedure DoPaint(const Canvas: TCanvas; const ARect: TRectF); virtual;
{ resources }
function GetStyleObject: TControl;
{ Handle }
procedure CreateHandle; override;
procedure DestroyHandle; override;
procedure ResizeHandle; override;
{ inherited }
procedure Realign; override;
procedure PaintRects(const UpdateRects: array of TRectF); override;
// function GetImeWindowRect: TRectF; override;
public
constructor Create(AOwner: TComponent); override;
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
destructor Destroy; override;
procedure InitializeNewForm; override;
procedure AddObject(AObject: TFmxObject); override;
procedure UpdateStyle; override;
property Canvas: TCanvas read FCanvas;
property Fill: TBrush read FFill write SetFill;
property StyleBook: TStyleBook read FStyleBook write SetStyleBook;
property ActiveControl: TStyledControl read GetActiveControl write SetActiveControl;
property StyleLookup: WideString read FStyleLookup write SetStyleLookup;
property OnPaint: TOnPaintEvent read FOnPaint write FOnPaint;
end;
TForm = class(TCustomForm)
published
property BiDiMode;
property Caption;
property Cursor default crDefault;
property BorderStyle default TFmxFormBorderStyle.bsSizeable;
property BorderIcons default [TBorderIcon.biSystemMenu, TBorderIcon.biMinimize, TBorderIcon.biMaximize];
property ClientHeight;
property ClientWidth;
property Left;
property Top;
property Margins;
property Position default TFormPosition.poDefaultPosOnly;
property Width;
property Height;
property ShowActivated default True;
property StaysOpen default True;
property Transparency;
property TopMost default False;
property Visible;
property WindowState default TWindowState.wsNormal;
property OnCreate;
property OnDestroy;
property OnClose;
property OnCloseQuery;
property OnActivate;
property OnDeactivate;
property OnKeyDown;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
property Fill;
property StyleBook;
property ActiveControl;
property StyleLookup;
property OnPaint;
end;
TCustomForm3D = class(TCommonCustomForm, IViewport3D)
private
FContext: TContext3D;
FCamera: TCamera;
FLights: TList;
FDesignCamera: TCamera;
FDesignCameraZ: TDummy;
FDesignCameraX: TDummy;
FDesignGrid: TControl3D;
FFill: TAlphaColor;
FMultisample: TMultisample;
FUsingDesignCamera: Boolean;
FDrawing: Boolean;
FOnRender: TRenderEvent;
FEffectBitmap: TBitmap;
procedure SetFill(const Value: TAlphaColor);
procedure SetMultisample(const Value: TMultisample);
function GetFill: TAlphaColor;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{ Handle }
procedure CreateHandle; override;
procedure DestroyHandle; override;
procedure ResizeHandle; override;
{ inherited }
procedure Realign; override;
procedure PaintRects(const UpdateRects: array of TRectF); override;
function ObjectAtPoint(P: TPointF): IControl; override;
function FindTarget(P: TPointF; const Data: TDragObject): IControl; override;
{ IViewport3D }
function GetObject: TFmxObject;
function GetContext: TContext3D;
function GetScene: IScene;
function GetDesignCamera: TCamera;
procedure SetDesignCamera(const ACamera: TCamera);
procedure NeedRender;
{ }
function ScreenToLocal(P: TPointF): TPointF;
function LocalToScreen(P: TPointF): TPointF;
public
constructor Create(AOwner: TComponent); override;
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
destructor Destroy; override;
procedure InitializeNewForm; override;
procedure AddObject(AObject: TFmxObject); override;
procedure RemoveObject(AObject: TFmxObject); override;
property Context: TContext3D read FContext write FContext;
property Multisample: TMultisample read FMultisample write SetMultisample default TMultisample.ms4Samples;
property Color: TAlphaColor read GetFill write SetFill default TAlphaColors.White;
property Camera: TCamera read FCamera write FCamera;
property UsingDesignCamera: Boolean read FUsingDesignCamera write FUsingDesignCamera default True;
property OnRender: TRenderEvent read FOnRender write FOnRender;
end;
TForm3D = class(TCustomForm3D)
published
property BiDiMode;
property Caption;
property Cursor default crDefault;
property BorderStyle default TFmxFormBorderStyle.bsSizeable;
property BorderIcons default [TBorderIcon.biSystemMenu, TBorderIcon.biMinimize, TBorderIcon.biMaximize];
property ClientHeight;
property ClientWidth;
property Left;
property Top;
property Margins;
property Position default TFormPosition.poDefaultPosOnly;
property Width;
property Height;
property ShowActivated default True;
property StaysOpen default True;
property Transparency;
property TopMost default False;
property Visible;
property WindowState default TWindowState.wsNormal;
property OnCreate;
property OnDestroy;
property OnClose;
property OnCloseQuery;
property OnActivate;
property OnDeactivate;
property OnKeyDown;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
property Multisample default TMultisample.ms4Samples;
property Color default TAlphaColors.White;
property Camera;
property UsingDesignCamera default True;
property OnRender;
end;
TScreen = class(TComponent)
private
FManagingDataModules: Boolean;
FForms: TList;
FDataModules: TList;
procedure AddDataModule(DataModule: TDataModule);
procedure AddForm(AForm: TCommonCustomForm);
function GetForm(Index: Integer): TCommonCustomForm;
function GetFormCount: Integer;
procedure RemoveDataModule(DataModule: TDataModule);
procedure RemoveForm(AForm: TCommonCustomForm);
function GetDataModule(Index: Integer): TDataModule;
function GetDataModuleCount: Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property FormCount: Integer read GetFormCount;
property Forms[Index: Integer]: TCommonCustomForm read GetForm;
property DataModuleCount: Integer read GetDataModuleCount;
property DataModules[Index: Integer]: TDataModule read GetDataModule;
end;
var
Screen: TScreen;
Application: TApplication;
implementation
uses
{$IFDEF MACOS}
Macapi.ObjectiveC,
{$ENDIF}
FMX_Dialogs, FMX_Platform, FMX_Menus, FMX_Objects3D, FMX_Layers3D;
procedure DoneApplication;
begin
Application.DestroyComponents;
Application.DestroyStyles;
end;
{ TApplication }
constructor TApplication.Create(AOwner: TComponent);
begin
inherited;
if not Assigned(Classes.ApplicationHandleException) then
Classes.ApplicationHandleException := HandleException;
if not Assigned(Classes.ApplicationShowException) then
Classes.ApplicationShowException := ShowException;
end;
procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
begin
SetLength(FCreateForms, Length(FCreateForms) + 1);
FCreateForms[High(FCreateForms)].InstanceClass := InstanceClass;
FCreateForms[High(FCreateForms)].Reference := @Reference;
end;
procedure TApplication.RealCreateForms;
var
Instance: TComponent;
I: Integer;
begin
// only one form are created
if Length(FCreateForms) > 0 then
begin
for I := 0 to High(FCreateForms) do
begin
Instance := TComponent(FCreateForms[I].InstanceClass.NewInstance);
TComponent(FCreateForms[I].Reference^) := Instance;
try
Instance.Create(Self);
except
TComponent(FCreateForms[I].Reference^) := nil;
raise;
end;
if (FMainForm = nil) and (Instance is TCommonCustomForm) then
begin
FMainForm := TCommonCustomForm(Instance);
FMainForm.Visible := True;
end;
end;
SetLength(FCreateForms, 0);
end;
end;
destructor TApplication.Destroy;
type
TExceptionEvent = procedure(E: Exception) of object;
var
P: TNotifyEvent;
E: TExceptionEvent;
begin
Classes.WakeMainThread := nil;
P := HandleException;
if @P = @Classes.ApplicationHandleException then
Classes.ApplicationHandleException := nil;
E := ShowException;
if @E = @Classes.ApplicationShowException then
Classes.ApplicationShowException := nil;
if FMainForm <> nil then
FMainForm.Free;
inherited;
end;
procedure TApplication.DestroyStyles;
begin
FreeAndNil(FDefaultStyles);
end;
procedure TApplication.FormDestroyed(AForm: TCommonCustomForm);
begin
if FMainForm = AForm then
FMainForm := nil;
end;
function IsClass(Obj: TObject; Cls: TClass): Boolean;
var
Parent: TClass;
begin
Parent := Obj.ClassType;
while (Parent <> nil) and (Parent.ClassName <> Cls.ClassName) do
Parent := Parent.ClassParent;
Result := Parent <> nil;
end;
procedure TApplication.HandleException(Sender: TObject);
var
O: TObject;
begin
O := ExceptObject;
if IsClass(O, Exception) then
begin
if not IsClass(O, EAbort) then
if Assigned(FOnException) then
FOnException(Sender, Exception(O))
else
ShowException(Exception(O));
end else
SysUtils.ShowException(O, ExceptAddr);
end;
function TApplication.DefaultStyles: TFmxObject;
var
S: TStream;
SR: TSearchRec;
begin
if FDefaultStyles = nil then
begin
if (FStyleFileName <> '') and FileExists(FStyleFileName) then
begin
S := TFileStream.Create(FStyleFileName, fmOpenRead);
try
FDefaultStyles := CreateObjectFromStream(nil, S);
finally
S.Free;
end;
// load custom styles
if FDefaultStyles <> nil then
if FindFirst(ChangeFileExt(FStyleFileName, '.*.Style'), $FFFF, SR) = 0 then
begin
try
repeat
S := TFileStream.Create(ExtractFilePath(FStyleFileName) + SR.Name, fmOpenRead);
try
MergeObjectFromStream(FDefaultStyles, S);
finally
S.Free;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
{ load default styles - important - because not default styles can be incomplete }
if (FDefaultStyles = nil) and FindRCData(HInstance, 'defaultstyle') then
begin
S := TResourceStream.Create(HInstance, 'defaultstyle', RT_RCDATA);
try
FDefaultStyles := CreateObjectFromStream(nil, S);
finally
S.Free;
end;
end;
end;
Result := FDefaultStyles;
end;
procedure TApplication.SetStyleFileName(const Value: WideString);
var
i: integer;
begin
if FStyleFileName <> Value then
begin
FStyleFileName := Value;
if FRunning then
begin
// Force loading in run-time only
FreeAndNil(FDefaultStyles);
DefaultStyles;
// Update forms
if SceneList <> nil then
for i := 0 to SceneList.Count - 1 do
IScene(SceneList[i]).UpdateStyle;
end;
end;
end;
procedure TApplication.ShowException(E: Exception);
var
Msg: WideString;
SubE: Exception;
begin
Msg := E.Message;
{$IFNDEF FPC}
while True do
begin
SubE := E.GetBaseException;
if SubE <> E then
begin
E := SubE;
if E.Message <> '' then
Msg := E.Message;
end
else
Break;
end;
{$ENDIF}
if (Msg <> '') and (Msg[Length(Msg)] > '.') then Msg := Msg + '.';
ShowMessage(Msg);
// MessageBox(PWideChar(Msg), PWideChar(GetTitle), MB_OK + MB_ICONSTOP);
end;
function TApplication.HandleMessage: Boolean;
begin
Result := Platform.HandleMessage;
if not Result then
Idle;
end;
procedure TApplication.DoIdle(var Done: Boolean);
begin
if Assigned(FOnIdle) then
FOnIdle(Self, Done);
end;
procedure TApplication.Idle;
var
Done: Boolean;
begin
Done := True;
try
DoIdle(Done);
if Done then
begin
// App idle
end;
except
HandleException(Self);
end;
{$IFDEF FPC}
if (GetCurrentThreadId = MainThreadID) and CheckSynchronize then
{$ELSE}
if (TThread.CurrentThread.ThreadID = MainThreadID) and CheckSynchronize then
{$ENDIF}
Done := False;
if Done then
Platform.WaitMessage;
end;
procedure TApplication.Run;
begin
FRunning := True;
AddExitProc(DoneApplication);
try
Platform.Run;
finally
FRunning := False;
end;
end;
procedure TApplication.Terminate;
begin
// Terminated is set to true in Platform.Terminate
if CallTerminateProcs then
Platform.Terminate;
end;
procedure TApplication.Initialize;
begin
if InitProc <> nil then TProcedure(InitProc);
end;
procedure TApplication.ProcessMessages;
begin
while Platform.HandleMessage do { loop };
end;
{ TCustomCommonForm }
constructor TCommonCustomForm.Create(AOwner: TComponent);
begin
GlobalNameSpace.BeginWrite;
try
inherited;
InitializeNewForm;
if (ClassType <> TCommonCustomForm) and not(csDesigning in ComponentState) then
begin
if not InitInheritedComponent(Self, TCommonCustomForm) then
raise EResNotFound.Create('Resource not found ' + ClassName);
end;
finally
GlobalNameSpace.EndWrite;
end;
end;
constructor TCommonCustomForm.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited Create(AOwner);
InitializeNewForm;
end;
procedure TCommonCustomForm.InitializeNewForm;
begin
FUpdating := 0;
{$IFNDEF FMI}
FWidth := 600;
FHeight := 400;
{$ELSE}
FWidth := 320;
FHeight := 480;
{$ENDIF}
FMargins := TBounds.Create(RectF(0, 0, 0, 0));
FMargins.OnChange := MarginsChanged;
FBorderIcons := [TBorderIcon.biSystemMenu, TBorderIcon.biMinimize, TBorderIcon.biMaximize];
FBorderStyle := TFmxFormBorderStyle.bsSizeable;
FShowActivated := True;
FStaysOpen := True;
FPosition := TFormPosition.poDefaultPosOnly;
CreateHandle;
Screen.AddForm(Self);
end;
destructor TCommonCustomForm.Destroy;
begin
Application.FormDestroyed(Self);
if FTarget <> nil then
begin
FTarget.RemoveFreeNotify(Self);
FTarget := nil;
end;
if FHovered <> nil then
begin
FHovered.RemoveFreeNotify(Self);
FHovered := nil;
end;
if FFocused <> nil then
begin
FFocused.RemoveFreeNotify(Self);
FFocused := nil;
end;
if FCaptured <> nil then
begin
FCaptured.RemoveFreeNotify(Self);
FCaptured := nil;
end;
FMargins.Free;
DestroyHandle;
Screen.RemoveForm(Self);
inherited;
end;
procedure TCommonCustomForm.CreateHandle;
begin
FHandle := Platform.CreateWindow(Self);
if TFmxFormState.fsRecreating in FormState then
Platform.SetWindowRect(Self, RectF(Left, Top, Left + Width, Top + Height));
end;
procedure TCommonCustomForm.DestroyHandle;
begin
Platform.DestroyWindow(Self);
end;
procedure TCommonCustomForm.AfterConstruction;
begin
inherited;
if Assigned(FOnCreate) then
FOnCreate(Self);
end;
procedure TCommonCustomForm.BeforeDestruction;
begin
if Assigned(FOnDestroy) then
FOnDestroy(Self);
inherited;
end;
procedure TCommonCustomForm.MarginsChanged(Sender: TObject);
begin
Realign;
end;
procedure TCommonCustomForm.Realign;
begin
end;
procedure TCommonCustomForm.Recreate;
begin
if (csDesigning in ComponentState) or (FUpdating > 0) then Exit;
FFormState := FFormState + [TFmxFormState.fsRecreating];
DestroyHandle;
CreateHandle;
if Visible then
Platform.ShowWindow(Self);
FFormState := FFormState - [TFmxFormState.fsRecreating];
end;
procedure TCommonCustomForm.PaintRects(const UpdateRects: array of TRectF);
begin
end;
{$IFNDEF FPC}
function TCommonCustomForm.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
// Route the QueryInterface through the Designer first
if (Designer = nil) or (Designer.QueryInterface(IID, Obj) <> 0) then
Result := inherited QueryInterface(IID, Obj)
else
Result := 0;
end;
{$ENDIF}
function TCommonCustomForm.CloseQuery: Boolean;
begin
Result := True;
if Assigned(FOnCloseQuery) then
FOnCloseQuery(Self, Result);
end;
procedure TCommonCustomForm.Close;
var
CloseAction: TCloseAction;
begin
if TFmxFormState.fsModal in FFormState then
ModalResult := mrCancel
else if CloseQuery then
begin
CloseAction := TCloseAction.caHide;
if Assigned(FOnClose) then
FOnClose(Self, CloseAction);
if CloseAction <> TCloseAction.caNone then
if Application.MainForm = Self then
Application.Terminate
else if CloseAction = TCloseAction.caHide then
Hide
else if CloseAction = TCloseAction.caMinimize then
// WindowState := wsMinimized
else
Release;
end;
end;
procedure TCommonCustomForm.Show;
begin
if not (csDesigning in ComponentState) then
begin
case FPosition of
TFormPosition.poScreenCenter:
begin
with Platform.GetScreenSize do
SetBounds(System.Round((X - Width) / 2), System.Round((Y - Height) / 2), Width, Height);
end;
end;
end;
Platform.ShowWindow(Self);
FVisible := True;
end;
procedure TCommonCustomForm.Hide;
begin
Platform.HideWindow(Self);
FVisible := False;
end;
function TCommonCustomForm.ShowModal: TModalResult;
begin
FFormState := FFormState + [TFmxFormState.fsModal];
Result := Platform.ShowWindowModal(Self);
FFormState := FFormState - [TFmxFormState.fsModal];
// recreate the underlying WinApi handle in order to make the window
// unowned; the recreation cannot be done in Platform.ShowWindowModal because
// the parent of the window is chosen depending on fsModal in FormState and
// inside the ShowWindowModal call fsModal is set - which is not what we need
if not (csDestroying in ComponentState) then
Recreate;
end;
procedure TCommonCustomForm.CloseModal;
var
CloseAction: TCloseAction;
begin
try
CloseAction := TCloseAction.caNone;
if CloseQuery then
begin
CloseAction := TCloseAction.caHide;
if Assigned(FOnClose) then
FOnClose(Self, CloseAction);
end;
case CloseAction of
TCloseAction.caNone:
ModalResult := mrNone;
TCloseAction.caFree:
Release;
end;
except
ModalResult := mrNone;
Application.HandleException(Self);
end;
end;
procedure TCommonCustomForm.Release;
begin
Platform.ReleaseWindow(Self);
end;
procedure TCommonCustomForm.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
NR, PR: TRectF;
SizeChanged: Boolean;
begin
if (ALeft <> FLeft) or (ATop <> FTop) or (AWidth <> FWidth) or (AHeight <> FHeight) then
begin
SizeChanged := (AWidth <> FWidth) or (AHeight <> FHeight);
FTop := ATop;
FLeft := ALeft;
FWidth := AWidth;
FHeight := AHeight;
NR := RectF(FLeft, FTop, FLeft + FWidth, FTop + FHeight);
// This procedure can be called by the platform in response to a change coming
// from another source. Check to see if the actual size reported by the
// platform indicates we actually need to change the value;
PR := Platform.GetWindowRect(Self);
if not EqualRect(PR, NR) then
begin
Platform.SetWindowRect(Self, NR);
end;
if SizeChanged or (csDesigning in ComponentState) then
ResizeHandle;
if Assigned(FOnResize) then
FOnResize(Self);
end;
end;
function IsDialogKey(Key: Word): boolean;
begin
Result:= True;
if {(key in [vkF1..vkF24]) or }(Key = vkCapital) or (Key = vkSnapshot) or
(Key = vkPause) or (Key = vkScroll) or (Key = vkMenu) or (Key = vkLWin) or (Key = vkRWin) or (key = 0) then
Result:= False;
end;
procedure TCommonCustomForm.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
var
List: TList;
i, CurIdx: Integer;
K: Word;
Ch: System.WideChar;
TabDirection : Integer;
begin
{ dialog key }
if IsDialogKey(Key) then
begin
for i := ChildrenCount - 1 downto 0 do
begin
if Children[i].IsIControl then
Children[i].AsIControl.DialogKey(Key, Shift)
else
if Children[i] is TMainMenu then
TMainMenu(Children[i]).DialogKey(Key, Shift)
else if Children[i] is TPopupMenu then
TPopupMenu(Children[i]).DialogKey(Key, Shift);
if Key = 0 then
Exit;
end;
if Key = 0 then
Exit;
end;
{ change focus }
if (Key = vkTab) then
begin
Key := 0;
List := TList.Create;
GetTabOrderList(List, True);
if ssShift in Shift then
TabDirection := -1
else
TabDirection := 1;
CurIdx := List.IndexOf(Pointer(FFocused));
for i := 0 to List.Count-1 do
begin
Inc(CurIdx, TabDirection);
if (TabDirection > 0) and (CurIdx >= List.Count) then
CurIdx := 0
else
if (TabDirection < 0) and (CurIdx < 0) then
CurIdx := List.Count - 1;
if IControl(List[CurIdx]).CheckForAllowFocus then
begin
IControl(List[CurIdx]).SetFocus;
break;
end;
end;
List.Free;
Exit;
end;
{ focused handler }
if FFocused <> nil then
FFocused.KeyDown(Key, KeyChar, Shift);
if Assigned(FOnKeyDown) and ((Key <> 0) or (KeyChar <> #0)) then
FOnKeyDown(Self, Key, KeyChar, Shift);
end;
procedure TCommonCustomForm.KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
begin
{ focused handler }
if FFocused <> nil then
FFocused.KeyUp(Key, KeyChar, Shift);
if Assigned(FOnKeyUp) and ((Key <> 0) or (KeyChar <> #0)) then
FOnKeyUp(Self, Key, KeyChar, Shift);
end;
function TCommonCustomForm.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
begin
Result := NewObj;
Exit;
end;
end;
end;
procedure TCommonCustomForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
R: TRectF;
Obj: IControl;
SG: ISizeGrip;
NewCursor: TCursor;
i: Integer;
begin
{ translate coord }
FMousePos := PointF(X, Y);
FDownPos := FMousePos;
if Assigned(FOnMouseDown) then
FOnMouseDown(Self, Button, Shift, X, Y);
Obj := IControl(ObjectAtPoint(ClientToScreen(FMousePos)));
if (Obj <> nil) then
if (IInterface(Obj).QueryInterface(ISizeGrip, SG) = 0) then
StartWindowResize
else
begin
P := Obj.ScreenToLocal(ClientToScreen(PointF(FMousePos.X, FMousePos.Y)));
Obj.MouseDown(Button, Shift, P.X, P.Y);
if (Obj.DragMode = TDragMode.dmAutomatic) then
Obj.BeginAutoDrag;
NewCursor := Obj.Cursor;
end
else // use the form cursor only if no control has been clicked
NewCursor := Cursor;
Platform.SetCursor(Self, NewCursor);
end;
procedure TCommonCustomForm.MouseLeave;
begin
MouseMove([], -1, -1);
end;
procedure TCommonCustomForm.MouseMove(Shift: TShiftState; X, Y: Single);
var
R: TRectF;
P, P1: TPointF;
Obj: IControl;
SG: ISizeGrip;
NewCursor: TCursor;
begin
NewCursor := Cursor;
{ drag }
if FDragging then
begin
SetBounds(round(Left + (X - FDownPos.X)), round(Top + (Y - FDownPos.Y)), Width, Height);
Exit;
end;
if FResizing then
begin
FResizeSize.X := round(FResizeSize.X + (X - FMousePos.X));
FResizeSize.Y := round(FResizeSize.Y + (Y - FMousePos.Y));
SetBounds(Left, Top, round(FResizeSize.X), round(FResizeSize.Y));
Cursor := crSizeNWSE;
FMousePos := PointF(X, Y);
Exit;
end;
if Assigned(FOnMouseMove) then
FOnMouseMove(Self, Shift, X, Y);
{ translate coord }
FMousePos := PointF(X, Y);
if (FCaptured <> nil) then
begin
if ((FCaptured.QueryInterface(ISizeGrip, SG) = 0) and Assigned(SG)) then
Platform.SetCursor(Self, crSizeNWSE)
else
Platform.SetCursor(Self, FCaptured.Cursor);
P := FCaptured.ScreenToLocal(ClientToScreen(PointF(FMousePos.X, FMousePos.Y)));
FCaptured.MouseMove(Shift, P.X, P.Y);
Exit;
end;
Obj := ObjectAtPoint(ClientToScreen(FMousePos));
if (Obj <> nil) then
begin
if (Obj <> FHovered) then
begin
if FHovered <> nil then
begin
FHovered.DoMouseLeave;
FHovered.RemoveFreeNotify(Self);
end;
FHovered := Obj;
FHovered.DoMouseEnter;
FHovered.AddFreeNotify(Self);
end;
P := Obj.ScreenToLocal(ClientToScreen(PointF(FMousePos.X, FMousePos.Y)));
Obj.MouseMove(Shift, P.X, P.Y);
if ((Obj.QueryInterface(ISizeGrip, SG) = 0) and Assigned(SG)) then
NewCursor := crSizeNWSE
else
NewCursor := Obj.Cursor;
end
else
begin
if FHovered <> nil then
begin
FHovered.DoMouseLeave;
FHovered.RemoveFreeNotify(Self);
FHovered := nil;
end;
end;
// set cursor
Platform.SetCursor(Self, NewCursor);
FDownPos := FMousePos;
end;
procedure TCommonCustomForm.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
Obj: IControl;
NewCursor: TCursor;
begin
{ drag }
if FDragging then
begin
FDragging := False;
ReleaseCapture;
end;
if FResizing then
begin
FResizing := False;
ReleaseCapture;
end;
if (FCaptured <> nil) then
begin
P := FCaptured.ScreenToLocal(ClientToScreen(PointF(FMousePos.X, FMousePos.Y)));
FCaptured.MouseUp(Button, Shift, P.X, P.Y);
ReleaseCapture;
Exit;
end;
if Assigned(FOnMouseUp) then
FOnMouseUp(Self, Button, Shift, X, Y);
Obj := ObjectAtPoint(ClientToScreen(FMousePos));
if (Obj <> nil) then
begin
P := Obj.ScreenToLocal(ClientToScreen(PointF(FMousePos.X, FMousePos.Y)));
Obj.MouseUp(Button, Shift, P.X, P.Y);
// we are over a control; use its cursor
NewCursor := Obj.Cursor;
end
else // the mouse is over the form; use the form cursor
NewCursor := Cursor;
// update the cursor
Platform.SetCursor(Self, NewCursor);
end;
procedure TCommonCustomForm.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
var
Obj: IControl;
MousePos: TPointF;
begin
MousePos := Platform.GetMousePos;
{ event }
if (FCaptured <> nil) then
begin
FCaptured.MouseWheel(Shift, WheelDelta, Handled);
Exit;
end;
if Assigned(FOnMouseWheel) then
FOnMouseWheel(Self, Shift, WheelDelta, Handled);
if not Handled then
begin
Obj := ObjectAtPoint(MousePos);
while (Obj <> nil) do
begin
Obj.MouseWheel(Shift, WheelDelta, Handled);
if Handled then
Break;
if (Obj.Parent <> nil) and (Obj.Parent.IsIControl) then
Obj := Obj.Parent.AsIControl
else
Obj := nil;
end;
end;
end;
procedure TCommonCustomForm.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
{$IFDEF WIN32}
if FDesigner <> nil then
FDesigner.Notification(AComponent, Operation);
{$ENDIF}
end;
procedure TCommonCustomForm.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
I: Integer;
OwnedComponent: TComponent;
begin
inherited GetChildren(Proc, Root);
if Root = Self then
for I := 0 to ComponentCount - 1 do
begin
OwnedComponent := Components[I];
if OwnedComponent is TFmxObject then
begin
if TFmxObject(OwnedComponent).Parent = nil then
Proc(OwnedComponent);
end
else
if not OwnedComponent.HasParent then Proc(OwnedComponent);
end;
end;
{ Drag and Drop }
function TCommonCustomForm.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
for i := 0 to ChildrenCount - 1 do
if Supports(Children[i], IControl, NewObj) and NewObj.Visible and NewObj.HitTest then
begin
NewObj := NewObj.FindTarget(P, Data);
if Assigned(NewObj) then
Exit(NewObj);
end;
end;
procedure TCommonCustomForm.FreeNotification(AObject: TObject);
begin
inherited ;
if (FHovered <> nil) and (FHovered.GetObject = AObject) then
FHovered := nil;
if (FTarget <> nil) and (FTarget.GetObject = AObject) then
FTarget := nil;
if (FCaptured <> nil) and (FCaptured.GetObject = AObject) then
FCaptured := nil;
if (FFocused <> nil) and (FFocused.GetObject = AObject) then
FFocused := nil;
end;
procedure TCommonCustomForm.DragDrop(const Data: TDragObject; const Point: TPointF);
begin
if FTarget <> nil then
FTarget.DragDrop(Data, FTarget.ScreenToLocal(Point));
end;
procedure TCommonCustomForm.DragEnter(const Data: TDragObject; const Point: TPointF);
var
NewTarget: IControl;
begin
NewTarget := FindTarget(Point, Data);
if (NewTarget <> FTarget) then
begin
if FTarget <> nil then
begin
FTarget.DragLeave;
FTarget.RemoveFreeNotify(Self);
end;
FTarget := NewTarget;
if FTarget <> nil then
begin
FTarget.AddFreeNotify(Self);
FTarget.DragEnter(Data, FTarget.ScreenToLocal(Point));
end;
end;
end;
procedure TCommonCustomForm.DragLeave;
begin
if FTarget <> nil then
begin
FTarget.DragLeave;
FTarget.RemoveFreeNotify(Self);
end;
FTarget := nil;
end;
procedure TCommonCustomForm.DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean);
var
NewTarget: IControl;
begin
NewTarget := FindTarget(Point, Data);
if (NewTarget <> FTarget) then
begin
if FTarget <> nil then
begin
FTarget.DragLeave;
FTarget.RemoveFreeNotify(Self);
end;
FTarget := NewTarget;
if FTarget <> nil then
begin
FTarget.AddFreeNotify(Self);
FTarget.DragEnter(Data, FTarget.ScreenToLocal(Point));
end;
end;
if FTarget <> nil then
FTarget.DragOver(Data, FTarget.ScreenToLocal(Point), Accept);
end;
procedure TCommonCustomForm.EndUpdate;
var
I: Integer;
begin
FUpdating := FUpdating - 1;
for I := 0 to ChildrenCount - 1 do
if (Children[I] is TControl) then
TControl(FChildren[I]).EndUpdate;
if FUpdating = 0 then
Recreate;
end;
procedure TCommonCustomForm.EnterMenuLoop;
var
List: TList;
i: Integer;
begin
List := TList.Create;
AddControlsToList(List);
for i := 0 to List.Count - 1 do
if (TStyledControl(List[i]) is TMenuBar) then
begin
TMenuBar(List[i]).StartMenuLoop;
Break;
end;
List.Free;
end;
procedure TCommonCustomForm.SetCaption(const Value: WideString);
begin
if FCaption <> Value then
begin
FCaption := Value;
Platform.SetWindowCaption(Self, FCaption);
{$IFDEF WIN32}
if (csDesigning in ComponentState) and (FDesigner <> nil) then
FDesigner.UpdateBorder;
{$ENDIF}
end;
end;
procedure TCommonCustomForm.SetHeight(const Value: Integer);
begin
SetBounds(Left, Top, Width, Value);
end;
procedure TCommonCustomForm.SetLeft(const Value: Integer);
begin
if (csDesigning in ComponentState) then
begin
DesignInfo := (DesignInfo and $FFFF0000) or (Cardinal(Value) and $FFFF);
if not (csLoading in ComponentState) and (Position <> TFormPosition.poDefaultSizeOnly) then
Position := TFormPosition.poDesigned;
end
else
SetBounds(Value, Top, Width, Height);
end;
procedure TCommonCustomForm.SetPosition(const Value: TFormPosition);
begin
if FPosition <> Value then
begin
FPosition := Value;
end;
end;
procedure TCommonCustomForm.SetTop(const Value: Integer);
begin
if (csDesigning in ComponentState) then
begin
DesignInfo := (DesignInfo and $0000FFFF) or (Value shl 16);
if not (csLoading in ComponentState) and (Position <> TFormPosition.poDefaultSizeOnly) then
Position := TFormPosition.poDesigned;
end
else
SetBounds(Left, Value, Width, Height);
end;
procedure TCommonCustomForm.SetWidth(const Value: Integer);
begin
SetBounds(Left, Top, Value, Height);
end;
procedure TCommonCustomForm.SetWindowState(const Value: TWindowState);
begin
if FWindowState <> Value then
begin
FWindowState := Value;
if not (csDesigning in ComponentState) then
Platform.SetWindowState(Self, FWindowState);
end;
end;
procedure TCommonCustomForm.MouseCapture;
begin
Platform.SetCapture(Self);
end;
procedure TCommonCustomForm.ReleaseCapture;
begin
Platform.ReleaseCapture(Self);
end;
procedure TCommonCustomForm.ResizeHandle;
begin
end;
procedure TCommonCustomForm.Invalidate;
begin
InvalidateRect(ClientRect);
end;
procedure TCommonCustomForm.InvalidateRect(R: TRectF);
begin
if csDestroying in ComponentState then
Exit;
Platform.InvalidateWindowRect(Self, R);
end;
function TCommonCustomForm.GetClientHeight: Integer;
begin
Result := round(Platform.GetClientSize(Self).Y);
end;
function TCommonCustomForm.GetClientWidth: Integer;
begin
Result := round(Platform.GetClientSize(Self).X);
end;
function TCommonCustomForm.GetContainerHeight: Single;
begin
Result := ClientHeight;
end;
function TCommonCustomForm.GetContainerWidth: Single;
begin
Result := ClientWidth;
end;
//function TCommonCustomForm.GetImeWindowRect: TRectF;
//begin
// Result := RectF(0, 0, ClientWidth, ClientHeight);
//end;
function TCommonCustomForm.GetTop: Integer;
begin
if (csDesigning in ComponentState) and (Parent <> nil) then
Result := SmallInt((DesignInfo and $FFFF0000) shr 16)
else
Result := FTop;
end;
function TCommonCustomForm.GetLeft: Integer;
begin
if (csDesigning in ComponentState) then
Result := SmallInt(DesignInfo and $0000FFFF)
else
Result := FLeft;
end;
procedure TCommonCustomForm.SetClientHeight(const Value: Integer);
begin
Platform.SetClientSize(Self, PointF(ClientWidth, Value));
end;
procedure TCommonCustomForm.SetClientWidth(const Value: Integer);
begin
Platform.SetClientSize(Self, PointF(Value, ClientHeight));
end;
procedure TCommonCustomForm.SetCursor(const Value: TCursor);
begin
FCursor := Value;
end;
procedure TCommonCustomForm.SetDesigner(ADesigner: IDesignerHook);
begin
FDesigner := ADesigner;
end;
procedure TCommonCustomForm.SetTransparency(const Value: Boolean);
begin
if FTransparency <> Value then
begin
FTransparency := Value;
Recreate;
end;
end;
procedure TCommonCustomForm.SetBorderStyle(const Value: TFmxFormBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
Recreate;
{$IFDEF WIN32}
if (csDesigning in ComponentState) and (FDesigner <> nil) then
FDesigner.UpdateBorder;
{$ENDIF}
end;
end;
procedure TCommonCustomForm.SetBiDiMode(const Value: TBiDiMode);
begin
FBiDiMode := Value;
end;
procedure TCommonCustomForm.SetBorderIcons(const Value: TBorderIcons);
begin
if FBorderIcons <> Value then
begin
FBorderIcons := Value;
Recreate;
{$IFDEF WIN32}
if (csDesigning in ComponentState) and (FDesigner <> nil) then
FDesigner.UpdateBorder;
{$ENDIF}
end;
end;
procedure TCommonCustomForm.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
if FVisible then
Show
else
Hide;
end;
end;
function TCommonCustomForm.ClientRect: TRectF;
begin
Result := RectF(0, 0, ClientWidth, ClientHeight);
end;
function TCommonCustomForm.ClientToScreen(const Point: TPointF): TPointF;
begin
Result := Platform.ClientToScreen(Self, Point);
end;
function TCommonCustomForm.ScreenToClient(const Point: TPointF): TPointF;
begin
Result := Platform.ScreenToClient(Self, Point);
end;
procedure TCommonCustomForm.SetTopMost(const Value: Boolean);
begin
if FTopMost <> Value then
begin
FTopMost := Value;
Recreate;
end;
end;
procedure TCommonCustomForm.Activate;
var
TSC: ITextServiceControl;
begin
if FFocused <> nil then
begin
if Supports(FFocused, ITextServiceControl, TSC) then
TSC.GetTextService.EnterControl(Handle);
end;
if Assigned(FOnActivate) then
FOnActivate(Self);
FActive := True;
end;
procedure TCommonCustomForm.Deactivate;
begin
if Assigned(FOnDeactivate) then
FOnDeactivate(Self);
FActive := False;
end;
procedure TCommonCustomForm.SetActive(const Value: Boolean);
begin
if FActive <> Value then
begin
FActive := Value;
end;
ApplyTriggerEffect(Self, 'IsActive');
StartTriggerAnimation(Self, 'IsActive');
end;
procedure TCommonCustomForm.DefineProperties(Filer: TFiler);
begin
inherited;
end;
procedure TCommonCustomForm.StartWindowDrag;
begin
if (csDesigning in ComponentState) then Exit;
FDragging := True;
FDownPos := FMousePos;
MouseCapture;
end;
procedure TCommonCustomForm.StartWindowResize;
begin
if (csDesigning in ComponentState) then Exit;
FResizing := True;
FDownPos := FMousePos;
FResizeSize := PointF(Width, Height);
FDownSize := FResizeSize;
MouseCapture;
end;
procedure TCommonCustomForm.ValidateRename(AComponent: TComponent; const CurName, NewName: String);
begin
inherited;
{$IFDEF WIN32}
if FDesigner <> nil then
FDesigner.ValidateRename(AComponent, CurName, NewName);
{$ENDIF}
end;
{ IRoot }
procedure TCommonCustomForm.AddObject(AObject: TFmxObject);
var
Obj: IAlignableObject;
begin
inherited;
if AObject = nil then Exit;
AObject.SetRoot(Self);
if Supports(AObject, IAlignableObject, Obj) then
begin
if (Obj.Align <> TAlignLayout.alNone) then
Realign
else
Invalidate;
end;
end;
function TCommonCustomForm.GetObject: TFmxObject;
begin
Result := Self;
end;
function TCommonCustomForm.GetActiveControl: TStyledControl;
begin
Result := FActiveControl;
end;
function TCommonCustomForm.GetBackIndex: Integer;
begin
Result := 1;
end;
function TCommonCustomForm.GetBiDiMode: TBiDiMode;
begin
Result := FBiDiMode;
end;
function TCommonCustomForm.GetCaptured: IControl;
begin
Result := FCaptured;
end;
procedure TCommonCustomForm.SetCaptured(const Value: IControl);
begin
if FCaptured <> Value then
begin
if FCaptured <> nil then
begin
ReleaseCapture;
FCaptured.RemoveFreeNotify(Self);
end;
FCaptured := Value;
if FCaptured <> nil then
begin
MouseCapture;
FCaptured.AddFreeNotify(Self);
end;
end;
end;
function TCommonCustomForm.GetFocused: IControl;
begin
Result := FFocused;
end;
procedure TCommonCustomForm.SetFocused(const Value: IControl);
var
TSControl: ITextServiceControl;
begin
if FFocused <> Value then
begin
if FFocused <> nil then
begin
FFocused.DoExit;
if Supports(FFocused, ITextServiceControl, TSControl) then
TSControl.GetTextService.ExitControl(Handle);
FFocused.RemoveFreeNotify(Self);
end;
FFocused := Value;
if FFocused <> nil then
begin
if Supports(FFocused, ITextServiceControl, TSControl) then
TSControl.GetTextService.EnterControl(Handle);
FFocused.DoEnter;
FFocused.AddFreeNotify(Self);
end;
end;
end;
procedure TCommonCustomForm.BeginInternalDrag(Source: TObject; ABitmap: FMX_Types.TBitmap);
var
D: TDragObject;
begin
Fillchar(D, SizeOf(D), 0);
D.Source := Source;
if Source is TFmxObject then
D.Data := TFmxObject(Source).Data;
Platform.BeginDragDrop(Self, D, ABitmap);
end;
procedure TCommonCustomForm.BeginUpdate;
var
I: Integer;
begin
FUpdating := FUpdating + 1;
for I := 0 to ChildrenCount - 1 do
if (Children[I] is TControl) then
TControl(FChildren[I]).BeginUpdate;
end;
procedure TCommonCustomForm.SetActiveControl(AControl: TStyledControl);
begin
if AControl <> FActiveControl then
begin
FActiveControl := AControl;
if (FActiveControl <> nil) and not(csLoading in ComponentState) then
FActiveControl.SetFocus;
end;
end;
{ TCustomForm }
procedure TCustomForm.InitializeNewForm;
begin
inherited;
AddScene(Self);
FStyleLookup := 'backgroundstyle';
FNeedStyleLookup := True;
FFill := TBrush.Create(TBrushKind.bkNone, TAlphaColors.White);
FFill.OnChanged := FillChanged;
end;
destructor TCustomForm.Destroy;
begin
RemoveScene(Self);
DeleteChildren;
if FChildren <> nil then
FreeAndNil(FChildren);
FreeAndNil(FFill);
inherited;
end;
// Required to force Delphi-style initialization when used from C++.
constructor TCustomForm.Create(AOwner: TComponent);
begin
inherited;
end;
constructor TCustomForm.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited;
end;
procedure TCustomForm.CreateHandle;
begin
inherited;
if DefaultCanvasClass <> nil then
FCanvas := DefaultCanvasClass.CreateFromWindow(Handle, ClientWidth, ClientHeight);
end;
procedure TCustomForm.DestroyHandle;
begin
FreeAndNil(FCanvas);
inherited;
end;
procedure TCustomForm.DoPaint(const Canvas: TCanvas; const ARect: TRectF);
begin
if Assigned(FOnPaint) then
FOnPaint(Self, Canvas, ClientRect);
end;
procedure TCustomForm.Loaded;
begin
inherited;
end;
procedure TCustomForm.AddUpdateRect(R: TRectF);
begin
if csLoading in ComponentState then
Exit;
if csDestroying in ComponentState then
Exit;
if not IntersectRect(R, RectF(0, 0, ClientWidth, ClientHeight)) then
Exit;
InvalidateRect(R);
end;
procedure TCustomForm.PaintRects(const UpdateRects: array of TRectF);
var
I, J: Integer;
R: TRectF;
CallOnPaint, AllowPaint: Boolean;
State: Pointer;
begin
if FDrawing then
Exit;
SetLength(FUpdateRects, Length(UpdateRects));
Move(UpdateRects[0], FUpdateRects[0], SizeOf(FUpdateRects[0]) * Length(FUpdateRects));
if Length(FUpdateRects) > 0 then
begin
FDrawing := True;
try
ApplyStyleLookup;
{ Split rects if rects too more }
if (Length(FUpdateRects) > 20) then
begin
for I := 1 to High(FUpdateRects) do
FUpdateRects[0] := UnionRect(FUpdateRects[0], FUpdateRects[I]);
SetLength(FUpdateRects, 1);
end;
{ draw back }
if Canvas.BeginScene(@FUpdateRects) then
try
if (FFill.Kind = TBrushKind.bkNone) or ((FFill.Color and $FF000000 = 0) and
(FFill.Kind = TBrushKind.bkSolid)) then
begin
for I := 0 to High(FUpdateRects) do
if Transparency then
Canvas.ClearRect(FUpdateRects[I], 0)
else
Canvas.ClearRect(FUpdateRects[I], FFill.Color and $FFFFFF);
end else
begin
if Transparency then
for I := 0 to High(FUpdateRects) do
Canvas.ClearRect(FUpdateRects[I], 0);
Canvas.Fill.Assign(FFill);
Canvas.FillRect(RectF(-1, -1, Width + 1, Height + 1), 0, 0, AllCorners, 1);
end;
{ children }
CallOnPaint := False;
for I := 0 to ChildrenCount - 1 do
if (Children[I] is TControl) and
((TControl(FChildren[I]).Visible) or (not TControl(FChildren[I]).Visible and (csDesigning in ComponentState) and not TControl(FChildren[I]).Locked)) then
with TControl(FChildren[I]) do
begin
if (Self.Children[I] = FResourceLink) then
begin
if Self.Transparency then Continue;
if (Self.Fill.Kind <> TBrushKind.bkNone) then Continue;
if (Self.Fill.Kind = TBrushKind.bkSolid) and (Self.Fill.Color <> Fill.DefaultColor) then Continue;
end;
if (csDesigning in ComponentState) and not DesignVisible then
Continue;
if (RectWidth(UpdateRect) = 0) or (RectHeight(UpdateRect) = 0) then
Continue;
AllowPaint := False;
if (csDesigning in ComponentState) or InPaintTo then
AllowPaint := True;
if not AllowPaint then
begin
R := UnionRect(ChildrenRect, UpdateRect);
for J := 0 to High(FUpdateRects) do
if IntersectRect(FUpdateRects[J], R) then
begin
AllowPaint := True;
Break;
end;
end;
if AllowPaint then
begin
if not HasAfterPaintEffect then
ApplyEffect;
Painting;
DoPaint;
AfterPaint;
if HasAfterPaintEffect then
ApplyEffect;
end;
{ Call OnPaint after style painted }
if (Self.Children[I] = FResourceLink) then
begin
Self.Canvas.SetMatrix(IdentityMatrix);
Self.DoPaint(Self.Canvas, ClientRect);
CallOnPaint := True;
end;
end;
{ Call OnPaint if style not loaded }
if not CallOnPaint then
begin
Canvas.SetMatrix(IdentityMatrix);
DoPaint(Canvas, ClientRect);
end;
{ draw grid }
{$IFDEF WIN32}
if (csDesigning in ComponentState) and (FDesigner <> nil) then
begin
Canvas.SetMatrix(IdentityMatrix);
FDesigner.PaintGrid;
end;
{$ENDIF}
finally
Canvas.EndScene;
end;
{ flush buffer }
if Canvas.Buffered then
for I := 0 to High(FUpdateRects) do
begin
R := FUpdateRects[I];
Canvas.FlushBufferRect(0, 0, ContextHandle, FUpdateRects[I]);
end;
finally
SetLength(FUpdateRects, 0);
FDrawing := False;
end;
end;
end;
procedure TCustomForm.Realign;
begin
AlignObjects(Self, FMargins, FCanvas.Width, FCanvas.Height, FLastWidth, FLastHeight, FDisableAlign);
InvalidateRect(ClientRect);
end;
procedure TCustomForm.AddObject(AObject: TFmxObject);
begin
inherited;
if AObject = nil then Exit;
if AObject is TControl then
TControl(AObject).SetNewScene(Self);
{ if (AObject is TControl) and (TControl(AObject).Align <> TAlignLayout.alNone) then
FNeedAlign := True;}
if (AObject is TControl) then
begin
TControl(AObject).RecalcOpacity;
TControl(AObject).RecalcAbsolute;
TControl(AObject).RecalcUpdateRect;
end;
end;
procedure TCustomForm.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FStyleBook) then
StyleBook := nil;
end;
procedure TCustomForm.SetFill(const Value: TBrush);
begin
FFill.Assign(Value);
end;
procedure TCustomForm.SetStyleLookup(const Value: WideString);
begin
FStyleLookup := Value;
FNeedStyleLookup := True;
if not (csLoading in ComponentState) then
begin
ApplyStyleLookup;
end;
end;
procedure TCustomForm.FillChanged(Sender: TObject);
begin
SetLength(FUpdateRects, 0);
AddUpdateRect(RectF(0, 0, ClientWidth, ClientHeight));
end;
function TCustomForm.GetCanvas: TCanvas;
begin
Result := FCanvas;
end;
function TCustomForm.GetUpdateRectsCount: Integer;
begin
Result := Length(FUpdateRects);
end;
function TCustomForm.GetUpdateRect(const Index: Integer): TRectF;
begin
Result := FUpdateRects[Index];
end;
//function TCustomForm.GetImeWindowRect: TRectF;
//begin
// if (FFocused <> nil) and (FFocused.GetObject is TControl) then
// begin
// Result := TControl(FFocused.GetObject).AbsoluteRect;
// end
// else
// Result := inherited GetImeWindowRect;
//end;
function TCustomForm.GetStyleObject: TControl;
var
Obj: TFmxObject;
ResourceObject: TControl;
S: TStream;
StyleName: WideString;
begin
ResourceObject := nil;
if (FStyleLookup <> '') then
begin
{ style }
Obj := nil;
if (FStyleBook <> nil) and (FStyleBook.Root <> nil) then
Obj := TControl(FStyleBook.Root.FindStyleResource(FStyleLookup));
if Obj = nil then
if Application.DefaultStyles <> nil then
Obj := TControl(Application.DefaultStyles.FindStyleResource(FStyleLookup));
if Obj = nil then
Obj := FMX_Types.FindStyleResource(FStyleLookup);
if (Obj <> nil) and (Obj is TControl) then
begin
ResourceObject := TControl(Obj.Clone(nil));
ResourceObject.StyleName := '';
end;
end;
if (ResourceObject = nil) and (Application.DefaultStyles <> nil) then
begin
if FStyleLookup <> '' then
begin
StyleName := FStyleLookup;
ResourceObject := TControl(FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
if ResourceObject = nil then
begin
StyleName := ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
if (ResourceObject = nil) and (Application.DefaultStyles <> nil) then
begin
if FStyleLookup <> '' then
begin
StyleName := FStyleLookup;
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
if ResourceObject = nil then
begin
StyleName := ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil))
else
begin
// try parent Class
StyleName := ClassParent.ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
end;
end;
end;
Result := ResourceObject;
end;
procedure TCustomForm.ApplyStyleLookup;
var
ResourceObject: TControl;
begin
if FNeedStyleLookup then
begin
FNeedStyleLookup := False;
ResourceObject := GetStyleObject;
if ResourceObject <> nil then
begin
if FResourceLink <> nil then
begin
FResourceLink.Free;
FResourceLink := nil;
end;
ResourceObject.Align := TAlignLayout.alContents;
ResourceObject.DesignVisible := True;
FResourceLink := ResourceObject;
AddObject(ResourceObject);
{ bring to front }
FChildren.Remove(ResourceObject);
FChildren.Insert(0, ResourceObject);
Realign;
{ }
ResourceObject.Stored := False;
ResourceObject.Lock;
end;
end;
end;
function TCustomForm.GetStyleBook: TStyleBook;
begin
Result := FStyleBook;
end;
function TCustomForm.GetTransparency: Boolean;
begin
Result := Transparency;
end;
procedure TCustomForm.UpdateStyle;
var
i: Integer;
begin
for i := 0 to ChildrenCount - 1 do
Children[i].UpdateStyle;
FNeedStyleLookup := True;
if not (csLoading in ComponentState) and not (csDestroying in ComponentState) then
ApplyStyleLookup;
end;
procedure TCustomForm.SetStyleBook(const Value: TStyleBook);
begin
if FStyleBook <> Value then
begin
if FStyleBook <> nil then
FStyleBook.RemoveSceneUpdater(Self);
FStyleBook := Value;
if FStyleBook <> nil then
FStyleBook.AddSceneUpdater(Self);
UpdateStyle;
end;
end;
function TCustomForm.GetAnimatedCaret: Boolean;
begin
Result := True;
end;
procedure TCustomForm.ResizeHandle;
begin
inherited;
if (Canvas <> nil) and (ClientWidth > 0) and (ClientHeight > 0) then
begin
Canvas.ResizeBuffer(ClientWidth, ClientHeight);
Realign;
end;
end;
function TCustomForm.ScreenToLocal(P: TPointF): TPointF;
begin
Result := ScreenToClient(P);
end;
function TCustomForm.LocalToScreen(P: TPointF): TPointF;
begin
Result := ClientToScreen(P);
end;
{ TCustomForm3D }
procedure TCustomForm3D.InitializeNewForm;
begin
FMultisample := TMultisample.ms4Samples;
inherited;
FUsingDesignCamera := True;
FFill := TAlphaColors.White;
FLights := TList.Create;
FDesignCameraZ := TDummy.Create(nil);
with FDesignCameraZ do
begin
Tag := $FFFE;
Locked := True;
Stored := False;
end;
AddObject(FDesignCameraZ);
FDesignCameraX := TDummy.Create(nil);
with FDesignCameraX do
begin
Tag := $FFFE;
Parent := FDesignCameraZ;
Locked := True;
Stored := False;
RotationAngle.X := -20;
end;
FDesignCamera := TCamera.Create(nil);
with FDesignCamera do
begin
Tag := $FFFE;
Parent := FDesignCameraX;
Locked := True;
Stored := False;
Position.Point := Point3D(0, 0, -20);
end;
end;
destructor TCustomForm3D.Destroy;
begin
FreeAndNil(FEffectBitmap);
FLights.Free;
DeleteChildren;
if (FContext <> nil) then
FreeAndNil(FContext);
if FChildren <> nil then
FreeAndNil(FChildren);
inherited;
end;
// Required to force Delphi-style initialization when used from C++.
constructor TCustomForm3D.Create(AOwner: TComponent);
begin
inherited;
end;
constructor TCustomForm3D.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited;
end;
procedure TCustomForm3D.CreateHandle;
begin
inherited;
if DefaultContextClass <> nil then
FContext := DefaultContextClass.CreateFromWindow(Handle, ClientWidth, ClientHeight, FMultisample, True);
end;
procedure TCustomForm3D.ResizeHandle;
begin
inherited;
if (Context <> nil) and (ClientWidth > 0) and (ClientHeight > 0) then
begin
Context.SetSize(ClientWidth, ClientHeight);
Realign;
end;
end;
procedure TCustomForm3D.DestroyHandle;
begin
FreeAndNil(FContext);
inherited;
end;
procedure TCustomForm3D.PaintRects(const UpdateRects: array of TRectF);
var
i: Integer;
Ver: TVertexBuffer;
Ind: TIndexBuffer;
begin
if Context = nil then
Exit;
if FDrawing then Exit;
FDrawing := True;
try
if Context.BeginScene then
try
{ set matrix and camera }
if Camera <> nil then
Context.SetCamera(Camera);
{ Design Camera }
if (csDesigning in ComponentState) or FUsingDesignCamera and (FDesignCamera <> nil) then
Context.SetCamera(FDesignCamera);
{ set states }
Context.ResetScene;
{ start }
Context.Clear([TClearTarget.ctColor, TClearTarget.ctDepth], FFill, 1.0, 0);
if Assigned(FOnRender) then
FOnRender(Self, Context);
if FChildren <> nil then
begin
for i := 0 to FChildren.Count - 1 do
begin
if not (TFmxObject(FChildren[i]) is TControl3D) then Continue;
if TControl3D(FChildren[i]).Visible or (not TControl3D(FChildren[i]).Visible and (csDesigning in TControl3D(FChildren[i]).ComponentState) and not TControl3D(FChildren[i]).Locked) then
begin
if not (TObject(FChildren[i]) is TControl3D) then
Continue;
if (csDesigning in ComponentState) and not TControl3D(FChildren[i]).DesignVisible then
Continue;
TControl3D(FChildren[i]).DoRender;
end;
end;
{ post-processing }
for i := 0 to FChildren.Count - 1 do
if (TFmxObject(FChildren[i]) is TEffect) and (TEffect(FChildren[i]).Enabled) then
begin
if FEffectBitmap = nil then
FEffectBitmap := TBitmap.Create(FContext.Width, FContext.Height);
FEffectBitmap.Assign(Context);
TEffect(FChildren[i]).ProcessEffect(nil, FEffectBitmap, 1);
// create quad
Ver := TVertexBuffer.Create([TVertexFormat.vfVertex, TVertexFormat.vfTexCoord0], 4);
with Context.PixelToPixelPolygonOffset do
begin
Ver.Vertices[0] := Point3D(X, Y, 0);
Ver.TexCoord0[0] := PointF(0.0, 0.0);
Ver.Vertices[1] := Point3D(FEffectBitmap.Width + X, Y, 0);
Ver.TexCoord0[1] := PointF(1.0, 0.0);
Ver.Vertices[2] := Point3D(FEffectBitmap.Width + X, FEffectBitmap.Height + Y, 0);
Ver.TexCoord0[2] := PointF(1.0, 1.0);
Ver.Vertices[3] := Point3D(X, FEffectBitmap.Height + Y, 0);
Ver.TexCoord0[3] := PointF(0.0, 1.0);
end;
Ind := TIndexBuffer.Create(6);
Ind[0] := 0;
Ind[1] := 1;
Ind[2] := 3;
Ind[3] := 3;
Ind[4] := 1;
Ind[5] := 2;
// params
Context.SetMatrix(IdentityMatrix3D);
Context.SetContextState(TContextState.cs2DScene);
Context.SetContextState(TContextState.csAllFace);
Context.SetContextState(TContextState.csLightOff);
Context.SetContextState(TContextState.csAlphaBlendOff);
Context.SetContextState(TContextState.csAlphaTestOff);
Context.SetContextState(TContextState.csZWriteOff);
Context.SetContextState(TContextState.csZTestOff);
Context.SetContextState(TContextState.csTexLinear);
Context.SetContextState(TContextState.csTexReplace);
// texture
Context.SetTextureUnit(0, FEffectBitmap);
// render quad
Context.DrawTrianglesList(Ver, Ind, 1);
Ind.Free;
Ver.Free;
end;
end;
finally
{ buffer }
Context.EndScene;
end;
finally
{ off flag }
FDrawing := False;
end;
end;
procedure TCustomForm3D.AddObject(AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
TControl3D(AObject).SetNewViewport(Self);
if (csDesigning in ComponentState) and (AObject is TCamera) and (AObject.Tag <> $FFFE) then
Camera := TCamera(AObject);
end;
procedure TCustomForm3D.RemoveObject(AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
TControl3D(AObject).SetNewViewport(nil);
end;
procedure TCustomForm3D.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FCamera) then
FCamera := nil;
end;
function TCustomForm3D.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
D: TObjectAtPointData;
begin
Result := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
Result := NewObj;
end;
if Result = nil then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
Result := NewObj;
end;
end;
end;
function TCustomForm3D.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
Result := NewObj;
end;
if Result = nil then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
Result := NewObj;
end;
end;
end;
function TCustomForm3D.GetFill: TAlphaColor;
begin
Result := FFill;
end;
procedure TCustomForm3D.SetFill(const Value: TAlphaColor);
begin
if FFill <> Value then
begin
FFill := Value;
NeedRender;
end;
end;
function TCustomForm3D.ScreenToLocal(P: TPointF): TPointF;
begin
Result := ScreenToClient(P);
end;
function TCustomForm3D.LocalToScreen(P: TPointF): TPointF;
begin
Result := ClientToScreen(P);
end;
procedure TCustomForm3D.SetMultisample(const Value: TMultisample);
begin
if FMultisample <> Value then
begin
FMultisample := Value;
Recreate;
end;
end;
{ IViewport3D }
function TCustomForm3D.GetObject: TFmxObject;
begin
Result := Self;
end;
function TCustomForm3D.GetContext: TContext3D;
begin
Result := FContext;
end;
function TCustomForm3D.GetScene: IScene;
begin
Result := nil;
end;
function TCustomForm3D.GetDesignCamera: TCamera;
begin
Result := FDesignCamera;
end;
procedure TCustomForm3D.SetDesignCamera(const ACamera: TCamera);
begin
FDesignCamera := ACamera;
end;
procedure TCustomForm3D.NeedRender;
begin
InvalidateRect(RectF(0, 0, ClientWidth, FContext.Height)); // because is a HW context
end;
procedure TCustomForm3D.Realign;
begin
AlignObjects(Self, FMargins, FContext.Width, FContext.Height, FLastWidth, FLastHeight, FDisableAlign);
InvalidateRect(ClientRect);
end;
constructor TScreen.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// Let VCL manage datamodules if it is around
if (not Assigned(Classes.AddDataModule))
and (not Assigned(Classes.RemoveDataModule)) then
begin
Classes.AddDataModule := AddDataModule;
Classes.RemoveDataModule := RemoveDataModule;
FManagingDataModules := True
end
else
FManagingDataModules := False;
FForms := TList.Create;
FDataModules := TList.Create;
end;
procedure TScreen.AddDataModule(DataModule: TDataModule);
begin
FDataModules.Add(DataModule);
end;
procedure TScreen.AddForm(AForm: TCommonCustomForm);
function FindUniqueFormName(const Name: WideString): WideString;
var
I: Integer;
begin
I := 0;
Result := Name;
while FindGlobalComponent(Result) <> nil do
begin
Inc(I);
Result := Format('%s_%d', [Name, I]);
end;
end;
begin
if Length(AForm.Name) = 0 then
AForm.Name := FindUniqueFormName('form')
else
AForm.Name := FindUniqueFormName(AForm.Name);
FForms.Add(AForm);
end;
procedure TScreen.RemoveDataModule(DataModule: TDataModule);
begin
FDataModules.Remove(DataModule);
end;
procedure TScreen.RemoveForm(AForm: TCommonCustomForm);
begin
FForms.Remove(AForm);
end;
function TScreen.GetDataModule(Index: Integer): TDataModule;
begin
Result := TDataModule(FDataModules[Index]);
end;
function TScreen.GetDataModuleCount: Integer;
begin
Result := FDataModules.Count;
end;
function TScreen.GetForm(Index: Integer): TCommonCustomForm;
begin
Result := TCommonCustomForm(FForms[Index]);
end;
function TScreen.GetFormCount: Integer;
begin
Result := FForms.Count;
end;
destructor TScreen.Destroy;
var
I: Integer;
begin
FreeAndNil(FDataModules);
FreeAndNil(FForms);
if FManagingDataModules then
begin
Classes.AddDataModule := nil;
Classes.RemoveDataModule := nil;
end;
inherited Destroy;
end;
function FindGlobalComponent(const Name: string): TComponent;
var
I: Integer;
begin
for I := 0 to Screen.FormCount - 1 do
begin
Result := Screen.Forms[I];
if not (csInline in Result.ComponentState) and
(CompareText(Name, Result.Name) = 0) then Exit;
end;
for I := 0 to Screen.DataModuleCount - 1 do
begin
Result := Screen.DataModules[I];
if CompareText(Name, Result.Name) = 0 then Exit;
end;
Result := nil;
end;
initialization
RegisterFmxClasses([TApplication], [TApplication]);
Screen := TScreen.Create(nil);
Platform := PlatformClass.Create(nil);
Classes.RegisterFindGlobalComponentProc(FindGlobalComponent);
finalization
Classes.UnregisterFindGlobalComponentProc(FindGlobalComponent);
FreeAndNil(Screen);
// Platform global is freed in FMX_Types
end.
|
unit uSysObj;
interface
uses
Classes, UWorkerInfo;
type
TSysObj = class(TObject)
private
FAppPath: string;
FWorkerInfo: TWorkerInfo;
FConfigPath: string;
public
constructor Create;
destructor Destroy; override;
property AppPath: string read FAppPath write FAppPath;
property ConfigPath: string read FConfigPath write FConfigPath;
property WorkerInfo: TWorkerInfo read FWorkerInfo write FWorkerInfo;
end;
function Sys: TSysObj;
implementation
var
FSys: TSysObj;
function Sys: TSysObj;
begin
if not Assigned(FSys) then
FSys := TSysObj.Create;
Result := FSys;
end;
{ TSysObj }
constructor TSysObj.Create;
begin
inherited Create;
FWorkerInfo := TWorkerInfo.Create;
end;
destructor TSysObj.Destroy;
begin
FWorkerInfo.Free;
inherited;
end;
initialization
finalization
if Assigned(FSys) then
FSys.Free;
end.
|
unit untEasyWorkFlowActions;
interface
uses
SysUtils, Classes, Forms, ComCtrls, Graphics, atDiagram, DiagramActns,
DiagramExtra, ActnList, Dialogs, ImgList, Controls, wsClasses;
type
TDMEasyWorkFlowActions = class(TDataModule)
ActionList1: TActionList;
acHasTargetArrow: TAction;
acHasSourceArrow: TAction;
acNewDiagram: TAction;
acOpenDiagram: TAction;
acSaveDiagram: TAction;
acPrintDiagram: TAction;
acPreviewDiagram: TAction;
acAutomaticNodes: TAction;
acCopyAsImage: TAction;
acGroup: TAction;
acUngroup: TAction;
ActionList2: TActionList;
SaveDialog1: TSaveDialog;
OpenDialog1: TOpenDialog;
ImageList1: TImageList;
ImageList2: TImageList;
PrintDialog1: TPrintDialog;
ActionList3: TActionList;
acBold: TAction;
acItalic: TAction;
acUnderline: TAction;
acAlignLeft: TAction;
acAlignCenter: TAction;
acAlignRight: TAction;
acVertAlignTop: TAction;
acVertAlignMiddle: TAction;
acVertAlignBottom: TAction;
ImageList3: TImageList;
procedure acHasTargetArrowExecute(Sender: TObject);
procedure acHasSourceArrowExecute(Sender: TObject);
procedure acNewDiagramExecute(Sender: TObject);
procedure acOpenDiagramExecute(Sender: TObject);
procedure acSaveDiagramExecute(Sender: TObject);
procedure acPrintDiagramExecute(Sender: TObject);
procedure acPreviewDiagramExecute(Sender: TObject);
procedure acAutomaticNodesExecute(Sender: TObject);
procedure acCopyAsImageExecute(Sender: TObject);
procedure acGroupExecute(Sender: TObject);
procedure acUngroupExecute(Sender: TObject);
procedure acHasTargetArrowUpdate(Sender: TObject);
procedure acHasSourceArrowUpdate(Sender: TObject);
procedure acAutomaticNodesUpdate(Sender: TObject);
procedure acGroupUpdate(Sender: TObject);
procedure acUngroupUpdate(Sender: TObject);
procedure acBoldExecute(Sender: TObject);
procedure acItalicExecute(Sender: TObject);
procedure acUnderlineExecute(Sender: TObject);
procedure acAlignLeftExecute(Sender: TObject);
procedure acAlignCenterExecute(Sender: TObject);
procedure acAlignRightExecute(Sender: TObject);
procedure acVertAlignTopExecute(Sender: TObject);
procedure acVertAlignMiddleExecute(Sender: TObject);
procedure acVertAlignBottomExecute(Sender: TObject);
procedure acBoldUpdate(Sender: TObject);
procedure acItalicUpdate(Sender: TObject);
procedure acUnderlineUpdate(Sender: TObject);
procedure acAlignLeftUpdate(Sender: TObject);
procedure acAlignCenterUpdate(Sender: TObject);
procedure acAlignRightUpdate(Sender: TObject);
procedure acVertAlignTopUpdate(Sender: TObject);
procedure acVertAlignMiddleUpdate(Sender: TObject);
procedure acVertAlignBottomUpdate(Sender: TObject);
private
{ Private declarations }
// FDiagram: TatDiagram;
FDiagram: TWorkflowDiagram;
FToolbar: TDiagramToolbar;
FTabControl: TTabControl;
FOnModified: TNotifyEvent;
FModified: boolean;
FOldFormClose: TCloseEvent;
FOnSaveDiagram: TNotifyEvent;
procedure SetDiagram(const Value: TWorkflowDiagram);
procedure SetModified(Value: boolean);
procedure SetActionsDiagram(ActionList: TActionList);
procedure DiagramModified(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure TabControlChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
function FirstCellSelected: TTextCell;
procedure SwitchSelectedFontStyle(AStyle: TFontStyle; AInclude: boolean);
procedure SetSelectedAlignment(AAlign: TAlignment);
procedure SetSelectedVertAlign(AAlign: TVertAlign);
public
{ Public declarations }
procedure PrepareDiagram;
procedure PrepareForm(AForm: TForm);
procedure PrepareCategoryTab(ATabControl: TTabControl; AToolbar: TDiagramToolbar);
property Diagram: TWorkflowDiagram read FDiagram write SetDiagram;
property Modified: boolean read FModified;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
property OnSaveDiagram: TNotifyEvent read FOnSaveDiagram write FOnSaveDiagram;
end;
var
DMEasyWorkFlowActions: TDMEasyWorkFlowActions;
implementation
{$R *.dfm}
{ TDMEasyWorkFlowActions }
procedure TDMEasyWorkFlowActions.PrepareCategoryTab(
ATabControl: TTabControl; AToolbar: TDiagramToolbar);
var
c: integer;
SL: TStringList;
ATab: string;
begin
FTabControl := ATabControl;
if FTabControl <> nil then
begin
SL := TStringList.Create;
SL.Add('All objects');
try
for c := 0 to RegDControlList.Count - 1 do
begin
ATab := RegDControlList[c].Category;
if (ATab <> '') and (SL.IndexOf(ATab) = -1) then
SL.Add(RegDControlList[c].Category);
end;
FTabControl.Tabs := SL;
finally
SL.Free;
end;
FTabControl.OnChange := TabControlChange;
FToolbar := AToolbar;
end;
end;
procedure TDMEasyWorkFlowActions.PrepareDiagram;
begin
if FDiagram <> nil then
begin
FDiagram.ConnectionLineId := 'TDiagramLine';
end;
end;
procedure TDMEasyWorkFlowActions.PrepareForm(AForm: TForm);
begin
if AForm <> nil then
begin
AForm.OnCloseQuery := FormCloseQuery;
FOldFormClose := AForm.OnClose;
AForm.OnClose := FormClose;
end;
end;
procedure TDMEasyWorkFlowActions.SetDiagram(const Value: TWorkflowDiagram);
begin
FDiagram := Value;
end;
procedure TDMEasyWorkFlowActions.acHasTargetArrowExecute(Sender: TObject);
begin
//This line is needed to keep action active
end;
procedure TDMEasyWorkFlowActions.acHasSourceArrowExecute(Sender: TObject);
begin
//This line is needed to keep action active
end;
procedure TDMEasyWorkFlowActions.acNewDiagramExecute(Sender: TObject);
begin
if not FModified or (MessageDlg('创建一个新流程图并取消当前发生的变更?',
mtInformation, [mbYes, mbNo], 0) = mrYes) then
begin
FDiagram.Clear;
SetModified(False);
end;
end;
procedure TDMEasyWorkFlowActions.SetModified(Value: boolean);
begin
if FModified <> Value then
begin
FModified := Value;
if Assigned(FOnModified) then
FOnModified(FDiagram);
end;
end;
procedure TDMEasyWorkFlowActions.acOpenDiagramExecute(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
if not FModified or (MessageDlg('打开一个新流程图并取消当前发生的变更?',
mtInformation, [mbYes, mbNo], 0) = mrYes) then
begin
FDiagram.LoadFromFile(OpenDialog1.FileName);
SetModified(False);
end;
end;
end;
procedure TDMEasyWorkFlowActions.acSaveDiagramExecute(Sender: TObject);
begin
if Assigned(FOnSaveDiagram) then
begin
FOnSaveDiagram(Sender);;
SetModified(false);
end
else
if SaveDialog1.Execute then
begin
FDiagram.SaveToFile(SaveDialog1.FileName);
SetModified(false);
end;
end;
procedure TDMEasyWorkFlowActions.acPrintDiagramExecute(Sender: TObject);
begin
if PrintDialog1.Execute then
FDiagram.Print;
end;
procedure TDMEasyWorkFlowActions.acPreviewDiagramExecute(Sender: TObject);
begin
FDiagram.Preview;
end;
procedure TDMEasyWorkFlowActions.acAutomaticNodesExecute(Sender: TObject);
begin
acAutomaticNodes.Checked := not acAutomaticNodes.Checked;
FDiagram.AutomaticNodes := acAutomaticNodes.Checked;
FDiagram.Modified;
end;
procedure TDMEasyWorkFlowActions.acCopyAsImageExecute(Sender: TObject);
begin
FDiagram.CopyBitmapToClipboard;
end;
procedure TDMEasyWorkFlowActions.acGroupExecute(Sender: TObject);
begin
FDiagram.GroupSelectedBlocks;
end;
procedure TDMEasyWorkFlowActions.acUngroupExecute(Sender: TObject);
begin
FDiagram.UngroupSelectedBlocks;
end;
procedure TDMEasyWorkFlowActions.acHasTargetArrowUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := FDiagram.SelectedLinkCount > 0;
end;
procedure TDMEasyWorkFlowActions.acHasSourceArrowUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := FDiagram.SelectedLinkCount > 0;
end;
procedure TDMEasyWorkFlowActions.acAutomaticNodesUpdate(Sender: TObject);
begin
acAutomaticNodes.Checked := FDiagram.AutomaticNodes;
end;
procedure TDMEasyWorkFlowActions.acGroupUpdate(Sender: TObject);
begin
acGroup.Enabled := (FDiagram <> nil) and (FDiagram.SelectedCount(cfIgnoreMembers) > 1);
end;
procedure TDMEasyWorkFlowActions.acUngroupUpdate(Sender: TObject);
var
c: integer;
Ok: boolean;
begin
Ok := false;
if FDiagram <> nil then
for c := 0 to FDiagram.SelectedCount - 1 do
if FDiagram.Selecteds[c].IsGroup and not FDiagram.Selecteds[c].IsMember then
begin
Ok := true;
break;
end;
acUngroup.Enabled := Ok;
end;
procedure TDMEasyWorkFlowActions.acBoldExecute(Sender: TObject);
begin
SwitchSelectedFontStyle(fsBold, not acBold.Checked);
end;
procedure TDMEasyWorkFlowActions.acItalicExecute(Sender: TObject);
begin
SwitchSelectedFontStyle(fsItalic, not acItalic.Checked);
end;
procedure TDMEasyWorkFlowActions.acUnderlineExecute(Sender: TObject);
begin
SwitchSelectedFontStyle(fsUnderline, not acUnderline.Checked);
end;
procedure TDMEasyWorkFlowActions.acAlignLeftExecute(Sender: TObject);
begin
SetSelectedAlignment(taLeftJustify);
end;
procedure TDMEasyWorkFlowActions.acAlignCenterExecute(Sender: TObject);
begin
SetSelectedAlignment(taCenter);
end;
procedure TDMEasyWorkFlowActions.acAlignRightExecute(Sender: TObject);
begin
SetSelectedAlignment(taRightJustify);
end;
procedure TDMEasyWorkFlowActions.acVertAlignTopExecute(Sender: TObject);
begin
SetSelectedVertAlign(vaTop);
end;
procedure TDMEasyWorkFlowActions.acVertAlignMiddleExecute(Sender: TObject);
begin
SetSelectedVertAlign(vaCenter);
end;
procedure TDMEasyWorkFlowActions.acVertAlignBottomExecute(Sender: TObject);
begin
SetSelectedVertAlign(vaBottom);
end;
procedure TDMEasyWorkFlowActions.acBoldUpdate(Sender: TObject);
begin
acBold.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acBold.Checked := (FirstCellSelected <> nil) and (fsBold in FirstCellSelected.Font.Style);
end;
procedure TDMEasyWorkFlowActions.acItalicUpdate(Sender: TObject);
begin
acItalic.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acItalic.Checked := (FirstCellSelected <> nil) and (fsItalic in FirstCellSelected.Font.Style);
end;
procedure TDMEasyWorkFlowActions.acUnderlineUpdate(Sender: TObject);
begin
acUnderline.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acUnderline.Checked := (FirstCellSelected <> nil) and (fsUnderline in FirstCellSelected.Font.Style);
end;
procedure TDMEasyWorkFlowActions.acAlignLeftUpdate(Sender: TObject);
begin
acAlignLeft.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acAlignLeft.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.Alignment = taLeftJustify);
end;
procedure TDMEasyWorkFlowActions.acAlignCenterUpdate(Sender: TObject);
begin
acAlignCenter.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acAlignCenter.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.Alignment = taCenter);
end;
procedure TDMEasyWorkFlowActions.acAlignRightUpdate(Sender: TObject);
begin
acAlignRight.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acAlignRight.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.Alignment = taRightJustify);
end;
procedure TDMEasyWorkFlowActions.acVertAlignTopUpdate(Sender: TObject);
begin
acVertAlignTop.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acVertAlignTop.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.VertAlign = vaTop);
end;
procedure TDMEasyWorkFlowActions.acVertAlignMiddleUpdate(Sender: TObject);
begin
acVertAlignMiddle.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acVertAlignMiddle.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.VertAlign = vaCenter);
end;
procedure TDMEasyWorkFlowActions.acVertAlignBottomUpdate(Sender: TObject);
begin
acVertAlignBottom.Enabled := (FDiagram <> nil) and (FirstCellSelected <> nil);
acVertAlignBottom.Checked := (FirstCellSelected <> nil) and (FirstCellSelected.VertAlign = vaBottom);
end;
procedure TDMEasyWorkFlowActions.DiagramModified(Sender: TObject);
begin
SetModified(True);
end;
function TDMEasyWorkFlowActions.FirstCellSelected: TTextCell;
var
AControl: TDiagramControl;
begin
result := nil;
if (FDiagram <> nil) then
begin
if FDiagram.EditingText then
result := FDiagram.EditingCell
else
if (FDiagram.SelectedCount > 0) then
begin
AControl := FDiagram.Selecteds[0];
while AControl.IsGroup and (TGroupBlock(AControl).Members.Count > 0) do
AControl := TGroupBlock(AControl).Members[0].DControl;
if (AControl <> nil) and (AControl.HasDefaultTextCell) then
result := AControl.DefaultTextCell;
if not result.Visible then
begin
repeat
result := AControl.SelectNextCell(result, true);
until (result.Visible) or (result = AControl.DefaultTextCell);
end;
end;
end;
end;
procedure TDMEasyWorkFlowActions.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
if Assigned(FOldFormClose) then
FOldFormClose(Sender, Action);
end;
procedure TDMEasyWorkFlowActions.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if Modified then
begin
Case MessageDlg('是否保存对当前流程图的更改?', mtInformation,
[mbYes, mbNo, mbCancel], 0) of
mrYes:
begin
acSaveDiagram.Execute;
CanClose := not Modified;
end;
mrNo:
CanClose := true;
mrCancel:
CanClose := false;
end;
end else
CanClose := true;
end;
procedure TDMEasyWorkFlowActions.SetActionsDiagram(
ActionList: TActionList);
var
c: integer;
begin
for c := 0 to ActionList.ActionCount - 1 do
if ActionList.Actions[c] is TDiagramAction then
TDiagramAction(ActionList.Actions[c]).Diagram := FDiagram;
end;
procedure TDMEasyWorkFlowActions.SetSelectedAlignment(AAlign: TAlignment);
var
c: integer;
d: integer;
begin
with FDiagram do
if EditingText then
EditingCell.Alignment := AAlign
else
for c := 0 to SelectedCount - 1 do if not Selecteds[c].IsGroup then
begin
for d := 0 to Selecteds[c].TextCells.Count - 1 do
Selecteds[c].TextCells[d].Alignment := AAlign;
end;
end;
procedure TDMEasyWorkFlowActions.SetSelectedVertAlign(AAlign: TVertAlign);
var
c: integer;
d: integer;
begin
with FDiagram do
if EditingText then
EditingCell.VertAlign := AAlign
else
for c := 0 to SelectedCount - 1 do if not Selecteds[c].IsGroup then
begin
for d := 0 to Selecteds[c].TextCells.Count - 1 do
Selecteds[c].TextCells[d].VertAlign := AAlign;
end;
end;
procedure TDMEasyWorkFlowActions.SwitchSelectedFontStyle(
AStyle: TFontStyle; AInclude: boolean);
procedure _SwitchStyle(AFont: TFont);
begin
if AInclude then
AFont.Style := AFont.Style + [AStyle]
else
AFont.Style := AFont.Style - [AStyle];
end;
var
c: integer;
d: integer;
begin
with FDiagram do
if EditingText then
_SwitchStyle(EditingCell.Font)
else
for c := 0 to SelectedCount - 1 do if not Selecteds[c].IsGroup then
begin
_SwitchStyle(Selecteds[c].Font);
for d := 0 to Selecteds[c].TextCells.Count - 1 do
if not Selecteds[c].TextCells[d].DControlFont then
_SwitchStyle(Selecteds[c].TextCells[d].Font);
end;
end;
procedure TDMEasyWorkFlowActions.TabControlChange(Sender: TObject);
begin
if (FTabControl <> nil) and (FToolbar <> nil) then
begin
if (FTabControl.TabIndex = 0) or (FTabControl.Tabs.Count <= 0) then
FToolbar.Category := ''
else
FToolbar.Category := FTabControl.Tabs[FTabControl.TabIndex];
end;
end;
end.
|
unit DomDocumentTest;
interface
implementation
uses
// NTX
ntxTestUnit, ntxTestResult,
// unit to be tested
microdom,
// HELP UNITS
udomtest_init;
{*******************************************************************************
Test_DomDocument - 12.05.20 11:56
by: JL
********************************************************************************}
procedure Test_DomDocument(trs: TntxTestResults);
const
TESTNAME = 'class TuDomDocument';
var
t: TntxTest;
dd: TuDomDocument;
begin
t:=trs.NewTest(TESTNAME);
t.Start;
dd:=nil;
try
t.Subtest('constructor').Start
.Call(
function(t: TntxTest): Boolean
begin
dd:=TuDomDocument.Create;
Result:=true;
end
)
.Done;
t.Subtest('Parse').Start
.Call(
function(t: TntxTest): Boolean
var
res: Boolean;
begin
res:=dd.Parse('<ROOT>value</ROOT>');
t
.Eq(res, true, 'result value')
.Eq(dd.Name, 'ROOT', 'root tag')
.Eq(dd.Value, 'value', 'value')
.Eq(dd.ChildNodes.Count, 0, 'count of child nodes');
Result:=true;
end
)
.Done;
finally
if Assigned(dd) then
t.Subtest('destructor').Start
.Call(
function(t: TntxTest): Boolean
begin
dd.Free;
Result:=true;
end
)
.Done;
t.Done;
end;
end; {Test_DomDocument}
initialization
begin
RegisterTest('TuDomDocument', Test_DomDocument);
end;
end.
|
unit UpdateVillageNamesAndAddresses;
{To use this template:
1. Save the form it under a new name.
2. Rename the form in the Object Inspector.
3. Rename the table in the Object Inspector. Then switch
to the code and do a blanket replace of "Table" with the new name.
4. Change UnitName to the new unit name.}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, Mask, Types,
wwdblook, Psock, NMFtp, ShellAPI;
type
TUpdateVillagesNameAndAddressForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
CloseButton: TBitBtn;
TitleLabel: TLabel;
StartButton: TBitBtn;
Label1: TLabel;
ParcelTable: TTable;
Label6: TLabel;
SwisCodeListBox: TListBox;
Label2: TLabel;
SwisCodeTable: TwwTable;
NMFTP: TNMFTP;
NotificationEMailAddressComboBox: TwwDBLookupCombo;
EmailAddressesTable: TwwTable;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure StartButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
SelectedSwisCodes : TStringList;
Procedure InitializeForm; {Open the tables and setup.}
Function RecMeetsCriteria(ParcelTable : TTable) : Boolean;
Procedure ExtractNamesAndAddresses(var ExtractFile : TextFile;
var Cancelled : Boolean);
Procedure SendExtractFileToWebsite( ExtractFileName : String;
var Cancelled : Boolean);
Procedure SendEmailToVillage(EMailAddress : String;
ExtractFileName : String);
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, UtilEXSD,
PASTypes, Prog;
{$R *.DFM}
{========================================================}
procedure TUpdateVillagesNameAndAddressForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TUpdateVillagesNameAndAddressForm.InitializeForm;
var
Quit : Boolean;
begin
UnitName := 'UpdateVillageNamesAndAddresses'; {mmm}
OpenTablesForForm(Self, NextYear);
FillOneListBox(SwisCodeListBox, SwisCodeTable, 'SwisCode',
'MunicipalityName', 25, True, True, GlblProcessingType, GetTaxRlYr);
end; {InitializeForm}
{===================================================================}
Function TUpdateVillagesNameAndAddressForm.RecMeetsCriteria(ParcelTable : TTable) : Boolean;
begin
Result := (SelectedSwisCodes.IndexOf(ParcelTable.FieldByName('SwisCode').Text) > -1);
end; {RecMeetsCriteria}
{===================================================================}
Procedure TUpdateVillagesNameAndAddressForm.ExtractNamesAndAddresses(var ExtractFile : TextFile;
var Cancelled : Boolean);
var
FirstTimeThrough, Done : Boolean;
SwisSBLKey : String;
begin
ProgressDialog.Start(GetRecordCount(ParcelTable), True, True);
ParcelTable.First;
FirstTimeThrough := True;
Done := False;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ParcelTable.Next;
If ParcelTable.EOF
then Done := True;
If ((not Done) and
RecMeetsCriteria(ParcelTable))
then
begin
SwisSBLKey := ExtractSSKey(ParcelTable);
with ParcelTable do
Writeln(ExtractFile, SwisSBLKey,
FormatExtractField(FieldByName('Name1').Text),
FormatExtractField(FieldByName('Name2').Text),
FormatExtractField(FieldByName('Address1').Text),
FormatExtractField(FieldByName('Address2').Text),
FormatExtractField(FieldByName('Street').Text),
FormatExtractField(FieldByName('City').Text),
FormatExtractField(FieldByName('State').Text),
FormatExtractField(FieldByName('Zip').Text),
FormatExtractField(FieldByName('ZipPlus4').Text));
end; {If ((not Done) and ...}
ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey));
Application.ProcessMessages;
Cancelled := ProgressDialog.Cancelled;
until (Done or Cancelled);
ProgressDialog.Finish;
end; {ExtractNameAddrChanges}
{===================================================================}
Procedure TUpdateVillagesNameAndAddressForm.SendExtractFileToWebsite( ExtractFileName : String;
var Cancelled : Boolean);
var
Connected : Boolean;
TempFile : File of Byte;
_FileSize : LongInt;
begin
Connected := True;
try
NMFTP.Connect;
except
Connected := False;
MessageDlg('There was an error connecting to the website for uploading.' + #13 +
'Please make sure that you are connected to the internet and try again.',
mtError, [mbOK], 0);
Cancelled := True;
end;
If Connected
then
try
NMFTP.ChangeDir('www');
NMFTP.ChangeDir('nameaddressupdates');
except
MessageDlg('There was an error changing to www/nameaddressupdates.' + #13 +
'Please make sure that you are connected to the internet and try again.',
mtError, [mbOK], 0);
Cancelled := True;
end;
If (Connected and
(not Cancelled))
then
try
NMFTP.Mode(MODE_ASCII);
AssignFile(TempFile, ExtractFileName);
Reset(TempFile);
_FileSize := FileSize(TempFile);
CloseFile(TempFile);
NMFTP.Allocate(_FileSize);
NMFTP.Upload(ExtractFileName, StripPath(ExtractFileName));
except
Cancelled := True;
MessageDlg('There was an error sending the extract file ' + ExtractFileName + ' to the website.' + #13 +
'Please try again.', mtError, [mbOK], 0);
end;
NMFTP.Disconnect;
end; {SendExtractFileToWebsite}
{===================================================================}
Procedure TUpdateVillagesNameAndAddressForm.SendEmailToVillage(EMailAddress : String;
ExtractFileName : String);
var
TempStr : String;
TempPChar : PChar;
TempLen : Integer;
begin
TempStr := 'mailto:' + EMailAddress + '?subject=PAS Name \ Address Update' +
'&body=There is now an update for PAS names and addresses from the Town of Ramapo.';
TempLen := Length(TempStr);
TempPChar := StrAlloc(TempLen + 1);
StrPCopy(TempPChar, TempStr);
ShellExecute(0, 'open', TempPChar, nil, nil, SW_SHOWNORMAL);
StrDispose(TempPChar);
end; {SendEmailToVillage}
{==============================================================}
Procedure TUpdateVillagesNameAndAddressForm.StartButtonClick(Sender: TObject);
var
ExtractFile : TextFile;
VillageName, ExtractFileName,
CurrentDateStr, CurrentTimeStr : String;
I : Integer;
Cancelled : Boolean;
begin
Cancelled := False;
SelectedSwisCodes := TStringList.Create;
VillageName := '';
For I := 0 to (SwisCodeListBox.Items.Count - 1) do
If SwisCodeListBox.Selected[I]
then
begin
SelectedSwisCodes.Add(Take(6, SwisCodeListBox.Items[I]));
If (VillageName <> '')
then VillageName := VillageName + '_';
VillageName := VillageName + Trim(Copy(SwisCodeListBox.Items[I], 10, 20));
end; {If SwisCodeListBox.Selected[I]}
CurrentTimeStr := TimeToStr(Now);
CurrentTimeStr := StringReplace(CurrentTimeStr, ':', '', [rfReplaceAll]);
CurrentTimeStr := StringReplace(CurrentTimeStr, ' ', '', [rfReplaceAll]);
CurrentDateStr := DateToStr(Date);
CurrentDateStr := StringReplace(CurrentDateStr, '/', '', [rfReplaceAll]);
CurrentDateStr := StringReplace(CurrentDateStr, '\', '', [rfReplaceAll]);
ExtractFileName := GlblDrive + ':' + AddDirectorySlashes(GlblExportDir) +
VillageName + '_' + CurrentDateStr + '_' +
CurrentTimeStr + '.csv';
AssignFile(ExtractFile, ExtractFileName);
Rewrite(ExtractFile);
ExtractNamesAndAddresses(ExtractFile, Cancelled);
CloseFile(ExtractFile);
If not Cancelled
then SendExtractFileToWebsite(ExtractFileName, Cancelled);
If not Cancelled
then SendEmailToVillage(NotificationEMailAddressComboBox.Text, ExtractFileName);
If Cancelled
then MessageDlg('The name \ address update file was NOT sent because the extract was cancelled or the connection failed.' + #13 +
'Please try again.', mtWarning, [mbOK], 0)
else MessageDlg('The name \address update file for the village of ' + VillageName + ' was sent and' +
' is now available for updating the village files.', mtInformation, [mbOK], 0);
SelectedSwisCodes.Free;
end; {StartButtonClick}
{===================================================================}
Procedure TUpdateVillagesNameAndAddressForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
{$i deltics.unicode.inc}
unit Deltics.Unicode.Transcode.Utf8ToCodepoint;
interface
uses
Deltics.Unicode.Types;
function _Utf8ToCodepoint(var aUtf8: PUtf8Char; var aMaxChars: Integer): Codepoint; overload;
implementation
uses
Deltics.Unicode;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function _Utf8ToCodepoint(var aUtf8: PUtf8Char;
var aMaxChars: Integer): Codepoint;
const
BYTE_OR_BYTES : array[FALSE..TRUE] of String = ('byte', 'bytes');
var
orgPtr: PUtf8Char;
orgChars: Integer;
numContinuationBytes: Integer;
leadByte: Byte;
continuationByte: Byte;
begin
result := 0;
if aMaxChars < 1 then
raise ENoData.Create('No Utf8 characters available');
orgPtr := aUtf8;
orgChars := aMaxChars;
try
leadByte := Byte(aUtf8^);
Inc(aUtf8);
Dec(aMaxChars);
if (leadByte and $80) = $00 then
begin
result := Codepoint(leadByte);
EXIT;
end;
if (leadByte and $e0) = $c0 then
numContinuationBytes := 1
else if (leadByte and $f0) = $e0 then
numContinuationBytes := 2
else if (leadByte and $f8) = $f0 then
numContinuationBytes := 3
else
raise EInvalidEncoding.Create('0x%.2x is not a valid byte in Utf8', [leadByte]);
if aMaxChars < numContinuationBytes then
raise EMoreData.Create('%d continuation %s required, %d available', [
numContinuationBytes,
BYTE_OR_BYTES[numContinuationBytes > 1],
aMaxChars]);
case numContinuationBytes of
1: result := ((leadByte and $1f) shl 6);
2: result := ((leadByte and $0f) shl 12);
3: result := ((leadByte and $07) shl 18);
end;
while numContinuationBytes > 0 do
begin
continuationByte := Byte(aUtf8^);
if (continuationByte and $c0) <> $80 then
raise EInvalidEncoding.Create('0x%.2x is not a valid continuation byte', [continuationByte]);
Inc(aUtf8);
Dec(aMaxChars);
Dec(numContinuationBytes);
result := result or ((continuationByte and $3f) shl (numContinuationBytes * 6));
end;
except
aUtf8 := orgPtr;
aMaxChars := orgChars;
raise;
end;
end;
end.
|
{ /*
MIT License
Copyright (c) 2014-2020 Wuping Xin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ }
unit AAPI_User;
interface
{ Aimsun MicroApi time notations:
ATime: Absolute simulation time in seconds;
ATimeSta: Stationary simulation time, in seconds;
ATimeTrans: Warm-up period, in seconds;
ASimStep: Simulation step. in seconds.
For example, a simulation scenario starts at 07:00, with 5 minutes of warm-up
period, and Aimsun has finished a simulation runtime of 1 minute, with 1
second as the simulation step. Thus:
ATime
= 5*60 + 60
= 360.0
ATimeSta
= 7*3600 +60
= 25260.0
ATimeTrans
= 5*60
= 300.0
ASimStep
= 1.0
Note by Wuping Xin, 2020-03-15 20:25 PM
Aimsun offical MicroApi (in C) was poorly designed, lacking in consistent naming
style with Apis logics completely dis-orgnized. It does not even have minimal
performance considerations, for example, a lot of its methods pass large struct
by value, a practice that should be avoided in the first place. This Object Pascal
porting of Aimsun's original MicroApi cannot fix those fundamental design issues
but at least with better naming style in terms of the Pascal language.
}
{$REGION 'Initialization Functions'}
/// <summary> Fires when Aimsun loads the MicroApi dll.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPILoad: Integer; cdecl;
/// <summary> Fires when Aimsun is about to start the simulation, i.e., right
/// before running the first simulation step. This should be where to put
/// initialization code for the user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIInit: Integer; cdecl;
{$ENDREGION}
{$REGION 'Timestep-wise Functions'}
/// <summary> Fires at the beginning of every simulation step.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer; cdecl;
/// <summary> Fires at the end of every simulation step.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIPostManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer; cdecl;
{$ENDREGION}
{$REGION 'Finialization Functions'}
/// <summary> Fires when Aimsun has finished all simulation steps. This should
/// be where to put clean-up code of the user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIFinish: Integer; cdecl;
/// <summary> Fires when Aimsun unloads the MicroApi dll.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIUnLoad: Integer; cdecl;
{$ENDREGION}
{$REGION 'Simulation Events'}
/// <summary> Fires when an vehicle enters a boundary section of the network,
/// i.e., the vehicle enters its first travelling section (not the virtual queue
/// if any).
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterVehicle(AVehID: Integer; ASectionID: Integer): Integer; cdecl;
/// <summary> Fires when a vehicle exits its last traveling section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitVehicle(AVehID: Integer; ASectionID: Integer): Integer; cdecl;
/// <summary> Fires when a new pedestrian enters the network.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterPedestrian(APedID: Integer; AOrigCentroid: Integer): Integer; cdecl;
/// <summary> Fires when a pedestrian exits the network.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitPedestrian(APedID: Integer; ADestCentroid: Integer): Integer; cdecl;
/// <summary> Fires when a vehicle enters a new section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIEnterVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer; cdecl;
/// <summary> Fires when a vehicle exits a section.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIExitVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer; cdecl;
/// <summary> Fires before performing a new round of route choice calculation.
/// Section or turning costs can be modified here based on some user logic.
/// </summary>
/// <returns> Integer, 0 success code; negative error code.
/// </returns>
function AAPIPreRouteChoiceCalculation(ATime: Double; ATimeSta: Double): Integer; cdecl;
{$ENDREGION}
implementation
uses
System.Classes, System.SysUtils, AKIProxie;
function AAPIEnterVehicle(AVehID: Integer; ASectionID: Integer): Integer;
begin
Result := 0;
end;
function AAPIEnterVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer;
begin
Result := 0;
end;
function AAPIExitVehicle(AVehID: Integer; ASectionID: Integer): Integer;
begin
Result := 0;
end;
function AAPIExitVehicleSection(AVehID: Integer; ASectionID: Integer; ATime: Double): Integer;
begin
Result := 0;
end;
function AAPIFinish: Integer;
begin
Result := 0;
end;
function AAPILoad: Integer;
begin
Result := 0;
end;
function AAPIInit: Integer;
begin
Result := 0;
end;
function AAPIManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer;
begin
var LSectionsCount := AKIInfNetNbSectionsANG();
for var I := 0 to LSectionsCount - 1 do
begin
var LSectionID := AKIInfNetGetSectionANGId(I);
var LVehsCount := AKIVehStateGetNbVehiclesSection(LSectionID, True);
for var J := 0 to LVehsCount - 1 do
begin
var LVehInfo := AKIVehStateGetVehicleInfSection(LSectionID, J);
AKIPrintStringEx(Format('Vehicle %d, Section %d, Lane %d, CurPos %f, CurSpeed %f',
[
LVehInfo.VehID,
LVehInfo.SectionID,
LVehInfo.LaneID,
LVehInfo.CurrentPos,
LVehInfo.CurrentSpeed
]));
end;
end;
var LJunctionsCount := AKIInfNetNbJunctions();
for var I := 0 to LJunctionsCount - 1 do
begin
var LJunctionID := AKIInfNetGetJunctionId(I);
var LVehsCount := AKIVehStateGetNbVehiclesJunction(LJunctionID);
for var J := 0 to LVehsCount - 1 do
begin
var LVehInfo := AKIVehStateGetVehicleInfJunction(LJunctionID, J);
AKIPrintStringEx(Format('Vehicle %d, Node %d, From %d, To %d CurPos %f, CurSpeed %f',
[
LVehInfo.VehID,
LVehInfo.JunctionID,
LVehInfo.FromSectionID,
LVehInfo.ToSectionID,
LVehInfo.CurrentPos,
LVehInfo.CurrentSpeed
]));
end;
end;
Result := 0;
end;
function AAPIPostManage(ATime: Double; ATimeSta: Double; ATimeTrans: Double; ASimStep: Double): Integer;
begin
Result := 0;
end;
function AAPIPreRouteChoiceCalculation(ATime: Double; ATimeSta: Double): Integer;
begin
Result := 0;
end;
function AAPIUnLoad: Integer;
begin
Result := 0;
end;
function AAPIEnterPedestrian(APedID: Integer; AOrigCentroid: Integer): Integer;
begin
Result := 0;
end;
function AAPIExitPedestrian(APedID: Integer; ADestCentroid: Integer): Integer;
begin
Result := 0;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MongoDBDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, System.JSON.Types;
type
// TFDPhysMongoConnectionDefParams
// Generated for: FireDAC MongoDB driver
/// <summary> TFDPhysMongoConnectionDefParams class implements FireDAC MongoDB driver specific connection definition class. </summary>
TFDPhysMongoConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetPort: Integer;
procedure SetPort(const AValue: Integer);
function GetMoreHosts: String;
procedure SetMoreHosts(const AValue: String);
function GetUseSSL: Boolean;
procedure SetUseSSL(const AValue: Boolean);
function GetLoginTimeout: Integer;
procedure SetLoginTimeout(const AValue: Integer);
function GetReadTimeout: Integer;
procedure SetReadTimeout(const AValue: Integer);
function GetTimeZone: TJsonDateTimeZoneHandling;
procedure SetTimeZone(const AValue: TJsonDateTimeZoneHandling);
function GetMongoAdvanced: String;
procedure SetMongoAdvanced(const AValue: String);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property Server: String read GetServer write SetServer stored False;
property Port: Integer read GetPort write SetPort stored False default 27017;
property MoreHosts: String read GetMoreHosts write SetMoreHosts stored False;
property UseSSL: Boolean read GetUseSSL write SetUseSSL stored False;
property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False default 0;
property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout stored False default 300;
property TimeZone: TJsonDateTimeZoneHandling read GetTimeZone write SetTimeZone stored False default TJsonDateTimeZoneHandling.Local;
property MongoAdvanced: String read GetMongoAdvanced write SetMongoAdvanced stored False;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysMongoConnectionDefParams
// Generated for: FireDAC MongoDB driver
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetPort: Integer;
begin
if not FDef.HasValue(S_FD_ConnParam_Common_Port) then
Result := 27017
else
Result := FDef.AsInteger[S_FD_ConnParam_Common_Port];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetPort(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetMoreHosts: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Mongo_MoreHosts];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetMoreHosts(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Mongo_MoreHosts] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetUseSSL: Boolean;
begin
Result := FDef.AsBoolean[S_FD_ConnParam_Mongo_UseSSL];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetUseSSL(const AValue: Boolean);
begin
FDef.AsBoolean[S_FD_ConnParam_Mongo_UseSSL] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetLoginTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetLoginTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetReadTimeout: Integer;
begin
if not FDef.HasValue(S_FD_ConnParam_Mongo_ReadTimeout) then
Result := 300
else
Result := FDef.AsInteger[S_FD_ConnParam_Mongo_ReadTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetReadTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Mongo_ReadTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetTimeZone: TJsonDateTimeZoneHandling;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Mongo_TimeZone];
if CompareText(s, 'Local') = 0 then
Result := TJsonDateTimeZoneHandling.Local
else if CompareText(s, 'UTC') = 0 then
Result := TJsonDateTimeZoneHandling.UTC
else
Result := TJsonDateTimeZoneHandling.Local;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetTimeZone(const AValue: TJsonDateTimeZoneHandling);
const
C_TimeZone: array[TJsonDateTimeZoneHandling] of String = ('Local', 'UTC');
begin
FDef.AsString[S_FD_ConnParam_Mongo_TimeZone] := C_TimeZone[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnectionDefParams.GetMongoAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Mongo_MongoAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnectionDefParams.SetMongoAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Mongo_MongoAdvanced] := AValue;
end;
end.
|
unit IdEcho;
interface
uses
Classes,
IdGlobal,
IdTCPClient;
type
TIdEcho = class(TIdTCPClient)
protected
FEchoTime: Cardinal;
public
constructor Create(AOwner: TComponent); override;
function Echo(AText: string): string;
property EchoTime: Cardinal read FEchoTime;
published
property Port default IdPORT_ECHO;
end;
implementation
uses
IdComponent,
IdTCPConnection,
SysUtils;
constructor TIdEcho.Create(AOwner: TComponent);
begin
inherited;
Port := IdPORT_ECHO;
end;
function TIdEcho.Echo(AText: string): string;
var
StartTime: Cardinal;
begin
BeginWork(wmWrite, Length(AText) + 2);
try
StartTime := IdGlobal.GetTickCount;
Write(AText);
finally
EndWork(wmWrite);
end;
BeginWork(wmRead);
try
Result := CurrentReadBuffer;
if IdGlobal.GetTickCount >= StartTime then
FEchoTime := IdGlobal.GetTickCount - StartTime
else
FEchoTime := High(Cardinal) - StartTime;
finally
EndWork(wmRead);
end;
end;
end.
|
unit f13_load;
interface
uses
csv_parser,
buku_handler,
user_handler,
peminjaman_Handler,
pengembalian_Handler,
kehilangan_handler,
tipe_data;
{ DEKLARASI FUNGSI DAN PROSEDUR }
procedure load(var data_buku: tabel_buku; var data_user: tabel_user; var data_peminjaman: tabel_peminjaman; var data_pengembalian: tabel_pengembalian; var data_kehilangan: tabel_kehilangan);
{ IMPLEMENTASI FUNGSI DAN PROSEDUR }
implementation
procedure load(var data_buku: tabel_buku; var data_user: tabel_user; var data_peminjaman: tabel_peminjaman; var data_pengembalian: tabel_pengembalian; var data_kehilangan: tabel_kehilangan);
{ DESKRIPSI : Memasukkan data dari .csv ke data di dalam program }
{ PARAMETER : semua tabel data }
{ KAMUS LOKAL }
var
temp : arr_str;
filename : string;
{ ALGORITMA }
begin
write('Masukkan nama File Buku: '); readln(filename);
temp := baca_csv(filename);
data_buku := buku_handler.tambah(temp);
write('Masukkan nama File User: '); readln(filename);
temp := baca_csv(filename);
data_user := user_handler.tambah(temp);
write('Masukkan nama File Peminjaman: '); readln(filename);
temp := baca_csv(filename);
data_peminjaman := peminjaman_Handler.tambah(temp);
write('Masukkan nama File Pengembalian: '); readln(filename);
temp := baca_csv(filename);
data_pengembalian := pengembalian_handler.tambah(temp);
write('Masukkan nama File Buku Hilang: '); readln(filename);
temp := baca_csv(filename);
data_kehilangan := kehilangan_handler.tambah(temp);
WriteLn('File perpustakaan berhasil dimuat!')
end;
end. |
program FizzBuzz;
var i: Integer;
begin
for i := 1 to 15 do
begin
if i mod 15 = 0 then
writeln ('FizzBuzz')
else if i mod 3 = 0 then
writeln ('Fizz')
else if i mod 5 = 0 then
writeln ('Buzz')
else
writeln (i)
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program PARIGAME;
Const
maxN =500;
Var
t,n :SmallInt;
D,C :Array[0..maxN,0..maxN] of Byte;
F :Array[0..maxN,0..maxN] of Boolean;
procedure Enter;
var
i,j :SmallInt;
k :LongInt;
begin
Read(n);
for i:=1 to n do
begin
D[i,0]:=0; C[0,i]:=0;
end;
for i:=1 to n do
for j:=1 to n do
begin
Read(k);
k:=k mod 2;
D[i,j]:=(D[i,j-1]+k) mod 2;
C[j,i]:=(C[j,i-1]+k) mod 2;
end;
end;
procedure Optimize;
var
i,j :SmallInt;
begin
for i:=1 to n do
begin
F[i,0]:=false; F[0,i]:=false;
end;
for i:=1 to n do
for j:=1 to n do
F[i,j]:=((not F[i-1,j]) and (D[i,j]=0)) or
((not F[i,j-1]) and (C[j,i]=0));
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Read(t);
repeat
Dec(t);
Enter;
Optimize;
if (F[n,n]) then
WriteLn('YES')
else
WriteLn('NO');
until (t=0);
Close(Input); Close(Output);
End. |
unit BodyTypesSimpleQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BodyTypesBaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TQueryBodyTypesSimple = class(TQueryBodyTypesBase)
private
{ Private declarations }
protected
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyInsertOrUpdate;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TQueryBodyTypesSimple.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
// Удаляем вариант корпуса
QueryBodyVariations.W.LocateByPKAndDelete(W.PK.Value);
// Удаляем неиспользуемые корпуса
DropUnusedBodies;
end;
procedure TQueryBodyTypesSimple.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
ApplyInsertOrUpdate;
end;
procedure TQueryBodyTypesSimple.ApplyInsertOrUpdate;
var
AID: Integer;
begin
QueryBodies.LocateOrAppend(W.Body.F.Value, W.IDBodyKind.F.Value);
QueryBodyData.LocateOrAppend(W.BodyData.F.Value, W.IDProducer.F.Value,
QueryBodies.W.PK.Value);
QueryBodyVariations.LocateOrAppend(QueryBodyData.W.PK.Value,
W.OutlineDrawing.F.AsString, W.LandPattern.F.AsString,
W.Variations.F.AsString, W.Image.F.AsString);
AID := QueryBodyVariations.W.PK.Value;
Assert(AID > 0);
W.IDS.F.Value := AID;
W.Body.F.Value := QueryBodies.W.Body.F.Value;
W.BodyData.F.Value := QueryBodyData.W.BodyData.F.Value;
W.IDBodyData.F.Value := QueryBodyData.W.PK.Value;
W.IDBody.F.Value := QueryBodies.W.PK.Value;
UpdateJEDEC;
UpdateOptions;
end;
procedure TQueryBodyTypesSimple.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
ApplyInsertOrUpdate;
end;
end.
|
unit ncaFrmConfigComissao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ncaFrmBaseOpcaoImgTxt, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Menus, cxMaskEdit, cxDropDownEdit,
cxTextEdit, cxCurrencyEdit, StdCtrls, cxButtons, cxLabel, dxGDIPlusClasses,
ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel;
type
TFrmConfigComissao = class(TFrmBaseOpcaoImgTxt)
LMDSimplePanel6: TLMDSimplePanel;
edComissaoPerc: TcxCurrencyEdit;
lbComissao: TcxLabel;
lbComissaoSobre: TcxLabel;
edComissaoLucro: TcxComboBox;
btnPremium: TcxButton;
procedure btnPremiumClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
function NumItens: Integer; override;
{ Public declarations }
end;
var
FrmConfigComissao: TFrmConfigComissao;
implementation
uses ncaFrmPri, ncClassesBase, ncaDM;
{$R *.dfm}
{ TFrmConfigComissao }
function TFrmConfigComissao.Alterou: Boolean;
begin
Result := (gConfig.ComissaoPerc <> edComissaoPerc.Value) or
(gConfig.ComissaoLucro <> (edComissaoLucro.ItemIndex=1));
end;
procedure TFrmConfigComissao.btnPremiumClick(Sender: TObject);
begin
inherited;
OpenPremium('comissao');
end;
procedure TFrmConfigComissao.FormCreate(Sender: TObject);
begin
inherited;
lbComissao.Enabled := gConfig.IsPremium;
edComissaoPerc.Enabled := gConfig.IsPremium;
lbComissaoSobre.Enabled := gConfig.IsPremium;
edComissaoLucro.Enabled := gConfig.IsPremium;
btnPremium.Visible := not gConfig.IsPremium;
end;
procedure TFrmConfigComissao.Ler;
begin
inherited;
edComissaoPerc.Value := gConfig.ComissaoPerc;
edComissaoLucro.ItemIndex := Byte(gConfig.ComissaoLucro);
end;
function TFrmConfigComissao.NumItens: Integer;
begin
Result := 1;
end;
procedure TFrmConfigComissao.Renumera;
begin
RenumLB(lbComissao, 0);
end;
procedure TFrmConfigComissao.Salvar;
begin
inherited;
gConfig.ComissaoPerc := edComissaoPerc.Value;
gConfig.ComissaoLucro := (edComissaoLucro.ItemIndex=1);
end;
end.
|
unit uDrawLib;
interface
uses Forms, Math, Graphics, uMain, uMyTypes, Windows, SysUtils, Dialogs, Classes, uObjectFont;
procedure KruzPlocha(stred: TMyPoint; priemer: double; farVypln, farOkolo: TColor; hrubka: integer=1);
procedure KruzObvod(stred: TMyPoint; priemer: double; farba: TColor; hrubka: integer=1; styl: TPenStyle=psSolid);
procedure ObdlzPlocha(stred: TMyPoint; rozmerX, rozmerY, radius, priemerZapichu: double; farVypln, farOkolo: TColor; hrubka: integer=1);
procedure ObdlzObvod(stred: TMyPoint; rozmerX, rozmerY, radius: double; farba: TColor; hrubka: integer=1; styl: TPenStyle=psSolid);
procedure Ciara(zaciatok, koniec: TMyPoint; farba: TColor; sirka: double = 0; styl: TPenStyle=psSolid);
procedure Obluk(stred: TMyPoint; priemer, uholStart, uholEnd: double; farOkolo: TColor; hrubka: integer=1; uzatvorit: boolean=false; styl: TPenStyle=psSolid);
function TextWidth(txt: string; velkost: double; qpfont: TMyFont): double;
procedure Text(txt: string; bodVlozenia: TMyPoint; velkost, celkova_sirka: double; typVelkosti, zarovnanie: string; farba: TColor; nastroj: double; FontTextu: TMyFont; rotacia: Double = 0);
procedure Text_old(txt: string; bodVlozenia: TMyPoint; velkost: double; typVelkosti, zarovnanie: string; farba: TColor);
function ZrkadliUhol(uhol: double; OkoloOsi: char = 'y'): double;
function CiaraOffset(zaciatok: TMyPoint; koniec: TMyPoint; strana: char; distance: double): TMyPoint2D;
procedure CiaraOffset2(var usecka: TMyPoint2D; strana: char; distance: double);
function RotujBodOkoloBoduPX(bod, stredRotacie: TPoint; uhol: double): TPoint;
function RotujBodOkoloBoduMM(bod, stredRotacie: TMyPoint; uhol: double): TMyPoint;
implementation
uses uDebug, uConfig;
function RotujBodOkoloBoduMM(bod, stredRotacie: TMyPoint; uhol: double): TMyPoint;
var
s,c: Double;
begin
// stupne na radiany
uhol := uhol * piDelene180;
s := Sin(uhol);
c := Cos(uhol);
bod.X := bod.X - stredRotacie.X;
bod.Y := bod.Y - stredRotacie.Y;
// pri vypocte rotacie milimetrovych hodnot su trochu inak znamienka pri Ypsilone (de facto sa rotuje do opacneho smeru) lebo v MM systeme Y smerom nahor stupa (v PX systeme je to naopak)
Result.X := c * bod.X - s * bod.Y + stredRotacie.X;
Result.Y := s * bod.X + c * bod.Y + stredRotacie.Y;
end;
function RotujBodOkoloBoduPX(bod, stredRotacie: TPoint; uhol: double): TPoint;
var
s,c: Double;
begin
// stupne na radiany
uhol := uhol * piDelene180;
s := Sin(uhol);
c := Cos(uhol);
bod.X := bod.X - stredRotacie.X;
bod.Y := bod.Y - stredRotacie.Y;
Result.X := Round( c * bod.X + s * bod.Y + stredRotacie.X );
Result.Y := Round( -s * bod.X + c * bod.Y + stredRotacie.Y );
end;
procedure KruzPlocha(stred: TMyPoint; priemer: double; farVypln, farOkolo: TColor; hrubka: integer=1);
begin
BackPlane.Canvas.Brush.Color := farVypln;
BackPlane.Canvas.Pen.Color := farOkolo;
BackPlane.Canvas.Pen.Width := hrubka;
BackPlane.Canvas.Ellipse(
PX(stred.X - (priemer/2), 'x'),
PX(stred.Y - (priemer/2), 'y') + 1,
PX(stred.X + (priemer/2), 'x') + 1,
PX(stred.Y + (priemer/2), 'y')
);
end;
procedure KruzObvod(stred: TMyPoint; priemer: double; farba: TColor; hrubka: integer=1; styl: TPenStyle=psSolid);
begin
BackPlane.Canvas.Brush.Style := bsClear;
BackPlane.Canvas.Pen.Color := farba;
BackPlane.Canvas.Pen.Width := hrubka;
BackPlane.Canvas.Pen.Style := styl;
BackPlane.Canvas.Ellipse(
PX(stred.X - (priemer/2), 'x'),
PX(stred.Y - (priemer/2), 'y') + 1,
PX(stred.X + (priemer/2), 'x') + 1,
PX(stred.Y + (priemer/2), 'y')
);
end;
procedure ObdlzPlocha(stred: TMyPoint; rozmerX, rozmerY, radius, priemerZapichu: double; farVypln, farOkolo: TColor; hrubka: integer=1);
var
tmp_x_MM, tmp_y_MM: double;
begin
BackPlane.Canvas.Brush.Color := farVypln;
BackPlane.Canvas.Pen.Color := farOkolo;
BackPlane.Canvas.Pen.Width := hrubka;
BackPlane.Canvas.RoundRect(
Px(stred.X-(rozmerX/2),'x'),
Px(stred.Y-(rozmerY/2),'y')+1,
Px(stred.X+(rozmerX/2),'x')+1,
Px(stred.Y+(rozmerY/2),'y'),
Px(radius*2),
Px(radius*2)
);
if radius = 0 then begin // ak ma v rohoch R0, vykreslime zapichy
BackPlane.Canvas.Pen.Color := BackPlane.Canvas.Brush.Color;
// tmp_x(resp.y)_MM je posunutie kruznice zapichu od rohu
tmp_x_MM := (priemerZapichu/2)*(1-cos( PI/4 )); // tmp_x_MM = R-(R*cos45') = R*(1-cos45')
tmp_y_MM := (priemerZapichu/2)*(1-sin( PI/4 )); // tmp_y_MM = R-(R*sin45') = R*(1-sin45')
BackPlane.Canvas.Ellipse(
Px(stred.X-(rozmerX/2)-tmp_x_MM,'x'),
Px(stred.Y-(rozmerY/2)-tmp_y_MM,'y'),
Px(stred.X-(rozmerX/2)+(priemerZapichu-tmp_x_MM),'x'),
Px(stred.Y-(rozmerY/2)+(priemerZapichu-tmp_y_MM),'y')
);
BackPlane.Canvas.Ellipse(
Px(stred.X+(rozmerX/2)+tmp_x_MM,'x')+1,
Px(stred.Y-(rozmerY/2)-tmp_y_MM,'y'),
Px(stred.X+(rozmerX/2)-(priemerZapichu-tmp_x_MM),'x')+1,
Px(stred.Y-(rozmerY/2)+(priemerZapichu-tmp_y_MM),'y')
);
BackPlane.Canvas.Ellipse(
Px(stred.X+(rozmerX/2)+tmp_x_MM,'x')+1,
Px(stred.Y+(rozmerY/2)+tmp_y_MM,'y'),
Px(stred.X+(rozmerX/2)-(priemerZapichu-tmp_x_MM),'x')+1,
Px(stred.Y+(rozmerY/2)-(priemerZapichu-tmp_y_MM),'y')
);
BackPlane.Canvas.Ellipse(
Px(stred.X-(rozmerX/2)-tmp_x_MM,'x'),
Px(stred.Y+(rozmerY/2)+tmp_y_MM,'y'),
Px(stred.X-(rozmerX/2)+(priemerZapichu-tmp_x_MM),'x'),
Px(stred.Y+(rozmerY/2)-(priemerZapichu-tmp_y_MM),'y')
);
end; // ak ma v rohoch R=0
end;
procedure ObdlzObvod(stred: TMyPoint; rozmerX, rozmerY, radius: double; farba: TColor; hrubka: integer=1; styl: TPenStyle=psSolid);
begin
BackPlane.Canvas.Brush.Style := bsClear;
BackPlane.Canvas.Pen.Color := farba;
BackPlane.Canvas.Pen.Width := hrubka;
BackPlane.Canvas.Pen.Style := styl;
BackPlane.Canvas.RoundRect(
Px(stred.X-(rozmerX/2),'x'),
Px(stred.Y-(rozmerY/2),'y')+1,
Px(stred.X+(rozmerX/2),'x')+1,
Px(stred.Y+(rozmerY/2),'y'),
Px(radius*2),
Px(radius*2)
);
end;
procedure Ciara(zaciatok, koniec: TMyPoint; farba: TColor; sirka: double = 0; styl: TPenStyle=psSolid);
begin
BackPlane.Canvas.Pen.Color := farba;
if sirka > 0 then BackPlane.Canvas.Pen.Width := PX(sirka)
else BackPlane.Canvas.Pen.Width := 1;
BackPlane.Canvas.Pen.Style := styl;
BackPlane.Canvas.MoveTo( PX(zaciatok.X, 'x'), PX(zaciatok.Y, 'y') );
BackPlane.Canvas.LineTo( PX(koniec.X, 'x'), PX(koniec.Y, 'y') );
end;
procedure Obluk(stred: TMyPoint; priemer, uholStart, uholEnd: double; farOkolo: TColor; hrubka: integer=1; uzatvorit: boolean=false; styl: TPenStyle=psSolid);
var
startPoint, endPoint: TMyPoint;
polomer: Double;
uholStartRad, uholEndRad: Double;
uholStartCos, uholStartSin, uholEndCos, uholEndSin: Double;
begin
BackPlane.Canvas.Brush.Style := bsClear;
BackPlane.Canvas.Pen.Color := farOkolo;
BackPlane.Canvas.Pen.Width := hrubka;
BackPlane.Canvas.Pen.Style := styl;
uholStartRad := DegToRad(uholStart);
uholEndRad := DegToRad(uholEnd);
uholStartCos := cos(uholStartRad);
uholStartSin := sin(uholStartRad);
uholEndCos := cos(uholEndRad);
uholEndSin := sin(uholEndRad);
// vypocitam body, ktore urcuju start/stop obluka (na obrovskom polomere aby to bolo presnejsie)
// (podla rovnice kruznice X = A + r*cos ALFA ; Y = B + r*sin BETA)
startPoint.X := stred.X + ( 999 * uholStartCos );
startPoint.Y := stred.Y + ( 999 * uholStartSin );
endPoint.X := stred.X + ( 999 * uholEndCos );
endPoint.Y := stred.Y + ( 999 * uholEndSin );
// SetArcDirection( GetDC(BackPlane.Canvas.Handle) , AD_COUNTERCLOCKWISE);
polomer := priemer/2;
BackPlane.Canvas.Arc(
PX(stred.X - polomer, 'x'),
PX(stred.Y - polomer, 'y') + 1,
PX(stred.X + polomer, 'x') + 1,
PX(stred.Y + polomer, 'y'),
PX(startPoint.X, 'x'), PX(startPoint.Y, 'y'),
PX(endPoint.X, 'x'), PX(endPoint.Y, 'y')
);
if uzatvorit then begin
// vypocitam body (leziace na kruznici), ktore urcuju start/stop obluka
// (podla rovnice kruznice X = A + r*cos ALFA ; Y = B + r*sin BETA)
startPoint.X := stred.X + ( polomer * uholStartCos );
startPoint.Y := stred.Y + ( polomer * uholStartSin );
endPoint.X := stred.X + ( polomer * uholEndCos );
endPoint.Y := stred.Y + ( polomer * uholEndSin );
BackPlane.Canvas.MoveTo( PX(startPoint.X, 'x'), PX(startPoint.Y, 'y') );
BackPlane.Canvas.LineTo( PX(endPoint.X, 'x'), PX(endPoint.Y, 'y') );
end;
end;
function TextWidth(txt: string; velkost: double; qpfont: TMyFont): double;
var
i: Integer;
indexZnaku: Integer;
sizeFaktor: double;
begin
sizeFaktor := velkost / 10;
Result := 0;
for i := 1 to Length(txt) do begin
indexZnaku := Ord(Char(txt[i]));
if Assigned(qpfont.Items[indexZnaku]) then begin // ak taky znak pozna, pripocita jeho sirku
Result := Result + ((qpfont[indexZnaku].sirkaZnaku + qpfont[indexZnaku].sirkaMedzery) * sizeFaktor);
end else begin
// ak taky znak nepozna,....
Result := Result + (sirkaNeznamehoZnaku * sizeFaktor);
end;
end;
// od posledneho znaku odpocita sirku medzery za nim - tu uz nam netreba
if Result > 0 then
Result := Result - (qpfont[indexZnaku].sirkaMedzery * sizeFaktor);
end;
procedure Text(txt: string; bodVlozenia: TMyPoint; velkost, celkova_sirka: double; typVelkosti, zarovnanie: string; farba: TColor; nastroj: double; FontTextu: TMyFont; rotacia: Double = 0);
var
posunX, posunY: integer;
i,j,x,y: integer;
vyslednyBod: TPoint;
stredRotacie: TPoint;
offsetPX: integer;
sizeFaktor: double;
indexZnaku: integer;
begin
offsetPX := 0;
if zarovnanie = taCenter then // zarovnaj na stred
posunX := -PX(celkova_sirka / 2);
if zarovnanie = taRight then // zarovnaj doprava
posunX := 0;
if zarovnanie = taLeft then // zarovnaj dolava
posunX := -PX(celkova_sirka);
posunY := PX(velkost / 2);
//velkost := velkost - nastroj; // aby SKUTOCNA velkost textu nebola zvacsena o priemer nastroja EDIT: vypnute, lebo sa menila tym padom aj sirka textu (podla toho aky gravir bol zvoleny) a to asi nem dobre
sizeFaktor := velkost / 10;
x := PX(bodVlozenia.X,'x') + posunX;
y := PX(bodVlozenia.Y,'y') + posunY;
if rotacia <> 0 then begin
stredRotacie.X := PX(bodVlozenia.X,'x');
stredRotacie.Y := PX(bodVlozenia.Y,'y');
end;
BackPlane.Canvas.Pen.Style := psSolid;
BackPlane.Canvas.Pen.Color := farba;
BackPlane.Canvas.Pen.Width := PX(nastroj);
for i := 1 to Length(txt) do begin
indexZnaku := Ord(Char(txt[i]));
if (indexZnaku > FontTextu.Capacity) OR (not Assigned(FontTextu.Items[indexZnaku])) then
indexZnaku := Ord(Char('?')); // ak taky znak nepozna, vykresli '?'
for j := 0 to Length(FontTextu.Znaky[indexZnaku].Points)-1 do begin
vyslednyBod.X := x + offsetPX + PX( FontTextu.Znaky[indexZnaku].Points[j].bod.X * sizeFaktor );
vyslednyBod.Y := y - PX( FontTextu.Znaky[indexZnaku].Points[j].bod.Y * sizeFaktor );
if rotacia <> 0 then begin
vyslednyBod := RotujBodOkoloBoduPX(vyslednyBod, stredRotacie, rotacia);
end;
if FontTextu.Znaky[indexZnaku].Points[j].kresli then
BackPlane.Canvas.LineTo(vyslednyBod.X , vyslednyBod.Y)
else
BackPlane.Canvas.MoveTo(vyslednyBod.X , vyslednyBod.Y);
end;
offsetPX := offsetPX + PX((FontTextu.Znaky[indexZnaku].sirkaZnaku + FontTextu.Znaky[indexZnaku].sirkaMedzery) * sizeFaktor);
end;
{
// nastavenie velkosti pisma
BackPlane.Canvas.Font.Size := 1;
if typVelkosti = 'WIDTHALL' then
while BackPlane.Canvas.TextWidth(txt) < PX(velkost) do
BackPlane.Canvas.Font.Size := BackPlane.Canvas.Font.Size + 1
else
BackPlane.Canvas.Font.Size := PX(velkost);
// nastavenie zarovnania v X
posunX := 0;
if zarovnanie = '0' then // 0 = zarovnaj na stred
posunX := Round( BackPlane.Canvas.TextWidth(txt) / 2 );
if zarovnanie = '2' then // 2 = zarovnaj dolava
posunX := BackPlane.Canvas.TextWidth(txt);
// nastavenie zarovnania v Y
posunY := Round( BackPlane.Canvas.TextHeight(txt) / 2 );
}
end;
procedure Text_old(txt: string; bodVlozenia: TMyPoint; velkost: double; typVelkosti, zarovnanie: string; farba: TColor);
var
posunX, posunY: integer;
begin
BackPlane.Canvas.Brush.Style := bsClear;
BackPlane.Canvas.Pen.Color := farba;
BackPlane.Canvas.Font.Name := 'Simplex';
BackPlane.Canvas.Font.Color := farba;
// nastavenie velkosti pisma
BackPlane.Canvas.Font.Size := 1;
if typVelkosti = 'WIDTHALL' then
while BackPlane.Canvas.TextWidth(txt) < PX(velkost) do
BackPlane.Canvas.Font.Size := BackPlane.Canvas.Font.Size + 1
else
BackPlane.Canvas.Font.Size := PX(velkost);
// nastavenie zarovnania v X
posunX := 0;
if zarovnanie = '0' then // 0 = zarovnaj na stred
posunX := Round( BackPlane.Canvas.TextWidth(txt) / 2 );
if zarovnanie = '2' then // 2 = zarovnaj dolava
posunX := BackPlane.Canvas.TextWidth(txt);
// nastavenie zarovnania v Y
posunY := Round( BackPlane.Canvas.TextHeight(txt) / 2 );
// vykreslenie
BackPlane.Canvas.TextOut( PX(bodVlozenia.X,'x')-posunX, PX(bodVlozenia.Y,'y')-posunY, txt );
end;
function ZrkadliUhol(uhol: double; OkoloOsi: char = 'y'): double;
begin
(*
if (OkoloOsi = 'y') then begin
if (Uhol >= 0) AND (Uhol < 90) then
result := 90 + (90 - Uhol);
if (Uhol >= 90) AND (Uhol < 180) then
result := 90 - (Uhol - 90);
if (Uhol >= 180) AND (Uhol < 270) then
result := 270 + (270 - Uhol);
if (Uhol >= 270) AND (Uhol < 360) then
result := 270 - (Uhol - 270);
end else begin
end;
*)
result := uhol;
end;
function CiaraOffset(zaciatok: TMyPoint; koniec: TMyPoint; strana: char; distance: double): TMyPoint2D;
var
uhol, dx, dy: double;
begin
if koniec.X = zaciatok.X then begin
if (koniec.Y > zaciatok.Y) then uhol := DegToRad(90)
else uhol := DegToRad(270);
end else
uhol := ArcTan((koniec.Y-zaciatok.Y) / (koniec.X-zaciatok.X));
dx := sin( uhol ) * distance;
dy := cos( uhol ) * distance;
if strana = 'L' then begin
dx := -dx;
dy := -dy;
end;
// showmessage('['+floattostr(zaciatok.X)+','+floattostr(zaciatok.Y)+']...['+floattostr(koniec.X)+','+floattostr(koniec.Y)+'] o '+ floattostr(distance)+' uhlom '+floattostr(radtodeg(uhol))+' = ' + floattostr(dx)+','+floattostr(dy));
result.first.X := zaciatok.X + dx;
result.first.Y := zaciatok.Y - dy;
result.second.X := koniec.X + dx;
result.second.Y := koniec.Y - dy;
end;
procedure CiaraOffset2(var usecka: TMyPoint2D; strana: char; distance: double);
begin
// iny sposob volania funkcie na offset ciary - da sa takto volat aj s parametrom, ktorym je premenna
usecka := CiaraOffset(usecka.first, usecka.second, strana, distance);
end;
begin
end.
|
unit FC.StockChart.UnitTask.TradeLine.AnalysisDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Contnrs,
Dialogs, BaseUtils,SystemService, ufmDialogClose_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Spin,
StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, DB, Grids, DBGrids, MultiSelectDBGrid,
ColumnSortDBGrid, EditDBGrid, MemoryDS, ComCtrls, FC.StockChart.CustomDialog_B, ImgList, JvCaptionButton,
JvComponentBase, JvDockControlForm, JvExExtCtrls, JvNetscapeSplitter;
type
TfmTradeLineAnalysisDialog = class(TfmStockChartCustomDialog_B)
taReport: TMemoryDataSet;
DataSource1: TDataSource;
taReportNo: TIntegerField;
taReportDateTime: TDateTimeField;
taReportPrice: TFloatField;
Panel1: TPanel;
Label1: TLabel;
Panel2: TPanel;
buStart2: TButton;
JvNetscapeSplitter1: TJvNetscapeSplitter;
lvIndicators: TExtendListView;
taReportProfit: TIntegerField;
taReportIndicator: TFloatField;
alActions: TActionList;
acStart: TAction;
taReportOrderKind: TStringField;
Panel3: TPanel;
edFilter: TExtendComboBox;
grReport: TEditDBGrid;
buOpenOrder: TRadioButton;
buCloseOrder: TRadioButton;
ckSyncAllCharts: TExtendCheckBox;
procedure lvIndicatorsDblClick(Sender: TObject);
procedure edFilterKeyPress(Sender: TObject; var Key: Char);
procedure acStartUpdate(Sender: TObject);
procedure lvIndicatorsCreateItemClass(Sender: TCustomListView; var ItemClass: TListItemClass);
procedure grReportBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure buStart2Click(Sender: TObject);
procedure buOKClick(Sender: TObject);
procedure grReportDblClick(Sender: TObject);
private
FIndicator: ISCIndicatorTradeLine;
procedure CollectIndicators;
public
class procedure Run(const aIndicator: ISCIndicatorTradeLine; const aStockChart: IStockChart);
constructor Create(const aStockChart: IStockChart); override;
destructor Destroy; override;
end;
implementation
uses Math,StockChart.Definitions.Drawing, ufmForm_B;
{$R *.dfm}
type
TIndicatorListItem = class (TListItem)
Indicator: ISCIndicatorValueSupport;
end;
{ TfmCalculateWidthDialog }
procedure TfmTradeLineAnalysisDialog.acStartUpdate(Sender: TObject);
begin
inherited;
TAction(Sender).Enabled:=lvIndicators.Selected<>nil;
end;
procedure TfmTradeLineAnalysisDialog.buOKClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfmTradeLineAnalysisDialog.buStart2Click(Sender: TObject);
var
i,j: integer;
aOrder: ISCIndicatorTradeLineItem;
aIndicator: ISCIndicatorValueSupport;
aTime: TDateTime;
begin
aIndicator:=TIndicatorListItem(lvIndicators.Selected).Indicator;
taReport.DisableControls;
taReport.Open;
taReport.EmptyTable;
try
for i := 0 to FIndicator.ItemCount - 1 do
begin
aOrder:=FIndicator.GetItem(i);
if aOrder.GetKind<>mkNone then
continue;
taReport.Append;
taReportNo.Value:=taReport.RecordCount+1;
taReportOrderKind.Value:=OrderKindNames[aOrder.GetOrderKind];
if buOpenOrder.Checked then
begin
taReportDateTime.Value:=aOrder.GetOpenTime;
taReportPrice.Value:=aOrder.GetOpenPrice;
aTime:=aOrder.GetOpenTime;
end
else begin
taReportDateTime.Value:=aOrder.GetCloseTime;
taReportPrice.Value:=aOrder.GetClosePrice;
aTime:=aOrder.GetClosePrice;
end;
if aOrder.GetClosePrice<>0 then //незакрытый ордер
begin
if aOrder.GetOrderKind=okBuy then
taReportProfit.Value:=FIndicator.GetInputData.PriceToPoint(aOrder.GetClosePrice-aOrder.GetOpenPrice)
else
taReportProfit.Value:=FIndicator.GetInputData.PriceToPoint(-aOrder.GetClosePrice+aOrder.GetOpenPrice);
end;
j:=(aIndicator as ISCIndicator).GetInputData.FindExactMatched(aTime);
if j<>-1 then
taReportIndicator.Value:=FIndicator.GetInputData.RoundPrice(aIndicator.GetValue(j));
taReport.Post;
end;
finally
taReport.First;
taReport.EnableControls;
end;
end;
procedure TfmTradeLineAnalysisDialog.CollectIndicators;
var
aIndicators: ISCIndicatorCollectionReadOnly;
i: integer;
begin
lvIndicators.HandleNeeded;
aIndicators:=StockChart.FindIndicators(ISCIndicatorValueSupport);
for i := 0 to aIndicators.Count-1 do
begin
with lvIndicators.Items.Add as TIndicatorListItem do
begin
Caption:=aIndicators.Items[i].Caption;
Indicator:=aIndicators.Items[i] as ISCIndicatorValueSupport;
end;
end;
lvIndicators.ViewStyle:=vsIcon;
lvIndicators.ViewStyle:=vsList;
end;
constructor TfmTradeLineAnalysisDialog.Create(const aStockChart: IStockChart);
var
s: string;
i: integer;
begin
inherited;
s:='';
for i:= 0 to taReport.FieldCount- 1 do
begin
s:=s+taReport.Fields[i].FieldName+', ';
end;
s:='Filter. Available fields: '+StrDeleteRightEdge(s,', ');
edFilter.Hint:=s;
RegisterPersistValue(buOpenOrder,true);
RegisterPersistValue(buCloseOrder,false);
RegisterPersistValue(ckSyncAllCharts,true);
end;
destructor TfmTradeLineAnalysisDialog.Destroy;
begin
inherited;
end;
procedure TfmTradeLineAnalysisDialog.edFilterKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then
begin
taReport.Filter:=edFilter.Text;
taReport.Filtered:=true;
end;
end;
procedure TfmTradeLineAnalysisDialog.grReportBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
begin
if (Column.Field=taReportProfit) or (Column.Field=taReportIndicator) then
begin
if Column.Field.IsNull then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWindow
else if Column.Field.AsFloat<0 then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightBlue
else
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebBisque;
end
else if Column.Field=taReportOrderKind then
begin
if Column.Field.IsNull then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWindow
else if Column.Field.AsString=OrderKindNames[okSell] then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightBlue
else
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebBisque;
end;
end;
procedure TfmTradeLineAnalysisDialog.grReportDblClick(Sender: TObject);
var
aX1,aX2: TDateTime;
begin
inherited;
TWaitCursor.SetUntilIdle;
if ckSyncAllCharts.Checked then
begin
aX1:=taReportDateTime.Value;
aX2:=aX1+StockChart.StockSymbol.GetTimeIntervalValue/MinsPerDay;
StockChart.GetProject.HilightOnCharts(aX1,aX2,true);
end
else begin
StockChart.LocateTo(taReportDateTime.Value,lmCenter);
StockChart.Mark(taReportDateTime.Value);
end;
end;
procedure TfmTradeLineAnalysisDialog.lvIndicatorsCreateItemClass(Sender: TCustomListView;
var ItemClass: TListItemClass);
begin
inherited;
ItemClass:=TIndicatorListItem;
end;
procedure TfmTradeLineAnalysisDialog.lvIndicatorsDblClick(Sender: TObject);
begin
inherited;
if lvIndicators.Selected<>nil then
acStart.Execute;
end;
class procedure TfmTradeLineAnalysisDialog.Run(const aIndicator: ISCIndicatorTradeLine; const aStockChart: IStockChart);
begin
with TfmTradeLineAnalysisDialog.Create(aStockChart) do
begin
FIndicator:=aIndicator;
Caption:=IndicatorFactory.GetIndicatorInfo((FIndicator as ISCIndicator).GetIID).Name+': '+Caption;
CollectIndicators;
Forms.Application.ProcessMessages;
Show;
end;
end;
end.
|
unit LLVM.Imports.Disassembler;
interface
//based on Disassembler.h
uses
LLVM.Imports,
LLVM.Imports.Types,
LLVM.Imports.DisassemblerTypes;
(*
* Create a disassembler for the TripleName. Symbolic disassembly is supported
* by passing a block of information in the DisInfo parameter and specifying the
* TagType and callback functions as described above. These can all be passed
* as NULL. If successful, this returns a disassembler context. If not, it
* returns NULL. This function is equivalent to calling
* LLVMCreateDisasmCPUFeatures() with an empty CPU name and feature set.
*)
function LLVMCreateDisasm(TripleName: PLLVMChar; DisInfo: Pointer; TagType: Integer; GetOpInfo: TLLVMOpInfoCallback; SymbolLookUp: TLLVMSymbolLookupCallback): TLLVMDisasmContextRef; cdecl; external CLLVMLibrary;
(*
* Create a disassembler for the TripleName and a specific CPU. Symbolic
* disassembly is supported by passing a block of information in the DisInfo
* parameter and specifying the TagType and callback functions as described
* above. These can all be passed * as NULL. If successful, this returns a
* disassembler context. If not, it returns NULL. This function is equivalent
* to calling LLVMCreateDisasmCPUFeatures() with an empty feature set.
*)
function LLVMCreateDisasmCPU(Triple: PLLVMChar; CPU: PLLVMChar; DisInfo: Pointer; TagType: Integer; GetOpInfo: TLLVMOpInfoCallback; SymbolLookUp: TLLVMSymbolLookupCallback): TLLVMDisasmContextRef; cdecl; external CLLVMLibrary;
(*
* Create a disassembler for the TripleName, a specific CPU and specific feature
* string. Symbolic disassembly is supported by passing a block of information
* in the DisInfo parameter and specifying the TagType and callback functions as
* described above. These can all be passed * as NULL. If successful, this
* returns a disassembler context. If not, it returns NULL.
*)
function LLVMCreateDisasmCPUFeatures(Triple: PLLVMChar; CPU: PLLVMChar; Features: PLLVMChar; DisInfo: Pointer; TagType: Integer; GetOpInfo: TLLVMOpInfoCallback; SymbolLookUp: TLLVMSymbolLookupCallback): TLLVMDisasmContextRef; cdecl; external CLLVMLibrary;
(*
* Set the disassembler's options. Returns 1 if it can set the Options and 0
* otherwise.
*)
function LLVMSetDisasmOptions(DC: TLLVMDisasmContextRef; Options: UInt64): LongBool; cdecl; external CLLVMLibrary;
const
{The option to produce marked up assembly.}
LLVMDisassembler_Option_UseMarkup = 1;
{The option to print immediates as hex.}
LLVMDisassembler_Option_PrintImmHex = 2;
{The option use the other assembler printer variant}
LLVMDisassembler_Option_AsmPrinterVariant = 4;
{The option to set comment on instructions}
LLVMDisassembler_Option_SetInstrComments = 8;
{The option to print latency information alongside instructions}
LLVMDisassembler_Option_PrintLatency = 16;
procedure LLVMDisasmDispose(DC: TLLVMDisasmContextRef); cdecl; external CLLVMLibrary;
(*
* Disassemble a single instruction using the disassembler context specified in
* the parameter DC. The bytes of the instruction are specified in the
* parameter Bytes, and contains at least BytesSize number of bytes. The
* instruction is at the address specified by the PC parameter. If a valid
* instruction can be disassembled, its string is returned indirectly in
* OutString whose size is specified in the parameter OutStringSize. This
* function returns the number of bytes in the instruction or zero if there was
* no valid instruction.
*)
function LLVMDisasmInstruction(DC: TLLVMDisasmContextRef; Bytes: PByte; BytesSize: UInt64; PC: UInt64; OutString: PLLVMChar; OutStringSize: TLLVMSizeT): TLLVMSizeT; cdecl; external CLLVMLibrary;
implementation
end.
|
unit UEmpForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, pegradpanl, StdCtrls, Mask, Grids, DBGrids, Db, DBTables, pegraphic, DBClient, MIDAScon,
Tmax_DataSetText, OnDBGrid, OnFocusButton, ComCtrls, OnShapeLabel,
OnGrDBGrid, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl,
OnPopupEdit;
type
TFm_EmpForm = class(TForm)
ds1: TDataSource;
Query1: TTMaxDataSet;
Panel2: TPanel;
BB_close: TOnFocusButton;
Sb_Ok: TOnFocusButton;
Sb_Close: TOnFocusButton;
Grid1: TOnGrDbGrid;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Sb_CloseClick(Sender: TObject);
procedure Sb_OkClick(Sender: TObject);
procedure Grid1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FOrgDept : string;
Fempno : string;
Fkorname : string;
SqlText : string;
public
Edit : TOnWinPopupEdit;
FCloseYn : Boolean;
property OrgDeptList : string read FOrgDept write FOrgDept;
property empno : string read Fempno write Fempno;
property korname : string read Fkorname write Fkorname;
procedure SqlOpen;
end;
var
Fm_EmpForm : TFm_EmpForm;
implementation
uses PEA1072A1;
{$R *.DFM}
procedure TFm_EmpForm.FormCreate(Sender: TObject);
begin
FCloseYn := False;
end;
procedure TFm_EmpForm.Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssleft in shift then
begin
Releasecapture;
Self.Perform(WM_SYSCOMMAND, $F012, 0);
end;
end;
procedure TFm_EmpForm.Sb_CloseClick(Sender: TObject);
begin
Fempno := '';
Fkorname := '';
FCloseYn := True;
Edit.PopupForm.ClosePopup(False);
end;
procedure TFm_EmpForm.Sb_OkClick(Sender: TObject);
begin
if Query1.FieldByName('E1Valconyn').AsString = 'N' then
begin
MessageDlg('1차평가자께서 최종평가완료하지 않으신 평가자입니다.'+#13#13+
'궁금하신 사항은 HR팀에 문의하여 주십시오.',mtInformation,[mbOK],0);
end;
// else
begin
Fempno := Query1.FieldByName('empno').AsString;
Fkorname := Query1.FieldByName('korname').AsString;
FCloseYn := False;
Edit.PopupForm.ClosePopup(False);
end;
end;
procedure TFm_EmpForm.SqlOpen;
var
i : integer;
Field : TField;
Str : string;
OleData : OleVariant;
SqlText : string;
begin
SqlText := Format(' SELECT A.EMPNO, A.KORNAME, A.ORGNUM,B.DEPTCODE,B.DEPTNAME, '+
' A.PAYCL, C.CODENAME PAYCLNAME, A.PAYRA, E.CODENAME PAYRANAME, '+
' A.jobgun , D.codename, '+
' A.E1valconyn conyn, null, '+
' decode(A.E1valconyn, ''Y'',''평가완료'',''미평가'') prog '+
' FROM PEHREMAS A, PYCDEPT B, PYCCODE C, PYCCODE D, PYCCODE E '+
' WHERE A.RABASDATE= ''%s'' '+
' AND A.RESTIYN = ''Y'' '+
' AND A.DEPTCODE = B.DEPTCODE '+
' AND A.ORGNUM = B.ORGNUM '+
' AND A.PAYCL = C.CODENO(+) AND C.CODEID(+) = ''I112'' '+
' AND A.JOBGUN = D.CODENO(+) AND D.CODEID(+) = ''I115'' '+
' AND A.PAYRA = E.CODENO(+) AND E.CODEID(+) = ''I113'' '+
' AND A.empno in (select empno from petremas where rabasdate = ''%s'') '
,[FM_MAIN.vRabasdate,FM_MAIN.vRabasdate]);
if (FM_MAIN.AEmpno = FM_MAIN.Workemp1) or (FM_MAIN.AEmpno = FM_MAIN.Workemp2) or
(FM_MAIN.AEmpno = FM_MAIN.Workemp3) or (FM_MAIN.AEmpno = FM_MAIN.Workemp4) or
(FM_MAIN.AEmpno = FM_MAIN.Workemp5) or (Copy(FM_MAIN.AEmpno,1,1) = 'D') then
else if (FM_Main.vRabasdate = FM_Main.vRabasNew) then //평가결과오픈시
SqlText := SqlText + Format(' AND ( (A.EMPNO = ''%s'') ',[FM_MAIN.AEmpno])+
Format(' or (A.E1EMPNO = ''%s'') ',[FM_MAIN.AEmpno])+
Format(' or (A.E2EMPNO = ''%s'') ) ',[FM_MAIN.AEmpno])
else //조직개편이후 : 평가 이후에 팀장 변경시 새로운 팀장이 이전 평가 내역 볼수 있도록.
SqlText := SqlText + Format(' AND A.empno in (select empno from PEHREMAS where rabasdate = ''%s'' ', [FM_MAIN.vRabasNew])+
Format(' AND ( (A.E1EMPNO = ''%s'') ',[FM_MAIN.AEmpno] )+
Format(' or (A.E2EMPNO = ''%s'') ) ) ',[FM_MAIN.AEmpno] );
SqlText := SqlText + ' ORDER BY A.DEPTCODE, A.PAYRA, A.EMPNO ';
with Query1 do
begin
Close;
ClearFieldInFo;
AddField('EMPNO' , ftString, 4 );
AddField('KORNAME' , ftString, 12 );
AddField('ORGNUM' , ftString, 3 );
AddField('DEPTCODE' , ftString, 6 );
AddField('DEPTNAME' , ftString, 60 );
AddField('PAYCL' , ftString, 3 );
AddField('PAYCLNAME' , ftString, 20 );
AddField('PAYRA' , ftString, 3 );
AddField('PAYRANAME' , ftString, 20 );
AddField('JOBGUN' , ftString, 2 );
AddField('JOBGUNNAME' , ftString, 20 );
AddField('E1VALCONYN' , ftString, 1 );
AddField('FINYN' , ftString, 1 );
AddField('PROG' , ftString, 11 );
Sql.Clear;
Sql.Text := SqlText;
memo1.text := SqlText;
ServiceName := 'PIT1030A_SEL9';
Open;
if FM_Main.E_empno.Text <> '' then
Locate('EMPNO',vararrayof([FM_Main.E_empno.Text]),[loCaseInsensitive]);
end;
for i := 0 to Query1.FieldCount - 1 do
begin
Field := Query1.Fields[i];
Field.Visible := False;
case Field.Index of
0 : begin
Field.Visible := True;
Field.DisplayWidth := 8;
Field.DisplayLabel := '사 번';
end;
1 : begin
Field.Visible := True;
Field.DisplayWidth := 12;
Field.DisplayLabel := '성 명';
end;
8 : begin
Field.Visible := True;
Field.DisplayWidth := 10;
Field.DisplayLabel := '직 책';
end;
4 : begin
Field.Visible := True;
Field.DisplayWidth := 32;
Field.DisplayLabel := '부 서 명';
end;
13: begin
Field.Visible := True;
Field.DisplayWidth := 16;
Field.DisplayLabel := '진행상황';
end;
end;
end;
Width := GetDisplayWidth(Grid1.Canvas,Grid1.Font,87) + 36;
end;
procedure TFm_EmpForm.Grid1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = Chr(13) then
begin
Key := #0;
Sb_OkClick(Sender);
end;
end;
end.
|
unit Form.BaseEditForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseForm, dxSkinsCore,
dxSkinMetropolis, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Vcl.Menus, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxClasses, dxSkinsForm,
System.ImageList, Vcl.ImgList;
type
TfrmBaseEditor = class(TfrmBase)
pnlButton: TPanel;
btnOK: TcxButton;
btnCancel: TcxButton;
pnlHeader: TPanel;
pnlEditor: TPanel;
bvlTop: TBevel;
bvlBottom: TBevel;
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FHeader: string;
private
function GetHeader: string;
procedure SetHeader(const Value: string);
public
property Header : string read GetHeader write SetHeader;
end;
var
frmBaseEditor: TfrmBaseEditor;
implementation
{$R *.dfm}
{ TfrmBaseEditor }
procedure TfrmBaseEditor.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmBaseEditor.btnOKClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfrmBaseEditor.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = 13) and (ssCtrl in Shift) then
btnOKClick(nil);
if (Key = 27) then
btnCancelClick(nil);
end;
function TfrmBaseEditor.GetHeader: string;
begin
Result := FHeader;
end;
procedure TfrmBaseEditor.SetHeader(const Value: string);
begin
if FHeader <> Value then begin
FHeader := Value;
pnlHeader.Caption := FHeader;
end;
end;
end.
|
unit uFIFO_rec;
interface
uses windows, sysutils, math;
{$Q-}
{$R-}
type
tFIFO_rec_stat_direction = packed record
count : int64;
errors : int64;
end;
tFIFO_rec_stat = packed record
min : integer;
max : integer;
readed : tFIFO_rec_stat_direction;
writed : tFIFO_rec_stat_direction;
end;
pFIFO_rec = ^tFIFO_rec;
tFIFO_rec=packed record
wr : Cardinal;
rd : Cardinal;
size : integer;
mask : integer;
stat_readed : int64; // for old prorams compatibility
stat_writed : int64; // for old prorams compatibility
errors_readed : cardinal; // for old prorams compatibility
errors_writed : cardinal; // for old prorams compatibility
stat : tFIFO_rec_stat; //main statistics
end;
procedure _FIFO_rec_init(var fifo:tFIFO_rec; v_size:integer; var fixed_size:integer);
procedure _FIFO_rec_reset(var fifo:tFIFO_rec);
procedure _FIFO_rec_stat_reset(var fifo:tFIFO_rec);
function _FIFO_rec_count(var fifo:tFIFO_rec; fixed_size:integer):integer;
function _FIFO_rec_count_ratio(var fifo:tFIFO_rec; fixed_size:integer):integer;
function _FIFO_rec_free(var fifo:tFIFO_rec; fixed_size:integer):integer;
function _FIFO_rec_free_ratio(var fifo:tFIFO_rec; fixed_size:integer):integer;
procedure _FIFO_rec_write(var fifo:tFIFO_rec; data:pointer; fixed_size:integer; buffer:pointer; buf_size:integer);
procedure _FIFO_rec_read(var fifo:tFIFO_rec; data:pointer; fixed_size:integer; buffer:pointer; buf_size:integer);
procedure _FIFO_rec_read_void(var fifo:tFIFO_rec; fixed_size:integer; buf_size:integer);
//const
// fifo_no_tid = $FFFFFFFF;
implementation
uses classes;
////////////////////////////////////////////////////////////////////////////////
procedure MemoryBarrier;
{$IF defined(CPU386)}
asm
PUSH EAX
XCHG [ESP],EAX
POP EAX
mfence
end;
{$ELSE}
begin
end;
{$IFEND}
procedure _FIFO_rec_init(var fifo:tFIFO_rec; v_size:integer; var fixed_size:integer);
var
size_2_pwr : byte;
k : integer;
begin
size_2_pwr := 0;
for k:= 30 downto 1 do
if ((1 shl k) and v_size) <> 0 then
if (((1 shl k)-1) and v_size) <> 0 then
begin
size_2_pwr := k+1;
break;
end
else
begin
size_2_pwr := k;
break;
end;
fixed_size := 1 shl size_2_pwr;
fifo.size := fixed_size;
fifo.mask := fixed_size - 1;
_FIFO_rec_reset(fifo);
end;
procedure _FIFO_rec_reset(var fifo:tFIFO_rec);
begin
fifo.rd := 0;
fifo.wr := 0;
_FIFO_rec_stat_reset(fifo);
MemoryBarrier;
fifo.wr := 0;
fifo.rd := 0;
_FIFO_rec_stat_reset(fifo);
MemoryBarrier;
end;
function _FIFO_rec_count(var fifo:tFIFO_rec; fixed_size:integer):integer;
begin
result := fifo.wr - fifo.rd;
if result > fixed_size then result := fixed_size;
if result < 0 then result := 0;
end;
function _FIFO_rec_free(var fifo:tFIFO_rec; fixed_size:integer):integer;
begin
result := fixed_size - _FIFO_rec_count(fifo, fixed_size);
end;
procedure _FIFO_rec_write(var fifo:tFIFO_rec; data:pointer; fixed_size:integer; buffer:pointer; buf_size:integer);
var
w,r : Cardinal;
ptr : pbyte;
buf : pbyte absolute buffer;
pos : cardinal;
cnt : integer;
begin
if buf_size <= 0 then exit;
MemoryBarrier;
inc(fifo.stat_writed, buf_size);
inc(fifo.stat.writed.count, buf_size);
w := fifo.wr;
r := fifo.rd;
pos := w mod fixed_size;
cnt := w - r;
if cnt < 0 then
begin
fifo.wr := r;
inc(fifo.errors_writed);
inc(fifo.stat.writed.errors);
cnt := 0;
end;
if fifo.stat.min > cnt then
fifo.stat.min := cnt;
if cnt >= fixed_size then
begin
fifo.wr := r + fixed_size;
inc(fifo.errors_writed);
inc(fifo.stat.writed.errors);
exit;
end;
if buf_size > fixed_size - cnt then
begin
inc(fifo.errors_writed);
inc(fifo.stat.writed.errors);
buf_size := fixed_size - cnt;
if buf_size = 0 then exit;
end;
if buf_size <= 0 then exit;
ptr := data;
inc(ptr, pos);
if pos + buf_size > fixed_size then
begin
move(buf^, ptr^, fixed_size - pos);
inc(buf, fixed_size - pos);
move(buf^, data^, buf_size - (fixed_size - pos));
end
else
move(buf^, ptr^, buf_size);
inc(cnt, buf_size);
if fifo.stat.max < cnt then
fifo.stat.max := cnt;
inc(fifo.wr, buf_size);
MemoryBarrier();
end;
procedure _FIFO_rec_read(var fifo:tFIFO_rec; data:pointer; fixed_size:integer; buffer:pointer; buf_size:integer);
var
w,r : cardinal;
ptr : pbyte;
buf : pbyte absolute buffer;
pos : cardinal;
cnt : integer;
begin
if buf_size <= 0 then exit;
MemoryBarrier;
inc(fifo.stat_readed, buf_size);
inc(fifo.stat.readed.count, buf_size);
w := fifo.wr;
r := fifo.rd;
pos := r mod fixed_size;
cnt := w - r;
if fifo.stat.max < cnt then
fifo.stat.max := cnt;
if cnt < 0 then
begin
fifo.rd := w;
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
exit;
end;
if cnt > fixed_size then
begin
fifo.rd := w - fixed_size;
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
cnt := fixed_size;
end;
if buf_size > cnt then
begin
inc(buf, cnt);
fillchar(buf^, buf_size - cnt, 0);
dec(buf, cnt);
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
buf_size := cnt;
end;
if buf_size <=0 then exit;
ptr := data;
inc(ptr, pos);
if pos + buf_size > fixed_size then
begin
move(ptr^, buf^, fixed_size - pos);
inc(buf, fixed_size - pos);
move(data^, buf^, buf_size - (fixed_size - pos));
end
else
move(ptr^, buf^, buf_size);
dec(cnt, buf_size);
if fifo.stat.min > cnt then
fifo.stat.min := cnt;
inc(fifo.rd, buf_size);
MemoryBarrier;
end;
procedure _FIFO_rec_read_void(var fifo:tFIFO_rec; fixed_size:integer; buf_size:integer);
var
w,r : int64;
cnt : integer;
begin
if buf_size <= 0 then exit;
MemoryBarrier;
inc(fifo.stat_readed, buf_size);
inc(fifo.stat.readed.count, buf_size);
w := fifo.wr;
r := fifo.rd;
cnt := w - r;
if fifo.stat.max < cnt then
fifo.stat.max := cnt;
if cnt < 0 then
begin
fifo.rd := r;
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
exit;
end;
if cnt > fixed_size then
begin
fifo.rd := r - fixed_size;
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
cnt := fixed_size;
end;
if buf_size > cnt then
begin
inc(fifo.errors_readed);
inc(fifo.stat.readed.errors);
buf_size := cnt;
end;
dec(cnt, buf_size);
if fifo.stat.min > cnt then
fifo.stat.min := cnt;
inc(fifo.rd, buf_size);
MemoryBarrier;
end;
procedure _FIFO_rec_stat_reset(var fifo:tFIFO_rec);
begin
fillchar(fifo.stat, sizeof(fifo.stat), 0);
fifo.stat.min := MaxInt;
fifo.stat_readed := 0;
fifo.stat_writed := 0;
fifo.errors_readed := 0;
fifo.errors_writed := 0;
MemoryBarrier;
end;
function _FIFO_rec_count_ratio(var fifo:tFIFO_rec; fixed_size:integer):integer;
begin
result:=round(_FIFO_rec_count(fifo, fixed_size)/fixed_size*1000);
end;
function _FIFO_rec_free_ratio(var fifo:tFIFO_rec; fixed_size:integer):integer;
begin
result:=round(_FIFO_rec_free(fifo, fixed_size)/fixed_size*1000);
end;
end.
|
unit BlowFishEx;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, BlowFish;
function BlowFishEncryptStr(const Src, AKey: string): string;
function BlowFishDecryptStr(const Src, AKey: string): string;
implementation
function BlowFishEncryptStr(const Src, AKey: string): string;
var
VInput: TStringStream;
VBF: TBlowFishEncryptStream;
begin
VInput := TStringStream.Create('');
VBF := TBlowFishEncryptStream.Create(AKey, VInput);
try
VBF.Write(Pointer(Src)^, Length(Src));
finally
VBF.Free;
Result := VInput.DataString;
VInput.Free;
end;
end;
function BlowFishDecryptStr(const Src, AKey: string): string;
var
VOutput: TStringStream;
VBF: TBlowFishDeCryptStream;
begin
VOutput := TStringStream.Create(Src);
VBF := TBlowFishDeCryptStream.Create(AKey, VOutput);
try
SetLength(Result, VOutput.Size);
VBF.Read(Pointer(Result)^, VOutput.Size);
finally
VBF.Free;
VOutput.Free;
end;
end;
end.
|
unit caHTML;
{$INCLUDE ca.inc}
interface
uses
Windows, SysUtils, Messages, Classes, caUtils, caClasses, caMatrix, Graphics,
caGraphics;
type
TcaHTMLAlignment = (haLeft, haRight, haTop, haTexttop, haMiddle,
haAbsMiddle, haBaseline, haBottom, haAbsBottom);
//----------------------------------------------------------------------------
// TcaHTMLFont
//----------------------------------------------------------------------------
TcaFontNumber = 0..3;
TcaHTMLFont = class(TObject)
private
FBold: Boolean;
FColor: String;
FSize: Integer;
FTypeFace: String;
public
procedure Assign(ASourceFont: TcaHTMLFont);
property Bold: Boolean read FBold write FBold;
property Color: String read FColor write FColor;
property Size: Integer read FSize write FSize;
property TypeFace: String read FTypeFace write FTypeFace;
end;
//----------------------------------------------------------------------------
// TcaHTML
//----------------------------------------------------------------------------
TcaHTML = class(TcaStringList)
private
FDefaultCellHeight: Integer;
FFontBold: Boolean;
FFont1: TcaHTMLFont;
FFont2: TcaHTMLFont;
FFont3: TcaHTMLFont;
function GetAlignment(AAlign: TcaHTMLAlignment): String;
procedure AddHeading(ALevel: Integer; const AText: String);
procedure SetFont(const ABold: Boolean; const AColorName: String; ASize: Integer; ATypeFace: String);
public
constructor Create;
destructor Destroy; override;
procedure Blank;
procedure Body(ABackColor: String = ''; const ABackImage: String = ''; AOnLoad: String = '';
ALink: String = ''; AVLink: String = ''; AALink: String = ''; ATextColor: String = '');
procedure Bold(const AText: String = '');
procedure CheckBox(const AName, AText: String; AChecked: Boolean; AFontNumber: TcaFontNumber = 0);
procedure Data(AWidth: Integer; AHeight: Integer = 0; AAlign: TcaHTMLAlignment = haLeft; AText: String = '';
AFontNumber: TcaFontNumber = 0; ABackColor: String = '';
AVAlign: TcaHTMLAlignment = haMiddle; AEndData: Boolean = True);
procedure EndBody;
procedure EndBold;
procedure EndData;
procedure EndFont;
procedure EndForm;
procedure EndHead;
procedure EndHRef;
procedure EndHTML;
procedure EndItalic;
procedure EndOrderedList;
procedure EndPara;
procedure EndRow;
procedure EndSelect;
procedure EndTable;
procedure EndUnderline;
procedure EndUnOrderedList;
procedure Font(AFontNumber: TcaFontNumber); overload;
procedure Font(const ABold: Boolean; const AColorName: String; ASize: Integer; const ATypeFace: String); overload;
procedure Form(const AName, AAction: String; const AMethod: String = 'POST');
procedure H1(const AText: String);
procedure H2(const AText: String);
procedure H3(const AText: String);
procedure H4(const AText: String);
procedure H5(const AText: String);
procedure H6(const AText: String);
procedure Head;
procedure HiddenField(const AName, AValue: String);
procedure HorzRule;
procedure HRef(const AURL: String; const ATarget: String = '';
const AOnMouseOver: String = ''; const AOnMouseOut: String = '';
const AOnMouseDown: String = ''; const AOnMouseUp: String = '');
procedure HTML;
procedure HTMLHead(const ATitle: String);
procedure Image(const AImage: String; AWidth: Integer = 0; AHeight: Integer = 0; ABorder: Integer = 0;
const AOnClick: String = ''; AAlign: TcaHTMLAlignment = haLeft; const AAlt: String = '';
AEndHRef: Boolean = False);
procedure RadioOption(const AName, AText, AValue: String; AChecked: Boolean; AFontNumber: Integer = 0);
procedure InputText(const AName: String; AValue: String = ''; ASize: Integer = 0;
AMaxLength: Integer = 0; APassword: Boolean = False);
procedure Italic(const AText: String = '');
procedure ListItem(const AText: String);
procedure OrderedList;
procedure Para(const AText: String = ''; AFontNumber: TcaFontNumber = 0);
procedure Row;
procedure Select(AName: String; ASize: Integer);
procedure SelectOption(const AText, AValue: String; ASelected: Boolean = False);
procedure SubmitButton(const AName, ACaption: String);
procedure Table(AWidth: Integer; AUsesPercent: Boolean = False; ABorder: Integer = 0; AHeight: Integer = 0; AExtraHTML: String = '');
procedure TextArea(const AName, AValue: String; ACols, ARows: Integer; AFontNumber: TcaFontNumber = 0);
procedure Title(const AText: String);
procedure Underline;
procedure UnOrderedList;
property DefaultCellHeight: Integer read FDefaultCellHeight write FDefaultCellHeight;
property Font1: TcaHTMLFont read FFont1;
property Font2: TcaHTMLFont read FFont2;
property Font3: TcaHTMLFont read FFont3;
end;
//----------------------------------------------------------------------------
// TcaWebPage
//----------------------------------------------------------------------------
TcaProcessWebTagEvent = procedure(Sender: TObject; const TagStr: String; var NewStr: String) of object;
TcaWebPage = class(TObject)
private
FAppName: String;
FBackColor: String;
FBackImage: String;
FDebugTables: Boolean;
FDocsFolder: String;
FHiddenFields: TStrings;
FHoverColor: String;
FLAlign: TcaHTMLAlignment;
FLinkActiveColor: String;
FLinkColor: String;
FLinkVisitedColor: String;
FLWidth: Integer;
FOnLoad: String;
FOnProcessTag: TcaProcessWebTagEvent;
FPage: TcaHTML;
FRadioName: String;
FRAlign: TcaHTMLAlignment;
FRWidth: Integer;
FScriptsFolder: String;
FText: String;
FTextColor: String;
function GetFont1: TcaHTMLFont;
function GetFont2: TcaHTMLFont;
function GetFont3: TcaHTMLFont;
function GetHTML: String;
function MakeHelpLink(const ACaption, AHelp: String): String;
function CleanText(const AText: String): String;
function CleanURL(const AText: String): String;
procedure FindTags(const S: String; var Tag1, Tag2: Integer);
procedure ProcessTags;
function GetDefaultCellHeight: Integer;
procedure SetDefaultCellHeight(const Value: Integer);
protected
function GetPageName: String; virtual;
function BuildLinkURL(const AFromSuffix, AToSuffix, AExtra: String): String;
procedure BuildBackLink(const AText: String);
procedure BuildLink(const AText, AFromSuffix, AToSuffix, AExtra: String);
procedure BuildLinkImage(const AImage, AURL, ATarget, AStatus, AAlt: String;
AUseRow: Boolean = True; AUseTable: Boolean = True);
procedure BuildLinkText(const AText: String; AFontNumber: TcaFontNumber = 0);
procedure BuildSubmitLink(const AText, AToPage: String);
procedure BuildPage; virtual;
procedure DoGetTableExtraHTML(var AExtraHTML: String); virtual;
procedure DoProcessTag(const TagStr: String; var NewStr: String); virtual;
public
constructor Create;
destructor Destroy; override;
procedure BeginForm; virtual;
procedure BeginPage(const ATitle: String; AFontNumber: TcaFontNumber = 0; AKillFocusRect: Boolean = False);
procedure BeginRadio(const ACaption, AName, AHelp: String; AFontNumber: TcaFontNumber = 0);
procedure BeginSelect(const ACaption, AName, AHelp: String; AFontNumber: TcaFontNumber = 0);
procedure BeginTable(AWidth: Integer; AUsesPercent: Boolean = False; ABorder: Integer = 0; AHeight: Integer = 0);
procedure BeginText;
procedure BlankRow;
procedure DoubleText(const ALeftText, ARightText: String; AFontNumber: TcaFontNumber = 0);
procedure EndFont;
procedure EndForm;
procedure EndPage;
procedure EndPara;
procedure EndRadio;
procedure EndSelect;
procedure EndTable;
procedure EndText(AFontNumber: TcaFontNumber = 0);
procedure LeftText(const AText: String; AFontNumber: TcaFontNumber = 0);
procedure LoadFromFile(const AFileName: String);
procedure Para(const AText: String = ''; AFontNumber: TcaFontNumber = 0);
procedure Radio(const AText, AValue: String; AChecked: Boolean; AFontNumber: TcaFontNumber = 0);
procedure RightText(const AText: String; AFontNumber: TcaFontNumber = 0);
procedure Select(const AText, AValue: String; ASelected: Boolean = False);
procedure AddText(const AText: String);
procedure TextArea(const AName, AValue: String; ACols, ARows: Integer; AFontNumber: TcaFontNumber = 0);
procedure TextLine(const AText: String; AFontNumber: TcaFontNumber = 0);
property BackColor: String read FBackColor write FBackColor;
property BackImage: String read FBackImage write FBackImage;
property DebugTables: Boolean read FDebugTables write FDebugTables;
property DefaultCellHeight: Integer read GetDefaultCellHeight write SetDefaultCellHeight;
property DocsFolder: String read FDocsFolder write FDocsFolder;
property Font1: TcaHTMLFont read GetFont1;
property Font2: TcaHTMLFont read GetFont2;
property Font3: TcaHTMLFont read GetFont3;
property HoverColor: String read FHoverColor write FHoverColor;
property HTML: String read GetHTML;
property LAlign: TcaHTMLAlignment read FLAlign write FLAlign;
property LinkActiveColor: String read FLinkActiveColor write FLinkActiveColor;
property LinkColor: String read FLinkColor write FLinkColor;
property LinkVisitedColor: String read FLinkVisitedColor write FLinkVisitedColor;
property LWidth: Integer read FLWidth write FLWidth;
property OnLoad: String read FOnLoad write FOnLoad;
property OnProcessTag: TcaProcessWebTagEvent read FOnProcessTag write FOnProcessTag;
property Page: TcaHTML read FPage;
property PageName: String read GetPageName;
property RAlign: TcaHTMLAlignment read FRAlign write FRAlign;
property RWidth: Integer read FRWidth write FRWidth;
property ScriptsFolder: String read FScriptsFolder write FScriptsFolder;
property TextColor: String read FTextColor write FTextColor;
end;
function Lorum: String;
function PostModern: String;
implementation
function Lorum: String;
begin
Result := 'lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy ';
Result := Result + 'nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. ut ';
Result := Result + 'wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit ';
Result := Result + 'lobortis nisl ut aliquip ex ea commodo consequat. duis te feugifacilisi. ';
Result := Result + 'duis autem dolor in hendrerit in vulputate velit esse molestie consequat, ';
Result := Result + 'vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et ';
Result := Result + 'iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue ';
Result := Result + 'duis dolore te feugat nulla facilisi. ut wisi enim ad minim veniam, quis ';
Result := Result + 'nostrud exerci taion ullamcorper suscipit lobortis nisl ut aliquip ex en ';
Result := Result + 'commodo consequat.';
end;
function PostModern: String;
begin
Result := 'Latin-looking words arranged in nonsensical sentences, set in columns to give the ';
Result := Result + 'appearance of text on a page. Dummy text is used by the designer to help ';
Result := Result + 'approximate the look of a page at a stage in the design process before the ';
Result := Result + 'written text has been received. This way the designer is able, in a very real ';
Result := Result + 'sense, to shape the material presence of words before they are written and before ';
Result := Result + 'their meaning is known. Conventionally, due to constraints of time, ability, budget, ';
Result := Result + 'and habit, the designer is not the author. So conventionally, the student of ';
Result := Result + 'typography is not encouraged to write (or even read prepared copy) which would waste ';
Result := Result + 'valuable time spent getting to grips with the mechanics of text layout. Such ';
Result := Result + 'established working/teaching methods increase the danger of the typographer ';
Result := Result + 'becoming detached from the meaning of texts. The treatment of copy in purely ';
Result := Result + 'formal terms, reduced to blocks of texture on a page, has lead to the typographer''s ';
Result := Result + 'obsession with craft and disregard of meaning. Dummy text is text that is not ';
Result := Result + 'meant to be read, but only looked at; a shape. The choice of latin is crucial to ';
Result := Result + 'this function in that it is a dead language. Working with dummy text, the ';
Result := Result + 'designer only brings into play part of his/her array of tools/skills to convey ';
Result := Result + 'meaning.';
end;
//----------------------------------------------------------------------------
// TcaHTMLFont
//----------------------------------------------------------------------------
procedure TcaHTMLFont.Assign(ASourceFont: TcaHTMLFont);
begin
Bold := ASourceFont.Bold;
Color := ASourceFont.Color;
Size := ASourceFont.Size;
TypeFace := ASourceFont.TypeFace;
end;
//----------------------------------------------------------------------------
// TcaHTML
//----------------------------------------------------------------------------
constructor TcaHTML.Create;
begin
inherited;
FFont1 := TcaHTMLFont.Create;
FFont2 := TcaHTMLFont.Create;
FFont3 := TcaHTMLFont.Create;
end;
destructor TcaHTML.Destroy;
begin
FFont1.Free;
FFont2.Free;
FFont3.Free;
inherited;
end;
procedure TcaHTML.AddHeading(ALevel: Integer; const AText: String);
begin
Add(Format('<h%d>%s</h%d>', [ALevel, AText, ALevel]));
end;
procedure TcaHTML.Blank;
begin
Add('<br>');
end;
procedure TcaHTML.Bold(const AText: String = '');
var
BoldStr: String;
begin
BoldStr := '<b>';
if AText <> '' then BoldStr := BoldStr + Format('%s</b>', [AText]);
Add(BoldStr);
end;
procedure TcaHTML.H1(const AText: String);
begin
AddHeading(1, AText);
end;
procedure TcaHTML.H2(const AText: String);
begin
AddHeading(2, AText);
end;
procedure TcaHTML.H3(const AText: String);
begin
AddHeading(3, AText);
end;
procedure TcaHTML.H4(const AText: String);
begin
AddHeading(4, AText);
end;
procedure TcaHTML.H5(const AText: String);
begin
AddHeading(5, AText);
end;
procedure TcaHTML.H6(const AText: String);
begin
AddHeading(6, AText);
end;
procedure TcaHTML.HTMLHead(const ATitle: String);
begin
HTML;
Head;
Title(ATitle);
EndHead;
end;
procedure TcaHTML.HorzRule;
begin
Add('<hr>');
end;
procedure TcaHTML.Italic(const AText: String = '');
var
ItalicStr: String;
begin
ItalicStr := '<i>';
if AText <> '' then ItalicStr := ItalicStr + Format('%s</i>', [AText]);
Add(ItalicStr);
end;
procedure TcaHTML.Title(const AText: String);
begin
Add(Format('<title>%s</title>', [AText]));
end;
procedure TcaHTML.EndHead;
begin
Add('</head>');
end;
procedure TcaHTML.Head;
begin
Add('<head>');
end;
procedure TcaHTML.EndHTML;
begin
Add('</html>');
end;
procedure TcaHTML.HTML;
begin
Add('<html>');
end;
procedure TcaHTML.EndBody;
begin
Add('</body>');
end;
procedure TcaHTML.Body(ABackColor: String = ''; const ABackImage: String = ''; AOnLoad: String = '';
ALink: String = ''; AVLink: String = ''; AALink: String = ''; ATextColor: String = '');
var
BodyStr: String;
begin
BodyStr := '<body ';
if ABackColor <> '' then
BodyStr := BodyStr + Format('bgcolor="%s" ', [ABackColor]);
if ABackImage <> '' then
BodyStr := BodyStr + Format('background="%s" ', [ABackImage]);
if AOnLoad <> '' then
BodyStr := BodyStr + Format('onload="%s" ', [AOnLoad]);
if ALink <> '' then
BodyStr := BodyStr + Format('link="%s" ', [ALink]);
if AVLink <> '' then
BodyStr := BodyStr + Format('vlink="%s" ', [AVLink]);
if AALink <> '' then
BodyStr := BodyStr + Format('alink="%s" ', [AALink]);
if ATextColor <> '' then
BodyStr := BodyStr + Format('text="%s" ', [ATextColor]);
BodyStr := Trim(BodyStr) + '>';
Add(BodyStr);
end;
procedure TcaHTML.Data(AWidth: Integer; AHeight: Integer = 0; AAlign: TcaHTMLAlignment = haLeft; AText: String = '';
AFontNumber: TcaFontNumber = 0; ABackColor: String = '';
AVAlign: TcaHTMLAlignment = haMiddle; AEndData: Boolean = True);
var
AlignStr: String;
VAlignStr: String;
DataStr: String;
CellHeight: Integer;
begin
if AHeight = 0 then
CellHeight := FDefaultCellHeight
else
CellHeight := AHeight;
AlignStr := GetAlignment(AAlign);
VAlignStr := GetAlignment(AVAlign);
if AText = '' then
begin
DataStr := Format('<td width="%d" align="%s" valign="%s" ', [AWidth, AlignStr, VAlignStr]);
if CellHeight <> 0 then DataStr := DataStr + Format('height="%d" ', [CellHeight]);
if ABackColor <> '' then DataStr := DataStr + Format('bgcolor="%s" ', [ABackColor]);
DataStr := Trim(DataStr) + '>';
Add(DataStr);
end
else
begin
AText := StringReplace(AText, '_', ' ', [rfReplaceAll]);
DataStr := Format('<td width="%d" align="%s" ', [AWidth, AlignStr]);
if CellHeight <> 0 then DataStr := DataStr + Format('height="%d" ', [CellHeight]);
if ABackColor <> '' then DataStr := DataStr + Format('bgcolor="%s" ', [ABackColor]);
Add(Trim(DataStr) + '>');
if AFontNumber > 0 then Font(AFontNumber);
Add(AText);
if AFontNumber > 0 then EndFont;
if AEndData then EndData;
end;
end;
procedure TcaHTML.EndBold;
begin
Add('</b>');
end;
procedure TcaHTML.EndData;
begin
Add('</td>');
end;
procedure TcaHTML.EndFont;
begin
Add('</font>');
if FFontBold then
begin
Add('</b>');
FFontBold := False;
end;
end;
procedure TcaHTML.EndForm;
begin
Add('</form>');
end;
procedure TcaHTML.EndHRef;
begin
Add('</a>');
end;
procedure TcaHTML.EndItalic;
begin
Add('</i>');
end;
procedure TcaHTML.EndOrderedList;
begin
Add('</ol>');
end;
procedure TcaHTML.EndPara;
begin
Add('</p>');
end;
procedure TcaHTML.Image(const AImage: String; AWidth: Integer = 0; AHeight: Integer = 0; ABorder: Integer = 0;
const AOnClick: String = ''; AAlign: TcaHTMLAlignment = haLeft; const AAlt: String = '';
AEndHRef: Boolean = False);
var
ImgStr: String;
AlignStr: String;
begin
AlignStr := GetAlignment(AAlign);
ImgStr := Format('<img src="%s" ', [AImage]);
if AWidth <> 0 then ImgStr := ImgStr + Format('width="%d" ', [AWidth]);
if AHeight <> 0 then ImgStr := ImgStr + Format('height="%d" ', [AHeight]);
ImgStr := ImgStr + Format('border="%d" ', [ABorder]);
if AOnClick <> '' then ImgStr := ImgStr + Format('onclick="%s" ', [AOnClick]);
if AAlt <> '' then ImgStr := ImgStr + Format('alt="%s" ', [AAlt]);
ImgStr := Trim(ImgStr) + '>';
if AEndHRef then ImgStr := ImgStr + '</a>';
Add(ImgStr);
end;
procedure TcaHTML.Para(const AText: String = ''; AFontNumber: TcaFontNumber = 0);
begin
if AText <> '' then
begin
if AFontNumber > 0 then Font(AFontNumber);
Add('<p>' + AText + '</p>');
if AFontNumber > 0 then EndFont;
end
else
Add('<p>');
end;
procedure TcaHTML.Font(AFontNumber: TcaFontNumber);
begin
case AFontNumber of
1: SetFont(FFont1.Bold, FFont1.Color, FFont1.Size, FFont1.TypeFace);
2: SetFont(FFont2.Bold, FFont2.Color, FFont2.Size, FFont2.TypeFace);
3: SetFont(FFont3.Bold, FFont3.Color, FFont3.Size, FFont3.TypeFace);
end;
end;
procedure TcaHTML.Font(const ABold: Boolean; const AColorName: String; ASize: Integer; const ATypeFace: String);
begin
SetFont(ABold, AColorName, ASize, ATypeFace);
end;
procedure TcaHTML.SetFont(const ABold: Boolean; const AColorName: String; ASize: Integer; ATypeFace: String);
var
FontStr: String;
begin
FontStr := '<font ';
if AColorName <> '' then FontStr := FontStr + Format('color="%s" ', [AColorName]);
FontStr := FontStr + Format('size="%d" ', [ASize]);
if ATypeFace <> '' then FontStr := FontStr + Format('face="%s" ', [ATypeFace]);
FontStr := Trim(FontStr) + '>';
if ABold then
begin
FontStr := FontStr + '<b>';
FFontBold := True;
end;
Add(FontStr);
end;
procedure TcaHTML.EndRow;
begin
Add('</tr>');
Add('');
end;
function TcaHTML.GetAlignment(AAlign: TcaHTMLAlignment): String;
begin
case AAlign of
haLeft: Result := 'Left';
haRight: Result := 'Right';
haTop: Result := 'Top';
haTexttop: Result := 'Texttop';
haMiddle: Result := 'Middle';
haAbsMiddle: Result := 'AbsMiddle';
haBaseline: Result := 'Baseline';
haBottom: Result := 'Bottom';
haAbsBottom: Result := 'AbsBottom';
else
Result := '';
end;
end;
procedure TcaHTML.Row;
begin
Add('<tr>');
end;
procedure TcaHTML.EndSelect;
begin
Add('</select>');
end;
procedure TcaHTML.EndTable;
begin
Add('</table>');
end;
procedure TcaHTML.EndUnOrderedList;
begin
Add('</ul>');
end;
procedure TcaHTML.EndUnderline;
begin
Add('</u>');
end;
procedure TcaHTML.Form(const AName, AAction: String; const AMethod: String = 'POST');
begin
Add(Format('<form name="%s" action="%s" method="%s">', [AName, AAction, AMethod]));
end;
procedure TcaHTML.HRef(const AURL: String; const ATarget: String = '';
const AOnMouseOver: String = ''; const AOnMouseOut: String = '';
const AOnMouseDown: String = ''; const AOnMouseUp: String = '');
var
HRefStr: String;
begin
HRefStr := Format('<a href="%s" ', [AURL]);
if ATarget <> '' then HRefStr := HRefStr + Format('target="%s" ', [ATarget]);
if AOnMouseOver <> '' then HRefStr := HRefStr + Format('OnMouseOver="%s" ', [AOnMouseOver]);
if AOnMouseOut <> '' then HRefStr := HRefStr + Format('OnMouseOut="%s" ', [AOnMouseOut]);
if AOnMouseDown <> '' then HRefStr := HRefStr + Format('OnMouseDown="%s" ', [AOnMouseDown]);
if AOnMouseUp <> '' then HRefStr := HRefStr + Format('OnMouseUp="%s" ', [AOnMouseUp]);
HRefStr := Trim(HRefStr) + '>';
Add(HRefStr);
end;
procedure TcaHTML.HiddenField(const AName, AValue: String);
var
HidPos: Integer;
Index: Integer;
PageStr: String;
begin
for Index := Count - 1 downto 0 do
begin
PageStr := Strings[Index];
HidPos := Pos(Format('<input type=hidden name="%s"', [AName]), PageStr);
if HidPos >= 1 then Self.Delete(Index);
end;
Add(Format('<input type=hidden name="%s" value="%s">', [AName, AValue]));
end;
procedure TcaHTML.RadioOption(const AName, AText, AValue: String; AChecked: Boolean; AFontNumber: Integer = 0);
var
RadioStr: String;
begin
RadioStr := Format('<input name="%s" type=radio value=%s ', [AName, AValue]);
if AChecked then RadioStr := RadioStr + 'checked ';
RadioStr := Trim(RadioStr) + '>';
Add(RadioStr);
Font(AFontNumber);
Add(AText);
EndFont;
end;
procedure TcaHTML.CheckBox(const AName, AText: String; AChecked: Boolean; AFontNumber: TcaFontNumber = 0);
var
CheckStr: String;
begin
CheckStr := Format('<input NAME="%s" type=checkbox value=checkbox ', [AName]);
if AChecked then CheckStr := CheckStr + 'checked ';
CheckStr := Trim(CheckStr) + '>';
Add(CheckStr);
Font(AFontNumber);
Add(AText);
EndFont;
end;
procedure TcaHTML.TextArea(const AName, AValue: String; ACols, ARows: Integer; AFontNumber: TcaFontNumber = 0);
var
TextAreaStr: String;
begin
TextAreaStr := Format('<textarea name="%s" cols="%d" rows="%d">', [AName, ACols, ARows]);
Font(AFontNumber);
Add(TextAreaStr);
Add(AValue);
Add('</textarea>');
EndFont;
end;
procedure TcaHTML.InputText(const AName: String; AValue: String = ''; ASize: Integer = 0;
AMaxLength: Integer = 0; APassword: Boolean = False);
var
InputStr: String;
begin
if APassword then
InputStr := '<input type=password '
else
InputStr := '<input type=text ';
if AName <> '' then InputStr := InputStr + Format('name="%s" ', [AName]);
if AValue <> '' then InputStr := InputStr + Format('value="%s" ', [AValue]);
if ASize <> 0 then InputStr := InputStr + Format('size="%d" ', [ASize]);
if AMaxLength <> 0 then InputStr := InputStr + Format('maxlength="%d" ', [AMaxLength]);
InputStr := Trim(InputStr) + '>';
Add(InputStr);
end;
procedure TcaHTML.ListItem(const AText: String);
begin
Add(Format('<li>%s', [AText]));
end;
procedure TcaHTML.OrderedList;
begin
Add('<ol>');
end;
procedure TcaHTML.Select(AName: String; ASize: Integer);
begin
Add(Format('<select name="%s" size="%d">', [AName, ASize]));
end;
procedure TcaHTML.SelectOption(const AText, AValue: String; ASelected: Boolean = False);
var
SelStr: String;
begin
SelStr := '';
if ASelected then SelStr := 'selected ';
Add(Format('<option %svalue="%s">%s</option>', [SelStr, AValue, AText]));
end;
procedure TcaHTML.SubmitButton(const AName, ACaption: String);
begin
Add(Format('<input type=submit name="%s" value="%s">', [AName, ACaption]));
end;
procedure TcaHTML.Table(AWidth: Integer; AUsesPercent: Boolean = False; ABorder: Integer = 0; AHeight: Integer = 0; AExtraHTML: String = '');
var
TblStr: String;
PctStr: String;
begin
TblStr := '<table ';
PctStr := '';
if AUsesPercent then PctStr := '%';
if AWidth <> 0 then TblStr := TblStr + Format('width="%d%s" ', [AWidth, PctStr]);
TblStr := TblStr + Format('border="%d" ', [ABorder]);
if AHeight <> 0 then TblStr := TblStr + Format('height="%d" ', [AHeight]);
TblStr := Trim(TblStr) + AExtraHTML + '>';
Add(TblStr);
end;
procedure TcaHTML.UnOrderedList;
begin
Add('<ul>');
end;
procedure TcaHTML.Underline;
begin
Add('<u>');
end;
//----------------------------------------------------------------------------
// TcaWebPage
//----------------------------------------------------------------------------
constructor TcaWebPage.Create;
begin
inherited;
FPage := TcaHTML.Create;
FLAlign := haRight;
FLWidth := 300;
FRAlign := haLeft;
FRWidth := 200;
FAppName := LowerCase(Utils.AppName);
FHiddenFields := TStringList.Create;
end;
destructor TcaWebPage.Destroy;
begin
FPage.Free;
FHiddenFields.Free;
inherited;
end;
procedure TcaWebPage.BeginPage(const ATitle: String; AFontNumber: TcaFontNumber = 0; AKillFocusRect: Boolean = False);
begin
FPage.Clear;
FPage.HTMLHead(CleanText(ATitle));
if FHoverColor <> '' then
begin
FPage.Add('<style type="text/css">');
FPage.Add('a:link, a:visited {text-decoration: none}');
FPage.Add(Format('a:hover {background: %s}', [FHoverColor]));
FPage.Add('a:focus {outline: none}');
FPage.Add('</style>');
end;
if AKillFocusRect then
begin
FPage.Add('<script>');
FPage.Add('<!-- cloaking enabled');
FPage.Add('function ssh() {');
FPage.Add('window.focus(); }');
FPage.Add('// cloaking disabled -->');
FPage.Add('</script>');
end;
FPage.Body(FBackColor, FBackImage, FOnLoad, FLinkColor, FLinkVisitedColor, FLinkActiveColor, FTextColor);
if AFontNumber > 0 then FPage.Font(AFontNumber);
if ATitle <> '' then FPage.Para(CleanText(ATitle));
if AFontNumber > 0 then EndFont;
end;
procedure TcaWebPage.EndPage;
begin
FPage.EndBody;
FPage.EndHTML;
end;
procedure TcaWebPage.BeginTable(AWidth: Integer; AUsesPercent: Boolean = False; ABorder: Integer = 0; AHeight: Integer = 0);
var
ExtraHTML: String;
begin
if FDebugTables then ABorder := 1;
ExtraHTML := '';
DoGetTableExtraHTML(ExtraHTML);
FPage.Table(AWidth, AUsesPercent, ABorder, AHeight, ExtraHTML);
end;
procedure TcaWebPage.EndTable;
begin
FPage.EndTable;
end;
procedure TcaWebPage.BeginSelect(const ACaption, AName, AHelp: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, MakeHelpLink(ACaption, AHelp), AFontNumber);
FPage.Data(FRWidth, 0);
FPage.Select(AName, 1);
end;
procedure TcaWebPage.Select(const AText, AValue: String; ASelected: Boolean = False);
begin
FPage.SelectOption(CleanText(AText), AValue, ASelected);
end;
procedure TcaWebPage.EndSelect;
begin
FPage.EndSelect;
FPage.EndData;
FPage.EndRow;
end;
procedure TcaWebPage.BeginRadio(const ACaption, AName, AHelp: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, MakeHelpLink(ACaption, AHelp), AFontNumber);
FPage.Data(FRWidth);
FRadioName := AName;
end;
procedure TcaWebPage.Radio(const AText, AValue: String; AChecked: Boolean; AFontNumber: TcaFontNumber = 0);
begin
FPage.RadioOption(FRadioName, CleanText(AText), AValue, AChecked, AFontNumber);
end;
procedure TcaWebPage.EndRadio;
begin
FPage.EndData;
FPage.EndRow;
end;
procedure TcaWebPage.BlankRow;
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, '_');
FPage.Data(FRWidth, 0, FRAlign, '_');
FPage.EndRow;
end;
procedure TcaWebPage.LeftText(const AText: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, CleanText(AText), AFontNumber);
FPage.Data(FRWidth, 0, FRAlign, '_');
FPage.EndRow;
end;
procedure TcaWebPage.RightText(const AText: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, '_');
FPage.Data(FRWidth, 0, FRAlign, CleanText(AText), AFontNumber);
FPage.EndRow;
end;
procedure TcaWebPage.DoubleText(const ALeftText, ARightText: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth, 0, FLAlign, CleanText(ALeftText), AFontNumber);
FPage.Data(FRWidth, 0, FRAlign, CleanText(ARightText), AFontNumber);
FPage.EndRow;
end;
procedure TcaWebPage.Para(const AText: String = ''; AFontNumber: TcaFontNumber = 0);
begin
FPage.Para(CleanText(AText), AFontNumber);
end;
function TcaWebPage.CleanText(const AText: String): String;
var
S: String;
begin
S := StringReplace(AText, '%20', ' ', [rfReplaceAll]);
Result := StringReplace(S, '_', ' ', [rfReplaceAll]);
end;
function TcaWebPage.CleanURL(const AText: String): String;
begin
Result := StringReplace(AText, ' ', '%20', [rfReplaceAll]);
end;
procedure TcaWebPage.BeginText;
begin
FText := '';
end;
procedure TcaWebPage.EndText(AFontNumber: TcaFontNumber = 0);
begin
FPage.Font(AFontNumber);
FPage.Add(FText);
FPage.EndFont;
FText := '';
end;
procedure TcaWebPage.AddText(const AText: String);
begin
FText := FText + ' ' + AText;
end;
procedure TcaWebPage.BeginForm;
begin
Page.Form(PageName, '/' + FScriptsFolder + '/' + Utils.AppName);
end;
procedure TcaWebPage.BuildLinkText(const AText: String; AFontNumber: TcaFontNumber = 0);
begin
Page.Bold;
Page.Underline;
TextLine(AText, AFontNumber);
Page.EndUnderline;
Page.EndBold;
end;
procedure TcaWebPage.BuildBackLink(const AText: String);
begin
BeginTable(360);
BlankRow;
FPage.Row;
FPage.Data(120);
FPage.EndData;
FPage.Data(120);
FPage.HRef('javascript:history.back();');
BuildLinkText(AText, 3);
FPage.EndHRef;
FPage.EndData;
FPage.EndRow;
EndTable;
end;
procedure TcaWebPage.BuildLink(const AText, AFromSuffix, AToSuffix, AExtra: String);
var
FromHRef: String;
ToHRef: String;
begin
BeginTable(360);
BlankRow;
FPage.Row;
FPage.Data(120);
FPage.EndData;
FPage.Data(120);
FromHRef := Utils.AppName + '?pagefrom=' + PageName + AFromSuffix;
ToHRef := '&pageto=' + PageName + AToSuffix;
FPage.HRef(FromHRef + ToHRef + '&' + AExtra);
BuildLinkText(AText, 3);
FPage.EndHRef;
FPage.EndData;
FPage.EndRow;
EndTable;
end;
procedure TcaWebPage.BuildLinkImage(const AImage, AURL, ATarget, AStatus, AAlt: String;
AUseRow: Boolean = True; AUseTable: Boolean = True);
var
OnMouseOver: String;
OnMouseOut: String;
begin
if AUseTable then BeginTable(500, False, 0, 40);
if AUseRow then Page.Row;
Page.Data(500, 0, haRight, '', 0, '', haMiddle, False);
OnMouseOver := Format('window.status=''%s''; return true;', [AStatus]);
OnMouseOut := 'window.status=''''';
Page.HRef(AURL, ATarget, OnMouseOver, OnMouseOut);
Page.Image(AImage, 176, 40, 0, '', haBottom, AAlt);
Page.EndHRef;
Page.EndData;
if AUseRow then Page.EndRow;
if AUseTable then EndTable;
end;
function TcaWebPage.BuildLinkURL(const AFromSuffix, AToSuffix, AExtra: String): String;
var
FromHRef: String;
ToHRef: String;
begin
FromHRef := Utils.AppName + '?pagefrom=' + PageName + AFromSuffix;
ToHRef := '&pageto=' + PageName + AToSuffix;
Result := FromHRef + ToHRef + '&' + AExtra;
end;
procedure TcaWebPage.BuildSubmitLink(const AText, AToPage: String);
begin
FPage.HiddenField('pagefrom', PageName);
FPage.HiddenField('pageto', AToPage);
BeginTable(360);
BlankRow;
FPage.Row;
FPage.Data(120);
FPage.EndData;
FPage.Data(120);
FPage.HRef('javascript:document.forms.' + PageName + '.submit();');
BuildLinkText(AText, 3);
FPage.EndHRef;
FPage.EndData;
FPage.EndRow;
EndTable;
end;
procedure TcaWebPage.TextLine(const AText: String; AFontNumber: TcaFontNumber = 0);
begin
FPage.Font(AFontNumber);
FPage.Add(AText);
FPage.EndFont;
end;
procedure TcaWebPage.TextArea(const AName, AValue: String; ACols, ARows: Integer; AFontNumber: TcaFontNumber = 0);
begin
FPage.Row;
FPage.Data(FLWidth);
FPage.TextArea(AName, AValue, ACols, ARows, AFontNumber);
FPage.EndData;
FPage.Data(FRWidth, 0, FRAlign, '_');
FPage.EndRow;
end;
procedure TcaWebPage.EndFont;
begin
FPage.EndFont;
end;
function TcaWebPage.GetHTML: String;
begin
BuildPage;
ProcessTags;
Result := FPage.Text;
end;
function TcaWebPage.MakeHelpLink(const ACaption, AHelp: String): String;
var
FatURL: String;
begin
if AHelp <> '' then
begin
FatURL := Format('?HelpName=%s&HelpText=%s', [CleanURL(ACaption), CleanURL(AHelp)]);
Result := '<A HREF=' + FAppName + FatURL + '>' + ACaption + '</A>';
end
else
Result := ACaption;
end;
procedure TcaWebPage.BuildPage;
begin
// Virtual
end;
procedure TcaWebPage.DoGetTableExtraHTML(var AExtraHTML: String);
begin
// Virtual
end;
function TcaWebPage.GetFont1: TcaHTMLFont;
begin
Result := FPage.Font1;
end;
function TcaWebPage.GetFont2: TcaHTMLFont;
begin
Result := FPage.Font2;
end;
function TcaWebPage.GetFont3: TcaHTMLFont;
begin
Result := FPage.Font3;
end;
procedure TcaWebPage.ProcessTags;
var
Index: Integer;
Tag1: Integer;
Tag2: Integer;
Line: String;
TagStr: String;
TagStrTnT: String;
NewStrTnT: String;
begin
for Index := 0 to FPage.Count - 1 do
begin
Line := FPage[Index];
FindTags(Line, Tag1, Tag2);
while (Tag1 > 0) and (Tag2 > 0) do
begin
TagStr := Copy(Line, Tag1, Tag2 - Tag1 + 1);
TagStrTnT := TagStr;
System.Delete(TagStrTnT, 1, 1);
SetLength(TagStrTnT, Length(TagStrTnT) - 1);
NewStrTnT := TagStrTnT;
DoProcessTag(TagStrTnT, NewStrTnT);
Line := StringReplace(Line, TagStr, NewStrTnT, []);
FindTags(Line, Tag1, Tag2);
end;
FPage[Index] := Line;
end;
end;
procedure TcaWebPage.FindTags(const S: String; var Tag1, Tag2: Integer);
var
Index: Integer;
begin
Tag1 := 0;
Tag2 := 0;
for Index := 1 to Length(S) do
begin
if S[Index] = '~' then
begin
if Tag1 = 0 then
Tag1 := Index
else
begin
Tag2 := Index;
Break;
end;
end;
end;
end;
procedure TcaWebPage.DoProcessTag(const TagStr: String; var NewStr: String);
begin
if Assigned(FOnProcessTag) then FOnProcessTag(Self, TagStr, NewStr);
end;
procedure TcaWebPage.EndForm;
begin
FPage.EndForm;
end;
procedure TcaWebPage.EndPara;
begin
FPage.EndPara;
end;
function TcaWebPage.GetPageName: String;
begin
Result := '';
end;
procedure TcaWebPage.LoadFromFile(const AFileName: String);
begin
FPage.LoadFromFile(Utils.AppPath + AFileName);
end;
function TcaWebPage.GetDefaultCellHeight: Integer;
begin
Result := FPage.DefaultCellHeight;
end;
procedure TcaWebPage.SetDefaultCellHeight(const Value: Integer);
begin
FPage.DefaultCellHeight := Value;
end;
end.
|
unit uSubTest;
interface
uses uCommon;
type
TInterval = record
EvtActionTimeRltvBeginIntrvl: Integer;
AlertDurationTime: Integer;
RTValue: Integer;
AvrgRTValue: Integer;
RTValCnt: Integer;
AmplitudeLimbToUp: Integer;
AvrgAmplitudeLimbToUp: Integer;
ReactionVelocityTime: Integer;
AvrgReactionVelocityTime: Integer;
AnswerType: TAnswers;
end;
TArrIntervals = array of TInterval;
type
TSubTest = class(TObject)
private
FName: string;
FTestNumber: Integer;
FIntervals: TArrIntervals;
FSessionDurationInMs: Integer;
procedure SetName(const Value: string);
procedure SetTestNumber(const Value: Integer);
function GetInterval(Index: Integer): TInterval;
function GetIntervalsCount: Integer;
procedure SetSessionDurationInMs(const Value: Integer);
public
constructor Create;
destructor Destroy; override;
procedure ClearIntervals;
function AddInterval(AInterval: TInterval): Integer;
property Name: string read FName write SetName;
property TestNumber: Integer read FTestNumber write SetTestNumber;
property Intervals[Index: Integer]: TInterval read GetInterval;
property IntervalsCount: Integer read GetIntervalsCount;
property SessionDurationInMs: Integer read FSessionDurationInMs write SetSessionDurationInMs;
// property AnswerType: TAnswers;
end;
implementation
{ TSubTest }
function TSubTest.AddInterval(AInterval: TInterval): Integer;
begin
Result := Length(FIntervals);
SetLength(FIntervals, Length(FIntervals) + 1);
FIntervals[Result] := AInterval;
end;
procedure TSubTest.ClearIntervals;
begin
Finalize(FIntervals);
end;
constructor TSubTest.Create;
begin
inherited;
end;
destructor TSubTest.Destroy;
begin
ClearIntervals;
inherited;
end;
function TSubTest.GetInterval(Index: Integer): TInterval;
begin
Result := FIntervals[Index];
end;
function TSubTest.GetIntervalsCount: Integer;
begin
Result := Length(FIntervals);
end;
procedure TSubTest.SetName(const Value: string);
begin
FName := Value;
end;
procedure TSubTest.SetSessionDurationInMs(const Value: Integer);
begin
FSessionDurationInMs := Value;
end;
procedure TSubTest.SetTestNumber(const Value: Integer);
begin
FTestNumber := Value;
end;
end.
|
{***********************************************************************
Unit gfx_masks.PAS v1.2 0801
(c) by Andreas Moser, AMoser@amoser.de
Delphi version : Delphi 4
gfx_mask is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
NOTE: This source is adapted from
"Magic Wand", Francesco Savastano 2001
Web site : http://digilander.iol.it/gensavas/francosava/
********************************************************************************}
unit gfx_masks;
interface
uses Windows,Graphics, SysUtils,extctrls, gfx_basedef;
procedure MaskMagicWand(var SrcBitmap:TBitmap;a,b:Integer;OldColor:TColor;Tolerance:Real;var mask:TBool2dArray);
procedure ShowMagicWandFrame(var SrcBitmap:TBitmap;var mask:TBool2dArray);
procedure ShowMagicWandMask(var SrcBitmap,DestBitmap:TBitmap;var mask:TBool2dArray);
procedure GetMagicWandSelection(var SrcBitmap, DestBitmap:TBitmap;var Mask:TBool2dArray);
implementation
var
fillx:array[0..80000]of integer;
filly:array[0..80000]of integer;
{magic wand algorithm same as seed fill algorithm}
procedure MaskMagicwand(var SrcBitmap:TBitmap;a,b:Integer;OldColor:TColor;Tolerance:Real;var Mask:TBool2dArray);
var
nf:integer;
i,j,ir:integer;
xf,yf:integer;
procedure MagicWandProcessor(var SrcBitmap:tbitmap;xf,yf:integer;var nf:integer;oldcolor:tcolor;tolerance:real;var mask:tbool2darray);
var
hh,ll,ss,h1,l1,s1,aa,bb,cc:real;
c1,c2,c3,pixr,pixg,pixb,oldr,oldg,oldb,newr,newg,newb:byte;
pix:tcolorref;
jj:byte;
xr,yr:longint;
gray:real;
pp:pRGBarray;
begin
oldr:=getrvalue(oldcolor);
oldg:=getgvalue(oldcolor);
oldb:=getbvalue(oldcolor);
for jj:=1 to 4 do
begin
case jj of
1:begin
xr:=xf+1;
yr:=yf;
end;
2:begin
xr:=xf-1;
yr:=yf;
end;
3:begin
xr:=xf;
yr:=yf+1;
end;
4:begin
xr:=xf;
yr:=yf-1;
end;
end;
if ((xr< SrcBitmap.width)and(jj=1))or((xr>=0)and(jj=2)) or ((yr< SrcBitmap.height)and(jj=3))or((yr>=0)and(jj=4)) then
begin
pp:=SrcBitmap.scanline[yr];
pix:=rgb(pp[xr].rgbtred,pp[xr].rgbtgreen,pp[xr].rgbtblue);
pixr:=getrvalue(pix);
pixg:=getgvalue(pix);
pixb:=getbvalue(pix);
if (not mask[xr,yr])and(abs(pixr-oldr)<=tolerance*150)and(abs(pixg-oldg)<=tolerance*150)and(abs(pixb-oldb)<=tolerance*150)then
begin
mask[xr,yr]:=true;
nf := nf+1;
fillx[nf]:= xr;
filly[nf]:= yr;
end;
end;
end;
end;
begin
Setlength(Mask,SrcBitmap.width+5,SrcBitmap.height+5);
nf := 1;
ir := 1;
fillx[nf]:= a;
filly[nf]:= b;
MagicWandProcessor(SrcBitmap,a,b,nf,OldColor,Tolerance,Mask);
while nf>ir do
begin
ir := ir+1;
xf := fillx[ir];
yf := filly[ir];
MagicWandProcessor(SrcBitmap,xf,yf,nf,OldColor,Tolerance,Mask);
if (nf>75000) then
begin
for i := 1 to nf-ir do
begin
fillx[i] := fillx[ir+i];
filly[i] := filly[ir+i];
end;
nf := nf-ir ;
ir := 0;
end;
end;
end;
procedure ShowMagicWandFrame(var SrcBitmap:TBitmap;var mask:TBool2dArray);
var
i,j:integer;
test:boolean;
pp:pRGBarray;
begin
for j:=1 to SrcBitmap.height-2 do
begin
pp:=SrcBitmap.scanline[j];
for i:=1 to SrcBitmap.width-2 do
begin
if mask[i,j]then
begin
test:= mask[i-1,j] and mask[i+1,j] and mask[i,j-1] and mask[i,j+1] ;
if not test then
begin
{simply invert the colors of the boundary pixels }
with pp[i] do
begin
rgbtred:=255-rgbtred;
rgbtgreen:=255-rgbtgreen;
rgbtblue:=255-rgbtblue;
end;
end;
end;
end;
end;
end;
procedure ShowMagicWandMask(var SrcBitmap,DestBitmap:TBitmap;var mask:TBool2dArray);
var
i,j:integer;
test,mStart:boolean;
pp,pd:pRGBarray;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for j:=1 to SrcBitmap.height-2 do
begin
pp:=SrcBitmap.scanline[j];
pd:=DestBitmap.scanline[j];
mStart:=False;
for i:=1 to SrcBitmap.width-2 do
begin
mStart:=mask[i,j];
if mask[i,j] then pd[i]:=pp[i];
end;
end;
end;
procedure GetMagicWandSelection(var SrcBitmap, DestBitmap:TBitmap;var Mask:TBool2dArray);
var i,j,ul,ut,lr,lb: Integer;
gUl,gUt,glR,glb:Boolean;
mStart:boolean;
pp,pd:pRGBarray;
begin
gul:=false;
gut:=false;
glr:=false;
glb:=false;
ul:=SrcBitmap.Width;
ut:=SrcBitmap.Height;
lr:=0;
lb:=0;
//get bounds
for j:=1 to SrcBitmap.Height-2 do
begin
for i:=1 to SrcBitmap.Width-2 do
begin
if Mask[i,j] then
begin
if j<ut then ut:=j;
if j>lb then lb:=j;
if i<ul then ul:=i;
if i>lr then lr:=i;
end;
end;
end;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Height:= lb-ut;
DestBitmap.Width:=lr-ul;
for j:=ut to lb-1 do
begin
pp:=SrcBitmap.scanline[j];
pd:=DestBitmap.scanline[j-ut];
mStart:=False;
for i:=ul to lr-1 do
begin
mStart:=mask[i,j];
if mask[i,j] then pd[i-ul]:=pp[i] else pd[i-ul]:=ColorToRGB(clNone);
end;
end;
end;
end.
|
unit ncaFrmCli;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxPCdxBarPopupMenu, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxStyles, cxClasses, dxBar,
cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
StdCtrls, cxRadioGroup, LMDPNGImage, ExtCtrls, cxTextEdit, cxPC, LMDControl,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxLabel,
cxButtonEdit, Menus, SpTBXFormPopupMenu, SpTBXItem, SpTBXControls, ncaFrmCliPesq,
dxBarExtItems, uNexTransResourceStrings_PT;
type
TFrmCli = class(TForm)
panCliente: TLMDSimplePanel;
panFoto: TLMDSimplePanel;
pgFoto: TcxPageControl;
tsFotoCad: TcxTabSheet;
imFoto: TImage;
tsFotoAvulso: TcxTabSheet;
imFotoAvulso: TImage;
BarMgr: TdxBarManager;
cmBuscar: TdxBarSubItem;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
barBotoes: TdxBar;
cmNome: TdxBarButton;
cmUsername: TdxBarButton;
cmCod: TdxBarButton;
cmNovo: TdxBarButton;
cmEditar: TdxBarButton;
pmCli: TSpTBXFormPopupMenu;
Timer1: TTimer;
Timer2: TTimer;
LMDSimplePanel1: TLMDSimplePanel;
panTopo: TLMDSimplePanel;
pgCli: TcxPageControl;
tsCliCad: TcxTabSheet;
panCad: TLMDSimplePanel;
panEditCad: TLMDSimplePanel;
tsAvulso: TcxTabSheet;
edAvulso: TcxTextEdit;
lbAvulso: TcxLabel;
tsFunc: TcxTabSheet;
lbFunc: TcxLabel;
lbComCad: TcxLabel;
lbSemCad: TcxLabel;
Timer3: TTimer;
edCad: TcxButtonEdit;
lbNome: TcxLabel;
panBotoes: TLMDSimplePanel;
panDockLupa: TLMDSimplePanel;
bdcBotoes: TdxBarDockControl;
cxLabel1: TcxLabel;
edFunc: TcxTextEdit;
panCliInfo: TLMDSimplePanel;
lbDebito: TcxLabel;
lbBuscar: TcxLabel;
cmFornecedor: TdxBarStatic;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmNomeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure edCadEnter(Sender: TObject);
procedure edCadPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edCadPropertiesChange(Sender: TObject);
procedure edCadKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edCadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure pmCliPopup(Sender: TObject);
procedure pmCliClosePopup(Sender: TObject; Selected: Boolean);
procedure FormDestroy(Sender: TObject);
procedure cmNovoClick(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
procedure cmEditarClick(Sender: TObject);
procedure lbSemCadClick(Sender: TObject);
procedure lbComCadFocusChanged(Sender: TObject);
procedure Timer3Timer(Sender: TObject);
procedure cmFornecedorClick(Sender: TObject);
procedure edCadExit(Sender: TObject);
procedure imFotoClick(Sender: TObject);
private
FSaveSt: String;
FPopped : Boolean;
FPesq : TFrmCliPesq;
FCliCad : Integer;
FOrdemCli : Byte;
FIgnoreChange: Boolean;
FFornecedor : Boolean;
FTipo : Byte;
FOnMudouCliente : TNotifyEvent;
FFirstCliEnter : Boolean;
FReadOnly : Boolean;
{ Private declarations }
procedure UpdateOrdemCliCad;
procedure UpdateCliCadInfo(aUpdateEdit: Boolean = False);
procedure SetCliCad(const Value: Integer);
procedure SetOrdemCli(const Value: Byte);
procedure SetFornecedor(const Value: Boolean);
procedure SetTipo(const Value: Byte);
procedure SetReadOnly(const Value: Boolean);
property OrdemCli: Byte
read FOrdemCli write SetOrdemCli;
public
procedure UpdateCliCadEdit(aSelectAll: Boolean);
procedure Reset;
procedure Init(aFornecedor, aShowFunc: Boolean; aCodigo: Integer; aNome, aNomeFunc: String; aTipo: Byte; aParent: TWinControl);
function Codigo: Integer;
function FidPontos: Double;
function Nome: String;
property Pesq: TFrmCliPesq
read FPesq;
function TipoAcessoPref: Integer;
property ReadOnly: Boolean
read FReadOnly write SetReadOnly;
property Tipo: Byte
read FTipo write SetTipo;
property OnMudouCliente: TNotifyEvent
read FOnMudouCliente write FOnMudouCliente;
property IgnoreChange: Boolean
read FIgnoreChange;
property Popped: Boolean
read FPopped;
property Fornecedor: Boolean
read FFornecedor write SetFornecedor;
property CliCad: Integer
read FCliCad write SetCliCad;
{ Public declarations }
end;
TFrmCliList = class
private
FItens : TThreadList;
public
constructor Create;
destructor Destroy; override;
function GetFrm: TFrmCli;
procedure ReleaseFrm(aFrm: TFrmCli);
end;
const
tcComCad = 0;
tcSemCad = 1;
tcFunc = 2;
var
FrmCli: TFrmCli;
gCliList : TFrmCliList;
implementation
uses ncaFrmPri, ufmImagens, ncaFrmCadCli, ncaDM, ncClassesBase;
// START resource string wizard section
// MMX resource string wizard section REMOVIDA - 08/04/13 12:30
{$R *.dfm}
procedure TFrmCli.cmEditarClick(Sender: TObject);
begin
if FFornecedor then begin
FPesq.cmEditarClick(nil);
Exit;
end;
FPesq.Tab.CancelRange;
TFrmCadCli.Create(Self).Editar(FPesq.Tab, nil);
UpdateCliCadInfo(True);
Dados.tbCli.Refresh;
Dados.tbCli.Locate('ID', FPesq.TabID.Value, []); // do not localize
end;
procedure TFrmCli.cmFornecedorClick(Sender: TObject);
begin
edCad.SetFocus;
end;
procedure TFrmCli.cmNomeClick(Sender: TObject);
begin
cmBuscar.Caption := TdxBarButton(Sender).Caption+':';
OrdemCli := TdxBarButton(Sender).Tag;
edCad.SetFocus;
end;
procedure TFrmCli.cmNovoClick(Sender: TObject);
var I : Integer;
begin
if FFornecedor then begin
FPesq.cmNovoClick(nil);
Exit;
end;
FPesq.Tab.CancelRange;
I := TFrmCadCli.Create(Self).Novo(FPesq.Tab, nil);
if I > 0 then begin
CliCad := I;
edCad.SetFocus;
Self.UpdateCliCadEdit(True);
Dados.tbCli.Refresh;
Dados.tbCli.Locate('ID', FPesq.TabID.Value, []); // do not localize
end;
end;
function TFrmCli.Codigo: Integer;
begin
if FTipo=0 then
Result := FCliCad else
Result := 0;
end;
procedure TFrmCli.edCadEnter(Sender: TObject);
begin
if FFirstCliEnter then Timer1.Enabled := True;
FFirstCliEnter := False;
Timer2.Enabled := True;
panEditCad.Color := $00B3FFFF;
barBotoes.Color := $00B3FFFF;
end;
procedure TFrmCli.edCadExit(Sender: TObject);
begin
panEditCad.Color := clWhite;
barBotoes.Color := clWhite;
end;
procedure TFrmCli.edCadKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
FSaveSt := edCad.EditingText;
end;
procedure TFrmCli.edCadKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (edCad.EditingText <> FSaveSt) and (not FPopped) then Timer1.Enabled := True;
FPesq.edBuscaKeyUp(Sender, Key, Shift);
end;
procedure TFrmCli.edCadPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
Timer1.Enabled := True;
end;
procedure TFrmCli.edCadPropertiesChange(Sender: TObject);
begin
if edCad.Focused and (not FIgnoreChange) then
FPesq.edBusca.EditValue := edCad.EditingText;
end;
function TFrmCli.FidPontos: Double;
begin
if Codigo>0 then
Result := FPesq.TabFidPontos.Value else
Result := 0;
end;
procedure TFrmCli.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmCli.Reset;
begin
if GShutingdown then exit;
FIgnoreChange := True;
try
panCliente.Parent := Self;
FFirstCliEnter := True;
FOnMudouCliente := nil;
FOrdemCli := 99;
FCliCad := 0;
FPopped := False;
ReadOnly := False;
FPesq.Reset;
edCad.Clear;
edAvulso.Clear;
edFunc.Clear;
OrdemCli := gConfig.CampoLocalizaCli;
tsCliCad.TabVisible := True;
tsAvulso.TabVisible := True;
tsFunc.TabVisible := True;
lbComCad.Visible := True;
lbSemCad.Visible := True;
lbFunc.Visible := True;
finally
FIgnoreChange := False;
end;
end;
procedure TFrmCli.FormCreate(Sender: TObject);
begin
FPesq := TFrmCliPesq.Create(Self);
pmCli.PopupForm := FPesq;
FReadOnly := False;
Reset;
end;
procedure TFrmCli.FormDestroy(Sender: TObject);
begin
FPesq.Free;
end;
procedure TFrmCli.imFotoClick(Sender: TObject);
begin
if clicad>0 then
FPesq.cmEditar.Click;
end;
procedure TFrmCli.Init(aFornecedor, aShowFunc: Boolean; aCodigo: Integer; aNome, aNomeFunc: String; aTipo: Byte; aParent: TWinControl);
begin
Fornecedor := aFornecedor;
if aFornecedor then begin
cmFornecedor.Visible := ivAlways;
cmBuscar.Visible := ivNever;
panBotoes.Width := 22;
end;
lbFunc.Visible := aShowFunc and (not aFornecedor);
edFunc.Text := aNomeFunc;
Tipo := aTipo;
if aTipo=1 then
edAvulso.Text := aNome;
CliCad := aCodigo;
if aCodigo>0 then
UpdateCliCadEdit(False);
if aParent<>nil then begin
aParent.Height := panCliente.Height;
panCliente.Parent := aParent;
end;
end;
procedure TFrmCli.lbComCadFocusChanged(Sender: TObject);
begin
Caption := FormatDateTime(SncaFrmCli_HhMmSs, Now);
end;
procedure TFrmCli.lbSemCadClick(Sender: TObject);
begin
Tipo := TcxLabel(Sender).Tag;
case FTipo of
0 : edCad.SetFocus;
1 : Timer3.Enabled := True;
end;
if Assigned(FOnMudouCliente) then
FOnMudouCliente(Self);
end;
function TFrmCli.Nome: String;
begin
case FTipo of
0 : Result := FPesq.TabNome.Value;
1 : Result := edAvulso.Text;
2 : Result := edFunc.Text;
end;
end;
procedure TFrmCli.pmCliClosePopup(Sender: TObject; Selected: Boolean);
begin
FPopped := False;
if FCliCad>0 then UpdateCliCadEdit(False);
end;
procedure TFrmCli.pmCliPopup(Sender: TObject);
begin
FPopped := True;
end;
procedure TFrmCli.SetCliCad(const Value: Integer);
var SaveIgnore, Alterou : Boolean;
begin
SaveIgnore := FIgnoreChange;
FIgnoreChange := True;
try
Alterou := (FCliCad<>Value);
if (Value>0) and (FPesq.TabID.Value <> Value) then begin
FPesq.Tab.CancelRange;
if not FPesq.Tab.Locate('ID', Value, []) then // do not localize
Raise Exception.Create(SncaFrmCli_Cliente+IntToStr(Value)+SncaFrmCli_NãoEncontradoNoBancoDeDados);
end;
FCliCad := Value;
if Alterou then begin
UpdateCliCadInfo;
if Assigned(FOnMudouCliente) then
FOnMudouCliente(Self);
end;
finally
FIgnoreChange := SaveIgnore;
end;
end;
procedure TFrmCli.SetFornecedor(const Value: Boolean);
begin
FFornecedor := Value;
panFoto.Visible := (not FFornecedor);
if FFornecedor then begin
lbBuscar.Caption := SncaFrmCli_Fornecedor;
lbComCad.Caption := SncaFrmCli_Fornecedor_1;
lbSemCad.Visible := false;
lbFunc.Visible := False;
lbAvulso.Caption := SncaFrmCli_Nome;
cmNome.Visible := ivNever;
cmUsername.Visible := ivNever;
cmCod.Visible := ivNever;
pgCli.ActivePage := tsCliCad;
FPesq.rgFornecedor.Checked := FFornecedor;
panTopo.Visible := False;
panCliente.Height := 60;
panCliente.Parent.Height := 60;
end else begin
lbComCad.Caption := SncaFrmCli_ClienteCOMCadastro;
lbSemCad.Caption := SncaFrmCli_ClienteSEMCadastro;
lbAvulso.Caption := SncaFrmCli_Nome;
end;
end;
procedure TFrmCli.SetOrdemCli(const Value: Byte);
begin
if FOrdemCli = Value then Exit;
FOrdemCli := Value;
UpdateOrdemCliCad;
end;
procedure TFrmCli.SetReadOnly(const Value: Boolean);
begin
if FReadOnly = Value then Exit;
FReadOnly := Value;
edCad.Enabled := not Value;
lbComCad.Enabled := not Value;
lbSemCad.Enabled := not Value;
lbFunc.Enabled := not Value;
end;
procedure TFrmCli.SetTipo(const Value: Byte);
procedure SetUnderline(L: TcxLabel);
var B : Boolean;
begin
B := (L.Tag=FTipo);
with L do
if B then begin
Style.TextStyle := [fsUnderline];
Style.TextColor := clBlack;
end else begin
Style.TextStyle := [];
Style.TextColor := $004B4B4B;
end;
end;
begin
FTipo := Value;
if FFornecedor then
pgCli.ActivePageIndex := 0
else
pgCli.ActivePageIndex := Value;
if (Value=0) or FFornecedor then
pgFoto.ActivePageIndex := 0 else
pgFoto.ActivePageIndex := 1;
SetUnderline(lbComCad);
SetUnderline(lbSemCad);
SetUnderline(lbFunc);
end;
procedure TFrmCli.Timer1Timer(Sender: TObject);
var P : TPoint;
begin
Timer1.Enabled := False;
P.X := 0;
P.Y := edCad.Height;
P := edCad.ClientToScreen(P);
pmCli.Popup(P.X, P.Y);
end;
procedure TFrmCli.Timer2Timer(Sender: TObject);
begin
Timer2.Enabled := False;
if edCad.Focused then
edCad.SelectAll;
end;
procedure TFrmCli.Timer3Timer(Sender: TObject);
begin
Timer3.Enabled := False;
case pgCli.ActivePageIndex of
0 : edCad.SetFocus;
1 : edAvulso.SetFocus;
end;
end;
function TFrmCli.TipoAcessoPref: Integer;
begin
if Codigo>0 then
Result := FPesq.TabTipoAcessoPref.Value else
Result := -1;
end;
procedure TFrmCli.UpdateCliCadEdit(aSelectAll: Boolean);
begin
FIgnoreChange := True;
try
if cmNome.Down or FFornecedor then
edCad.Text := FPesq.TabNome.Value
else
if cmUsername.Down then
edCad.Text := FPesq.TabUsername.Value
else
edCad.Text := FPesq.TabID.AsString;
if aSelectAll then Timer2.Enabled := True;
finally
FIgnoreChange := False;
end;
end;
procedure TFrmCli.UpdateCliCadInfo(aUpdateEdit: Boolean = False);
var s: String;
begin
if (FCliCad>0) then begin
if not FPesq.TabFoto.IsNull then begin
S := ExtractFilePath(ParamStr(0))+'temp.jpg'; // do not localize
FPesq.TabFoto.SaveToFile(S);
try imFoto.Picture.LoadFromFile(S); except end;
end else
imFoto.Picture.Assign(imFotoAvulso.Picture);
if FOrdemCli>0 then
lbNome.Caption := FPesq.TabNome.Value else
lbNome.Caption := FPesq.TabUsername.Value;
if FPesq.TabDebito.Value>0 then begin
lbDebito.Caption := SncaFrmCli_Débito + FloatToStrF(FPesq.TabDebito.Value, ffCurrency, 10, 2);
lbDebito.Visible := True;
end else
lbDebito.Visible := False;
if aUpdateEdit then UpdateCliCadEdit(False);
cmEditar.Enabled := True;
lbNome.Visible := (FOrdemCli>0)
end else begin
cmEditar.Enabled := False;
lbNome.Visible := False;
lbDebito.Visible := False;
end;
end;
procedure TFrmCli.UpdateOrdemCliCad;
begin
UpdateCliCadInfo(True);
if FPesq.Tab.active then begin
FIgnoreChange := True;
try
FPesq.Tab.CancelRange;
case FOrdemCli of
0 : begin
FPesq.rgNome.Checked := True;
lbBuscar.Caption := SncaFrmCli_Nome;
cmNome.Down := true;
end;
1 : begin
FPesq.rgUsername.Checked := True;
lbBuscar.Caption := SncaFrmCli_Username;
cmUsername.Down := true;
end;
2 : begin
FPesq.rgCod.Checked := True;
lbBuscar.Caption := SncaFrmCli_Código;
cmCod.Down := True;
end;
end;
CliCad := FCliCad;
if edCad.Focused then Timer2.Enabled := True;
finally
FIgnoreChange := False;
end;
end;
end;
{ TFrmCliList }
constructor TFrmCliList.Create;
begin
FItens := TThreadList.Create;
end;
destructor TFrmCliList.Destroy;
var I : Integer;
begin
with FItens.LockList do begin
while Count>0 do begin
TObject(Items[0]).Free;
Delete(0);
end;
end;
FItens.Free;
inherited;
end;
function TFrmCliList.GetFrm: TFrmCli;
begin
with FItens.LockList do
try
if Count>0 then begin
Result := TFrmCli(Items[0]);
Result.OnMudouCliente := nil;
Delete(0);
end else
Result := TFrmCli.Create(nil);
finally
FItens.UnlockList;
end;
end;
procedure TFrmCliList.ReleaseFrm(aFrm: TFrmCli);
begin
with FItens.LockList do
try
aFrm.pmCli.ClosePopup(False);
aFrm.Reset;
aFrm.CliCad := 0;
Add(aFrm);
finally
FItens.UnlockList;
end;
end;
initialization
gCliList := TFrmCliList.Create;
finalization
gCliList.Free;
end.
|
//-----------------------------------------
// Maciej Czekański
// maves90@gmail.com
//-----------------------------------------
unit Arkanoid;
interface
uses Math;
CONST
SCREEN_WIDTH = 800;
SCREEN_HEIGHT = 600;
BOUND = 40;
BRICK_WIDTH = 80;
BRICK_HEIGHT = 20;
PADDLE_WIDTH = 80;
MAX_PADDLE_WIDTH = 120;
MIN_PADDLE_WIDTH = 60;
MAX_ELEMENT_COUNT = 100;
LENGHTEN_SPEED = 75;
//Game state
GS_MENU = 2;
GS_GAME = 3;
GS_HIGHSCORES = 4;
GS_CREDITS = 5;
GS_GAMEOVER = 6;
//Brick Type
BT_NORMAL = 1;
BT_ROCK = 2;
BT_SOLID = 3;
//Powerup Type
PT_BALL = 1;
PT_SPEED_UP = 2;
PT_SLOW_DOWN = 3;
PT_FIREBALL = 4;
PT_LENGHTEN = 5;
PT_SHORTEN = 6;
PT_COUNT = 6;
//------------------------------------------------------------------------------------------------
// T Y P E S
//------------------------------------------------------------------------------------------------
TYPE
// Struktura opisująca klocek/ścianę
TBrick = object
rect: TRectF;
r, g, b: longint;
alive: boolean;
brickType: longint;
hitsToBreak: longint;
exploding: boolean;
explosionStartTime: Real;
end;
// Struktura opisująca bonus
TPowerup = object
pos: TVector2;
vel: TVector2;
alive: boolean;
powerupType: longint;
end;
// Struktura opisująca piłkę
TBall = object
pos: TVector2;
radius: Real;
vel: TVector2;
alive: boolean;
fireball: boolean;
hitCount: longint; // dla fireballa
end;
// Struktura opisująca paletkę
TPaddle = object
rect: TRectF;
lenghtening: boolean;
shortening: boolean;
end;
operator =(a, b: TBrick): boolean;
operator =(a, b: TPowerup): boolean;
operator =(a, b: TBall): boolean;
operator =(a, b: TPaddle): boolean;
implementation
// :TODO:
operator =(a, b: TBrick): boolean;
begin
result:= a.rect = b.rect;
end;
operator =(a, b: TPowerup): boolean;
begin
result:= a.pos = b.pos;
end;
operator =(a, b: TBall): boolean;
begin
result:= a.pos = b.pos;
end;
operator =(a, b: TPaddle): boolean;
begin
result:= a.rect = b.rect;
end;
begin
end. |
unit ufrmSysLangGuiContent;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils,
Vcl.AppEvnts, Vcl.Menus, Vcl.Samples.Spin,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.Memo,
Ths.Erp.Helper.ComboBox,
ufrmBase,
ufrmBaseInputDB
, Ths.Erp.Database.Table.View.SysViewTables
;
type
TfrmSysLangGuiContent = class(TfrmBaseInputDB)
lbllang: TLabel;
lblcode: TLabel;
lblval: TLabel;
lblcontent_type: TLabel;
lbltable_name: TLabel;
lblform_name: TLabel;
lblis_factory_setting: TLabel;
edtlang: TEdit;
edtcode: TEdit;
edtval: TEdit;
edtcontent_type: TEdit;
cbbtable_name: TComboBox;
edtform_name: TEdit;
chkis_factory_setting: TCheckBox;
procedure RefreshData();override;
procedure btnAcceptClick(Sender: TObject);override;
private
public
protected
procedure HelperProcess(Sender: TObject); override;
published
procedure FormShow(Sender: TObject); override;
end;
implementation
uses
Ths.Erp.Database.Singleton
, Ths.Erp.Database.Table.SysLangGuiContent
, Ths.Erp.Database.Table.SysLang
, ufrmHelperSysLang
;
{$R *.dfm}
procedure TfrmSysLangGuiContent.FormShow(Sender: TObject);
begin
inherited;
edtlang.CharCase := ecNormal;
edtcode.CharCase := ecNormal;
edtval.CharCase := ecNormal;
edtcontent_type.CharCase := ecNormal;
cbbtable_name.CharCase := ecNormal;
edtform_name.CharCase := ecNormal;
edtlang.OnHelperProcess := HelperProcess;
end;
procedure TfrmSysLangGuiContent.HelperProcess(Sender: TObject);
var
vHelperSysLang: TfrmHelperSysLang;
begin
if Sender.ClassType = TEdit then
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if TEdit(Sender).Name = edtlang.Name then
begin
vHelperSysLang := TfrmHelperSysLang.Create(TEdit(Sender), Self, nil, True, ifmNone, fomNormal);
try
vHelperSysLang.ShowModal;
if Assigned(TSysLangGuiContent(Table).Lang.FK.FKTable) then
TSysLangGuiContent(Table).Lang.FK.FKTable.Free;
TSysLangGuiContent(Table).Lang.FK.FKTable := vHelperSysLang.Table.Clone;
finally
vHelperSysLang.Free;
end;
end
end;
end;
end;
procedure TfrmSysLangGuiContent.RefreshData();
begin
if FormViewMode = ivmSort then
begin
lblcontent_type.Visible := False;
edtcontent_type.Visible := False;
lbltable_name.Visible := False;
cbbtable_name.Visible := False;
lblis_factory_setting.Visible := False;
chkis_factory_setting.Visible := False;
lblform_name.Visible := False;
edtform_name.Visible := False;
Height := 200;
end
else
if FormViewMode = ivmNormal then
begin
lblcontent_type.Visible := True;
edtcontent_type.Visible := True;
lbltable_name.Visible := True;
cbbtable_name.Visible := True;
lblis_factory_setting.Visible := True;
chkis_factory_setting.Visible := True;
lblform_name.Visible := True;
edtform_name.Visible := True;
Height := 290;
end;
if cbbtable_name.Items.IndexOf( TSysLangGuiContent(Table).TableName1.Value ) = -1 then
cbbtable_name.Items.Add( TSysLangGuiContent(Table).TableName1.Value );
inherited;
end;
procedure TfrmSysLangGuiContent.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
TSysLangGuiContent(Table).Lang.Value := edtlang.Text;
TSysLangGuiContent(Table).Code.Value := edtcode.Text;
TSysLangGuiContent(Table).ContentType.Value := edtcontent_type.Text;
TSysLangGuiContent(Table).TableName1.Value := cbbtable_name.Text;
TSysLangGuiContent(Table).Val.Value := edtval.Text;
TSysLangGuiContent(Table).IsFactorySetting.Value := chkis_factory_setting.Checked;
inherited;
end;
end
else
inherited;
end;
end.
|
{: GLFileNurbs<p>
Nurbs surfaces vector file loading.<p>
<b>History :</b><font size=-1><ul>
<li>11/08/03 - SG - Some minor changes
<li>05/08/03 - SG - Initial, adapted LoadFromStream from earlier tests
with GLNurbsSurface (depricated), originally coded
by Eric Grange.
</ul></font>
}
unit GLFileNurbs;
interface
uses
System.Classes, System.SysUtils,
GLVectorFileObjects,
GLVectorGeometry, GLVectorLists, GLApplicationFileIO,
GLParametricSurfaces, GLUtils;
type
// TGLNurbsSurface
//
TGLNurbsVectorFile = class(TVectorFile)
public
{ Public Declarations }
class function Capabilities : TDataFileCapabilities; override;
procedure LoadFromStream(stream : TStream); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLNurbsVectorFile ------------------
// ------------------
// Capabilities
//
class function TGLNurbsVectorFile.Capabilities : TDataFileCapabilities;
begin
Result:=[dfcRead];
end;
// LoadFromStream
//
procedure TGLNurbsVectorFile.LoadFromStream(stream : TStream);
function CleanupLine(const line : String) : String;
var
p : Integer;
begin
p:=Pos('#', line);
if p>0 then
Result:=LowerCase(Trim(Copy(line, 1, p-1)))
else Result:=LowerCase(Trim(line));
end;
function ReadSingleArray(sl : TStrings; idx : Integer; list : TSingleList) : Integer;
var
k : Integer;
buf : String;
vals : TStringList;
begin
vals:=TStringList.Create;
try
while idx<sl.Count do begin
buf:=CleanupLine(sl[idx]);
if buf=']' then Break;
vals.CommaText:=buf;
for k:=0 to vals.Count-1 do if vals[k]<>'' then
list.Add(GLUtils.StrToFloatDef(vals[k],0));
Inc(idx);
end;
Result:=idx;
finally
vals.Free;
end;
end;
function ReadVectorArray(sl : TStrings; idx : Integer; list : TAffineVectorList) : Integer;
var
buf : String;
vals : TStringList;
begin
vals:=TStringList.Create;
try
while idx<sl.Count do begin
buf:=CleanupLine(sl[idx]);
if buf=']' then Break;
vals.CommaText:=buf;
if vals.Count>=3 then
list.Add(GLUtils.StrToFloatDef(vals[0],0), GLUtils.StrToFloatDef(vals[1],0), GLUtils.StrToFloatDef(vals[2],0));
Inc(idx);
end;
Result:=idx;
finally
vals.Free;
end;
end;
var
sl, buf : TStringList;
ss : TStringStream;
i,j : Integer;
surface : TMOParametricSurface;
invert : Boolean;
invControlPoints : TAffineVectorList;
begin
ss:=TStringStream.Create('');
sl:=TStringList.Create;
buf:=TStringList.Create;
surface:=TMOParametricSurface.CreateOwned(Owner.MeshObjects);
with surface do begin
Name:='Nurbs'+IntToStr(Owner.IndexOf(surface));
Basis:=psbBSpline;
Renderer:=psrOpenGL;
AutoKnots:=False;
end;
invert:=False;
try
ss.CopyFrom(stream, stream.Size-stream.Position);
sl.Text:=ss.DataString;
i:=0; while i<sl.Count do begin
buf.CommaText:=CleanupLine(sl[i]);
if buf.Count>1 then begin
if buf[0]='uorder' then
surface.OrderU:=StrToIntDef(buf[1], 2)
else if buf[0]='vorder' then
surface.OrderV:=StrToIntDef(buf[1], 2)
else if buf[0]='uknot' then
i:=ReadSingleArray(sl, i+1, surface.KnotsU)
else if buf[0]='vknot' then
i:=ReadSingleArray(sl, i+1, surface.KnotsV)
else if buf[0]='weight' then
i:=ReadSingleArray(sl, i+1, surface.Weights)
else if buf[0]='udimension' then
surface.CountU:=StrToIntDef(buf[1], 0)
else if buf[0]='vdimension' then
surface.CountV:=StrToIntDef(buf[1], 0)
else if buf[0]='controlpoint' then
i:=ReadVectorArray(sl, i+1, Surface.ControlPoints)
else if buf[0]='ccw' then
invert:=(buf[1]='false');
end;
Inc(i);
end;
if invert then begin
invControlPoints:=TAffineVectorList.Create;
for i:=surface.CountV-1 downto 0 do
for j:=0 to surface.CountU-1 do
invControlPoints.Add(surface.ControlPoints[i*surface.CountU+j]);
surface.ControlPoints.Assign(invControlPoints);
invControlPoints.Free;
end;
finally
buf.Free;
sl.Free;
ss.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('nurbs', 'Nurbs model files', TGLNurbsVectorFile);
end.
|
unit uspQuery;
interface
uses
System.Classes, FireDAC.Comp.Client, FireDac.DApt, System.SysUtils;
type
TspQuery = class(TFDQuery)
private
FspColunas : TStringList;
FspTabelas : TStringList;
FspCondicoes : TStringList;
procedure SetspColunas(const Value: TStringList);
procedure SetspTabelas(const Value: TStringList);
procedure SetspCondicoes(const Value: TStringList);
procedure MontaSelect(Query : TStringList);
procedure MontaFrom(Query : TStringList);
procedure MontaWhere(Query : TStringList);
Public
Function GeraSQL : TstringList;
Published
property spColunas : TStringList read FspColunas write SetspColunas;
property spTabelas : TStringList read FspTabelas write SetspTabelas;
property spCondicoes : TStringList read FspCondicoes write SetspCondicoes;
end;
implementation
{ TspQuery }
Function TspQuery.GeraSQL:TstringList;
var
spSQL : TStringList;
begin
spSQL := TStringList.Create;
MontaSelect(spSql);
MontaFrom(spSql);
MontaWhere(spSql);
Result := spSQL;
end;
procedure TspQuery.MontaFrom(Query: TStringList);
var
s : String;
begin
Query.add('from');
for s in spTabelas do
Query.add(' ' + s );
end;
procedure TspQuery.MontaSelect(Query: TStringList);
var
s : string;
begin
Query.add('select');
if spColunas.Count = 0 then
Query.add(' *');
for s in spColunas do
begin
if Query.Count = 1 then
Query.add(' ' + s )
else
Query.add(' ,' + s);
end;
end;
procedure TspQuery.MontaWhere(Query: TStringList);
var
s : String;
begin
if spCondicoes.Count > 0 then
Query.add('where 1 = 1 ');
for s in spCondicoes do
Query.add(' and ' + s);
end;
procedure TspQuery.SetspColunas(const Value: TStringList);
begin
FspColunas := Value;
end;
procedure TspQuery.SetspCondicoes(const Value: TStringList);
begin
FspCondicoes := Value;
end;
procedure TspQuery.SetspTabelas(const Value: TStringList);
begin
if Value.Count > 1 then
raise Exception.Create('Quantidade de tabelas maior que 1!');
if Value.Count = 0 then
raise Exception.Create('Nenhuma tabela selecionada!');
FspTabelas := Value;
end;
end.
|
unit UnitTrial;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure Edit3Change(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
E : Boolean; // check errors
S1, S2: string; // get strings from 2 edit.text
N1, N2: Real; // floated numbers
(* procedure checks error of 2 input numbers *)
procedure Errorchecker(S1,S2: string; var Error: Boolean; var N1,N2: Real);
var E1,E2: Integer;
begin
Error := False;
Val(S1,N1,E1); // E1, E2: number errors
Val(S2,N2,E2);
if (E1 > 0) or (E2 > 0) then
begin
ShowMessage('ERROR: You have typed a WRONG character (letter or '
+ 'undigit value). Please check it and try again!');
Error := True;
end;
end;
(* procedure checks value of 2nd number for division *)
procedure Zerochecker(var Error: Boolean; N2: Real);
begin
Error := False;
if N2 = 0 then
begin
ShowMessage('MATH ERROR: CAN NOT DIVIDE "0". Try again!');
Error := True;
end;
end;
(* procedure clears 3rd edit *)
procedure TForm1.Edit3Change(Sender: TObject);
begin
Edit3.Clear;
Label4.Caption := '';
end;
(* ADDITION procedure *)
procedure TForm1.Button1Click(Sender: TObject);
begin
S1 := Edit1.Text; S2 := Edit2.Text;
Errorchecker(S1,S2,E,N1,N2);
if not E then
begin
Label4.Caption := ' +';
Edit3.Text := FloatToStr(N1 + N2);
end;
end;
(* SUBTRACTION procedure *)
procedure TForm1.Button2Click(Sender: TObject);
begin
S1 := Edit1.Text; S2 := Edit2.Text;
Errorchecker(S1,S2,E,N1,N2);
if not E then
begin
Label4.Caption := ' -';
Edit3.Text := FloatToStr(N1 - N2);
end;
end;
(* DIVISION procedure *)
procedure TForm1.Button3Click(Sender: TObject);
begin
S1 := Edit1.Text; S2 := Edit2.Text;
Errorchecker(S1,S2,E,N1,N2);
if not E then
begin
Zerochecker(E,N2);
if not E then
begin
Label4.Caption := ' /';
Edit3.Text := FloatToStr(N1 / N2);
end;
end;
end;
(* DIV procedure *)
procedure TForm1.Button4Click(Sender: TObject);
begin
S1 := Edit1.Text; S2 := Edit2.Text;
Errorchecker(S1,S2,E,N1,N2);
if not E then
if (N1 > Trunc(N1)) or (N2 > Trunc(N2)) then
ShowMessage('MATH ERROR: "Div" is used for only INTEGER value!')
else
begin
Zerochecker(E,N2);
if not E then
begin
Label4.Caption := 'DIV';
Edit3.Text := FloatToStr(Trunc(N1) div Trunc(N2));
end;
end;
end;
end.
|
unit oGridPanelFunctions;
{
================================================================================
*
* Application: CPRS - Utilities
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Provides a singleton interface to common CPRS funtions
* used with the TGridPanel object.
*
* Notes:
*
================================================================================
}
interface
uses
System.Classes,
System.SysUtils,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Forms,
iGridPanelIntf;
type
TGridPanelFunctions = class(TInterfacedObject, IGridPanelFunctions)
public
function AddCoverSheetControl(aGridPanel: TGridPanel; aControl: TControl; aCol, aRow: integer; aAlign: TAlign = alNone): boolean;
function AddRow(aGridPanel: TGridPanel; aSizeStyle: TSizeStyle; aValue: double): integer;
function AddColumn(aGridPanel: TGridPanel; aSizeStyle: TSizeStyle; aValue: double): integer;
function AddControl(aGridPanel: TGridPanel; aControl: TControl; aCol, aRow: integer; aAlign: TAlign = alNone): boolean;
function AlignColumns(aGridPanel: TGridPanel): boolean;
function AlignRows(aGridPanel: TGridPanel): boolean;
function ClearGrid(aGridPanel: TGridPanel): boolean;
function GetContents(aGridPanel: TGridPanel; aOutput: TStrings): integer;
function GetSizeStyleName(aSizeStyle: TSizeStyle): string;
function CollapseRow(aControl: TControl; aCollapsedHeight: integer): boolean;
function ExpandRow(aControl: TControl; aHeight: double; aStyle: TSizeStyle): boolean;
procedure FormatRows(aGridPanel: TGridPanel; aStyles: array of TSizeStyle; aValues: array of double);
end;
implementation
{ TGridPanelFunctions }
function TGridPanelFunctions.AddColumn(aGridPanel: TGridPanel; aSizeStyle: TSizeStyle; aValue: double): integer;
begin
{ Make sure row[0] exists }
while aGridPanel.RowCollection.Count < 1 do
aGridPanel.RowCollection.Add;
with aGridPanel.ColumnCollection.Add do
begin
SizeStyle := aSizeStyle;
Value := aValue;
end;
Result := aGridPanel.ColumnCollection.Count;
end;
function TGridPanelFunctions.AddControl(aGridPanel: TGridPanel; aControl: TControl; aCol, aRow: integer; aAlign: TAlign): boolean;
begin
try
{ Make sure col[0] exists }
while aGridPanel.ColumnCollection.Count < 1 do
aGridPanel.ColumnCollection.Add;
{ Make sure the row as aRow exists }
while aGridPanel.RowCollection.Count < (aRow + 1) do
aGridPanel.RowCollection.Add;
aControl.Parent := aGridPanel;
aGridPanel.ControlCollection.AddControl(aControl, aCol, aRow);
aControl.Align := aAlign;
aControl.Show;
Result := true;
except
Result := false;
end;
end;
function TGridPanelFunctions.AddCoverSheetControl(aGridPanel: TGridPanel; aControl: TControl; aCol, aRow: integer; aAlign: TAlign): boolean;
var
aGridPanelRow: TGridPanel;
begin
try
{ Make sure col[0] exists }
while aGridPanel.ColumnCollection.Count < 1 do
begin
aGridPanel.ColumnCollection.Add;
AlignColumns(aGridPanel);
end;
{ Make sure the row as aRow exists }
while aGridPanel.RowCollection.Count < (aRow + 1) do
begin
aGridPanel.RowCollection.Add;
aGridPanelRow := TGridPanel.Create(aGridPanel);
aGridPanelRow.Name := Format('%s_Row_%d', [aGridPanelRow.ClassName, aGridPanel.RowCollection.Count]);
ClearGrid(aGridPanelRow);
aGridPanelRow.RowCollection.Add;
aGridPanelRow.ColumnCollection.Add;
aGridPanelRow.Parent := aGridPanel;
aGridPanelRow.ShowCaption := false;
aGridPanelRow.TabStop := false;
aGridPanelRow.BorderStyle := bsNone;
aGridPanelRow.BevelInner := bvNone;
aGridPanelRow.BevelOuter := bvNone;
aGridPanelRow.ParentColor := true;
aGridPanelRow.Align := alClient;
aGridPanel.ControlCollection.AddControl(aGridPanelRow, 0, aGridPanel.RowCollection.Count - 1);
end;
AlignRows(aGridPanel);
{ Select the GridPane that is aRow }
aGridPanelRow := TGridPanel(aGridPanel.ControlCollection.Controls[0, aRow]);
{ Make sure the column exists }
while aGridPanelRow.ColumnCollection.Count < (aCol + 1) do
with aGridPanelRow.ColumnCollection.Add do
begin
Value := 20;
SizeStyle := ssPercent;
end;
AlignColumns(aGridPanelRow);
aControl.Parent := aGridPanelRow;
aGridPanelRow.ControlCollection.AddControl(aControl, aCol, 0);
aControl.Align := aAlign;
aControl.Visible := true;
Result := true;
except
Result := false;
end;
end;
function TGridPanelFunctions.AddRow(aGridPanel: TGridPanel; aSizeStyle: TSizeStyle; aValue: double): integer;
begin
{ Make sure col[0] exists }
while aGridPanel.ColumnCollection.Count < 1 do
aGridPanel.ColumnCollection.Add;
aGridPanel.RowCollection.BeginUpdate;
try
with aGridPanel.RowCollection.Add do
begin
SizeStyle := aSizeStyle;
Value := aValue;
end;
finally
aGridPanel.RowCollection.EndUpdate;
end;
Result := aGridPanel.RowCollection.Count;
end;
function TGridPanelFunctions.AlignColumns(aGridPanel: TGridPanel): boolean;
var
i: integer;
j: integer;
begin
aGridPanel.ColumnCollection.BeginUpdate;
try
j := 0;
for i := 0 to aGridPanel.ColumnCollection.Count - 1 do
if aGridPanel.ColumnCollection[i].SizeStyle = ssPercent then
inc(j);
for i := 0 to aGridPanel.ColumnCollection.Count - 1 do
if aGridPanel.ColumnCollection[i].SizeStyle = ssPercent then
aGridPanel.ColumnCollection[i].Value := (100 / j);
aGridPanel.ColumnCollection.EndUpdate;
Result := true;
except
aGridPanel.ColumnCollection.EndUpdate;
Result := false;
end;
end;
function TGridPanelFunctions.AlignRows(aGridPanel: TGridPanel): boolean;
var
i: integer;
j: integer;
begin
aGridPanel.RowCollection.BeginUpdate;
try
j := 0;
for i := 0 to aGridPanel.RowCollection.Count - 1 do
if aGridPanel.RowCollection[i].SizeStyle = ssPercent then
inc(j);
for i := 0 to aGridPanel.RowCollection.Count - 1 do
if aGridPanel.RowCollection[i].SizeStyle = ssPercent then
aGridPanel.RowCollection[i].Value := (100 / j);
aGridPanel.RowCollection.EndUpdate;
Result := true;
except
aGridPanel.RowCollection.EndUpdate;
Result := false;
end;
end;
function TGridPanelFunctions.ClearGrid(aGridPanel: TGridPanel): boolean;
var
aControl: TControl;
begin
try
while aGridPanel.ControlCollection.Count > 0 do
begin
aControl := aGridPanel.ControlCollection[0].control;
if aControl is TGridPanel then
begin
ClearGrid(TGridPanel(aControl));
TGridPanel(aControl).ControlCollection.Clear;
TGridPanel(aControl).ColumnCollection.Clear;
TGridPanel(aControl).RowCollection.Clear;
end;
aGridPanel.ControlCollection.RemoveControl(aControl);
FreeAndNil(aControl);
end;
aGridPanel.ControlCollection.Clear;
aGridPanel.RowCollection.Clear;
aGridPanel.ColumnCollection.Clear;
Result := true;
except
Result := false;
end;
end;
function TGridPanelFunctions.CollapseRow(aControl: TControl; aCollapsedHeight: integer): boolean;
var
aGridPanel: TGridPanel;
aIndex: integer;
begin
if aControl.Parent.ClassNameIs('TGridPanel') then
begin
aGridPanel := TGridPanel(aControl.Parent);
aIndex := aGridPanel.ControlCollection.IndexOf(aControl);
if aIndex < 0 then
raise Exception.Create('Control not in parent control collection');
aGridPanel.RowCollection.BeginUpdate;
with aGridPanel do
try
RowCollection[aIndex].SizeStyle := ssAbsolute;
RowCollection[aIndex].Value := aCollapsedHeight;
finally
RowCollection.EndUpdate;
end;
Result := true;
end
else
Result := false;
end;
function TGridPanelFunctions.ExpandRow(aControl: TControl; aHeight: double; aStyle: TSizeStyle): boolean;
var
aGridPanel: TGridPanel;
aIndex: integer;
begin
if aControl.Parent.ClassNameIs('TGridPanel') then
begin
aGridPanel := TGridPanel(aControl.Parent);
aIndex := aGridPanel.ControlCollection.IndexOf(aControl);
if aIndex < 0 then
raise Exception.Create('Control not in parent control collection');
aGridPanel.RowCollection.BeginUpdate;
with aGridPanel do
try
RowCollection[aIndex].SizeStyle := aStyle;
RowCollection[aIndex].Value := aHeight;
finally
RowCollection.EndUpdate;
end;
Result := true;
end
else
Result := false;
end;
procedure TGridPanelFunctions.FormatRows(aGridPanel: TGridPanel; aStyles: array of TSizeStyle; aValues: array of double);
var
i: integer;
begin
aGridPanel.RowCollection.BeginUpdate;
try
if High(aStyles) <> High(aValues) then
raise Exception.Create('MisMatch in number of styles vs values.');
if High(aStyles) <> (aGridPanel.RowCollection.Count - 1) then
raise Exception.Create('MisMatch in number of styles/values vs rows.');
for i := Low(aStyles) to High(aStyles) do
begin
aGridPanel.RowCollection[i].SizeStyle := aStyles[i];
aGridPanel.RowCollection[i].Value := aValues[i];
end;
finally
aGridPanel.RowCollection.EndUpdate;
end;
end;
function TGridPanelFunctions.GetContents(aGridPanel: TGridPanel; aOutput: TStrings): integer;
var
i: integer;
aControl: TControl;
begin
try
aOutput.Add('Here''s the stats so far');
aOutput.Add(Format('TGridPanel: %s (Rows: %d, Cols: %d)', [aGridPanel.Name, aGridPanel.RowCollection.Count, aGridPanel.ColumnCollection.Count]));
aOutput.Add('Rows');
aOutput.Add('----');
for i := 0 to aGridPanel.RowCollection.Count - 1 do
begin
aOutput.Add(Format(' Row %d, SizeStyle: %d', [i, ord(aGridPanel.RowCollection[i].SizeStyle)]));
aOutput.Add(Format(' Value : %0.5f', [aGridPanel.RowCollection[i].Value]));
end;
aOutput.Add('Columns');
aOutput.Add('-------');
for i := 0 to aGridPanel.ColumnCollection.Count - 1 do
begin
aOutput.Add(Format(' Col %d, SizeStyle: %d', [i, ord(aGridPanel.ColumnCollection[i].SizeStyle)]));
aOutput.Add(Format(' Value : %0.5f', [aGridPanel.ColumnCollection[i].Value]));
end;
aOutput.Add('Controls');
aOutput.Add('--------');
for i := 0 to aGridPanel.ControlCollection.Count - 1 do
begin
aControl := aGridPanel.ControlCollection[i].control;
aOutput.Add(Format(' Control %d, ClassName: %s (Name: %s)', [i, aControl.ClassName, aControl.Name]));
with aGridPanel.ControlCollection[i] do
aOutput.Add(Format(' Row: %d, Col: %d', [row, column]));
if aControl.ClassNameIs(aGridPanel.ClassName) then
begin
aOutput.Add(' ');
aOutput.Add(' Embedded TGridPanel');
aOutput.Add(' ===================');
GetContents(TGridPanel(aControl), aOutput);
aOutput.Add(' ===================');
aOutput.Add(' Embedded TGridPanel');
aOutput.Add(' ');
end;
end;
except
on e: Exception do
aOutput.Add(e.message);
end;
Result := aOutput.Count;
end;
function TGridPanelFunctions.GetSizeStyleName(aSizeStyle: TSizeStyle): string;
begin
case aSizeStyle of
ssAbsolute: Result := 'ssAbsolute';
ssPercent: Result := 'ssPercent';
ssauto: Result := 'ssAuto';
else
Result := 'Unknown';
end;
end;
end.
|
{ Unit to make assembly procedures available in Quick Pascal. }
UNIT DEMO;
INTERFACE
CONST
{ Constants }
CR = 13; { ASCII code for Return }
ESCAPE = 27; { ASCII code for Esc key }
MDA = 0; { Adapter constants }
CGA = 1;
MCGA = 2;
EGA = 3;
VGA = 4;
MONO = 0; { Display constants }
COLOR = 1;
{$A- Record members at 1-byte boundaries }
TYPE
{ Video configuration record }
vid_config = RECORD
vmode : BYTE; { Current mode }
dpage : BYTE; { Current display page }
rows : BYTE; { Number of display rows - 1 }
display : BYTE; { Either MONO or COLOR }
adapter : BYTE; { Adapter code }
CGAvalue : BYTE; { Enable value for CGA }
sgmnt : WORD; { Video segment with page offset }
END;
{ Disk statistics returned from GetDiskSize procedure }
disk_stat = RECORD
total : WORD; { total clusters }
avail : WORD; { available clusters }
sects : WORD; { sectors per cluster }
bytes : WORD; { bytes per sector }
END;
{ File information returned from FindFirst procedure }
file_info = RECORD
pad : STRING[21]; { pad to 43 bytes }
attrib : BYTE; { file attribute }
time : INTEGER; { file time }
date : INTEGER; { file date }
size : LONGINT; { file size }
name : STRING[13]; { file name }
END;
{ Procedure prototypes from COMMON.ASM }
PROCEDURE GetVidConfig;
PROCEDURE StrWrite( row : INTEGER; col : INTEGER; str : CSTRING );
PROCEDURE ClearBox( attr : WORD;
row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER );
FUNCTION GetVer : INTEGER;
FUNCTION SetCurPos( row : INTEGER; col : INTEGER ) : INTEGER;
{ Procedure prototypes from MISC.ASM }
FUNCTION WinOpen( row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER;
attr : WORD ) : INTEGER;
PROCEDURE WinClose( addr : WORD );
PROCEDURE SetCurSize( scan1 : WORD; scan2 : WORD );
FUNCTION GetCurSize : WORD ;
FUNCTION GetCurPos : WORD ;
FUNCTION GetShift : WORD ;
FUNCTION GetKeyClock( row : INTEGER; col : INTEGER ) : INTEGER;
FUNCTION GetMem : LONGINT;
FUNCTION VeriPrint : INTEGER;
FUNCTION VeriAnsi : INTEGER;
FUNCTION VeriCop : INTEGER;
FUNCTION SetLineMode( line : INTEGER ) : INTEGER;
PROCEDURE Pause( duration : WORD );
PROCEDURE Sound( freq : WORD; duration : WORD );
PROCEDURE WriteTTY( VAR str : CSTRING ; icolor : WORD );
PROCEDURE Colors( logic : INTEGER; attr : WORD;
row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER );
PROCEDURE BinToHex( num : INTEGER; VAR hexstr : CSTRING );
{ Procedure prototypes from MATH.ASM }
FUNCTION AddLong( long1 : LONGINT; long2 : LONGINT ) : LONGINT;
FUNCTION SubLong( long1 : LONGINT; long2 : LONGINT ) : LONGINT;
FUNCTION ImulLong( long1 : LONGINT; long2 : LONGINT ) : LONGINT;
{ FUNCTION *MulLong( long1 : LONGINT; long2 : LONGINT ) : LONGINT; }
FUNCTION DivLong( long1 : LONGINT; short2 : INTEGER;
VAR remn : INTEGER ) : INTEGER;
FUNCTION IdivLong( long1 : LONGINT; short2 : INTEGER;
VAR remn : INTEGER ) : INTEGER;
FUNCTION Quadratic( a: SINGLE; b : SINGLE; c : SINGLE;
VAR r1 : SINGLE; VAR r2 : SINGLE ) : INTEGER;
{ Procedure prototypes from FILE.ASM }
PROCEDURE ChangeDrive( drive : INTEGER );
PROCEDURE GetDiskSize( drive : INTEGER; VAR disk: disk_stat );
FUNCTION ReadCharAttr( VAR attr : INTEGER ) : INTEGER;
FUNCTION GetCurDir( VAR spec : CSTRING ) : INTEGER;
FUNCTION GetCurDisk : INTEGER;
FUNCTION CopyFile( imode : INTEGER;
VAR fspec1 : CSTRING;
VAR fspec2 : CSTRING ) : INTEGER;
FUNCTION DelFile( fspec : CSTRING ) : INTEGER;
FUNCTION MakeDir( pspec : CSTRING ) : INTEGER;
FUNCTION RemoveDir( pspec : CSTRING ) : INTEGER;
FUNCTION ChangeDir( pspec : CSTRING ) : INTEGER;
FUNCTION GetAttribute( fspec : CSTRING ) : INTEGER;
FUNCTION SetAttribute( attr : INTEGER; fspec : CSTRING ) : INTEGER;
FUNCTION RenameFile( fspec1 : CSTRING; fspec2 :CSTRING ) : INTEGER;
FUNCTION GetFileTime( handle : INTEGER; str : CSTRING ) : INTEGER;
FUNCTION FindFirst( attr : WORD; fspec : CSTRING; VAR finfo : file_info ) : INTEGER ;
FUNCTION FindNext( VAR finfo : file_info ) : INTEGER;
FUNCTION UniqueFile( attr : WORD; fspec : CSTRING ) : INTEGER;
FUNCTION OpenFile( access : INTEGER; fspec : CSTRING ) : INTEGER;
FUNCTION CloseFile( handle : INTEGER ) : INTEGER;
FUNCTION ReadFile( handle : INTEGER; len : INTEGER; pbuff :CSTRING ) : INTEGER;
FUNCTION GetStr( bufstr : CSTRING; maxlen : INTEGER ): INTEGER;
{ FUNCTION char *StrCompare( str1 : CSTRING; str2 : CSTRING; len : INTEGER );
FUNCTION char *StrFindChar( ichar : BYTE; str : CSTRING; INTEGER direct );
}
{ Procecedure prototype for internal procedure. }
PROCEDURE clear_scrn( attr : WORD; row1 : INTEGER; row2 : INTEGER );
IMPLEMENTATION
VAR
vconfig : vid_config; { Record for video configuration }
{$L COMMON.OBJ}
{ Procedure prototypes from COMMON.ASM }
PROCEDURE GetVidConfig; EXTERNAL;
PROCEDURE StrWrite( row : INTEGER; col : INTEGER; str : CSTRING ); EXTERNAL;
PROCEDURE ClearBox( attr : WORD;
row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER ); EXTERNAL;
FUNCTION GetVer : INTEGER;
FUNCTION SetCurPos( row : INTEGER; col : INTEGER ) : INTEGER;
{$L MISC.OBJ}
{ Procedure prototypes from MISC.ASM }
FUNCTION WinOpen( row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER;
attr : WORD ) INTEGER; EXTERNAL;
PROCEDURE WinClose( addr : WORD );
PROCEDURE SetCurSize( WORD scan1; WORD scan2 );
FUNCTION WORD GetCurSize : WORD ;
FUNCTION WORD GetCurPos : WORD ;
FUNCTION WORD GetShift : WORD ;
FUNCTION INTEGER GetKeyClock( row : INTEGER; col : INTEGER );
FUNCTION GetMem : LONGINT;
FUNCTION VeriPrint : INTEGER;
FUNCTION VeriAnsi : INTEGER;
FUNCTION VeriPrint : INTEGER;
FUNCTION SetLineMode( line : INTEGER ) : INTEGER;
PROCEDURE Pause( duration : WORD );
PROCEDURE Sound( freq : WORD; duration : WORD );
PROCEDURE WriteTTY( str : CSTRING; icolor : WORD );
PROCEDURE Colors( logic : INTEGER; attr : WORD;
row1 : INTEGER; col1 : INTEGER;
row2 : INTEGER; col2 : INTEGER; attr : WORD );
PROCEDURE BinToHex( num : INTEGER; hexstr : CSTRING );
{$L MATH.OBJ}
{ Procedure prototypes from MATH.ASM }
FUNCTION LONGINT AddLong( long1 : LONGINT; long2 : LONGINT ); EXTERNAL;
FUNCTION LONGINT SubLong( long1 : LONGINT; long2 : LONGINT ); EXTERNAL;
FUNCTION LONGINT ImulLong( long1 : LONGINT; long2 : LONGINT ); EXTERNAL;
FUNCTION LONGINT *MulLong( long1 : LONGINT; long2 : LONGINT ); EXTERNAL;
FUNCTION INTEGER DivLong( long1 : LONGINT; short2 : INTEGER;
VAR remn : INTEGER ); EXTERNAL;
FUNCTION INTEGER IdivLong( long1 : LONGINT; short2 : INTEGER;
VAR remn : INTEGER ); EXTERNAL;
FUNCTION INTEGER Quadratic( a: SINGLE; b : SINGLE; c : SINGLE;
VAR r1 : SINGLE; VAR r2 : SINGLE ); EXTERNAL;
{$L FILE.OBJ}
{ Procedure prototypes from FILE.ASM }
PROCEDURE ChangeDrive( drive : INTEGER ); EXTERNAL;
PROCEDURE GetDiskSize( drive : INTEGER; VAR disk : disk_stat ); EXTERNAL;
PROCEDURE GetVidConfig; EXTERNAL;
FUNCTION ReadCharAttr( VAR attr : INTEGER ) : INTEGER; EXTERNAL;
FUNCTION GetCurDir( VAR spec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION GetCurDisk : INTEGER; EXTERNAL;
FUNCTION CopyFile( imode : INTEGER;
VAR fspec1 : CSTRING;
VAR fspec2 : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION DelFile( fspec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION MakeDir( pspec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION RemoveDir( pspec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION ChangeDir( pspec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION GetAttribute( fspec : CSTRING ) : INTEGER; EXTERNAL;
FUNCTION SetAttribute( attr : INTEGER; char *fspec ) : INTEGER; EXTERNAL;
FUNCTION RenameFile( char *fspec1; char *fspec2 ) : INTEGER; EXTERNAL;
FUNCTION GetFileTime( handle : INTEGER; char *str ) : INTEGER; EXTERNAL;
FUNCTION FindFirst( attr : WORD; char *fspec; VAR finfo : file_info ) : INTEGER ; EXTERNAL;
FUNCTION FindNext( VAR finfo : file_info ) : INTEGER; EXTERNAL;
FUNCTION UniqueFile( attr : WORD; char *fspec ) : INTEGER; EXTERNAL;
FUNCTION OpenFile( access : INTEGER; char *fspec ) : INTEGER; EXTERNAL;
FUNCTION CloseFile( handle : INTEGER ) : INTEGER; EXTERNAL;
FUNCTION ReadFile( handle : INTEGER; len : INTEGER; char *pbuff ) : INTEGER; EXTERNAL;
FUNCTION SetCurPos( row : INTEGER; col : INTEGER ) : INTEGER; EXTERNAL;
FUNCTION GetStr( char *bufstr; INTEGER maxlen ): INTEGER; EXTERNAL;
FUNCTION char *StrCompare( char *str1; char *str2; INTEGER len ); EXTERNAL;
FUNCTION char *StrFindChar( char ichar; char *str; INTEGER direct ); EXTERNAL;
{ Procecedure prototype for internal procedure. }
PROCEDURE clear_scrn( attr, row1, row2 );
PROCEDURE clear_scrn( attr : WORD, row1 : INTEGER, row2 : INTEGER );
BEGIN
ClearBox( attr, row1, 0, row2, 79 );
END;
END.
|
unit fqWeb;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, Registry, SHDocVw;
type
TfqWebForm = class(TForm)
WebBrowser1: TWebBrowser;
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure LoadURL(URL: string; DB: string = '');
end;
implementation
{$R *.dfm}
constructor TfqWebForm.Create(AOwner: TComponent);
var
reg: TRegistry;
begin
// 关于 IE 内核
// 系统 IE 内核高于 IE7 时,TWebBrowser 控件默认创建的是 IE7 兼容模式,应用程序可以通过如下方法修改兼容版本
// HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
// 添加一个名称为应用程序自身名称的 DWORD 值,IE7/7000,IE8/8000,IE9/9000,IE10/10000,IE11/11000,Edge/>12000(只是模拟 userAgent,内核仍然是 IE11)
//
// 关于 UAC 控制
// 自 Vista 开始,操作系统增加了 UAC 控制功能,如果开启 UAC 的情况下,没有使用管理员权限执行程序,默认都会采用 UAC 虚拟化
// 对注册表没有写入权限时,操作将会被自动重定向到 HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\...
// 对目录没有写入权限时,操作将会被自动重定向到 C:\Users\用户名\AppData\Local\VirtualStore\...
// 因此以上操作在没有使用管理员权限执行程序时会被重定向到如下位置
// HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
reg := TRegistry.Create();
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKey('SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION', True);
reg.WriteInteger(ExtractFileName(Application.ExeName), 11000);
reg.CloseKey();
reg.Free();
inherited Create(AOwner);
end;
procedure TfqWebForm.LoadURL(URL: string; DB: string);
var
FileName: string;
Stream: TStream;
begin
if (DB <> '') then
begin
FileName := ExtractFilePath(Application.ExeName) + 'Web\database.js';
Stream := TFileStream.Create(FileName, fmCreate);
DB := 'var dbFile = "' + StringReplace(DB, '\', '\\', [rfReplaceAll ]) + '";';
DB := UTF8Encode(WideString(DB));
try
Stream.WriteBuffer(Pointer(DB)^, Length(DB));
finally
Stream.Free();
end;
end;
WebBrowser1.Navigate(WideString(URL));
end;
end.
|
(*****************************************************************************
* *
* This file is part of the UMLCat Component Library. *
* *
* See the file COPYING.modifiedLGPL.txt, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
*****************************************************************************
**)
unit uktansisxmldocs;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uktstrings,
uktstatestreams,
uktfilestreams,
uktansitextstreams,
uktsrchtypes,
uktdocs,
uktscanneroptions,
uktxmlfileansiscanners,
uktxmlfiletokens,
uktxmlfiletreenodetokens,
uktxmlfileansisymbols,
ukttreenodes,
ukttreecntrs,
uktsxmltreecntrs,
uktansisxmldocres,
dummy;
(**
** Description:
** This unit implements the "Document" Software Design Pattern,
** which allows to use a file in an application,
** with common features like Opening a file, saving a file.
**
** Examples: Bitmap editor, text or word processor editor,
** spreadsheet application.
**
** In this specific case, supports a Simple X.M.L. file.
**)
type
(* TCustomUKTANSIXMLDocument *)
TCustomUKTANSIXMLDocument = class(TCustomUKTDocument)
private
(* Private declarations *)
protected
(* Protected declarations *)
CurrentNode: TUKTSXMLTreeNode;
public
(* Public declarations *)
RootNode: TUKTSXMLTreeNode;
EncodingNode: TUKTSXMLTreeNode;
MainNode: TUKTSXMLTreeNode;
EoFNode: TUKTSXMLTreeNode;
// provides a filesystem access stream,
// used by "TextStream"
FileStream: TUKTFileStream;
// provides a text line based stream
TextStream: TCustomUKTAnsiTextStream;
Scanner: TCustomXMLFileANSIScanner;
TreeContainer: TCustomUKTSXMLTreeContainer;
protected
(* Protected declarations *)
(* Accesors declarations *)
procedure setFullPath(const AValue: string); override;
protected
(* Protected declarations *)
procedure InsertEncoding
(var ASymbol: TXMLFileANSISymbol);
procedure InsertComment
(var ASymbol: TXMLFileANSISymbol);
procedure InsertEoLn
(var ASymbol: TXMLFileANSISymbol);
procedure InsertEoPg
(var ASymbol: TXMLFileANSISymbol);
procedure InsertEoF
(var ASymbol: TXMLFileANSISymbol);
procedure InsertSpace
(var ASymbol: TXMLFileANSISymbol);
procedure InsertTab
(var ASymbol: TXMLFileANSISymbol);
procedure InsertSingle
(var ASymbol: TXMLFileANSISymbol);
procedure InsertText
(var ASymbol: TXMLFileANSISymbol);
procedure StartBlock
(var ASymbol: TXMLFileANSISymbol);
procedure FinishBlock
(var ASymbol: TXMLFileANSISymbol);
procedure ProcessSymbol
(var ASymbol: TXMLFileANSISymbol);
procedure InternalNewFile(); override;
procedure InternalNewAsFile(); override;
procedure InternalSaveFile(); override;
procedure InternalOpenFile(); override;
protected
(* Protected declarations *)
procedure GenerateSXML
(var ANode: TUKTTreeNode;
const AParam: pointer; const ADirection: TUKTTreeDirection);
public
(* Public declarations *)
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
public
(* Public declarations *)
function CreateRoot(): TUKTSXMLTreeNode;
procedure GenerateDocument(var AText: string);
end;
(* TUKTANSIXMLDocument *)
TUKTANSIXMLDocument = class(TCustomUKTANSIXMLDocument)
published
(* published declarations *)
(* TCustomUKTDocument: *)
property AskOverwrite;
property Encoding;
property ExtNewAs;
property ExtOpen;
property ExtSave;
property ExtSaveAs;
property HasName;
property HasEncoding;
property IsClipboardEmpty;
property Modified;
property ReadOnly;
property FullPath;
property SearchMode;
property OnModified;
property OnPathChanged;
property OnSearchModeChanged;
property OnConfirmUser;
property BeforeNewFile;
property AfterNewFile;
property BeforeNewAsFile;
property AfterNewAsFile;
property BeforeOpenFile;
property AfterOpenFile;
property BeforeSaveFile;
property AfterSaveFile;
property BeforeSaveAsFile;
property AfterSaveAsFile;
(* TCustomUKTANSIXMLDocument: *)
end;
implementation
(* TCustomUKTANSIXMLDocument *)
procedure TCustomUKTANSIXMLDocument.setFullPath(const AValue: string);
begin
FFullPath := AValue;
if (FileStream <> nil) then
begin
FileStream.Path := AValue;
end;
DelegateOnPathChanged(AValue);
end;
procedure TCustomUKTANSIXMLDocument.InsertEncoding
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkEncoding;
ANewNode.TextValue
:= uktstrings.TrimDelimitersCopy(ASymbol.Text, '<?', '?>');
ANewNode.Text
:= uktstrings.PadDelimitersCopy(ASymbol.Text, '<?', '?>');
end;
procedure TCustomUKTANSIXMLDocument.InsertComment
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkComment;
ANewNode.TextValue
:= uktstrings.TrimDelimitersCopy(ASymbol.Text, '<!--', '-->');
ANewNode.Text
:= uktstrings.PadDelimitersCopy(ASymbol.Text, '<!--', '-->');
end;
procedure TCustomUKTANSIXMLDocument.InsertEoLn
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkEoLn;
ANewNode.TextValue := #13#10;
ANewNode.Text := '[EoLn]';
end;
procedure TCustomUKTANSIXMLDocument.InsertEoPg
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkEoLn;
ANewNode.TextValue := #12;
ANewNode.Text := '[EoPg]';
end;
procedure TCustomUKTANSIXMLDocument.InsertEoF
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkEoLn;
ANewNode.TextValue := #26;
ANewNode.Text := '[FILEBREAK]';
// --> check if its "main" node
if (EoFNode = nil) then
begin
EoFNode := ANewNode;
end;
end;
procedure TCustomUKTANSIXMLDocument.InsertSpace
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
end;
procedure TCustomUKTANSIXMLDocument.InsertTab
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkTab;
ANewNode.TextValue := #9;
ANewNode.Text := '[TAB]';
end;
procedure TCustomUKTANSIXMLDocument.InsertSingle
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkSingle;
ANewNode.TextValue
:= uktstrings.TrimDelimitersCopy(ASymbol.Text, '<', '/>');
ANewNode.Text
:= uktstrings.PadDelimitersCopy(ASymbol.Text, '<', '/>');
end;
procedure TCustomUKTANSIXMLDocument.InsertText
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkText;
ANewNode.TextValue := ASymbol.Text;
ANewNode.Text := ASymbol.Text;
end;
procedure TCustomUKTANSIXMLDocument.StartBlock
(var ASymbol: TXMLFileANSISymbol);
var ANewNode: TUKTSXMLTreeNode;
begin
// add child node to non-visual node
ANewNode :=
(Self.CurrentNode.Insert() as TUKTSXMLTreeNode);
ANewNode.CanInsert := false; // < --
ANewNode.CanEdit := true;
ANewNode.CanRemove := true;
ANewNode.Symbol := ASymbol;
ANewNode.TreeToken := uktxmlfiletreenodetokens.xmlfiletrntkBlock;
ANewNode.TextValue
:= uktstrings.TrimDelimitersCopy(ASymbol.Text, '<', '>');
ANewNode.Text
:= uktstrings.PadDelimitersCopy(ASymbol.Text, '<', '>');
// --> check if its "main" node
if (MainNode = nil) then
begin
MainNode := ANewNode;
end;
// "start" tags move "current" as parent node
Self.CurrentNode := ANewNode;
end;
procedure TCustomUKTANSIXMLDocument.FinishBlock
(var ASymbol: TXMLFileANSISymbol);
begin
// "start" tags move "current" to parent node
Self.CurrentNode := TUKTSXMLTreeNode(Self.CurrentNode.Parent());
end;
procedure TCustomUKTANSIXMLDocument.ProcessSymbol
(var ASymbol: TXMLFileANSISymbol);
begin
// --> there must be a root "document" node,
// --> at this moment
case (ASymbol.Token) of
uktxmlfiletokens.xmlfiletkEoLn:
begin
InsertEoLn((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkEoPg:
begin
InsertEoPg((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkEoF:
begin
InsertEoF((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkSpace:
begin
InsertSpace((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkTab:
begin
InsertTab((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkText:
begin
InsertText((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkEncoding:
begin
InsertEncoding((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkStart:
begin
StartBlock((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkFinish:
begin
FinishBlock((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkSingle:
begin
InsertSingle((* var *) ASymbol);
end;
uktxmlfiletokens.xmlfiletkBlock:
begin
Self.DoNothing();
end
else
begin
end;
end;
end;
procedure TCustomUKTANSIXMLDocument.InternalNewFile();
begin
// --> assign internal fields
RootNode := nil;
inherited InternalNewFile();
EncodingNode := nil;
MainNode := nil;
EoFNode := nil;
end;
procedure TCustomUKTANSIXMLDocument.InternalNewAsFile();
var ASymbol: TXMLFileANSISymbol;
begin
// --> assign internal fields
FAskOverwrite := FALSE;
FHasName := FALSE;
FSearchIndex := 1;
FSearchMode := uktsrchtypes.srrSearch;
SearchMode := uktsrchtypes.srrNone;
// sera actualizado al activar ventana
// will be updated when window is activated
FIsClipboardEmpty := TRUE;
FModified := FALSE;
FHasName := FALSE;
FReadOnly := FALSE;
FHasEncoding := FALSE;
FAskOverwrite := FALSE;
RootNode := nil;
EncodingNode := nil;
MainNode := nil;
EoFNode := nil;
// update full source path
FileStream.Path := Self.FullPath;
// indicate requested initial state of stream
FileStream.State := uktstatestreams.ssReset;
// --> scan or parse file
if (Scanner.Start()) then
begin
// initial assignation, will change
Self.CurrentNode := TUKTSXMLTreeNode(Self.TreeContainer.Items.Root());
uktxmlfileansisymbols.Clear((* var *) ASymbol);
while (Scanner.Next()) do
begin
Scanner.ReadCurrentSymbol((* var *) ASymbol);
ProcessSymbol((* var *) ASymbol);
end;
ASymbol.Token := uktxmlfiletokens.xmlfiletkEoF;
ASymbol.Text := #26;
ProcessSymbol((* var *) ASymbol);
Scanner.Finish();
end;
// clear source path, avoiding overwrite
FullPath := NewFileName(ExtNew);
FileStream.Path := Self.FullPath;
end;
procedure TCustomUKTANSIXMLDocument.InternalSaveFile();
var AText: string; TextFile: System.Text;
begin
AText := '';
GenerateDocument(AText);
System.Assign(TextFile, Self.FullPath);
System.Rewrite(TextFile);
Write(TextFile, AText);
System.Close(TextFile);
// --> assign internal fields
inherited InternalSaveFile();
end;
procedure TCustomUKTANSIXMLDocument.InternalOpenFile();
var ASymbol: TXMLFileANSISymbol;
begin
// --> assign internal fields
RootNode := nil;
inherited InternalOpenFile();
EncodingNode := nil;
MainNode := nil;
EoFNode := nil;
// update full source path
FileStream.Path := Self.FullPath;
// indicate requested initial state of stream
FileStream.State := uktstatestreams.ssReset;
// --> scan or parse file
if (Scanner.Start()) then
begin
// initial assignation, will change
Self.CurrentNode := TUKTSXMLTreeNode(Self.TreeContainer.Items.Root());
uktxmlfileansisymbols.Clear((* var *) ASymbol);
while (Scanner.Next()) do
begin
Scanner.ReadCurrentSymbol((* var *) ASymbol);
ProcessSymbol((* var *) ASymbol);
end;
ASymbol.Token := uktxmlfiletokens.xmlfiletkEoF;
ASymbol.Text := #26;
ProcessSymbol((* var *) ASymbol);
Scanner.Finish();
end;
end;
constructor TCustomUKTANSIXMLDocument.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// provides a filesystem access stream
FileStream := TUKTFileStream.Create(nil);
// provides a text line based stream
TextStream := TCustomUKTAnsiTextStream.Create(nil);
// assign source & destination to filesystem
TextStream.Reference := FileStream;
Scanner := TCustomXMLFileANSIScanner.Create(nil);
// assign options
Scanner.Options().Clear();
Scanner.Options().EoF := uktscanneroptions.scnopReturnTag;
Scanner.Options().EoPg := uktscanneroptions.scnopReturnTag;
Scanner.Options().EoLn := uktscanneroptions.scnopReturnTag;
Scanner.Options().Tabs := uktscanneroptions.scnopReturnTag;
Scanner.Options().Spaces := uktscanneroptions.scnopReturnTag;
Scanner.Options().Specials := uktscanneroptions.scnopReturnTag;
// assign source of text
Scanner.Stream := TextStream;
// create tree-container & tree-collection.
// without any items, no even, root-item
TreeContainer := TCustomUKTSXMLTreeContainer.Create(nil);
end;
destructor TCustomUKTANSIXMLDocument.Destroy();
begin
TreeContainer.Free();
// assign source of text
Scanner.Stream := nil;
// assign options
Scanner.Options().Clear();
Scanner.Free();
// assign source & destination to filesystem
TextStream.Reference := nil;
// provides a text line based stream
TextStream.Free();
// provides a filesystem access stream
FileStream.Free();
inherited Destroy();
end;
procedure TCustomUKTANSIXMLDocument.GenerateSXML
(var ANode: TUKTTreeNode;
const AParam: pointer; const ADirection: TUKTTreeDirection);
var S: PString;
ASXMLNode: TUKTSXMLTreeNode;
ATag: TXMLFileTreeNodeToken;
begin
S := PString(AParam);
// ...
ASXMLNode := TUKTSXMLTreeNode(ANode);
ATag := ASXMLNode.TreeToken;
if (ADirection = ukttreenodes.tdStart) then
begin
case (ATag) of
uktxmlfiletreenodetokens.xmlfiletrntkEoPg:
begin
S^ := S^ + #13#10 + uktstrings.StringOfChar('-', 40) + #13#10;
end;
uktxmlfiletreenodetokens.xmlfiletrntkEoLn:
begin
S^ := S^ + #13#10;
end;
uktxmlfiletreenodetokens.xmlfiletrntkSpace:
begin
S^ := S^ + resSharedTagSpace;
end;
uktxmlfiletreenodetokens.xmlfiletrntkEncoding:
begin
S^ := S^ + '<?' + ASXMLNode.TextValue + '?>';
//if (ASXMLNode.NewLineAfter) then
if (ASXMLNode.Selected) then
begin
S^ := S^ + #13#10;
end;
end;
uktxmlfiletreenodetokens.xmlfiletrntkBlock:
begin
S^ := S^ + '<' + ASXMLNode.TextValue + '>';
//if (ASXMLNode.NewLineAfter) then
if (ASXMLNode.Selected) then
begin
S^ := S^ + #13#10;
end;
end;
uktxmlfiletreenodetokens.xmlfiletrntkSingle:
begin
S^ := S^ + '<' + ASXMLNode.TextValue + '>';
//if (ASXMLNode.NewLineAfter) then
if (ASXMLNode.Selected) then
begin
S^ := S^ + #13#10;
end;
end;
uktxmlfiletreenodetokens.xmlfiletrntkText:
begin
S^ := S^ + ASXMLNode.TextValue;
end;
uktxmlfiletreenodetokens.xmlfiletrntkComment:
begin
S^ := S^ + ASXMLNode.TextValue;
end;
uktxmlfiletreenodetokens.xmlfiletrntkEoF:
begin
Self.DoNothing();
end;
end;
end else if
(ATag = uktxmlfiletreenodetokens.xmlfiletrntkBlock) then
begin
S^ := S^ + '</' + ASXMLNode.TextValue + '>';
(*
//if (ASXMLNode.NewLineAfter) then
if (ASXMLNode.Selected) then
begin
S^ := S^ + #13#10;
end;
*)
end;
end;
function TCustomUKTANSIXMLDocument.CreateRoot(): TUKTSXMLTreeNode;
begin
Result := nil;
Self.RootNode :=
TUKTSXMLTreeNode(Self.TreeContainer.Items.InsertRoot());
Self.CurrentNode := Self.RootNode;
Result := Self.RootNode;
end;
procedure TCustomUKTANSIXMLDocument.GenerateDocument(var AText: string);
begin
AText := '';
{$ifdef Delphi}
TreeContainer.Items.Root().ForBoth(GenerateSXML, @AText);
{$endif}
{$ifdef FPC}
TreeContainer.Items.Root().ForBoth(@GenerateSXML, @AText);
{$endif}
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BindMethodsFormU;
interface
uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ActnList, Data.Bind.Components,
System.Generics.Collections, System.Bindings.Methods, DesignIntf,
System.Actions;
type
TBindMethodsForm = class(TForm)
HelpBtn: TButton;
OKBtn: TButton;
CancelBtn: TButton;
ActionList1: TActionList;
AcceptAction: TAction;
ListView1: TListView;
CheckBoxSelectAll: TCheckBox;
ActionSelectAll: TAction;
procedure HelpBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DataBindingListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure DataBindingListDblClick(Sender: TObject);
procedure AcceptActionUpdate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ListView1Click(Sender: TObject);
procedure ListView1Change(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure actnSelectAllUpdate(Sender: TObject);
procedure actSelectAllExecute(Sender: TObject);
procedure ListView1InfoTip(Sender: TObject; Item: TListItem;
var InfoTip: string);
private
FSortColumn: Integer;
FDictionary: TDictionary<Pointer, TMethodDescription>;
FBindArtifacts: TBindArtifacts;
FArtifactDictionary: TDictionary<string,
TBindArtifactItem>;
FModified: Boolean;
FUpdateAllChecked: Boolean;
FAllChecked: Boolean;
FAllUnchecked: Boolean;
FChecking: Boolean;
FDesignerIntf: IDesigner;
function AddArtifact(AArtifact: TMethodDescription): TListItem;
procedure AddArtifacts(AUpdateColumns: Boolean);
function GetRegKey: string;
procedure SetBindArtifacts(const Value: TBindArtifacts);
procedure Modified;
procedure CheckAllItems(ACheck: Boolean);
procedure UpdateAllChecked;
function GetAllChecked: Boolean;
function GetAllUnChecked: Boolean;
procedure SelectAllItems;
procedure LoadSizes;
procedure SaveSizes;
procedure SetDesigner(const Value: IDesigner);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ApplyChanges;
property BindArtifacts: TBindArtifacts read FBindArtifacts write SetBindArtifacts;
property DesignerIntf: IDesigner read FDesignerIntf write SetDesigner;
end;
implementation
{$R *.dfm}
uses DsnConst, System.Win.Registry;
procedure TBindMethodsForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TBindMethodsForm.ListView1Change(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
//
if Change = ctState then
begin
FUpdateAllChecked := True;
Modified;
end;
end;
procedure TBindMethodsForm.ListView1Click(Sender: TObject);
begin
//
end;
procedure TBindMethodsForm.ListView1InfoTip(Sender: TObject;
Item: TListItem; var InfoTip: string);
var
LMethod: TMethodDescription;
begin
if Item <> nil then
begin
if not FDictionary.ContainsKey(Item.Data) then
begin
Assert(False);
end;
LMethod := FDictionary[Item.Data];
if LMethod.Description <> '' then
InfoTip := LMethod.Description
else
InfoTip := LMethod.Name;
end;
end;
procedure TBindMethodsForm.Modified;
begin
FModified := True;
end;
function TBindMethodsForm.AddArtifact(AArtifact: TMethodDescription): TListItem;
function FrameworkName(AFrameworkClass: TPersistentClass): string;
begin
if (AFrameworkClass = nil) or TComponent.InheritsFrom(AFrameworkClass) then
Result := ''
else
begin
if TControl.InheritsFrom(AFrameworkClass) then
Result := 'VCL' // Do not localize
else
Result := 'FMX' // Do not localize
end;
end;
var
LItem: TListItem;
LCaption: string;
I: Integer;
LBindArtifactItem: TBindArtifactItem;
LHaveItem: Boolean;
begin
LItem := ListView1.Items.Add;
with LItem do
begin
LHaveItem := FArtifactDictionary.TryGetValue(AArtifact.ID, LBindArtifactItem);
Caption := AArtifact.Name;
for I := 1 to ListView1.Columns.Count - 1 do
begin
case I of
1: LCaption := AArtifact.UnitName;
2: LCaption := FrameworkName(AArtifact.FrameWorkClass);
else
LCaption := '';
end;
LItem.SubItems.Add(LCaption);
end;
if LHaveItem then
LItem.Checked := LBindArtifactItem.State = TBindArtifactState.eaInclude
else
LItem.Checked := AArtifact.DefaultEnabled;
end;
Result := LItem;
end;
procedure TBindMethodsForm.AddArtifacts(AUpdateColumns: Boolean);
var
LDescription: TMethodDescription;
LCounter: Integer;
LItem: TListItem;
LKeys: TList<string>;
begin
LCounter := 0;
LKeys := TList<string>.Create;
try
ListView1.Items.BeginUpdate;
try
ListView1.Items.Clear;
FDictionary.Clear;
for LDescription in TBindingMethodsFactory.GetRegisteredMethods do
begin
// Converters with the same ID are considered part of the same set (e.g.; FloatToStr ID is for extended and single converters)
if not LKeys.Contains(LDescription.ID) then
begin
LItem := AddArtifact(LDescription);
LItem.Data := Pointer(LCounter);
FDictionary.Add(LItem.Data, LDescription);
Inc(LCounter);
LKeys.Add(LDescription.ID);
end;
end;
finally
ListView1.Items.EndUpdate;
FUpdateAllChecked := True;
end;
finally
LKeys.Free;
end;
end;
procedure TBindMethodsForm.ApplyChanges;
var
LListItem: TListItem;
LDescription: TMethodDescription;
LBindArtifact: TBindArtifactItem;
LHaveItems: Boolean;
LChecked: Boolean;
begin
for LListItem in ListView1.Items do
begin
if not FDictionary.ContainsKey(LListItem.Data) then
begin
Assert(False);
continue;
end;
LDescription := FDictionary[LListItem.Data];
LChecked := LListItem.Checked;
LHaveItems := FArtifactDictionary.TryGetValue(LDescription.ID, LBindArtifact);
if (not LHaveItems) then
begin
if LChecked <> LDescription.DefaultEnabled then
begin
LBindArtifact := TBindArtifactItem(FBindArtifacts.Add);
LBindArtifact.ID := LDescription.ID;
if LChecked then
LBindArtifact.State := TBindArtifactState.eaInclude
else
LBindArtifact.State := TBindArtifactState.eaExclude
end;
end
else
begin
if LChecked then
begin
if LDescription.DefaultEnabled then
begin
//if this is defaultEnabled, remove the item instead of marking the state
FBindArtifacts.Delete(LBindArtifact.Index);
FArtifactDictionary.Remove(LDescription.ID);
end
else
LBindArtifact.State := TBindArtifactState.eaInclude
end
else
LBindArtifact.State := TBindArtifactState.eaExclude
end;
end;
end;
constructor TBindMethodsForm.Create(AOwner: TComponent);
begin
inherited;
FDictionary := TDictionary<Pointer, TMethodDescription>.Create;
FArtifactDictionary := TDictionary<string,
TBindArtifactItem>.Create;
end;
const
sWidth = 'Width';
sHeight = 'Height';
procedure TBindMethodsForm.LoadSizes;
var
LIndex: Integer;
LSubKey: string;
begin
LSubKey := TBindMethodsForm.ClassName;
with TRegIniFile.Create(GetRegKey) do
try
Width := ReadInteger(LSubKey, sWidth, Width);
Height := ReadInteger(LSubKey, sHeight, Height);
for LIndex := 0 to ListView1.Columns.Count - 1 do
with ListView1.Columns.Items[LIndex] do
Width := ReadInteger(LSubKey, sWidth+IntToStr(LIndex), Width);
finally
Free;
end;
end;
procedure TBindMethodsForm.SaveSizes;
var
LIndex: Integer;
LSubKey: string;
begin
LSubKey := TBindMethodsForm.ClassName;
with TRegIniFile.Create(GetRegKey) do
try
EraseSection(LSubKey);
WriteInteger(LSubKey, sWidth, Width);
WriteInteger(LSubKey, sHeight, Height);
for LIndex := 0 to ListView1.Columns.Count - 1 do
with ListView1.Columns.Items[LIndex] do
WriteInteger(LSubKey, sWidth+IntToStr(LIndex), Width);
finally
Free;
end;
end;
function TBindMethodsForm.GetRegKey: string;
begin
Result := DesignerIntf.GetBaseRegKey + '\' + sIniEditorsName + '\Expr Methods Editor';
end;
procedure TBindMethodsForm.SetBindArtifacts(
const Value: TBindArtifacts);
var
LItem: TCollectionItem;
LBindArtifactItem: TBindArtifactItem;
begin
FBindArtifacts := Value;
FArtifactDictionary.Clear;
if FBindArtifacts <> nil then
for LItem in FBindArtifacts do
begin
LBindArtifactItem := TBindArtifactItem(LItem);
FArtifactDictionary.Add(LBindArtifactItem.ID, LBindArtifactItem);
end;
ListView1.Clear;
AddArtifacts(True);
FUpdateAllChecked := True;
end;
procedure TBindMethodsForm.SetDesigner(const Value: IDesigner);
begin
FDesignerIntf := Value;
if FDesignerIntf <> nil then
LoadSizes;
end;
procedure TBindMethodsForm.FormShow(Sender: TObject);
begin
ListView1.SetFocus;
end;
procedure TBindMethodsForm.DataBindingListCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if Abs(FSortColumn) = 1 then
Compare := FSortColumn * AnsiCompareText(Item1.Caption, Item2.Caption) else
Compare := FSortColumn * AnsiCompareText(Item1.SubItems[0], Item2.SubItems[0]);
end;
procedure TBindMethodsForm.DataBindingListDblClick(Sender: TObject);
begin
// if OKBtn.Enabled then OKBtn.Click;
end;
destructor TBindMethodsForm.Destroy;
begin
FDictionary.Free;
FArtifactDictionary.Free;
inherited;
end;
procedure TBindMethodsForm.AcceptActionUpdate(Sender: TObject);
begin
AcceptAction.Enabled := FModified;
end;
procedure TBindMethodsForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DesignerIntf <> nil then
SaveSizes;
end;
procedure TBindMethodsForm.UpdateAllChecked;
var
I: Integer;
begin
if FUpdateAllChecked then
begin
FUpdateAllChecked := False;
FAllChecked := True;
FAllUnchecked := True;
for I := 0 to ListView1.Items.Count - 1 do
begin
if not ListView1.Items[I].Checked then
FAllChecked := False
else
FAllUnchecked := False
end;
if FAllChecked and FAllUnchecked then
FAllChecked := False;
end;
end;
procedure TBindMethodsForm.CheckAllItems(ACheck: Boolean);
var
I: Integer;
begin
for I := 0 to ListView1.Items.Count - 1 do
begin
ListView1.Items[I].Checked := ACheck;
end;
end;
function TBindMethodsForm.GetAllChecked: Boolean;
begin
UpdateAllChecked;
Result := FAllChecked;
end;
function TBindMethodsForm.GetAllUnChecked: Boolean;
begin
UpdateAllChecked;
Result := FAllUnChecked;
end;
procedure TBindMethodsForm.actnSelectAllUpdate(Sender: TObject);
begin
if FChecking then
Exit;
FChecking := True;
try
if GetAllChecked then
CheckBoxSelectAll.State := TCheckBoxState.cbChecked
else if GetAllUnchecked then
CheckBoxSelectAll.State := TCheckBoxState.cbUnchecked
else
CheckBoxSelectAll.State := TCheckBoxState.cbGrayed;
finally
FChecking := False;
end;
end;
procedure TBindMethodsForm.actSelectAllExecute(Sender: TObject);
begin
SelectAllItems;
end;
procedure TBindMethodsForm.SelectAllItems;
begin
if FChecking then
Exit;
if GetAllChecked then
//CheckAll(TCheckState.csUnCheckedNormal)
CheckAllItems(False)
else if GetAllUnchecked then
//CheckAll(TCheckState.csCheckedNormal)
CheckAllItems(True)
else
//CheckAll(TCheckState.csUnCheckedNormal);
CheckAllItems(False);
end;
end.
|
unit CertiorariDuplicatesDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls;
type
TCertiorariDuplicatesDialog = class(TForm)
YesButton: TBitBtn;
NoButton: TBitBtn;
CertiorariTable: TTable;
DescriptionLabel: TLabel;
DuplicateCertiorariList: TListBox;
OKButton: TBitBtn;
PromptLabel: TLabel;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
CertiorariYear : String;
CertiorariNumber : LongInt;
AskForConfirmation : Boolean;
end;
var
CertiorariDuplicatesDialog: TCertiorariDuplicatesDialog;
implementation
{$R *.DFM}
uses PASUtils, WinUtils;
{===============================================================}
Procedure TCertiorariDuplicatesDialog.FormShow(Sender: TObject);
var
FirstTimeThrough, Done : Boolean;
begin
Caption := 'Parcels with certiorari #' + IntToStr(CertiorariNumber) + '.';
DescriptionLabel.Caption := 'The following parcels all have certiorari #' +
IntToStr(CertiorariNumber) + '.';
try
CertiorariTable.Open;
except
MessageDlg('Error opening Certiorari table.', mtError, [mbOK], 0);
end;
If AskForConfirmation
then
begin
PromptLabel.Visible := True;
YesButton.Visible := True;
NoButton.Visible := True;
end
else
begin
OKButton.Visible := True;
OKButton.Default := True;
end;
SetRangeOld(CertiorariTable, ['TaxRollYr', 'CertiorariNumber'],
[CertiorariYear, IntToStr(CertiorariNumber)],
[CertiorariYear, IntToStr(CertiorariNumber)]);
Done := False;
FirstTimeThrough := True;
CertiorariTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else CertiorariTable.Next;
If CertiorariTable.EOF
then Done := True;
If not Done
then DuplicateCertiorariList.Items.Add(ConvertSwisSBLToDashDot(CertiorariTable.FieldByName('SwisSBLKey').Text));
until Done;
end; {FormShow}
{==============================================================}
Procedure TCertiorariDuplicatesDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CertiorariTable.Close;
Action := caFree;
end;
end.
|
unit AGraficoComprativoAno;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, PainelGradiente, Componentes1, Localizacao, ExtCtrls, Spin,Series,
TeeProcs,TeEngine,Graficos, FMTBcd, DB, SqlExpr, UnNotaFiscal;
type
TTipoGraficoComparativo = (tgComparativoAnoCliente);
TFGraficoComparativoAno = class(TFormularioPermissao)
PCliente: TPanelColor;
SpeedButton1: TSpeedButton;
LNomeCliente: TLabel;
Label7: TLabel;
ECliente: TRBEditLocaliza;
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
BMostrarConta: TSpeedButton;
BGerar: TBitBtn;
BFechar: TBitBtn;
PanelColor1: TPanelColor;
Label1: TLabel;
EAno1: TSpinEditColor;
Label2: TLabel;
EAno2: TSpinEditColor;
Grafico: TRBGraDinamico;
Tabela: TSQLQuery;
PVendedor: TPanelColor;
SpeedButton2: TSpeedButton;
LVendedor: TLabel;
Label4: TLabel;
EVendedor: TRBEditLocaliza;
OpenDialog1: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BGerarClick(Sender: TObject);
private
{ Private declarations }
VprTipoGrafico : TTipoGraficoComparativo;
procedure ConfiguraTela;
procedure CarGraficoComparativoAnoCliente(VpaCodCliente : Integer;VpaNomCliente : String);
procedure GeraGraficoComparativoAnoCliente;
public
{ Public declarations }
procedure GraficoComparativoAnoCliente;
end;
var
FGraficoComparativoAno: TFGraficoComparativoAno;
implementation
uses APrincipal, FunData, Constantes, FunNumeros, Constmsg, FunSql, FunString;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFGraficoComparativoAno.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
EAno1.Value := Ano(date)-1;
EAno2.Value := Ano(date);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFGraficoComparativoAno.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFGraficoComparativoAno.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFGraficoComparativoAno.BGerarClick(Sender: TObject);
begin
case VprTipoGrafico of
tgComparativoAnoCliente: GeraGraficoComparativoAnoCliente;
end;
end;
procedure TFGraficoComparativoAno.ConfiguraTela;
begin
case VprTipoGrafico of
tgComparativoAnoCliente:
begin
Caption := 'Comparativo Cliente Ano Faturamento ';
PainelGradiente1.Caption := ' Comparativo Cliente Ano Faturamento ';
end;
end;
end;
procedure TFGraficoComparativoAno.CarGraficoComparativoAnoCliente(VpaCodCliente : Integer;VpaNomCliente : String);
var
VpfMes : Integer;
VpfData : String;
VpfSerie1, VpfSerie2 : TBarSeries;
Vpflaco: Integer;
VpfNomeMes : String;
VpfDatInicio, VpfDatFim : TDateTime;
begin
Grafico.InicializaGrafico;
VpfSerie1 := TBarSeries.Create(Self);
Grafico.AGrafico.AddSeries(VpfSerie1);
VpfSerie1.Marks.Style := smsValue;
VpfSerie1.ColorEachPoint := false;
VpfSerie1.BarBrush.Color := clYellow;
VpfSerie1.Title := IntToStr(EAno1.Value);
VpfSerie2 := TBarSeries.Create(Self);
Grafico.AGrafico.AddSeries(VpfSerie2);
VpfSerie2.Marks.Style := smsValue;
VpfSerie2.ColorEachPoint := false;
VpfSerie2.BarBrush.Color := clYellow;
VpfSerie2.Title := IntToStr(EAno2.Value);
for VpfMes := 1 to 12 do
begin
VpfNomeMes := TextoMes(MontaData(1,VpfMes,2000),false);
VpfDatInicio := MontaData(1,VpfMes,EAno1.Value);
VpfDatFim := UltimoDiaMes(VpfDatInicio);
Grafico.AGrafico.Series[0].Add(ArredondaDecimais(FunNotaFiscal.RValNotasClientePeriodo(VpfDatInicio,VpfDatFim,VpaCodCliente),2),VpfNomeMes);
VpfDatInicio := MontaData(1,VpfMes,EAno2.Value);
VpfDatFim := UltimoDiaMes(VpfDatInicio);
Grafico.AGrafico.Series[1].Add(ArredondaDecimais(FunNotaFiscal.RValNotasClientePeriodo(VpfDatInicio,VpfDatFim,VpaCodCliente),2),VpfNomeMes);
end;
Grafico.AInfo.TituloGrafico := VpaNomCliente;
Grafico.AInfo.TituloFormulario := 'Comparativo Ano Cliente';
Grafico.AInfo.TituloY := 'Valor Notas';
Grafico.AInfo.RodapeGrafico := varia.NomeFilial;
end;
{******************************************************************************}
procedure TFGraficoComparativoAno.GeraGraficoComparativoAnoCliente;
begin
if (ECliente.AInteiro = 0) and
(EVendedor.AInteiro = 0) then
begin
aviso('CLIENTE NÃO PREENCHIDO!!!'#13'É necessário preencher o código do cliente');
end;
if ECliente.AInteiro <> 0 then
begin
CarGraficoComparativoAnoCliente(ECliente.AInteiro,LNomeCliente.Caption);
Grafico.Executa;
end
else
begin
AdicionaSQLAbreTabela(Tabela,'Select I_COD_CLI, C_NOM_CLI from CADCLIENTES '+
' Where I_COD_VEN = '+EVendedor.TEXT );
while not tabela.eof do
begin
CarGraficoComparativoAnoCliente(Tabela.FieldByName('I_COD_CLI').AsInteger,Tabela.FieldByName('C_NOM_CLI').AsString);
Grafico.ExportaBMP(Varia.DiretorioSistema+'\'+CopiaAteChar(LVendedor.Caption,' ')+'\'+DeletaEspaco(DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('C_NOM_CLI').AsString,'.'),'/'),'\')+'.bmp'));
tabela.next;
end;
Tabela.Close;
end;
end;
{******************************************************************************}
procedure TFGraficoComparativoAno.GraficoComparativoAnoCliente;
begin
VprTipoGrafico := tgComparativoAnoCliente;
ConfiguraTela;
showModal;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFGraficoComparativoAno]);
end.
|
unit InventDTOU;
interface
type TInventDTO=class(TObject)
private
Fdesinvent: string;
Fdate_: string;
Fidinvent: Integer;
procedure Setdate_(const Value: string);
procedure Setdesinvent(const Value: string);
procedure Setidinvent(const Value: Integer);
published
property desinvent: string read Fdesinvent write Setdesinvent;
property idinvent: Integer read Fidinvent write Setidinvent;
property date_:string read Fdate_ write Setdate_;
end;
implementation
{ TInventDTO }
procedure TInventDTO.Setdate_(const Value: string);
begin
Fdate_ := Value;
end;
procedure TInventDTO.Setdesinvent(const Value: string);
begin
Fdesinvent := Value;
end;
procedure TInventDTO.Setidinvent(const Value: Integer);
begin
Fidinvent := Value;
end;
end.
|
unit fCSRemaining;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ORCtrls, ExtCtrls, VA508AccessibilityManager, StrUtils,
ORFn, uCore, rOrders;
type
TfrmCSRemaining = class(TForm)
lblCSRemaining: TVA508StaticText;
lstCSRemaining: TCaptionListBox;
cmdOK: TButton;
VA508AccessibilityManager1: TVA508AccessibilityManager;
VA508ComponentAccessibility1: TVA508ComponentAccessibility;
procedure cmdOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure CSRemaining(orders: TStrings; csorders: TStrings);
implementation
procedure CSRemaining(orders: TStrings; csorders: TStrings);
var
ShownCurrentUserLabel, ShownOtherUsersLabel: boolean;
Display: String;
i,j: Integer;
frmCSRemaining: TfrmCSRemaining;
UnsignedOrders,HaveOrders,OthersCSOrders: TStrings;
show: boolean;
begin
ShownCurrentUserLabel := False;
ShownOtherUsersLabel := False;
OthersCSOrders := TStringList.Create;
HaveOrders := TStringList.Create;
UnsignedOrders := TStringList.Create;
frmCSRemaining := TfrmCSRemaining.Create(Application);
try
LoadUnsignedOrders(UnsignedOrders,HaveOrders);
for i := 0 to Pred(UnsignedOrders.Count) do
begin
//if UnsignedOrders[i] is not in either orders or csorders then continue
show := false;
for j := 0 to orders.Count - 1 do
begin
if (not(orders.objects[j]=nil) and (Piece(unsignedOrders[i],u,1)=TChangeItem(orders.objects[j]).ID)) then show := true;
end;
for j := 0 to csorders.Count - 1 do
begin
if (not(csorders.objects[j]=nil) and (Piece(unsignedOrders[i],u,1)=TChangeItem(csorders.objects[j]).ID)) then show := true;
end;
if not(show) then continue;
Display := TextForOrder(Piece(UnsignedOrders[i],U,1));
if Piece(UnsignedOrders[i],U,6)='1' then
begin
if User.DUZ=StrToInt64Def(Piece(UnsignedOrders[i],U,2),0) then
begin
if ShownCurrentUserLabel=False then
begin
frmCSRemaining.lstCSRemaining.AddItem('My Unsigned Controlled Substance Orders',nil);
ShownCurrentUserLabel:=True;
end;
frmCSRemaining.lstCSRemaining.AddItem(' '+AnsiReplaceText(Display,CRLF,' '),TObject(UnsignedOrders[i]));
end
else
OthersCSOrders.Add(UnsignedOrders[i]);
end;
end;
for i := 0 to Pred(OthersCSOrders.Count) do
begin
Display := TextForOrder(Piece(OthersCSOrders[i],U,1));
if ShownOtherUsersLabel=False then
begin
frmCSRemaining.lstCSRemaining.AddItem(' ',nil);
frmCSRemaining.lstCSRemaining.AddItem('Other User''s Unsigned Controlled Substance Orders',nil);
ShownOtherUsersLabel := True;
end;
frmCSRemaining.lstCSRemaining.AddItem(' '+AnsiReplaceText(Display,CRLF,' '),TObject(OthersCSOrders[i]));
end;
if frmCSRemaining.lstCSRemaining.Count>0 then frmCSRemaining.ShowModal;
finally
FreeAndNil(OthersCSOrders);
FreeAndNil(HaveOrders);
FreeAndNil(UnsignedOrders);
FreeAndNil(frmCSRemaining);
end;
end;
{$R *.dfm}
procedure TfrmCSRemaining.cmdOKClick(Sender: TObject);
begin
self.Close;
end;
end.
|
unit IconAddU;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ToolWin, ComCtrls, ActnList, toolsapi;
procedure Register;
implementation
uses DisplayU;
{This Procedure fire off a small modal dialog that allows the user to load a
bitmap and view the names of the IDE's Actions.}
Procedure DisplayChoices(Var IconFileName, ActionName: string; IDE: INTAServices);
var
i: integer;
Alist: TCustomActionList;
begin
DisplayForm := TDisplayForm.Create(nil);
try
Alist := IDE.GetActionList;
for i := 0 to Alist.ActionCount -1 do
begin
DisplayForm.ComboBox1.items.add(TAction(Alist.Actions[i]).name);
end;
DisplayForm.Showmodal;
IconFileName := DisplayForm.OpenPictureDialog1.filename;
ActionName := DisplayForm.ComboBox1.text;
finally
DisplayForm.free;
end;
end;
{This function just adds a given bitmap to the IDE's imagelist. There are no
safety features to make sure the image will work. We it only checks to see if
it worked.
Return value is the new index of the image.
}
function AddIconToImageList(IconFileName: string; IDE: INTAServices): integer;
var
Image: TBitmap;
begin
Image := TBitmap.Create;
try
Image.LoadFromFile(IconFileName);
Result := IDE.AddMasked(Image, Image.TransparentColor, 'New image');
finally
Image.free;
end;
if Result = -1 then
Exception.Create('Error loading image for ToolButton in a custom package');
end;
{This procedure runs through the IDE's action list looking to match up two
action names. Once found, it assigns the action a new image index.}
Procedure SetImageToAction(ActionNAme: String; Index: integer; IDE: INTAServices);
var
Alist: TCustomActionList;
i: integer;
begin
Alist := IDE.GetActionList;
for i := 0 to Alist.ActionCount -1 do
begin
if ActionName = TAction(Alist.Actions[i]).name then //Can use caption too
begin
if (Alist.actions[i]) is TAction then
(Alist.actions[i] as Taction).Imageindex := Index;
break
end;
end;
end;
{Opentools API packages use the register procedure to execute the code when
the IDE is each time loaded. }
procedure Register;
var
IDE: INTAServices;
IconFileName: string;
ActionName: string;
Index: integer;
begin
//All function use IDE interface, so grab it just once
IDE := (BorlandIDEServices as INTAServices);
{This function should just be used to decide the icon names and action names
once. Otherwise you'll have a dialog pop everything you load Delphi. It is
left as an excerise to the user to store and load these names as needed}
DisplayChoices(IconFileName, ActionName, IDE);
if ( (ActionName <> '') and (IconFileName <> '') ) then //make sure of some input
begin
index := AddIconToImageList(IconFileName, IDE);
SetImageToAction(ActionName, Index, IDE);
end;
end;
end.
|
unit UPrjSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, 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,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TPrjSearchForm = class(TForm)
Panel1: TPanel;
DBNavigator1: TDBNavigator;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
DBEdit4: TDBEdit;
DBEdit5: TDBEdit;
DBEdit2: TDBEdit;
DBEdit1: TDBEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button6: TButton;
DBLookupComboBox1: TDBLookupComboBox;
DBRadioGroup1: TDBRadioGroup;
Label2: TLabel;
Label9: TLabel;
Label10: TLabel;
Button7: TButton;
PrjQuery: TFDQuery;
PrjQueryP_NAME: TWideStringField;
PrjQueryP_STARTDATE: TSQLTimeStampField;
PrjQueryP_ENDDATE: TSQLTimeStampField;
PrjQueryP_MEMBERCOUNT: TIntegerField;
PrjQueryP_STATUS: TIntegerField;
PrjQueryP_MANAGER_ID: TIntegerField;
PrjQueryDataSource: TDataSource;
PrjQueryP_ID: TIntegerField;
Label3: TLabel;
Edit1: TEdit;
DBGrid1: TDBGrid;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PrjSearchForm: TPrjSearchForm;
implementation
{$R *.dfm}
uses UDm;
procedure TPrjSearchForm.Button1Click(Sender: TObject);
begin
dm.PrjTable.Insert;
end;
procedure TPrjSearchForm.Button2Click(Sender: TObject);
begin
if MessageDlg('삭제하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mryes then
try
dm.PrjTable.Delete;
except
on e:exception do
showmessage(e.Message);
end;
end;
procedure TPrjSearchForm.Button3Click(Sender: TObject);
begin
dm.PrjTable.Cancel;
end;
procedure TPrjSearchForm.Button4Click(Sender: TObject);
begin
if MessageDlg('저장하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mryes then
try
dm.PrjTable.Post;
except
showmessage('먼저입력후 저장해주세요');
end;
end;
procedure TPrjSearchForm.Button5Click(Sender: TObject);
begin
// dm.PrjTable.Refresh;
end;
procedure TPrjSearchForm.Button6Click(Sender: TObject);
begin
dm.PrjTable.Edit;
end;
procedure TPrjSearchForm.Button7Click(Sender: TObject);
begin
DBGrid1.DataSource := PrjQueryDataSource;
PrjQuery.Refresh;
end;
procedure TPrjSearchForm.Edit1Change(Sender: TObject);
begin
dm.PrjTable.IndexFieldNames := 'p_name';
dm.PrjTable.FindNearest([Edit1.text]);
end;
procedure TPrjSearchForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := CaFree;
end;
end.
|
unit uPrecacheThread;
interface
uses
Classes, Windows, SysUtils, Dialogs;
const
BufferSize = 10485760;
ExtFilesNotToCache: array[1..3] of string = ('.rtf', '.iso', '.chm');
type
TPrecacheThread = class(TThread)
private
// ts: TTime;
Buffer: array of AnsiChar;
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create;
procedure Terminate;
procedure CacheFile(const FileName: string);
end;
implementation
uses Mainform;
constructor TPrecacheThread.Create;
begin
inherited Create(False);
SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
Priority := tpLower;
end; { TPrecacheThread.Create }
procedure TPrecacheThread.CacheFile(const FileName: string);
var
hFile: THandle;
BytesRead: Cardinal;
begin
try
hFile := CreateFile(PChar(Filename), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
if hFile = INVALID_HANDLE_VALUE then
Exit;
repeat
if Terminated then
Break;
if not ReadFile(hFile, Buffer, BufferSize, BytesRead, nil) then
Break;
until BytesRead <> BufferSize;
CloseHandle(hFile);
except
end;
end;
procedure TPrecacheThread.Execute;
var
VBPath: string;
hFind: THandle;
wfa: ^WIN32_FIND_DATAW;
i: Integer;
begin
// ts := Now;
try
if not FileExists(ExeVBPath) then
Exit;
if Terminated then
Exit;
VBPath := ExtractFilePath(ExeVBPath);
New(wfa);
hFind := FindFirstFile(PChar(VBPath + '*.*'), wfa^);
if hFind = INVALID_HANDLE_VALUE then
Exit;
SetLength(Buffer, BufferSize + 1);
repeat
if wfa.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
begin
i := Low(ExtFilesNotToCache);
while i <= High(ExtFilesNotToCache) do
begin
if ExtractFileExt(wfa.cFileName) = ExtFilesNotToCache[i] then
Break;
Inc(i);
end;
if i <= High(ExtFilesNotToCache) then
Continue;
Cachefile(VBPath + wfa.cFileName);
end;
if Terminated then
Exit;
until not Windows.FindNextFile(hFind, wfa^);
Windows.FindClose(hFind);
VBPath := VBPath + 'ExtensionPacks\Oracle_VM_VirtualBox_Extension_Pack\';
if not DirectoryExists(VBPath) then
Exit;
if FileExists(VBPath + 'ExtPack.xml') then
CacheFile(VBPath + 'ExtPack.xml')
else
Exit;
if TOSversion.Architecture = arIntelX86 then
VBPath := VBPath + 'win.x86\'
else if TOSversion.Architecture = arIntelX64 then
VBPath := VBPath + 'win.amd64\';
New(wfa);
hFind := FindFirstFile(PChar(VBPath + '*.*'), wfa^);
if hFind = INVALID_HANDLE_VALUE then
Exit;
repeat
if wfa.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
Cachefile(VBPath + wfa.cFileName);
if Terminated then
Exit;
until not Windows.FindNextFile(hFind, wfa^);
Windows.FindClose(hFind);
finally
FPCJobDone := True;
SetLength(Buffer, 0);
if not Terminated then
Terminate;
end;
end; { TPrecacheThread.Execute }
procedure TPrecacheThread.Terminate;
var
dt: Cardinal;
begin
TThread(Self).Terminate;
dt := GetTickCount;
while (not FPCJobDone) and ((GetTickCount - dt) <= 5000) do
Sleep(1);
if FPSJobDone and FPCJobDone and FRegJobDone and FUnregJobDone then
SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Informix metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.InfxMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysInfxMetadata = class (TFDPhysConnectionMetadata)
private
FTxSupported: Boolean;
protected
function GetKind: TFDRDBMSKind; override;
function GetIdentityInsertSupported: Boolean; override;
function GetCatalogSeparator: Char; override;
function GetGeneratorSupported: Boolean; override;
function GetTxSupported: Boolean; override;
function GetTxSavepoints: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetAsyncNativeTimeout: Boolean; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetColumnOriginProvided: Boolean; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String;
AIsUnicode, ATxSupported: Boolean);
end;
TFDPhysInfxCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetIdentity(ASessionScope: Boolean): String; override;
function GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String; override;
function GetSingleRowTable: String; override;
function GetRowId(var AAlias: String): String; override;
function GetPessimisticLock: String; override;
function GetSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetCommitSavepoint(const AName: String): String; override;
function GetCall(const AName: String): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysInfxMetadata.Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String;
AIsUnicode, ATxSupported: Boolean);
begin
inherited Create(AConnectionObj, AServerVersion, AClientVersion, AIsUnicode);
if ACSVKeywords <> '' then
FKeywords.CommaText := ACSVKeywords;
FTxSupported := ATxSupported;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Informix;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetParamNameMaxLength: Integer;
begin
Result := 128;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetCatalogSeparator: Char;
begin
Result := ':';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetTxSupported: Boolean;
begin
Result := FTxSupported;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetTxSavepoints: Boolean;
begin
Result := FTxSupported;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_Infx_DBMS_ALERT;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetGeneratorSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvNone;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soInlineView];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetAsyncNativeTimeout: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
Result := aeCollectAllErrors;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.GetColumnOriginProvided: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
if CompareText(AStr, S_FD_True) = 0 then
Result := '''t'''
else
Result := '''f''';
Result := 'CAST(' + Result + ' AS BOOLEAN)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'DATE(' + InternalEscapeDateTime(AStr) + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
if Pos(':', AStr) = 0 then
Result := 'TO_DATE(' + AnsiQuotedStr(AStr + ' 00:00:00', '''')
else
Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''');
Result := Result + ', ''%Y-%m-%d %H:%M:%S'')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''%T'')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3, A4: String;
rSeq: TFDPhysEscapeData;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(ASeq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
case ASeq.FFunc of
// the same
// char
efASCII,
efCHAR_LENGTH,
efCONCAT,
efLEFT,
efLENGTH,
efLTRIM,
efOCTET_LENGTH,
efREPLACE,
efRIGHT,
efRTRIM,
efSPACE,
// numeric
efACOS,
efASIN,
efATAN,
efATAN2,
efABS,
efCOS,
efDEGREES,
efEXP,
efFLOOR,
efLOG10,
efMOD,
efRADIANS,
efROUND,
efSIN,
efSQRT,
efTAN,
// date and time
efMONTH,
efYEAR: Result := sName + AddArgs;
// character
efCHAR: Result := 'CHR' + AddArgs;
efBIT_LENGTH: Result := '(OCTET_LENGTH(' + A1 + ') * 8)';
efINSERT: Result := '(SUBSTR(' + A1 + ', 1, (' + A2 + ') - 1) || ' + A4 +
' || SUBSTR(' + A1 + ', (' + A2 + ' + ' + A3 + ')))';
efLCASE: Result := 'LOWER' + AddArgs;
efLOCATE: Result := 'INSTR(' + A2 + ', ' + A1 + ', ' + A3 + ')';
efPOSITION: Result := 'INSTR(' + A2 + ', ' + A1 + ')';
efREPEAT: Result := 'RPAD(' + A1 + ', (' + A2 + ') * LENGTH(' + A1 + '), ' + A1 + ')';
efSUBSTRING: Result := 'SUBSTR' + AddArgs;
efUCASE: Result := 'UPPER' + AddArgs;
// numeric
efCEILING: Result := 'CEIL' + AddArgs;
efCOT: Result := '(1 / TAN(' + A1 + '))';
efLOG: Result := 'LOGN' + AddArgs;
efPOWER: Result := 'POW' + AddArgs;
efSIGN: Result := 'CASE WHEN ' + A1 + ' > 0 THEN 1 WHEN ' + A1 + ' < 0 THEN -1 ELSE 0 END';
efTRUNCATE: Result := 'TRUNC' + AddArgs;
efPI: Result := S_FD_Pi;
efRANDOM: Result := 'dbms_random_random()';
// date and time
efCURDATE: Result := 'CURRENT YEAR TO DAY';
efCURTIME: Result := 'CURRENT HOUR TO FRACTION';
efDAYNAME: Result := 'TO_CHAR(' + A1 + ', ''%A'')';
efDAYOFMONTH: Result := 'DAY' + AddArgs;
efDAYOFWEEK: Result := '(WEEKDAY(' + A1 + ') + 1)';
efDAYOFYEAR: Result := '(DATE(' + A1 + ') - MDY(1, 1, YEAR(' + A1 + ')) + 1)';
efHOUR: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''%H''))';
efMINUTE: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''%M''))';
efMONTHNAME: Result := 'TO_CHAR(' + A1 + ', ''%B'')';
efQUARTER: Result := 'TRUNC(MONTH(' + A1 + ') / 3 + 1)';
efSECOND: Result := 'TO_NUMBER(TO_CHAR(' + A1 + ', ''%S''))';
efWEEK: Result := 'TRUNC(1 + (' + A1 + ' - MDY(1, 1, YEAR(' + A1 + ')) + WEEKDAY(MDY(1, 1, YEAR(' + A1 + ')))) / 7)';
efNOW: Result := 'CURRENT';
efEXTRACT:
begin
rSeq.FKind := eskFunction;
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'DAY' then
A1 := 'DAYOFMONTH';
rSeq.FName := A1;
SetLength(rSeq.FArgs, 1);
rSeq.FArgs[0] := ASeq.FArgs[1];
EscapeFuncToID(rSeq);
Result := InternalEscapeFunction(rSeq);
end;
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'YEAR' then
Result := 'ADD_MONTHS(' + A3 + ', 12 * (' + A2 + '))'
else if A1 = 'MONTH' then
Result := 'ADD_MONTHS(' + A3 + ', ' + A2 + ')'
else if A1 = 'WEEK' then
Result := '(' + A3 + ' + INTERVAL (' + IntToStr(StrToInt(A2) * 7) + ') DAY TO DAY)'
else if A1 = 'DAY' then
Result := '(' + A3 + ' + INTERVAL (' + A2 + ') DAY TO DAY)'
else if A1 = 'HOUR' then
Result := '(' + A3 + ' + INTERVAL (' + A2 + ') HOUR TO HOUR)'
else if A1 = 'MINUTE' then
Result := '(' + A3 + ' + INTERVAL (' + A2 + ') MINUTE TO MINUTE)'
else if A1 = 'SECOND' then
Result := '(' + A3 + ' + INTERVAL (' + A2 + ') SECOND TO SECOND)'
else if A1 = 'FRAC_SECOND' then
Result := '(' + A3 + ' + INTERVAL (' + A2 + ') FRACTION TO FRACTION)'
else
UnsupportedEscape(ASeq);
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'YEAR' then
Result := 'TRUNC(MONTHS_BETWEEN(' + A3 + ', ' + A2 + ') / 12)'
else if A1 = 'MONTH' then
Result := 'MONTHS_BETWEEN(' + A3 + ', ' + A2 + ')'
else if A1 = 'WEEK' then
Result := 'TRUNC((DATE(' + A3 + ') - DATE(' + A2 + ')) / 7)'
else if A1 = 'DAY' then
Result := '(DATE(' + A3 + ') - DATE(' + A2 + '))'
else if A1 = 'HOUR' then
Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * 24.0)'
else if A1 = 'MINUTE' then
Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0))'
else if A1 = 'SECOND' then
Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0))'
else if A1 = 'FRAC_SECOND' then
Result := 'TRUNC(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0 * 1000000.0))'
else
UnsupportedEscape(ASeq);
end;
// system
efCATALOG: Result := 'DBINFO(''dbname'')';
efSCHEMA: Result := 'USER';
efIFNULL: Result := 'NVL' + AddArgs;
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efDECODE: Result := sName + AddArgs;
// convert
efCONVERT:
begin
A2 := UpperCase(FDUnquote(Trim(A2), ''''));
if (A2 = 'LONGVARCHAR') or (A2 = 'WLONGVARCHAR') then
A2 := 'LVARCHAR'
else if A2 = 'WCHAR' then
A2 := 'NCHAR'
else if A2 = 'WVARCHAR' then
A2 := 'NVARCHAR'
else if (A2 = 'TIMESTAMP') or (A2 = 'DATETIME') then
A2 := 'DATETIME YEAR TO FRACTION'
else if A2 = 'DATE' then
A2 := 'DATETIME YEAR TO DAY'
else if A2 = 'TIME' then
A2 := 'DATETIME HOUR TO FRACTION'
else if A2 = 'DOUBLE' then
A2 := 'DOUBLE PRECISION'
else if A2 = 'TINYINT' then
A2 := 'SMALLINT'
else if A2 = 'SMALLINT' then
A2 := 'INTEGER'
else if (A2 = 'VARBINARY') or (A2 = 'BINARY') or (A2 = 'LONGVARBINARY') then
A2 := 'BYTE'
else if not ((A2 = 'NUMERIC') or (A2 = 'DECIMAL') or
(A2 = 'REAL') or (A2 = 'FLOAT') or (A2 = 'BIGINT') or
(A2 = 'CHAR') or (A2 = 'VARCHAR') or (A2 = 'INTEGER')) then
UnsupportedEscape(ASeq);
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'EXECUTE' then
Result := skExecute
else if sToken = 'BEGIN' then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysInfxCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
Result := 'DBINFO(''sqlca.sqlerrd1'')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetReadGenerator(const AName,
AAlias: String; ANextValue, AFullSelect: Boolean): String;
begin
if AName <> '' then begin
Result := AName;
if ANextValue then
Result := Result + '.NEXTVAL'
else
Result := Result + '.CURRVAL';
end
else
Result := GetIdentity(True);
if AAlias <> '' then
Result := Result + ' ' + AAlias;
if AFullSelect then
Result := 'SELECT ' + Result + BRK + 'FROM ' + GetSingleRowTable;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetSingleRowTable: String;
begin
Result := 'SYSMASTER:"informix".SYSDUAL';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetRowId(var AAlias: String): String;
begin
Result := 'ROWID';
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
begin
Result := Result + 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK +
'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK +
'FOR UPDATE';
FCommandKind := skSelectForLock;
ASSERT(lNeedFrom);
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
Result := 'RELEASE SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'EXECUTE PROCEDURE ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
function GetLimit: String;
begin
if (ASkip > 0) and (ARows + ASkip <> MAXINT) then
Result := 'SKIP ' + IntToStr(ASkip) + ' FIRST ' + IntToStr(ARows)
else if ASkip > 0 then
Result := 'SKIP ' + IntToStr(ASkip)
else if ARows >= 0 then
Result := 'FIRST ' + IntToStr(ARows)
else
Result := '';
end;
var
s: String;
iAfter: Integer;
begin
// SKIP N FIRST M
if (ASkip + ARows <> MAXINT) and
FDStartsWithKW(ASQL, 'SELECT', iAfter) and
not FDStartsWithKW(ASQL, 'SELECT SKIP', iAfter) and
not FDStartsWithKW(ASQL, 'SELECT FIRST', iAfter) and
not FDStartsWithKW(ASQL, 'SELECT LIMIT', iAfter) then begin
s := UpperCase(ASQL);
// Informix: does not support FIRST 0 and returns "syntax error"
if ARows = 0 then
Result := 'SELECT * FROM (' + BRK + ASQL + BRK + ') A' + BRK + 'WHERE 0 = 1'
else if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or FDHasKW(s, 'EXCEPT') then
Result := 'SELECT ' + GetLimit + ' * FROM (' + BRK + ASQL + BRK + ') A'
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT ' + GetLimit + ' DISTINCT ' + Copy(ASQL, iAfter, MAXINT)
else
Result := 'SELECT ' + GetLimit + Copy(ASQL, iAfter, MAXINT);
end
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
if caAutoInc in AColumn.ActualAttributes then begin
if AColumn.DataType in [dtSByte, dtInt16, dtInt32, dtByte, dtUInt16] then
Result := 'SERIAL'
else
Result := 'SERIAL8';
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'BOOLEAN';
dtSByte,
dtInt16,
dtByte:
Result := 'SMALLINT';
dtInt32,
dtUInt16:
Result := 'INTEGER';
dtInt64,
dtUInt32,
dtUInt64:
Result := 'INT8';
dtSingle:
Result := 'SMALLFLOAT';
dtDouble,
dtExtended:
Result := 'FLOAT';
dtCurrency:
Result := 'MONEY' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4);
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime,
dtDateTimeStamp:
Result := 'DATETIME YEAR TO FRACTION';
dtTime:
Result := 'DATETIME HOUR TO FRACTION';
dtDate:
Result := 'DATE';
dtTimeIntervalYM:
Result := 'INTERVAL YEAR TO MONTH';
dtTimeIntervalFull,
dtTimeIntervalDS:
Result := 'INTERVAL DAY TO FRACTION';
dtAnsiString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'NCHAR'
else
Result := 'NVARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString,
dtBlob:
Result := 'BYTE';
dtMemo,
dtWideMemo,
dtXML:
Result := 'TEXT';
dtHMemo,
dtWideHMemo:
Result := 'CLOB';
dtHBlob,
dtHBFile:
Result := 'BLOB';
dtGUID:
Result := 'CHAR(38)';
dtUnknown,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Informix, S_FD_Infx_RDBMS);
end.
|
unit U_Element;
interface
type
ELEMENT = CARDINAL;
// ecriture du paramètre e sur la sortie standard
procedure ecrireElement(const e : ELEMENT);
// saisie de la valeur paramètre e sur la sortie standard
procedure lireElement(out e : ELEMENT);
// egal(e1, e2) = VRAI si et seulement si e1 = e2
function egal(e1,e2 : ELEMENT) : BOOLEAN;
// inferieur(e1, e2) = VRAI si et seulement si e1 < e2
function inferieur(e1,e2 : ELEMENT) : BOOLEAN;
// inferieurOuEgal(e1, e2) = VRAI si et seulement si e1 <= e2
function inferieurOuEgal(e1,e2 : ELEMENT) : BOOLEAN;
// renvoie un element aleatoire entre 1 et max
function elementAleatoire (max : ELEMENT) : ELEMENT;
implementation
// egal(e1, e2) = VRAI si et seulement si e1 = e2
function egal(e1,e2 : ELEMENT) : BOOLEAN;
begin
egal := e1 = e2;
end {egal};
// inferieur(e1, e2) = VRAI si et seulement si e1 < e2
function inferieur(e1,e2 : ELEMENT) : BOOLEAN;
begin
inferieur := e1 < e2;
end {inferieur};
// inferieurOuEgal(e1, e2) = VRAI si et seulement si e1 <= e2
function inferieurOuEgal(e1,e2 : ELEMENT) : BOOLEAN;
begin
inferieurOuEgal := e1 <= e2;
end {inferieurOuEgal};
// ecriture du paramètre e sur la sortie standard
procedure ecrireElement(const e : ELEMENT);
begin
write(e);
end { ecrireElement };
// saisie de la valeur paramètre e sur la sortie standard
procedure lireElement(out e : ELEMENT);
begin
read(e);
end {lireElement};
// renvoie un element aleatoire entre 1 et max
function elementAleatoire (max : ELEMENT) : ELEMENT;
begin
elementAleatoire := random(max);
end {elementAleatoire};
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeBollingerEditor;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls,
{$ENDIF}
TeCanvas, TeePenDlg, StatChar, TeeBaseFuncEdit;
type
TBollingerFuncEditor = class(TBaseFunctionEditor)
Label3: TLabel;
ENum: TEdit;
UpDown1: TUpDown;
CheckBox1: TCheckBox;
Label1: TLabel;
Edit1: TEdit;
ButtonPen1: TButtonPen;
ButtonPen2: TButtonPen;
procedure ENumChange(Sender: TObject);
private
{ Private declarations }
protected
procedure ApplyFormChanges; override;
Procedure SetFunction; override;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
procedure TBollingerFuncEditor.ApplyFormChanges;
begin
inherited;
with TBollingerFunction(IFunction) do
begin
Period:=UpDown1.Position;
Exponential:=CheckBox1.Checked;
Deviation:=StrToFloat(Edit1.Text);
end;
end;
procedure TBollingerFuncEditor.ENumChange(Sender: TObject);
begin
EnableApply;
end;
Procedure TBollingerFuncEditor.SetFunction;
begin
inherited;
with TBollingerFunction(IFunction) do
begin
UpDown1.Position:=Round(Period);
CheckBox1.Checked:=Exponential;
Edit1.Text:=FloatToStr(Deviation);
ButtonPen1.LinkPen(UpperBandPen);
ButtonPen2.LinkPen(LowBandPen);
end;
end;
initialization
RegisterClass(TBollingerFuncEditor);
end.
|
{
Copyright (c) 2012, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit MedDMUnit;
interface
uses
Windows, SysUtils, Classes, AppEvnts, Forms, LDSLogger, ibxFBUtils, IBDatabase,
DB, IBCustomDataSet, Dialogs;
type
TMedDataModule = class(TDataModule)
ApplicationEvents1: TApplicationEvents;
FMedDB: TIBDatabase;
FTranR: TIBTransaction;
FTranW: TIBTransaction;
IBDataSet1: TIBDataSet;
procedure DataModuleCreate(Sender: TObject);
procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MedDataModule: TMedDataModule;
implementation
{$R *.dfm}
uses MedDBStruct, MedGlobalUnit, MedLoginFrm;
procedure TMedDataModule.ApplicationEvents1Exception(Sender: TObject;
E: Exception);
begin
ALog.LogStr('Произошла ошибка: ' + E.Message);
Application.MessageBox(PChar(E.Message), 'ОШИБКА!', MB_ICONERROR);
end;
procedure TMedDataModule.DataModuleCreate(Sender: TObject);
begin
// Запоминаем ссылки на компоненты с более короткими именами
MedDB := FMedDB;
TranR := FTranR;
TranW := FTranW;
// Проверка структуры БД
BuildDBStructure;
if MedDB.Connected then
begin
ShowMessage('ВНИМАНИЕ РАЗРАБОТЧИКУ! Соединение с БД уже установлено!!!');
fb.DisconnectDB(MedDB);
end;
MedDB.Params.Values['user_name'] := FBUser;
MedDB.Params.Values['password'] := FBPassword;
MedDB.DatabaseName := Format('%s/%d:%s', [FBServer, FBPort, FBFile]);
{
user_name=sysdba
password=masterkey
lc_ctype=WIN1251
}
try
fb.ConnectDB(MedDB);
except
on E: Exception do
raise ReCreateEObject(E, 'Подключение к базе данных');
end;
if CheckOnFirstStart then
begin
IsAdmin := True;
UserID := 0;
UserName := 'Запуск под администратором';
end
else
begin
if ShowLoginForm then
begin
ALog.LogStrFmt('Пользователь %s прошел авторизацию', [UserName], tlpInformation);
ALog.DefaultPrefix := UserName;
end else
begin
ALog.LogStr('Пользователь отказался от авторизации. Приложение будет закрыто');
fb.DisconnectDB(MedDB);
end;
end;
end;
procedure TMedDataModule.DataModuleDestroy(Sender: TObject);
begin
fb.DisconnectDB(MedDB);
end;
end.
|
unit ucardthread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Windows, Messages, ucardworker, uconfig, uother;
const
WM_TASK_READ_CARD = WM_USER + 1000;
WM_TASK_WRITE_SINGLE_CARD = WM_USER + 1001;
WM_TASK_WRITE_BATCH_CARD = WM_USER + 1002;
WM_TASK_CLEAN_CARD = WM_USER + 1003;
WM_TASK_FINISH = WM_USER + 1004;
WM_TASK_RELOAD_CONFIG = WM_USER + 1005;
WM_THREAD_LOG = WM_USER + 1006;
WM_THREAD_STATE = WM_USER + 1007;
type
TCurrentWorkingState = (cwsMultipleCard = 0, cwsCleanCard = 1,
cwsFinished = 2, cwsNoSpecialState = 3, cwsErrorConnection = 4);
{ TCardThread }
TCardThread = class(TThread)
private
CardWorker: TCardWorker;
wnd: HWND;
State: TCurrentWorkingState;
procedure ReadCard();
procedure WriteSingleCard(aMsg: TMsg);
procedure WriteMultipleCard();
procedure CleanCard();
procedure LogData(const str: string);
procedure StopTasks();
procedure ReloadConfig();
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: boolean; FormHandle: HWND);
destructor Destroy; override;
end;
implementation
{ TCardThread }
procedure TCardThread.ReadCard();
var
Response: string;
begin
try
LogData('Читаю карту:');
Response := CardWorker.ReadCard();
Response := ExtractBetween(Response, ';', '?');
if Length(Response) > 0 then
LogData(Response)
else
LogData('Карта пуста.');
LogData('Операция завершена.');
state := cwsFinished;
except
on E: Exception do
LogData(E.Message);
end;
end;
procedure TCardThread.WriteSingleCard(aMsg: TMsg);
var
Data: string;
CardData: string;
begin
LogData('Запись карты:');
try
Data := PChar(aMsg.lParam);
CardData := CardWorker.WriteCard(Data);
LogData('Записано: ' + CardData);
case CardWorker.StatusByte of
$30: LogData('Операция завершена.');
$31: LogData('Выполнено с ошибкой чтения/записи.');
$32: LogData('Неправильный формат команды!');
$34: LogData('Неправильная команда!');
$39: LogData('Неправильно проведена карта!');
end;
state := cwsFinished;
except
on E: Exception do
LogData(E.Message);
end;
end;
procedure TCardThread.WriteMultipleCard();
var
CardData: string;
begin
try
LogData('Запись карты:');
CardData := CardWorker.WriteCard();
LogData('Записано: ' + CardData);
case CardWorker.StatusByte of
$30: LogData('Операция завершена.');
$31: LogData('Выполнено с ошибкой чтения/записи.');
$32: LogData('Неправильный формат команды!');
$34: LogData('Неправильная команда!');
$39: LogData('Неправильно проведена карта!');
end;
config.CurrentCardValue := Config.CurrentCardValue + 1;
config.Save;
except
on E: Exception do
LogData(E.Message);
end;
end;
procedure TCardThread.CleanCard();
begin
try
LogData('Очищаю карту:');
CardWorker.EraseCard();
LogData('Операция завершена.');
except
on E: Exception do
LogData(E.Message);
end;
end;
procedure TCardThread.LogData(const str: string);
begin
PostMessage(wnd, WM_THREAD_LOG, 0, UIntPtr(PChar(str)));
end;
procedure TCardThread.StopTasks();
begin
State := cwsNoSpecialState;
CardWorker.Reset();
end;
procedure TCardThread.ReloadConfig();
begin
if (State <> cwsErrorConnection) then
CardWorker.Disconnect;
CardWorker.Connect;
if CardWorker.State = csErrorConn then
State := cwsErrorConnection
else
State := cwsNoSpecialState;
end;
procedure TCardThread.Execute;
var
aMsg: TMsg;
begin
while not terminated do
begin
if PeekMessage(amsg, 0, 0, 0, PM_REMOVE) then
begin
TranslateMessage(aMsg);
DispatchMessage(aMsg);
end else
Sleep(100);
if aMsg.message > 0 then
begin
if ((state = cwsErrorConnection) and (aMsg.message <> WM_TASK_RELOAD_CONFIG)) then
begin
sleep(100);
continue;
end;
case aMsg.message of
WM_TASK_READ_CARD: ReadCard();
WM_TASK_WRITE_SINGLE_CARD: WriteSingleCard(aMsg);
WM_TASK_WRITE_BATCH_CARD: state := cwsMultipleCard;
WM_TASK_CLEAN_CARD: state := cwsCleanCard;
WM_TASK_FINISH: state := cwsFinished;
WM_TASK_RELOAD_CONFIG: ;
end;
end;
aMsg.message:=0;
case state of
cwsMultipleCard: WriteMultipleCard();
cwsCleanCard: CleanCard();
cwsNoSpecialState: sleep(100);
cwsFinished: StopTasks();
end;
//Sleep(10);
PostMessage(wnd, WM_THREAD_STATE, 0, integer(state));
end;
end;
constructor TCardThread.Create(CreateSuspended: boolean; FormHandle: HWND);
begin
CardWorker := TCardWorker.Create;
CardWorker.Connect;
wnd := FormHandle;
State := cwsNoSpecialState;
inherited Create(CreateSuspended);
FreeOnTerminate := True;
end;
destructor TCardThread.Destroy;
begin
CardWorker.Free;
inherited Destroy;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.