text stringlengths 14 6.51M |
|---|
unit pFIBPreferences;
interface
{$I ..\FIBPlUS.INC}
uses
Windows, Messages, SysUtils, Classes,
{$IFDEF D_XE2}
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.StdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls,
{$ENDIF}
pFIBProps,uFIBEditorForm
{$IFDEF D6+}
,Variants
{$ENDIF}
;
type
TfrmFIBPreferences = class(TFIBEditorCustomForm)
z: TPageControl;
TabSheet1: TTabSheet;
TabSheet4: TTabSheet;
GroupBox1: TGroupBox;
chRequiredFields: TCheckBox;
chSetReadOnlyFields: TCheckBox;
chImportDefaultValues: TCheckBox;
chUseBooleanField: TCheckBox;
chApplyRepositary: TCheckBox;
chGetOrderInfo: TCheckBox;
chAskRecordCount: TCheckBox;
GroupBox2: TGroupBox;
chTrimCharFields: TCheckBox;
chRefreshAfterPost: TCheckBox;
chRefreshDeletedRecord: TCheckBox;
chStartTransaction: TCheckBox;
chAutoFormatFields: TCheckBox;
chProtectedEdit: TCheckBox;
chKeepSorting: TCheckBox;
chPersistentSorting: TCheckBox;
GroupBox3: TGroupBox;
chForceOpen: TCheckBox;
chForceMasterRefresh: TCheckBox;
chWaitEndMasterScroll: TCheckBox;
EdPrefixGen: TEdit;
EdSufixGen: TEdit;
Label4: TLabel;
Label5: TLabel;
Button1: TButton;
Button2: TButton;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
chStoreConnected: TCheckBox;
chSynchronizeTime: TCheckBox;
chUpperOldNames: TCheckBox;
chUseLoginPrompt: TCheckBox;
Label6: TLabel;
CharSetC: TComboBox;
Label8: TLabel;
DialectC: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
cmbTimeOutAction: TComboBox;
edTimeout: TEdit;
cmbTPBMode: TComboBox;
ChGo1: TCheckBox;
ChParamCheck: TCheckBox;
chAutoStartTransaction: TCheckBox;
chAutoCommitTransaction: TCheckBox;
chUseSQLINT64ToBCD: TCheckBox;
chVisibleRecno: TCheckBox;
GroupBox4: TGroupBox;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
edDateFormat: TEdit;
edTimeFormat: TEdit;
edDisplayNumFormat: TEdit;
edEditNumFormat: TEdit;
chIgnoreMasterClose: TCheckBox;
chUseGuidField: TCheckBox;
chFetchAll: TCheckBox;
chEmptyStrToNull: TCheckBox;
chCloseDsgnConnect: TCheckBox;
chCacheCalcFields: TCheckBox;
edDateTimeDisplay: TEdit;
Label7: TLabel;
chUseLargeIntField: TCheckBox;
chUseSelectForLock: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure chCloseDsgnConnectClick(Sender: TObject);
private
procedure LoadPreferences;
procedure SavePreferences;
procedure SaveToReg;
public
{ Public declarations }
end;
var
frmFIBPreferences: TfrmFIBPreferences;
bCloseDesignConnect:boolean;
procedure ShowFIBPreferences;
implementation
{$R *.DFM}
uses RegUtils, FIBToolsConsts;
procedure ShowFIBPreferences;
begin
if frmFIBPreferences =nil then
frmFIBPreferences:=TfrmFIBPreferences.Create(Application);
with frmFIBPreferences do begin
try
LoadPreferences;
if ShowModal=mrOk then begin
SavePreferences ;
SaveToReg
end;
finally
Free;
frmFIBPreferences:=nil
end;
end;
end;
{ TfrmFIBPreferences }
procedure TfrmFIBPreferences.LoadPreferences;
begin
chAskRecordCount.Checked:=
psAskRecordCount in DefaultPrepareOptions;
chGetOrderInfo.Checked:=
psGetOrderInfo in DefaultPrepareOptions;
chApplyRepositary.Checked:=
psApplyRepositary in DefaultPrepareOptions;
chUseBooleanField.Checked:=
psUseBooleanField in DefaultPrepareOptions;
chUseGuidField.Checked:=
psUseGuidField in DefaultPrepareOptions;
chUseLargeIntField.Checked:=
psUseLargeIntField in DefaultPrepareOptions;
chUseSQLINT64ToBCD.Checked:=
psSQLINT64ToBCD in DefaultPrepareOptions;
chImportDefaultValues.Checked:=
pfImportDefaultValues in DefaultPrepareOptions;
chSetReadOnlyFields.Checked:=
pfSetReadOnlyFields in DefaultPrepareOptions;
chRequiredFields.Checked:=
pfSetRequiredFields in DefaultPrepareOptions;
chEmptyStrToNull.Checked:=
psSetEmptyStrToNull in DefaultPrepareOptions;
chPersistentSorting .Checked:=
poPersistentSorting in DefaultOptions;
chKeepSorting .Checked:=
poKeepSorting in DefaultOptions;
chProtectedEdit .Checked:=
poProtectedEdit in DefaultOptions;
chAutoFormatFields .Checked:=
poAutoFormatFields in DefaultOptions;
chStartTransaction .Checked:=
poStartTransaction in DefaultOptions;
chRefreshDeletedRecord.Checked:=
poRefreshDeletedRecord in DefaultOptions;
chRefreshAfterPost .Checked:=
poRefreshAfterPost in DefaultOptions;
chTrimCharFields .Checked:=
poTrimCharFields in DefaultOptions;
chVisibleRecno .Checked:=
poVisibleRecno in DefaultOptions;
chFetchAll .Checked:=
poFetchAll in DefaultOptions;
chCacheCalcFields .Checked:=
poCacheCalcFields in DefaultOptions;
chUseSelectForLock .Checked:=
poUseSelectForLock in DefaultOptions;
chWaitEndMasterScroll.Checked:=
dcWaitEndMasterScroll in DefaultDetailConditions;
chForceMasterRefresh.Checked:=
dcForceMasterRefresh in DefaultDetailConditions;
chForceOpen.Checked:=
dcForceOpen in DefaultDetailConditions;
chIgnoreMasterClose.Checked:=
dcIgnoreMasterClose in DefaultDetailConditions;
DialectC.ItemIndex :=DefSQLDialect-1;
CharSetC.Text :=DefCharSet;
chUseLoginPrompt.Checked :=DefUseLoginPrompt;
chUpperOldNames.Checked :=DefUpperOldNames;
chSynchronizeTime.Checked :=DefSynchronizeTime;
chStoreConnected.Checked :=DefStoreConnected;
cmbTimeOutAction.ItemIndex:=Ord(DefTimeOutAction);
edTimeout.Text :=IntToStr(DefTimeOut);
cmbTPBMode.ItemIndex :=Ord(DefTPBMode);
ChGo1.Checked :=DefGoToFirstRecordOnExecute;
ChParamCheck.Checked :=DefParamCheck;
chAutoCommitTransaction.Checked:=qoAutoCommit in DefQueryOptions;
chAutoStartTransaction .Checked:=qoStartTransaction in DefQueryOptions;
EdPrefixGen.Text := DefPrefixGenName;
EdSufixGen .Text := DefSufixGenName;
edDateFormat.Text := dDefDateFormat;
edTimeFormat.Text := dDefTimeFormat;
edDisplayNumFormat.Text := dDefDisplayFormatNum;
edDateTimeDisplay.Text := dDefDateTimeFormat;
edEditNumFormat.Text := dDefEditFormatNum ;
chCloseDsgnConnect.Checked:=bCloseDesignConnect
end;
procedure TfrmFIBPreferences.SavePreferences;
begin
if chAskRecordCount.Checked then
Include (DefaultPrepareOptions,psAskRecordCount)
else
Exclude (DefaultPrepareOptions,psAskRecordCount);
if chGetOrderInfo.Checked then
Include (DefaultPrepareOptions,psGetOrderInfo)
else
Exclude (DefaultPrepareOptions,psGetOrderInfo);
if chApplyRepositary.Checked then
Include (DefaultPrepareOptions,psApplyRepositary)
else
Exclude (DefaultPrepareOptions,psApplyRepositary);
if chUseBooleanField.Checked then
Include (DefaultPrepareOptions,psUseBooleanField)
else
Exclude (DefaultPrepareOptions,psUseBooleanField);
if chUseGuidField.Checked then
Include (DefaultPrepareOptions,psUseGuidField)
else
Exclude (DefaultPrepareOptions,psUseGuidField);
if chUseLargeIntField.Checked then
Include (DefaultPrepareOptions,psUseLargeIntField)
else
Exclude (DefaultPrepareOptions,psUseLargeIntField);
if chUseSQLINT64ToBCD.Checked then
Include (DefaultPrepareOptions,psSQLINT64ToBCD)
else
Exclude (DefaultPrepareOptions,psSQLINT64ToBCD);
if chImportDefaultValues.Checked then
Include (DefaultPrepareOptions,pfImportDefaultValues)
else
Exclude (DefaultPrepareOptions,pfImportDefaultValues);
if chSetReadOnlyFields.Checked then
Include (DefaultPrepareOptions,pfSetReadOnlyFields)
else
Exclude (DefaultPrepareOptions,pfSetReadOnlyFields);
if chRequiredFields.Checked then
Include (DefaultPrepareOptions,pfSetRequiredFields)
else
Exclude (DefaultPrepareOptions,pfSetRequiredFields);
if chEmptyStrToNull.Checked then
Include (DefaultPrepareOptions,psSetEmptyStrToNull)
else
Exclude (DefaultPrepareOptions,psSetEmptyStrToNull);
if chPersistentSorting .Checked then
Include (DefaultOptions, poPersistentSorting)
else
Exclude (DefaultOptions, poPersistentSorting) ;
if chKeepSorting .Checked then
Include (DefaultOptions , poKeepSorting)
else
Exclude (DefaultOptions, poKeepSorting) ;
if chProtectedEdit .Checked then
Include (DefaultOptions, poProtectedEdit)
else
Exclude (DefaultOptions, poProtectedEdit);
if chStartTransaction .Checked then
Include (DefaultOptions , poStartTransaction)
else
Exclude (DefaultOptions , poStartTransaction) ;
if chAutoFormatFields .Checked then
Include (DefaultOptions, poAutoFormatFields)
else
Exclude (DefaultOptions, poAutoFormatFields) ;
if chRefreshDeletedRecord.Checked then
Include (DefaultOptions , poRefreshDeletedRecord)
else
Exclude (DefaultOptions, poRefreshDeletedRecord);
if chRefreshAfterPost .Checked then
Include (DefaultOptions,poRefreshAfterPost)
else
Exclude (DefaultOptions , poRefreshAfterPost) ;
if chTrimCharFields .Checked then
Include (DefaultOptions,poTrimCharFields)
else
Exclude (DefaultOptions,poTrimCharFields);
if chVisibleRecno .Checked then
Include (DefaultOptions,poVisibleRecno)
else
Exclude (DefaultOptions,poVisibleRecno);
if chFetchAll .Checked then
Include (DefaultOptions,poFetchAll)
else
Exclude (DefaultOptions,poFetchAll);
if chCacheCalcFields .Checked then
Include (DefaultOptions,poCacheCalcFields)
else
Exclude (DefaultOptions,poCacheCalcFields);
if chUseSelectForLock .Checked then
Include (DefaultOptions,poUseSelectForLock)
else
Exclude (DefaultOptions,poUseSelectForLock);
if chWaitEndMasterScroll.Checked then
Include (DefaultDetailConditions,dcWaitEndMasterScroll)
else
Exclude (DefaultDetailConditions,dcWaitEndMasterScroll);
if chForceMasterRefresh.Checked then
Include (DefaultDetailConditions,dcForceMasterRefresh)
else
Exclude (DefaultDetailConditions,dcForceMasterRefresh);
if chForceOpen.Checked then
Include (DefaultDetailConditions,dcForceOpen)
else
Exclude (DefaultDetailConditions,dcForceOpen);
if chIgnoreMasterClose.Checked then
Include (DefaultDetailConditions,dcIgnoreMasterClose)
else
Exclude (DefaultDetailConditions,dcIgnoreMasterClose);
if chAutoCommitTransaction.Checked then
Include (DefQueryOptions,qoAutoCommit)
else
Exclude (DefQueryOptions,qoAutoCommit);
if chAutoStartTransaction .Checked then
Include (DefQueryOptions,qoStartTransaction )
else
Exclude (DefQueryOptions,qoStartTransaction );
DefStoreConnected := chStoreConnected.Checked;
DefSynchronizeTime := chSynchronizeTime.Checked;
DefUpperOldNames := chUpperOldNames.Checked;
DefUseLoginPrompt := chUseLoginPrompt.Checked;
DefCharSet := CharSetC.Text;
DefSQLDialect := DialectC.ItemIndex+1 ;
DefTimeOutAction :=TTransactionAction1(cmbTimeOutAction.ItemIndex);
DefTimeOut := StrToInt(edTimeout.Text);
DefTPBMode := TTPBMode(cmbTPBMode.ItemIndex);
DefGoToFirstRecordOnExecute:= ChGo1.Checked;
DefParamCheck := ChParamCheck.Checked;
DefPrefixGenName := EdPrefixGen.Text;
DefSufixGenName := EdSufixGen .Text;
dDefDateFormat:=edDateFormat.Text;
dDefTimeFormat:=edTimeFormat.Text;
dDefDisplayFormatNum:= edDisplayNumFormat.Text;
dDefEditFormatNum := edEditNumFormat.Text ;
dDefDateTimeFormat := edDateTimeDisplay.Text;
end;
procedure TfrmFIBPreferences.SaveToReg;
begin
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','Options'],
['PersistentSorting',
'KeepSorting',
'ProtectedEdit',
'AutoFormatFields',
'StartTransaction',
'RefreshDeletedRecord',
'RefreshAfterPost',
'TrimCharFields',
'VisibleRecno',
'FetchAll',
'CacheCalcFields'
],
[
chPersistentSorting.Checked,
chKeepSorting.Checked,
chProtectedEdit.Checked,
chAutoFormatFields.Checked,
chStartTransaction.Checked,
chRefreshDeletedRecord.Checked,
chRefreshAfterPost.Checked,
chTrimCharFields.Checked,
chVisibleRecno .Checked,
chFetchAll .Checked,
chCacheCalcFields.Checked
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','PrepareOptions'],
['AskRecordCount',
'GetOrderInfo',
'ApplyRepositary',
'UseBooleanField',
'ImportDefaultValues',
'SetReadOnlyFields',
'RequiredFields',
'SQLINT64ToBCD',
'UseGuidField',
'SetEmptyStrToNull',
'UseLargeIntField'
],
[ chAskRecordCount.Checked,
chGetOrderInfo.Checked,
chApplyRepositary.Checked,
chUseBooleanField.Checked,
chImportDefaultValues.Checked,
chSetReadOnlyFields.Checked,
chRequiredFields.Checked,
chUseSQLINT64ToBCD.Checked,
chUseGuidField.Checked,
chEmptyStrToNull.Checked,
chUseLargeIntField.Checked
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','DetailConditions'],
[
'WaitEndMasterScroll',
'ForceMasterRefresh',
'ForceOpen',
'IgnoreMasterClose'
],
[
chWaitEndMasterScroll.Checked,
chForceMasterRefresh.Checked,
chForceOpen.Checked,
chIgnoreMasterClose.Checked
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','DefFormatFields'],
['DateFormat',
'TimeFormat',
'NumericDisplayFormat',
'NumericEditFormat',
'DateTimeFormat'
],
[
edDateFormat.Text,
edTimeFormat.Text,
edDisplayNumFormat.Text,
edEditNumFormat.Text,
edDateTimeDisplay.Text
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','Other'],
[
'DefPrefixGenName',
'DefSufixGenName'
],
[
EdPrefixGen.Text,
EdSufixGen .Text
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataBase'],
[
'DialectC',
'CharSetC',
'UseLoginPrompt',
'UpperOldNames',
'SynchronizeTime',
'StoreConnected',
'CloseDesignConnectAfterRun'
],
[
DialectC.ItemIndex+1,
CharSetC.Text,
chUseLoginPrompt.Checked,
chUpperOldNames.Checked,
chSynchronizeTime.Checked,
chStoreConnected.Checked,
chCloseDsgnConnect.Checked
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBQuery'],
[
'GoToFirstRecordOnExecute',
'ParamCheck',
'AutoStartTransaction',
'AutoCommitTransaction'
],
[
ChGo1.Checked,
ChParamCheck.Checked,
chAutoStartTransaction .Checked,
chAutoCommitTransaction.Checked
]
);
DefWriteToRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBTransaction'],
[
'TimeOutAction',
'TimeOut',
'TPBMode'
],
[
cmbTimeOutAction.ItemIndex,
edTimeout.Text,
cmbTPBMode.ItemIndex
]
);
end;
procedure LoadFromReg;
var Values:Variant;
begin
Values:=
DefReadFromRegistry(['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','Options'],
[
'PersistentSorting',
'KeepSorting',
'ProtectedEdit',
'AutoFormatFields',
'StartTransaction',
'RefreshDeletedRecord',
'RefreshAfterPost',
'TrimCharFields',
'VisibleRecno',
'FetchAll',
'CacheCalcFields'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
if Values[0,0] then
Include (DefaultOptions, poPersistentSorting)
else
Exclude (DefaultOptions, poPersistentSorting);
if Values[1,1] then
if Values[0,1] then
Include (DefaultOptions , poKeepSorting)
else
Exclude (DefaultOptions , poKeepSorting);
if Values[1,2] then
if Values[0,2] then
Include (DefaultOptions, poProtectedEdit)
else
Exclude (DefaultOptions, poProtectedEdit);
if Values[1,3] then
if Values[0,3] then
Include (DefaultOptions, poAutoFormatFields)
else
Exclude (DefaultOptions, poAutoFormatFields);
if Values[1,4] then
if Values[0,4] then
Include (DefaultOptions , poStartTransaction)
else
Exclude (DefaultOptions , poStartTransaction);
if Values[1,5] then
if Values[0,5] then
Include (DefaultOptions, poRefreshDeletedRecord)
else
Exclude (DefaultOptions, poRefreshDeletedRecord);
if Values[1,6] then
if Values[0,6] then
Include (DefaultOptions,poRefreshAfterPost)
else
Exclude (DefaultOptions,poRefreshAfterPost);
if Values[1,7] then
if Values[0,7] then
Include (DefaultOptions,poTrimCharFields )
else
Exclude (DefaultOptions,poTrimCharFields );
if Values[1,8] then
if Values[0,8] then
Include (DefaultOptions,poVisibleRecno )
else
Exclude (DefaultOptions,poVisibleRecno );
if Values[1,9] then
if Values[0,9] then
Include (DefaultOptions,poFetchAll )
else
Exclude (DefaultOptions,poFetchAll );
if Values[1,10] then
if Values[0,10] then
Include (DefaultOptions,poCacheCalcFields )
else
Exclude (DefaultOptions,poCacheCalcFields );
end;
Values:=
DefReadFromRegistry(['Software',RegFIBRoot,
RegPreferences,'pFIBDataSet','DefFormatFields'],
['DateFormat',
'TimeFormat',
'NumericDisplayFormat',
'NumericEditFormat',
'DateTimeFormat'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
dDefDateFormat:=VarToStr(Values[0,0]);
if Values[1,1] then
dDefTimeFormat:=VarToStr(Values[0,1]);
if Values[1,2] then
dDefDisplayFormatNum:= VarToStr(Values[0,2]);
if Values[1,3] then
dDefEditFormatNum := VarToStr(Values[0,3]);
if Values[1,4] then
dDefDateTimeFormat := VarToStr(Values[0,4]);
end;
Values:=
DefReadFromRegistry(['Software',RegFIBRoot,
RegPreferences,'pFIBDataSet','DetailConditions'],
['WaitEndMasterScroll', 'ForceMasterRefresh','ForceOpen','IgnoreMasterClose']
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
if Values[0,0] then
Include (DefaultDetailConditions,dcWaitEndMasterScroll)
else
Exclude (DefaultDetailConditions,dcWaitEndMasterScroll);
if Values[1,1] then
if Values[0,1] then
Include (DefaultDetailConditions,dcForceMasterRefresh)
else
Exclude (DefaultDetailConditions,dcForceMasterRefresh);
if Values[1,2] then
if Values[0,2] then
Include (DefaultDetailConditions,dcForceOpen)
else
Exclude (DefaultDetailConditions,dcForceOpen);
if Values[1,3] then
if Values[0,3] then
Include (DefaultDetailConditions,dcIgnoreMasterClose)
else
Exclude (DefaultDetailConditions,dcIgnoreMasterClose);
end;
Values:=
DefReadFromRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','PrepareOptions'],
['AskRecordCount',
'GetOrderInfo',
'ApplyRepositary',
'UseBooleanField',
'ImportDefaultValues',
'SetReadOnlyFields',
'RequiredFields',
'SQLINT64ToBCD',
'UseGuidField',
'SetEmptyStrToNull',
'UseLargeIntField'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
if Values[0,0] then
Include (DefaultPrepareOptions,psAskRecordCount)
else
Exclude (DefaultPrepareOptions,psAskRecordCount);
if Values[1,1] then
if Values[0,1] then
Include (DefaultPrepareOptions,psGetOrderInfo)
else
Exclude (DefaultPrepareOptions,psGetOrderInfo);
if Values[1,2] then
if Values[0,2] then
Include (DefaultPrepareOptions,psApplyRepositary)
else
Exclude (DefaultPrepareOptions,psApplyRepositary);
if Values[1,3] then
if Values[0,3] then
Include (DefaultPrepareOptions,psUseBooleanField)
else
Exclude (DefaultPrepareOptions,psUseBooleanField);
if Values[1,4] then
if Values[0,4] then
Include (DefaultPrepareOptions,pfImportDefaultValues)
else
Exclude (DefaultPrepareOptions,pfImportDefaultValues);
if Values[1,5] then
if Values[0,5] then
Include (DefaultPrepareOptions,pfSetReadOnlyFields)
else
Exclude (DefaultPrepareOptions,pfSetReadOnlyFields);
if Values[1,6] then
if Values[0,6] then
Include (DefaultPrepareOptions,pfSetRequiredFields)
else
Exclude (DefaultPrepareOptions,pfSetRequiredFields);
if Values[1,7] then
if Values[0,7] then
Include (DefaultPrepareOptions,psSQLINT64ToBCD )
else
Exclude (DefaultPrepareOptions,psSQLINT64ToBCD );
if Values[1,8] then
if Values[0,8] then
Include (DefaultPrepareOptions,psUseGuidField)
else
Exclude (DefaultPrepareOptions,psUseGuidField);
if Values[1,9] then
if Values[0,9] then
Include (DefaultPrepareOptions,psSetEmptyStrToNull)
else
Exclude (DefaultPrepareOptions,psSetEmptyStrToNull);
if Values[1,10] then
if Values[0,10] then
Include (DefaultPrepareOptions,psUseLargeIntField)
else
Exclude (DefaultPrepareOptions,psUseLargeIntField);
end;
Values:=
DefReadFromRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataSet','Other'],
[
'DefPrefixGenName',
'DefSufixGenName'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
DefPrefixGenName:=Values[0,0];
if Values[1,1] then
DefSufixGenName:=Values[0,1];
end;
Values:=DefReadFromRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBDataBase'],
[
'DialectC',
'CharSetC',
'UseLoginPrompt',
'UpperOldNames',
'SynchronizeTime',
'StoreConnected',
'CloseDesignConnectAfterRun'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
DefSQLDialect:=Values[0,0];
if Values[1,1] then
DefCharSet:=Values[0,1];
if Values[1,2] then
DefUseLoginPrompt:=Values[0,2];
if Values[1,3] then
DefUpperOldNames:=Values[0,3];
if Values[1,4] then
DefSynchronizeTime:=Values[0,4];
if Values[1,5] then
DefStoreConnected :=Values[0,5];
if Values[1,6] then
bCloseDesignConnect:=Values[0,6];
end;
Values:=DefReadFromRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBQuery'],
[
'GoToFirstRecordOnExecute',
'ParamCheck',
'AutoStartTransaction',
'AutoCommitTransaction'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
DefGoToFirstRecordOnExecute:=Values[0,0];
if Values[1,1] then
DefParamCheck:=Values[0,1];
if Values[1,2] then
if Values[0,2] then
Include(DefQueryOptions,qoStartTransaction);
if Values[1,3] then
if Values[0,3] then
Include(DefQueryOptions,qoAutoCommit);
end;
Values:=DefReadFromRegistry(
['Software',RegFIBRoot,RegPreferences,'pFIBTransaction'],
[
'TimeOutAction',
'TimeOut',
'TPBMode'
]
);
if VarType(Values)<>varBoolean then
begin
if Values[1,0] then
DefTimeOutAction :=TTransactionAction1(Values[0,0]);
if Values[1,1] then
DefTimeOut := Values[0,1];
if Values[1,2] then
DefTPBMode := TTPBMode(Values[0,2]);
end;
end;
procedure TfrmFIBPreferences.FormCreate(Sender: TObject);
begin
Caption := FPTPrefCaption;
Label4.Caption := FPTGeneratorPref;
Label5.Caption := FPTGeneratorSuf;
Label6.Caption := FPTCharSet;
Label8.Caption := FPTSQLDialect;
chStoreConnected.Caption := FPTStoreConnected;
chSynchronizeTime.Caption := FPTSyncTime;
chUpperOldNames.Caption := FPTUpperOldNames;
chUseLoginPrompt.Caption := FPTUseLoginPromt;
Label1.Caption := FPTTimeoutAction;
Label2.Caption := FPTTimeout;
ChGo1.Caption := FPTGotoFirstRecord;
ChParamCheck.Caption := FPTCheckParam;
chAutoStartTransaction.Caption := FPTAutoStartTrans;
chAutoCommitTransaction.Caption := FPTAutoCommitTrans;
Button1.Caption := SOKButton;
Button2.Caption := SCancelButton;
end;
procedure TfrmFIBPreferences.chCloseDsgnConnectClick(Sender: TObject);
begin
bCloseDesignConnect:=chCloseDsgnConnect.Checked
end;
initialization
{$IFNDEF FIBPLUS_TRIAL}
LoadFromReg;
{$ENDIF}
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Collections.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Comparers.Intf;
{$I ADAPT_RTTI.inc}
type
// Callbacks
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
TADListItemCallbackAnon<T> = reference to procedure(const AItem: T);
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
TADListItemCallbackOfObject<T> = procedure(const AItem: T) of object;
TADListItemCallbackUnbound<T> = procedure(const AItem: T);
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
TADListMapCallbackAnon<TKey, TValue> = reference to procedure(const AKey: TKey; const AValue: TValue);
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
TADListMapCallbackOfObject<TKey, TValue> = procedure(const AKey: TKey; const AValue: TValue) of object;
TADListMapCallbackUnbound<TKey, TValue> = procedure(const AKey: TKey; const AValue: TValue);
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
TADTreeNodeValueCallbackAnon<V> = reference to procedure(const Value: V);
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
TADTreeNodeValueCallbackOfObject<V> = procedure(const Value: V) of object;
TADTreeNodeValueCallbackUnbound<V> = procedure(const Value: V);
{$IFDEF FPC}
TArray<T> = Array of T; // FreePascal doesn't have this defined (yet)
{$ENDIF FPC}
/// <summary><c>A Simple Generic Array with basic Management Methods (Read-Only Interface).</c></summary>
IADArrayReader<T> = interface(IADInterface)
// Getters
/// <returns><c>The current Allocated Capacity of this Array.</c></returns>
function GetCapacity: Integer;
/// <returns><c>The Item from the Array at the given Index.</c></returns>
function GetItem(const AIndex: Integer): T;
// Properties
/// <returns><c>The current Allocated Capacity of this Array.</c></returns>
property Capacity: Integer read GetCapacity;
/// <returns><c>The Item from the Array at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem; default;
end;
/// <summary><c>A Simple Generic Array with basic Management Methods (Read/Write Interface).</c></summary>
IADArray<T> = interface(IADArrayReader<T>)
// Getters
/// <returns><c>Read-Only Interfaced Reference to this Array.</c></returns>
function GetReader: IADArrayReader<T>;
// Setters
/// <summary><c>Sets the Allocated Capacity to the given value.</c></summary>
procedure SetCapacity(const ACapacity: Integer);
/// <summary><c>Assigns the given Item into the Array at the given Index.</c></summary>
procedure SetItem(const AIndex: Integer; const AItem: T);
// Management Methods
/// <summary><c>Empties the Array and sets it back to the original Capacity you specified in the Constructor.</c></summary>
procedure Clear;
/// <summary><c>Finalizes the given Index and shifts subsequent Items to the Left.</c></summary>
procedure Delete(const AIndex: Integer); overload;
/// <summary><c>Finalized the Items from the given Index and shifts all subsequent Items to the Left.</c></summary>
procedure Delete(const AFirstIndex, ACount: Integer); overload;
/// <summary><c>Low-level Finalization of Items in the Array between the given </c>AIndex<c> and </c>AIndex + ACount<c>.</c></summary>
procedure Finalize(const AIndex, ACount: Integer);
/// <summary><c>Shifts all subsequent Items to the Right to make room for the given Item.</c></summary>
procedure Insert(const AItem: T; const AIndex: Integer);
/// <summary><c>Shifts the Items between </c>AFromIndex<c> and </c>AFromIndex + ACount<c> to the range </c>AToIndex<c> and </c>AToIndex + ACount<c> in a single (efficient) operation.</c></summary>
procedure Move(const AFromIndex, AToIndex, ACount: Integer);
// Properties
/// <summary><c>Sets the Allocated Capacity to the given value.</c></summary>
/// <returns><c>The current Allocated Capacity of this Array.</c></returns>
property Capacity: Integer read GetCapacity write SetCapacity;
/// <summary><c>Assigns the given Item into the Array at the given Index.</c></summary>
/// <returns><c>The Item from the Array at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem write SetItem; default;
/// <returns><c>Read-Only Interfaced Reference to this Array.</c></returns>
property Reader: IADArrayReader<T> read GetReader;
end;
/// <summary><c>Common Type-Insensitive Read-Only Interface for all Generic Collections.</c></summary>
/// <remarks>
/// <para><c>All Collection Classes should implement this Interface AS WELL AS their Context-Specific Interface(s).</c></para>
/// </remarks>
IADCollectionReader = interface(IADInterface)
['{1083E5D0-8D0F-4ABB-9479-AEF8E26BE663}']
// Getters
/// <returns><c>The present Capacity of the Collection.</c></returns>
function GetCapacity: Integer;
/// <returns><c>The nunmber of Items in the Collection.</c></returns>
function GetCount: Integer;
/// <returns><c>The initial Capacity of the Collection (at the point of Construction).</c></returns>
function GetInitialCapacity: Integer;
/// <summary><c>Determines whether or not the List is Compact.</c></summary>
/// <returns>
/// <para>True<c> if the List is Compact.</c></para>
/// <para>False<c> if the List is NOT Compact.</c></para>
/// </returns>
function GetIsCompact: Boolean;
/// <returns>
/// <para>True<c> if there are NO Items in the Collection.</c></para>
/// <para>False<c> if there are Items in the Collection.</c></para>
/// </returns>
function GetIsEmpty: Boolean;
/// <returns>
/// <para>ssSorted<c> if the Collection is Sorted.</c></para>
/// <para>ssUnsorted<c> if the Collection is NOT Sorted.</c></para>
/// <para>ssUnknown<c> if the Sorted State of the Collection is Unknown.</c></para>
/// </returns>
function GetSortedState: TADSortedState;
// Properties
/// <returns><c>The present Capacity of the Collection.</c></returns>
property Capacity: Integer read GetCapacity;
/// <returns><c>The nunmber of Items in the Collection.</c></returns>
property Count: Integer read GetCount;
/// <returns><c>The initial Capacity of the Collection (at the point of Construction).</c></returns>
property InitialCapacity: Integer read GetInitialCapacity;
/// <returns>
/// <para>True<c> if the Collection is Compact.</c></para>
/// <para>False<c> if the Collection is NOT Compact.</c></para>
/// </returns>
property IsCompact: Boolean read GetIsCompact;
/// <returns>
/// <para>True<c> if there are NO Items in the Collection.</c></para>
/// <para>False<c> if there are Items in the Collection.</c></para>
/// </returns>
property IsEmpty: Boolean read GetIsEmpty;
/// <returns>
/// <para>ssSorted<c> if the Collection is Sorted.</c></para>
/// <para>ssUnsorted<c> if the Collection is NOT Sorted.</c></para>
/// <para>ssUnknown<c> if the Sorted State of the Collection is Unknown.</c></para>
/// </returns>
property SortedState: TADSortedState read GetSortedState;
end;
/// <summary><c>Common Type-Insensitive Interface for all Generic Collections.</c></summary>
/// <remarks>
/// <para><c>All Collection Classes should implement this Interface AS WELL AS their Context-Specific Interface(s).</c></para>
/// </remarks>
IADCollection = interface(IADCollectionReader)
['{B75BF54B-1400-4EFD-96A5-278E9F101B35}']
// Getters
/// <returns><c>Read-Only Interfaced Reference to this Collection.</c></returns>
function GetReader: IADCollectionReader;
// Setters
/// <summary><c>Manually specify the Capacity of the Collection.</c></summary>
/// <remarks>
/// <para><c>Note that the Capacity should always be equal to or greater than the Count.</c></para>
/// </remarks>
procedure SetCapacity(const ACapacity: Integer);
// Management Methods
/// <summary><c>Removes all Items from the Collection.</c></summary>
procedure Clear;
// Properties
/// <summary><c>Manually specify the Capacity of the Collection.</c></summary>
/// <remarks>
/// <para><c>Note that the Capacity should always be equal to or greater than the Count.</c></para>
/// </remarks>
/// <returns><c>The present Capacity of the Collection.</c></returns>
property Capacity: Integer read GetCapacity write SetCapacity;
/// <returns><c>Read-Only Interfaced Reference to this Collection.</c></returns>
property Reader: IADCollectionReader read GetReader;
end;
/// <summary><c>An Allocation Algorithm for Lists.</c></summary>
/// <remarks><c>Dictates how to grow an Array based on its current Capacity and the number of Items we're looking to Add/Insert.</c></remarks>
IADExpander = interface(IADInterface)
['{B4742A80-74A7-408E-92BA-F854515B6D24}']
function CheckExpand(const ACapacity, ACurrentcount, AAdditionalRequired: Integer): Integer;
end;
/// <summary><c>A Geometric Allocation Algorithm for Lists.</c></summary>
/// <remarks>
/// <para><c>When the number of Vacant Slots falls below the Threshold, the number of Vacant Slots increases by the value of the current Capacity multiplied by the Mulitplier.</c></para>
/// </remarks>
IADExpanderGeometric = interface(IADExpander)
['{CAF4B15C-9BE5-4A66-B31F-804AB752A102}']
// Getters
function GetCapacityMultiplier: Single;
function GetCapacityThreshold: Integer;
// Setters
procedure SetCapacityMultiplier(const AMultiplier: Single);
procedure SetCapacityThreshold(const AThreshold: Integer);
// Properties
property CapacityMultiplier: Single read GetCapacityMultiplier write SetCapacityMultiplier;
property CapacityThreshold: Integer read GetCapacityThreshold write SetCapacityThreshold;
end;
/// <summary><c>Provides Getter and Setter for any Type utilizing a Expander Type.</c></summary>
IADExpandable = interface(IADInterface)
['{586ED0C9-E067-468F-B929-92F086E43D91}']
// Getters
function GetExpander: IADExpander;
// Setters
procedure SetExpander(const AExpander: IADExpander);
// Properties
property Expander: IADExpander read GetExpander write SetExpander;
end;
/// <summary><c>A Deallocation Algorithm for Lists.</c></summary>
/// <remarks><c>Dictates how to shrink an Array based on its current Capacity and the number of Items we're looking to Delete.</c></remarks>
IADCompactor = interface(IADInterface)
['{B7D577D4-8425-4C5D-9DDB-5864C3676199}']
function CheckCompact(const ACapacity, ACurrentCount, AVacating: Integer): Integer;
end;
/// <summary><c>Provides Getter and Setter for any Type utilizing a Compactor Type.</c></summary>
IADCompactable = interface(IADInterface)
['{13208869-7530-4B3A-89D4-AFA2B164536B}']
// Getters
function GetCompactor: IADCompactor;
// Setters
procedure SetCompactor(const ACompactor: IADCompactor);
// Management Method
/// <summary><c>Compacts the size of the underlying Array to the minimum required Capacity.</c></summary>
/// <remarks>
/// <para><c>Note that any subsequent addition to the List will need to expand the Capacity and could lead to reallocation.</c></para>
/// </remarks>
procedure Compact;
// Properties
property Compactor: IADCompactor read GetCompactor write SetCompactor;
end;
/// <summary><c>Common Behaviour for List and Map Sorters.</c></summary>
IADSorter = interface(IADInterface)
['{C52DB3EA-FEF4-4BD8-8332-D867907CEACA}']
end;
/// <summary><c>Sorting Alogirthm for Lists.</c></summary>
IADListSorter<T> = interface(IADSorter)
procedure Sort(const AArray: IADArray<T>; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload;
procedure Sort(AArray: Array of T; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload;
end;
/// <summary><c>Sorting Alogirthm for Maps.</c></summary>
IADMapSorter<TKey, TValue> = interface(IADSorter)
procedure Sort(const AArray: IADArray<IADKeyValuePair<TKey, TValue>>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload;
procedure Sort(AArray: Array of IADKeyValuePair<TKey, TValue>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload;
end;
/// <summary><c>Common Iterator Methods for all List-Type Collections.</c></summary>
/// <remarks>
/// <para><c>All List-Type Collection Classes should implement this Interface AS WELL AS their Context-Specific Interface(s).</c></para>
/// </remarks>
IADIterableList<T> = interface(IADInterface)
// Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListItemCallbackAnon<T>; const ADirection: TADIterateDirection = idRight); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListItemCallbackOfObject<T>; const ADirection: TADIterateDirection = idRight); overload;
procedure Iterate(const ACallback: TADListItemCallbackUnbound<T>; const ADirection: TADIterateDirection = idRight); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListItemCallbackOfObject<T>); overload;
procedure IterateBackward(const ACallback: TADListItemCallbackUnbound<T>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListItemCallbackOfObject<T>); overload;
procedure IterateForward(const ACallback: TADListItemCallbackUnbound<T>); overload;
end;
/// <summary><c>Common Iterator Methods for all Map-Type Collections.</c></summary>
/// <remarks>
/// <para><c>All Map-Type Collection Classes should implement this Interface AS WELL AS their Context-Specific Interface(s).</c></para>
/// </remarks>
IADIterableMap<TKey, TValue> = interface(IADInterface)
// Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListMapCallbackAnon<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListMapCallbackOfObject<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload;
procedure Iterate(const ACallback: TADListMapCallbackUnbound<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); overload;
procedure IterateBackward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); overload;
procedure IterateForward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); overload;
end;
/// <summary><c>Common Type-Insensitive Read-Only Interface for all List Collections.</c></summary>.
IADListReader<T> = interface(IADCollection)
// Getters
/// <returns><c>The Item at the given Index.</c></returns>
function GetItem(const AIndex: Integer): T;
/// <returns><c>Iterator Interfaced Reference for this List.</c></returns>
function GetIterator: IADIterableList<T>;
// Properties
/// <returns><c>The Item at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem; default;
/// <returns><c>Iterator Interfaced Reference for this List.</c></returns>
property Iterator: IADIterableList<T> read GetIterator;
end;
/// <summary><c>Common Type-Insensitive Read/Write Interface for all List Collections.</c></summary>.
IADList<T> = interface(IADListReader<T>)
// Getters
/// <returns><c>Read-Only Interfaced Reference to this List.</c></returns>
function GetReader: IADListReader<T>;
// Setters
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
procedure SetItem(const AIndex: Integer; const AItem: T);
// Management Methods
/// <summary><c>Adds the given Item into the Collection.</c></summary>
/// <returns><c>The Index of the Item in the Collection.</c></returns>
function Add(const AItem: T): Integer; overload;
/// <summary><c>Adds Items from the given List into this List.</c></summary>
procedure Add(const AItems: IADListReader<T>); overload;
/// <summary><c>Adds multiple Items into the Collection.</c></summary>
procedure AddItems(const AItems: Array of T);
/// <summary><c>Deletes the Item at the given Index.</c></summary>
procedure Delete(const AIndex: Integer);
/// <summary><c>Deletes the Items from the Start Index to Start Index + Count.</c></summary>
procedure DeleteRange(const AFirst, ACount: Integer);
/// <summary><c>Insert the given Item at the specified Index.</c></summary>
/// <remarks><c>Will Expand the List if necessary.</c></remarks>
procedure Insert(const AItem: T; const AIndex: Integer);
/// <summary><c>Insert the given Items starting at the specified Index.</c></summary>
/// <remarks><c>Will Expand the List if necessary.</c></remarks>
procedure InsertItems(const AItems: Array of T; const AIndex: Integer);
/// <summary><c>Sort the List using the Default Sorter and the given Comparer</c></summary>
procedure Sort(const AComparer: IADComparer<T>); overload;
/// <summary><c>Sort the List using the given Sorter and the given Comparer</c></summary>
procedure Sort(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>); overload;
/// <summary><c>Sort PART of the List using the Default Sorter and the given Comparer</c></summary>
procedure SortRange(const AComparer: IADComparer<T>; const AFromIndex: Integer; const AToIndex: Integer); overload;
/// <summary><c>Sort PART of the List using the given Sorter and the given Comparer</c></summary>
procedure SortRange(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>; const AFromIndex: Integer; const AToIndex: Integer); overload;
// Properties
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
/// <returns><c>The Item at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem write SetItem; default;
/// <returns><c>Read-Only Interfaced Reference to this List.</c></returns>
property Reader: IADListReader<T> read GetReader;
end;
/// <summary><c>Read-Only Interface for all Sorted List Types.</c></summary>
IADSortedListReader<T> = interface(IADListReader<T>)
// Management Methods
/// <summary><c>Performs a Lookup to determine whether the given Item is in the List.</c></summary>
/// <returns>
/// <para>True<c> if the Item is in the List.</c></para>
/// <para>False<c> if the Item is NOT in the List.</c></para>
/// </returns>
function Contains(const AItem: T): Boolean;
/// <summary><c>Performs Lookups to determine whether the given Items are ALL in the List.</c></summary>
/// <returns>
/// <para>True<c> if ALL Items are in the List.</c></para>
/// <para>False<c> if NOT ALL Items are in the List.</c></para>
/// </returns>
function ContainsAll(const AItems: Array of T): Boolean;
/// <summary><c>Performs Lookups to determine whether ANY of the given Items are in the List.</c></summary>
/// <returns>
/// <para>True<c> if ANY of the Items are in the List.</c></para>
/// <para>False<c> if NONE of the Items are in the List.</c></para>
/// </returns>
function ContainsAny(const AItems: Array of T): Boolean;
/// <summary><c>Performs Lookups to determine whether ANY of the given Items are in the List.</c></summary>
/// <returns>
/// <para>True<c> if NONE of the Items are in the List.</c></para>
/// <para>False<c> if ANY of the Items are in the List.</c></para>
function ContainsNone(const AItems: Array of T): Boolean;
/// <summary><c>Compares each Item in this List against those in the Candidate List to determine Equality.</c></summary>
/// <returns>
/// <para>True<c> ONLY if the Candidate List contains ALL Items from this List, and NO additional Items.</c></para>
/// <para>False<c> if not all Items are present or if any ADDITIONAL Items are present.</c></para>
/// </returns>
/// <remarks>
/// <para><c>This ONLY compares Items, and does not include ANY other considerations.</c></para>
/// </remarks>
function EqualItems(const AList: IADList<T>): Boolean;
/// <summary><c>Retreives the Index of the given Item within the List.</c></summary>
/// <returns>
/// <para>-1<c> if the given Item is not in the List.</c></para>
/// <para>0 or Greater<c> if the given Item IS in the List.</c></para>
/// </returns>
function IndexOf(const AItem: T): Integer;
end;
/// <summary><c>Read/Write Interface for all Sorted List Types.</c></summary>
IADSortedList<T> = interface(IADSortedListReader<T>)
// Getters
/// <returns><c>Read-Only Interfaced Reference to this List.</c></returns>
function GetReader: IADSortedListReader<T>;
// Setters
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
procedure SetItem(const AIndex: Integer; const AItem: T);
// Management Methods
/// <summary><c>Adds the given Item into the Collection.</c></summary>
/// <returns><c>The Index of the Item in the Collection.</c></returns>
function Add(const AItem: T): Integer; overload;
/// <summary><c>Adds Items from the given List into this List.</c></summary>
procedure Add(const AItems: IADListReader<T>); overload;
/// <summary><c>Adds multiple Items into the Collection.</c></summary>
procedure AddItems(const AItems: Array of T);
/// <summary><c>Deletes the Item at the given Index.</c></summary>
procedure Delete(const AIndex: Integer);
/// <summary><c>Deletes the Items from the Start Index to Start Index + Count.</c></summary>
procedure DeleteRange(const AFirst, ACount: Integer);
/// <summary><c>Insert the given Item at the specified Index.</c></summary>
/// <remarks><c>Will Expand the List if necessary.</c></remarks>
procedure Insert(const AItem: T; const AIndex: Integer);
/// <summary><c>Insert the given Items starting at the specified Index.</c></summary>
/// <remarks><c>Will Expand the List if necessary.</c></remarks>
procedure InsertItems(const AItems: Array of T; const AIndex: Integer);
/// <summary><c>Deletes the given Item from the List.</c></summary>
/// <remarks><c>Performs a Lookup to divine the given Item's Index.</c></remarks>
procedure Remove(const AItem: T);
/// <summary><c>Deletes the given Items from the List.</c></summary>
/// <remarks><c>Performs a Lookup for each Item to divine their respective Indexes.</c></remarks>
procedure RemoveItems(const AItems: Array of T);
// Properties
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
/// <returns><c>The Item at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem write SetItem; default;
/// <returns><c>Read-Only Interfaced Reference to this List.</c></returns>
property Reader: IADSortedListReader<T> read GetReader;
end;
/// <summary><c>Common Type-Insensitive Read-Only Interface for all Map Collections.</c></summary>.
IADMapReader<TKey, TValue> = interface(IADCollection)
// Getters
/// <returns><c>The Item corresponding to the given Key.</c></returns>
function GetItem(const AKey: TKey): TValue;
/// <returns><c>Iterator Interfaced Reference for this Map.</c></returns>
function GetIterator: IADIterableMap<TKey, TValue>;
/// <returns><c>The Key-Value Pair at the given Index.</c></returns>
function GetPair(const AIndex: Integer): IADKeyValuePair<TKey, TValue>;
/// <returns><c>The Sorting Algorithm for the Map.</c></returns>
function GetSorter: IADMapSorter<TKey, TValue>;
// Management Methods
/// <summary><c>Performs a Lookup to determine whether the given Item is in the Map.</c></summary>
/// <returns>
/// <para>True<c> if the Item is in the List.</c></para>
/// <para>False<c> if the Item is NOT in the Map.</c></para>
/// </returns>
function Contains(const AKey: TKey): Boolean;
/// <summary><c>Performs Lookups to determine whether the given Items are ALL in the Map.</c></summary>
/// <returns>
/// <para>True<c> if ALL Items are in the Map.</c></para>
/// <para>False<c> if NOT ALL Items are in the Map.</c></para>
/// </returns>
function ContainsAll(const AKeys: Array of TKey): Boolean;
/// <summary><c>Performs Lookups to determine whether ANY of the given Items are in the Map.</c></summary>
/// <returns>
/// <para>True<c> if ANY of the Items are in the Map.</c></para>
/// <para>False<c> if NONE of the Items are in the Map.</c></para>
/// </returns>
function ContainsAny(const AKeys: Array of TKey): Boolean;
/// <summary><c>Performs Lookups to determine whether ANY of the given Items are in the Map.</c></summary>
/// <returns>
/// <para>True<c> if NONE of the Items are in the Map.</c></para>
/// <para>False<c> if ANY of the Items are in the Map.</c></para>
function ContainsNone(const AKeys: Array of TKey): Boolean;
/// <summary><c>Compares each Item in this Map against those in the Candidate Map to determine Equality.</c></summary>
/// <returns>
/// <para>True<c> ONLY if the Candidate Map contains ALL Items from this Map, and NO additional Items.</c></para>
/// <para>False<c> if not all Items are present or if any ADDITIONAL Items are present.</c></para>
/// </returns>
/// <remarks>
/// <para><c>This ONLY compares Items, and does not include ANY other considerations.</c></para>
/// </remarks>
function EqualItems(const AMap: IADMapReader<TKey, TValue>): Boolean;
/// <summary><c>Retreives the Index of the given Item within the Map.</c></summary>
/// <returns>
/// <para>-1<c> if the given Item is not in the Map.</c></para>
/// <para>0 or Greater<c> if the given Item IS in the Map.</c></para>
/// </returns>
function IndexOf(const AKey: TKey): Integer;
// Properties
/// <returns><c>The Item corresponding to the given Key.</c></returns>
property Items[const AKey: TKey]: TValue read GetItem; default;
/// <returns><c>Iterator Interfaced Reference for this Map.</c></returns>
property Iterator: IADIterableMap<TKey, TValue> read GetIterator;
/// <returns><c>The Key-Value Pair at the given Index.</c></returns>
property Pairs[const AIndex: Integer]: IADKeyValuePair<TKey, TValue> read GetPair;
/// <returns><c>The Sorting Algorithm for the Map.</c></returns>
property Sorter: IADMapSorter<TKey, TValue> read GetSorter;
end;
/// <summary><c>Common Type-Insensitive Read/Write Interface for all Map Collections.</c></summary>.
IADMap<TKey, TValue> = interface(IADMapReader<TKey, TValue>)
// Getters
/// <returns><c>Read-Only Interfaced Reference to this Map.</c></returns>
function GetReader: IADMapReader<TKey, TValue>;
// Setters
/// <summary><c>Assigns the given Value to the given Key (replacing any existing Value.)</c></summary>
procedure SetItem(const AKey: TKey; const AValue: TValue);
/// <summary><c>Defines the Sorting Algorithm for the Map.</c></summary>
procedure SetSorter(const ASorter: IADMapSorter<TKey, TValue>);
// Management Methods
/// <summary><c>Adds the given Key-Value Pair into the Map.</c></summary>
/// <returns>
/// <para><c>The Index of the Item in the Map.</c></para>
/// </returns>
function Add(const AItem: IADKeyValuePair<TKey, TValue>): Integer; overload;
/// <summary><c>Adds the given Key-Value Pair into the Map.</c></summary>
/// <returns>
/// <para><c>The Index of the Item in the Map.</c></para>
/// </returns>
function Add(const AKey: TKey; const AValue: TValue): Integer; overload;
/// <summary><c>Adds multiple Items into the Map.</c></summary>
procedure AddItems(const AItems: Array of IADKeyValuePair<TKey, TValue>); overload;
/// <summary><c>Adds Items from the given Map into this Map.</c></summary>
procedure AddItems(const AMap: IADMapReader<TKey, TValue>); overload;
/// <summary><c>Compacts the size of the underlying Array to the minimum required Capacity.</c></summary>
/// <remarks>
/// <para><c>Note that any subsequent addition to the Map will need to expand the Capacity and could lead to reallocation.</c></para>
/// </remarks>
procedure Compact;
/// <summary><c>Deletes the Item at the given Index.</c></summary>
procedure Delete(const AIndex: Integer); overload;
/// <summary><c>Deletes the Items from the Start Index to Start Index + Count.</c></summary>
procedure DeleteRange(const AFromIndex, ACount: Integer); overload;
/// <summary><c>Deletes the given Item from the Map.</c></summary>
/// <remarks><c>Performs a Lookup to divine the given Item's Index.</c></remarks>
procedure Remove(const AKey: TKey);
/// <summary><c>Deletes the given Items from the Map.</c></summary>
/// <remarks><c>Performs a Lookup for each Item to divine their respective Indexes.</c></remarks>
procedure RemoveItems(const AKeys: Array of TKey);
// Properties
/// <summary><c>Assigns the given Value to the given Key (replacing any existing Value.)</c></summary>
/// <returns><c>The Item corresponding to the given Key.</c></returns>
property Items[const AKey: TKey]: TValue read GetItem write SetItem; default;
/// <returns><c>Read-Only Interfaced Reference to this Map.</c></returns>
property Reader: IADMapReader<TKey, TValue> read GetReader;
/// <summary><c>Defines the Sorting Algorithm for the Map.</c></summary>
/// <returns><c>The Sorting Algorithm for the Map.</c></returns>
property Sorter: IADMapSorter<TKey, TValue> read GetSorter write SetSorter;
end;
/// <summary><c>A Generic Fixed-Capacity Revolving List</c></summary>
/// <remarks>
/// <para><c>Accessible in Read-Only Mode.</c></para>
/// </remarks>
IADCircularListReader<T> = interface(IADListReader<T>)
// Getters
/// <returns>
/// <para>-1<c> if the Newest Item has subsequently been Deleted (or Invalidated).</c></para>
/// <para>0 or Greater<c> if the Newest Item is still Valid.</c></para>
/// </returns>
function GetNewestIndex: Integer;
/// <returns><c>The Newest Item.</c></returns>
function GetNewest: T;
/// <returns>
/// <para>-1<c> if the Oldest Item has subsequently been Deleted (or Invalidated).</c></para>
/// <para>0 or Greater<c> if the Oldest Item is still Valid.</c></para>
/// </returns>
function GetOldestIndex: Integer;
/// <returns><c>The Oldest Item.</c></returns>
function GetOldest: T;
// Properties
/// <returns>
/// <para>-1<c> if the Newest Item has subsequently been Deleted (or Invalidated).</c></para>
/// <para>0 or Greater<c> if the Newest Item is still Valid.</c></para>
/// </returns>
property NewestIndex: Integer read GetNewestIndex;
/// <returns><c>The Newest Item.</c></returns>
property Newest: T read GetNewest;
/// <returns>
/// <para>ssSorted<c> if the Collection is Sorted.</c></para>
/// <para>ssUnsorted<c> if the Collection is NOT Sorted.</c></para>
/// <para>ssUnknown<c> if the Sorted State of the Collection is Unknown.</c></para>
/// </returns>
property OldestIndex: Integer read GetOldestIndex;
/// <returns><c>The Oldest Item.</c></returns>
property Oldest: T read GetOldest;
end;
/// <summary><c>A Generic Fixed-Capacity Revolving List</c></summary>
/// <remarks>
/// <para><c>Accessible in Read/Write Mode.</c></para>
/// </remarks>
IADCircularList<T> = interface(IADCircularListReader<T>)
// Getters
/// <returns><c>Read-Only Interfaced Reference to this Circular List.</c></returns>
function GetReader: IADCircularListReader<T>;
// Setters
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
procedure SetItem(const AIndex: Integer; const AItem: T);
// Management Methods
/// <summary><c>Adds the given Item into the Collection.</c></summary>
/// <returns><c>The Index of the Item in the Collection.</c></returns>
function Add(const AItem: T): Integer; overload;
/// <summary><c>Adds Items from the given List into this List.</c></summary>
procedure Add(const AItems: IADListReader<T>); overload;
/// <summary><c>Adds multiple Items into the Collection.</c></summary>
procedure AddItems(const AItems: Array of T);
/// <summary><c>Deletes the Item at the given Index.</c></summary>
procedure Delete(const AIndex: Integer);
/// <summary><c>Deletes the Items from the Start Index to Start Index + Count.</c></summary>
procedure DeleteRange(const AFirst, ACount: Integer);
// Properties
/// <summary><c>Assigns the given Item to the given Index.</c></summary>
/// <returns><c>The Item at the given Index.</c></returns>
property Items[const AIndex: Integer]: T read GetItem write SetItem; default;
/// <returns><c>Read-Only Interfaced Reference to this Circular List.</c></returns>
property Reader: IADCircularListReader<T> read GetReader;
end;
/// <summary><c>Generic Interface for Read-Only Tree Nodes.</c></summary>
/// <remarks>
/// <para><c>Accessible in Read-Only Mode.</c></para>
/// </remarks>
IADTreeNodeReader<T> = interface(IADInterface)
// Geters
/// <returns><c>The number of Child Nodes directly beneath the given Node.</c></returns>
function GetChildCount: Integer;
/// <returns><c>The number of Child Nodes beneath the given Node, and all of their respective Child Nodes.</c></returns>
/// <remarks><c>This is an Aggregate Total, and can be computationally expensive. Use only when you really need to.</c></remarks>
function GetChildCountRecursive: Integer;
/// <returns><c>The Child Reader for the given Index.</c></returns>
function GetChildReader(const AIndex: Integer): IADTreeNodeReader<T>;
/// <returns><c>The Depth of the given Node relative to the Root.</c></returns>
function GetDepth: Integer;
/// <returns><c>The Index of the given Node relative to its Parent Node.</c></returns>
/// <remarks><c>Returns -1 if there is no Parent Node.</c></remarks>
function GetIndexAsChild: Integer;
/// <returns><c>The Child Index of the given Node relative to this one.</c></returns>
/// <remarks><c>Will return -1 if the given Node is NOT a Child of this one.</c></returns>
function GetIndexOf(const AChild: IADTreeNodeReader<T>): Integer;
/// <returns><c>Is the given Node a Branch.</c></returns>
function GetIsBranch: Boolean;
/// <returns><c>Is the given Node a Leaf.</c></returns>
function GetIsLeaf: Boolean;
/// <returns><c>Is the given Node the Root.</c></returns>
function GetIsRoot: Boolean;
/// <returns><c>Reference to the Parent of the given Node.</c></returns>
/// <remarks><c>This reference would be Nil for the Root Node.</c></summary>
function GetParentReader: IADTreeNodeReader<T>;
/// <returns><c>Reference to the Root Node.</c></returns>
/// <remarks><c>This reference would be Self for the Root Node.</c></remarks>
function GetRootReader: IADTreeNodeReader<T>;
/// <returns><c>The Value specialized to the given Generic Type.</c></returns>
function GetValue: T;
// Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
// Properties
/// <returns><c>The number of Child Nodes directly beneath the given Node.</c></returns>
property ChildCount: Integer read GetChildCount;
/// <returns><c>The number of Child Nodes beneath the given Node, and all of their respective Child Nodes.</c></returns>
/// <remarks><c>This is an Aggregate Total, and can be computationally expensive. Use only when you really need to.</c></remarks>
property ChildCountRecursive: Integer read GetChildCountRecursive;
/// <returns><c>The Child Reader for the given Index.</c></returns>
property ChildReader[const AIndex: Integer]: IADTreeNodeReader<T> read GetChildReader; default;
/// <returns><c>The Depth of the given Node relative to the Root.</c></returns>
property Depth: Integer read GetDepth;
/// <returns><c>The Index of the given Node relative to its Parent Node.</c></returns>
/// <remarks><c>Returns -1 if there is no Parent Node.</c></remarks>
property IndexAsChild: Integer read GetIndexAsChild;
/// <returns><c>The Child Index of the given Node relative to this one.</c></returns>
/// <remarks><c>Will return -1 if the given Node is NOT a Child of this one.</c></returns>
property IndexOf[const AChild: IADTreeNodeReader<T>]: Integer read GetIndexOf;
/// <returns><c>Is the given Node a Branch.</c></returns>
property IsBranch: Boolean read GetIsBranch;
/// <returns><c>Is the given Node a Leaf.</c></returns>
property IsLeaf: Boolean read GetIsLeaf;
/// <returns><c>Is the given Node the Root.</c></returns>
property IsRoot: Boolean read GetIsRoot;
/// <returns><c>Reference to the Parent of the given Node.</c></returns>
/// <remarks><c>This reference would be Nil for the Root Node.</c></summary>
property ParentReader: IADTreeNodeReader<T> read GetParentReader;
/// <returns><c>Reference to the Root Node.</c></returns>
/// <remarks><c>This reference would be Self for the Root Node.</c></remarks>
property RootReader: IADTreeNodeReader<T> read GetRootReader;
/// <returns><c>The Value specialized to the given Generic Type.</c></returns>
property Value: T read GetValue;
end;
/// <summary><c>Generic Interface for Read-Only Tree Nodes.</c></summary>
/// <remarks>
/// <para><c>Accessible in Read/Write Mode.</c></para>
/// </remarks>
IADTreeNode<T> = interface(IADTreeNodeReader<T>)
// Getters
/// <returns><c>Returns the Child at the given Index.</c></returns>
function GetChild(const AIndex: Integer): IADTreeNode<T>;
/// <returns><c>Reference to the Parent of the given Node.</c></returns>
/// <remarks><c>This reference would be Nil for the Root Node.</c></summary>
function GetParent: IADTreeNode<T>;
/// <returns><c>Read-Only Interface Reference for this Tree Node.</c></returns>
function GetReader: IADTreeNodeReader<T>;
/// <returns><c>Reference to the Root Node.</c></returns>
/// <remarks><c>This reference would be Self for the Root Node.</c></remarks>
function GetRoot: IADTreeNode<T>;
// Setters
/// <summary><c>Defines the Parent Node for this Node.</c></summary>
/// <remarks>
/// <para><c>Nil will unparent this Node from any existing Parent.</c></para>
/// <para><c>You can ONLY use a Read/Write Tree Node reference.</c></para>
/// </remarks>
procedure SetParent(const AParent: IADTreeNode<T>);
/// <summary><c>Defines the Value for this Node.</c></summary>
procedure SetValue(const AValue: T);
// Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, down, and executes the given Callback.</c></summary>
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>); overload;
/// <summary><c>Steps recursively through the Tree from the current node, up, and executes the given Callback.</c></summary>
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
// Management Methods
/// <summary><c>Adds the given Node as a Child of this Node.</c></summary>
procedure AddChild(const AChild: IADTreeNode<T>; const AIndex: Integer = -1);
/// <summary><c>Moves this Node to become a Child of the defined Parent Node, at the (optional) given Index.</c></summary>
/// <remarks><c>If no AIndex value is defined, it will become the new LAST Child of the new Parent Node.</c></remarks>
procedure MoveTo(const ANewParent: IADTreeNode<T>; const AIndex: Integer = -1); overload;
/// <summary><c>Moves this Child Node to a designated Child Index of its current Parent Node.</c></summary>
procedure MoveTo(const AIndex: Integer); overload;
/// <summary><c>Removes the given Node from this Node's Children.</c></summary>
procedure RemoveChild(const AChild: IADTreeNodeReader<T>);
/// <returns><c>Returns the Child at the given Index.</c></returns>
property Child[const AIndex: Integer]: IADTreeNode<T> read GetChild; default;
/// <summary><c>Defines the Parent Node for this Node.</c></summary>
/// <remarks>
/// <para><c>This reference would be Nil for the Root Node.</c></para>
/// <para><c>Nil will unparent this Node from any existing Parent.</c></para>
/// <para><c>You can ONLY use a Read/Write Tree Node reference.</c></para>
/// </remarks>
/// <returns><c>Reference to the Parent of the given Node.</c></returns>
property Parent: IADTreeNode<T> read GetParent write SetParent;
/// <returns><c>Read-Only Interface Reference for this Tree Node.</c></returns>
property Reader: IADTreeNodeReader<T> read GetReader;
/// <returns><c>Reference to the Root Node.</c></returns>
/// <remarks><c>This reference would be Self for the Root Node.</c></remarks>
property Root: IADTreeNode<T> read GetRoot;
/// <summary><c>Defines the Value for this Node.</c></summary>
/// <returns><c>The Value specialized to the given Generic Type.</c></returns>
property Value: T read GetValue write SetValue;
end;
/// <summary><c>Read-Only Interface for the special Stack/Queue Collection.</c></summary>
/// <remarks>
/// <para><c>Call .Iterator to get the IADIterableList Interface Reference.</c></para>
/// </remarks>
IADStackQueueReader<T> = interface(IADInterface)
// Getters
/// <returns><c>The total number of Items in the Queue AND Stack (full Priority range).</c></returns>
function GetCount: Integer; overload;
/// <returns><c>The total number of Items in the Queue AND Stack for the given Priority.</c></returns>
function GetCount(const APriority: Integer): Integer; overload;
/// <returns><c>An IADIterableList Interface Reference for this Stack/Queue.</c></returns>
function GetIterator: IADIterableList<T>;
/// <returns><c>The number of Items in the Queue (full Priority range).</c></returns>
function GetQueueCount: Integer; overload;
/// <returns><c>The number of Items in the Queue for the given Priority.</c></returns>
function GetQueueCount(const APriority: Integer): Integer; overload;
/// <returns><c>The number of Items in the Stack (full Priority range).</c></returns>
function GetStackCount: Integer; overload;
/// <returns><c>The number of Items in the Stack for the given Priority.</c></returns>
function GetStackCount(const APriority: Integer): Integer; overload;
// Properties
/// <returns><c>The total number of Items in the Queue AND Stack (full Priority range).</c></returns>
property CountTotal: Integer read GetCount;
/// <returns><c>The total number of Items in the Queue AND Stack for the given Priority.</c></returns>
property Count[const APriority: Integer]: Integer read GetCount;
/// <returns><c>An IADIterableList Interface Reference for this Stack/Queue.</c></returns>
property Iterator: IADIterableList<T> read GetIterator;
/// <returns><c>The number of Items in the Queue (full Priority range).</c></returns>
property QueueTotalCount: Integer read GetQueueCount;
/// <returns><c>The number of Items in the Queue for the given Priority.</c></returns>
property QueueCount[const APriority: Integer]: Integer read GetQueueCount;
/// <returns><c>The number of Items in the Stack (full Priority range).</c></returns>
property StackTotalCount: Integer read GetStackCount;
/// <returns><c>The number of Items in the Stack for the given Priority.</c></returns>
property StackCount[const APriority: Integer]: Integer read GetStackCount;
end;
/// <summary><c>Read/Write Interface for the special Stack/Queue Collection.</c></summary>
/// <remarks>
/// <para><c>Use IADStackQueueReader for Read-Only access.</c></para>
/// <para><c>Call .Reader to get an IADStackQueueReader Interface Reference to this Stack/Queue Object.</c></para>
/// </remarks>
IADStackQueue<T> = interface(IADStackQueueReader<T>)
// Getters
/// <returns><c>A Read-Only Interface Reference to this Stack/Queue.</c></returns>
function GetReader: IADStackQueueReader<T>;
// Management Methods
/// <summary><c>Adds an Item to the Queue with the Middle Priority.</c></summary>
procedure Queue(const AItem: T); overload;
/// <summary><c>Adds an Item to the Queue with the given Priority.</c></summary>
procedure Queue(const AItem: T; const APriority: Integer); overload;
/// <summary><c>Adds a List of Items to the Queue with the Middle Priority.</c></summary>
procedure Queue(const AItems: IADListReader<T>); overload;
/// <summary><c>Adds a List of Items to the Queue with the given Priority.</c></summary>
procedure Queue(const AItems: IADListReader<T>; const APriority: Integer); overload;
/// <summary><c>Adds an Array of Items to the Queue with the Middle Priority.</c></summary>
procedure Queue(const AItems: Array of T); overload;
/// <summary><c>Adds an Array of Items to the Queue with the given Priority.</c></summary>
procedure Queue(const AItems: Array of T; const APriority: Integer); overload;
/// <summary><c>Adds an Item to the Stack with the Middle Priority.</c></summary>
procedure Stack(const AItem: T); overload;
/// <summary><c>Adds an Item to the Stack with the given Priority.</c></summary>
procedure Stack(const AItem: T; const APriority: Integer); overload;
/// <summary><c>Adds a List of Items to the Stack with the Middle Priority.</c></summary>
procedure Stack(const AItems: IADListReader<T>); overload;
/// <summary><c>Adds a List of Items to the Stack with the given Priority.</c></summary>
procedure Stack(const AItems: IADListReader<T>; const APriority: Integer); overload;
/// <summary><c>Adds an Array of Items to the Stack with the Middle Priority.</c></summary>
procedure Stack(const AItems: Array of T); overload;
/// <summary><c>Adds an Array of Items to the Stack with the given Priority.</c></summary>
procedure Stack(const AItems: Array of T; const APriority: Integer); overload;
// Specialized Queue Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Queue when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessQueue(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Queue when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessQueue(const AOnItem: TADListItemCallbackOfObject<T>); overload;
/// <summary><c>Iterates the Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Queue when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessQueue(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Specialized Stack Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Stack (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStack(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Stack (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStack(const AOnItem: TADListItemCallbackOfObject<T>); overload;
/// <summary><c>Iterates the Stack (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack when it has been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStack(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Specialized Stack/Queue Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Stack and Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack and Queue when they have been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Iterates the Stack and Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack and Queue when they have been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackOfObject<T>); overload;
/// <summary><c>Iterates the Stack and Queue (fully Priority range, in order) and invokes the AOnItem Callback.</c></summary>
/// <remarks>
/// <para><c>Empties the Stack and Queue when they have been fully Iterated.</c></para>
/// <remarks>
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Properties
/// <returns><c>A Read-Only Interface Reference to this Stack/Queue.</c></returns>
property Reader: IADStackQueueReader<T> read GetReader;
end;
implementation
end.
|
unit SessionManager;
interface
uses
edbcomps;
type
TSessionManager = class
public
session : TEDBSession;
constructor Create(userId, password, hostName : String; hostPort : Integer);
destructor Destroy; override;
procedure Status(Sender: TObject; const StatusMessage: String);
procedure OnRemoteTimeout(Sender: TObject; var StayConnected : boolean);
end;
implementation
uses
SysUtils,
StrUtils,
ConsoleHelper;
{ TSessionManager }
constructor TSessionManager.Create(userId, password, hostName : String; hostPort : Integer);
begin
session := TEDBSession.Create(nil);
session.OnStatusMessage := Status;
session.OnLogMessage := Status;
session.AutoSessionName := true;
session.SessionType := stRemote;
session.LoginUser := userId;
session.LoginPassword := password;
session.CharacterSet := csAnsi;
if AnsiLeftStr(hostName, 2) = '\\' then
session.RemoteHost := AnsiRightStr(hostName, length(hostName) - 2) // '\\hostname'
else
session.RemoteAddress := hostName; //'127.0.0.1';
session.RemotePort := hostPort; //12010;
session.OnRemoteTimeout := OnRemoteTimeout;
end;
destructor TSessionManager.Destroy;
begin
FreeAndNil(session);
end;
procedure TSessionManager.OnRemoteTimeout(Sender: TObject;
var StayConnected: boolean);
var
c : Char;
begin
Write('This process is taking a long time... Continue (y/n)');
repeat
Read(c);
if c in ['y', 'Y'] then
StayConnected := True
else if c in ['n', 'N'] then
StayConnected := True
else
writeln('Try y or n');
until c in ['y', 'Y', 'n', 'N'];
end;
procedure TSessionManager.Status(Sender: TObject; const StatusMessage: String);
begin
VerboseWrite(StatusMessage);
end;
end.
|
unit Cert_Or_SmallClaimsDuplicatesDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls;
type
TCert_Or_SmallClaimsDuplicatesDialog = class(TForm)
YesButton: TBitBtn;
NoButton: TBitBtn;
Table: 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 }
CurrentYear : String;
IndexNumber : LongInt;
AskForConfirmation : Boolean;
Source : Char; {(C)ertiorari, (S)mall Claim}
ActionTypeName, IndexNumberFieldName : String;
end;
var
Cert_Or_SmallClaimsDuplicatesDialog: TCert_Or_SmallClaimsDuplicatesDialog;
implementation
{$R *.DFM}
uses PASUtils, WinUtils, GlblCnst;
{===============================================================}
Procedure TCert_Or_SmallClaimsDuplicatesDialog.FormShow(Sender: TObject);
var
FirstTimeThrough, Done : Boolean;
begin
case Source of
'C' : begin
ActionTypeName := 'certiorari';
IndexNumberFieldName := 'CertiorariNumber';
Table.TableName := CertiorariTableName;
Table.IndexName := 'BYYEAR_CERTNUM';
end; {'C'}
'S' : begin
ActionTypeName := 'small claims';
IndexNumberFieldName := 'IndexNumber';
Table.TableName := SmallClaimsTableName;
Table.IndexName := 'BYYEAR_INDEXNUM';
end; {'S'}
end; {case Source of}
Caption := 'Parcels with ' + ActionTypeName + ' #' +
IntToStr(IndexNumber) + '.';
DescriptionLabel.Caption := 'The following parcels all have ' + ActionTypeName +
' #' + IntToStr(IndexNumber) + '.';
PromptLabel.Caption := 'Do you want to add this ' + ActionTypeName + ' anyway?';
try
Table.Open;
except
MessageDlg('Error opening ' + ActionTypeName + ' 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(Table, ['TaxRollYr', IndexNumberFieldName],
[CurrentYear, IntToStr(IndexNumber)],
[CurrentYear, IntToStr(IndexNumber)]);
Done := False;
FirstTimeThrough := True;
Table.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Table.Next;
If Table.EOF
then Done := True;
If not Done
then DuplicateCertiorariList.Items.Add(ConvertSwisSBLToDashDot(Table.FieldByName('SwisSBLKey').Text));
until Done;
end; {FormShow}
{==============================================================}
Procedure TCert_Or_SmallClaimsDuplicatesDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
Table.Close;
Action := caFree;
end;
end.
|
unit vr_ctrl_utils;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, Forms, vr_utils, vr_classes, StdCtrls;
procedure form_LoadFromIni(const AFileName: string; const AForm: TForm; ASect: string = ''); overload;
procedure form_LoadFromIni(const F: IFPIniFileUTF8; const AForm: TForm; ASect: string = ''); overload;
procedure form_LoadFromIni(const F: IFPThreadIniFileUTF8; const AForm: TForm; const ASect: string = ''); overload;
procedure form_SaveToIni(const AFileName: string; const AForm: TForm; ASect: string = ''); overload;
procedure form_SaveToIni(const F: IFPIniFileUTF8; const AForm: TForm; ASect: string = ''); overload;
procedure form_SaveToIni(const F: IFPThreadIniFileUTF8; const AForm: TForm; const ASect: string = ''); overload;
function form_ByName(const FormName: string): TCustomForm; inline;
function cmb_IndexOfNoCaseSens(const cmb: TComboBox; const AItem: string): Integer;
function cmb_SelectNoCaseSens(const cmb: TComboBox; const AItem: string): Integer;
function cmb_Select(const cmb: TComboBox; const AItem: string): Integer;
//Delete and Set ItemIndex
function cmb_Delete(const cmb: TComboBox; AIndex: Integer): Boolean;
implementation
procedure form_LoadFromIni(const F: IFPThreadIniFileUTF8; const AForm: TForm;
const ASect: string);
var
ini: IFPIniFileUTF8;
begin
ini := F.Lock;
try
form_LoadFromIni(ini, AForm, ASect);
finally
F.Unlock;
end;
end;
procedure form_SaveToIni(const AFileName: string; const AForm: TForm;
ASect: string);
var
ini: IFPIniCachedFile;
begin
ini := ini_GetCacheFile(AFileName);
form_SaveToIni(ini, AForm, ASect);
end;
procedure form_SaveToIni(const F: IFPIniFileUTF8; const AForm: TForm;
ASect: string);
var
i: Integer;
begin
case AForm.WindowState of
//wsMinimized: i := 0;
wsNormal: i := 1;
wsMaximized: i := 2;
else i := 0;
end;//case
if ASect = '' then
begin
ASect := AForm.Name;
{$IFDEF TEST_MODE}
if ASect = '' then
ShowError('form_SaveToIni: AForm.Name = '''){$ENDIF}
end;
F.WriteInteger(ASect, 'WindowState', i);
if i = 1 then
begin
F.WriteInteger(ASect, 'Top', AForm.Top);
F.WriteInteger(ASect, 'Left', AForm.Left);
F.WriteInteger(ASect, 'Height', AForm.Height);
F.WriteInteger(ASect, 'Width', AForm.Width);
end
else
begin
F.WriteInteger(ASect, 'Top', AForm.RestoredTop);
F.WriteInteger(ASect, 'Left', AForm.RestoredLeft);
F.WriteInteger(ASect, 'Height', AForm.RestoredHeight);
F.WriteInteger(ASect, 'Width', AForm.RestoredWidth);
end;
end;
procedure form_LoadFromIni(const AFileName: string; const AForm: TForm;
ASect: string);
var
ini: IFPIniCachedFile;
begin
ini := ini_GetCacheFile(AFileName);
form_LoadFromIni(ini, AForm, ASect);
end;
procedure form_LoadFromIni(const F: IFPIniFileUTF8; const AForm: TForm;
ASect: string);
function _ReadInt(const AIdent: string; const ADefault, AMin: Integer): Integer;
begin
Result := F.ReadInteger(ASect, AIdent, ADefault);
if Result < AMin then
Result := AMin;
end;
var
i: Integer;
begin
if ASect = '' then
begin
ASect := AForm.Name;
{$IFDEF TEST_MODE}
if ASect = '' then
ShowError('form_LoadFromIni: AForm.Name = '''){$ENDIF}
end;
AForm.Top := _ReadInt('Top', AForm.Top, 1);
AForm.Left := _ReadInt('Left', AForm.Left, 1);
AForm.Height := _ReadInt('Height', AForm.Height, 200);
AForm.Width := _ReadInt('Width', AForm.Width, 200);
i := F.ReadInteger(ASect, 'WindowState', 1);
case i of
0: AForm.WindowState := wsMinimized;
2: AForm.WindowState := wsMaximized;
else //1
AForm.WindowState := wsNormal;
end;//case
end;
procedure form_SaveToIni(const F: IFPThreadIniFileUTF8; const AForm: TForm;
const ASect: string);
var
ini: IFPIniFileUTF8;
begin
ini := F.Lock;
try
form_SaveToIni(ini, AForm, ASect);
finally
F.Unlock;
end;
end;
function form_ByName(const FormName: string): TCustomForm;
begin
Result := Screen.FindForm(FormName);
end;
function cmb_IndexOfNoCaseSens(const cmb: TComboBox; const AItem: string
): Integer;
var
i: Integer;
begin
for i := 0 to cmb.Items.Count - 1 do
if SameText(cmb.Items[i], AItem) then
Exit(i);
Result := -1;
end;
function cmb_SelectNoCaseSens(const cmb: TComboBox; const AItem: string
): Integer;
begin
Result := cmb_IndexOfNoCaseSens(cmb, AItem);
if Result <> -1 then
cmb.ItemIndex := Result;
end;
function cmb_Select(const cmb: TComboBox; const AItem: string): Integer;
begin
Result := cmb.Items.IndexOf(AItem);
if Result <> -1 then
cmb.ItemIndex := Result;
end;
function cmb_Delete(const cmb: TComboBox; AIndex: Integer): Boolean;
var
Items: TStrings;
begin
Items := cmb.Items;
if (AIndex < 0) or (AIndex >= Items.Count) then Exit(False);
Result := True;
Items.Delete(AIndex);
if AIndex = Items.Count then
Dec(AIndex);
cmb.ItemIndex := AIndex;
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Multi-Rename text range selector dialog window
Copyright (C) 2007-2020 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit fSelectTextRange;
{$mode objfpc}{$H+}
interface
uses
//Lazarus, Free-Pascal, etc.
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ButtonPanel, Buttons, ExtCtrls,
//DC
uOSForms;
type
{ TfrmSelectTextRange }
TfrmSelectTextRange = class(TModalForm)
ButtonPanel: TButtonPanel;
edtSelectText: TEdit;
gbRangeDescription: TGroupBox;
gbCountFirstFrom: TGroupBox;
gbCountLastFrom: TGroupBox;
lblResult: TLabel;
lblValueToReturn: TLabel;
lblSelectText: TLabel;
rbDescriptionFirstLast: TRadioButton;
rbFirstFromStart: TRadioButton;
rbLastFromStart: TRadioButton;
rbDescriptionFirstLength: TRadioButton;
rbFirstFromEnd: TRadioButton;
rbLastFromEnd: TRadioButton;
procedure edtSelectTextKeyUp(Sender: TObject; var {%H-}Key: word; {%H-}Shift: TShiftState);
procedure edtSelectTextMouseUp(Sender: TObject; {%H-}Button: TMouseButton; {%H-}Shift: TShiftState; {%H-}X, {%H-}Y: integer);
procedure FormCreate(Sender: TObject);
procedure SomethingChange(Sender: TObject);
private
FCanvaForAutosize: TControlCanvas;
FSelStart, FSelFinish, FWholeLength: integer;
FPrefix: string;
procedure ResfreshHint;
public
property Prefix: string read FPrefix write FPrefix;
end;
function ShowSelectTextRangeDlg(TheOwner: TCustomForm; const ACaption, AText, sPrefix: string; var sResultingMaskValue: string): boolean;
implementation
{$R *.lfm}
uses
//Lazarus, Free-Pascal, etc.
//DC
uGlobs;
function ShowSelectTextRangeDlg(TheOwner: TCustomForm; const ACaption, AText, sPrefix: string; var sResultingMaskValue: string): boolean;
begin
with TfrmSelectTextRange.Create(TheOwner) do
try
Result := False;
Caption := ACaption;
edtSelectText.Constraints.MinWidth := FCanvaForAutosize.TextWidth(AText) + 20;
edtSelectText.Text := AText;
Prefix := sPrefix;
rbDescriptionFirstLength.Checked := not rbDescriptionFirstLast.Checked;
rbFirstFromEnd.Checked := not rbFirstFromStart.Checked;
rbLastFromEnd.Checked := not rbLastFromStart.Checked;
if ShowModal = mrOk then
begin
if (FSelFinish >= FSelStart) and (lblValueToReturn.Caption <> '') then
begin
sResultingMaskValue := lblValueToReturn.Caption;
Result := True;
end;
end;
finally
Free;
end;
end;
{ TfrmSelectTextRange }
procedure TfrmSelectTextRange.SomethingChange(Sender: TObject);
begin
ResfreshHint;
end;
procedure TfrmSelectTextRange.edtSelectTextKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
SomethingChange(Sender);
end;
procedure TfrmSelectTextRange.edtSelectTextMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
SomethingChange(Sender);
end;
procedure TfrmSelectTextRange.FormCreate(Sender: TObject);
begin
InitPropStorage(Self);
// TEdit "edtSelectText" does not have Canvas.
// We will use "FCanvaForAutosize" to determine the required width to hold the whole text.
// This way, we will see it all.
FCanvaForAutosize := TControlCanvas.Create;
FCanvaForAutosize.Control := edtSelectText;
FCanvaForAutosize.Font.Assign(edtSelectText.Font);
end;
procedure TfrmSelectTextRange.ResfreshHint;
var
sTempo: string;
begin
gbCountLastFrom.Enabled := not rbDescriptionFirstLength.Checked;
sTempo := '';
FSelStart := edtSelectText.SelStart + 1;
FSelFinish := edtSelectText.SelStart + edtSelectText.SelLength;
FWholeLength := length(edtSelectText.Text);
if (FSelFinish >= FSelStart) and (FWholeLength > 0) then
begin
if rbFirstFromStart.Checked then
begin
if FSelFinish = FSelStart then
sTempo := Format('%d', [FSelStart])
else
begin
if rbDescriptionFirstLength.Checked then
sTempo := Format('%d,%d', [FSelStart, succ(FSelFinish - FSelStart)])
else if rbLastFromStart.Checked then
sTempo := Format('%d:%d', [FSelStart, FSelFinish])
else
sTempo := Format('%d:-%d', [FSelStart, succ(FWholeLength - FSelFinish)]);
end;
end
else
begin
if FSelFinish = FSelStart then
sTempo := Format('-%d', [succ(FWholeLength - FSelStart)])
else
begin
if rbDescriptionFirstLength.Checked then
sTempo := Format('-%d,%d', [succ(FWholeLength - FSelFinish), succ(FSelFinish - FSelStart)])
else if rbLastFromStart.Checked then
sTempo := Format('-%d:%d', [succ(FWholeLength - FSelStart), FSelFinish])
else
sTempo := Format('-%d:-%d', [succ(FWholeLength - FSelStart), succ(FWholeLength - FSelFinish)]);
end;
end;
lblValueToReturn.Caption := Format('[%s%s]', [Prefix, sTempo]);
end
else
begin
lblValueToReturn.Caption := '';
end;
end;
end.
|
unit Model.Base;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client;
type
TdtmdlBase = class(TDataModule)
private
protected
procedure InsertException(E: Exception); virtual;
public
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdtmdlBase }
procedure TdtmdlBase.InsertException(E: Exception);
const
INSERT_EXCEPT = 'insert into exception values(%s,%s,%s,%s)';
var
LCon: TFDConnection;
begin
LCon := FindComponent('conConnection') as TFDConnection;
if LCon = nil then
Exit;
LCon.ExecSQL(Format(INSERT_EXCEPT, [QuotedStr(TGUID.NewGuid.ToString),
QuotedStr(E.ClassName), QuotedStr(E.Message),
QuotedStr(FormatDateTime('dd/mm/yyyy hh:mm:ss', Now))]));
end;
end.
|
{
@html(<b>)
Connection Traffic Limiter
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
Using this unit, you can set up and activate the network traffic limiter.
@html(<br>)
Network traffic limiter can limit the number of
packets that are actively being sent or received.
@html(<br>)
This can lower server's network traffic to a minimum,
while still being able to work with a high number of
active connections at once. Tests on some wireless network cards
have shown that using this limiter can prevent frequent connection
losses on low-bandwidth/high-traffic servers.
}
unit rtcConnLimit;
{$INCLUDE rtcDefs.inc}
interface
uses
Windows,
rtcTrashcan,
memXList,
memBinList,
rtcSyncObjs,
rtcInfo,
rtcTimer,
rtcThrPool;
const
RTC_THREAD_INFO_INDEX:string='RTCTHR';
// "Connect" action
RTC_ACTION_CONNECT=1;
// "Accept" action
RTC_ACTION_ACCEPT=2;
// "Read" action
RTC_ACTION_READ=3;
// "Write" action
RTC_ACTION_WRITE=4;
{@exclude}
RTC_ACTION_FIRST=1;
{@exclude}
RTC_ACTION_LAST=4;
{@exclude
Max. repeat count for actins with 0 as RTC_LIMIT_CONN_MAXREPEAT[] }
RTC_LIMIT_MAX_REPEAT:longword=MAXLONG;
var
{ To use a network traffic limiter, set @name to @true
(Default = @false; not limiting active connection count). }
RTC_LIMIT_CONN:boolean=False;
{ Number of active connections allowed at a time (0=unlimited).
Defined for each action type: Connect, Accept, Read, Write (respectively) }
RTC_LIMIT_CONN_COUNT:array[RTC_ACTION_FIRST..RTC_ACTION_LAST] of cardinal =
(10, 0, 0, 1);
{ Number of same-action iterations a connection may go through,
before it has to gives away the right to the next one waiting (0=unlimited).
Defined for each action type: Connect, Accept, Read, Write (respectively) }
RTC_LIMIT_CONN_MAXREPEAT:array[RTC_ACTION_FIRST..RTC_ACTION_LAST] of cardinal =
(1, 1, 1, 1);
{ Timeout (in seconds) which may not be exceeded between iterations,
or the connection will give the right up to the next one waiting (0=unlimited).
Defined for each action type: Connect, Accept, Read, Write (respectively) }
RTC_LIMIT_CONN_TIMEOUT:array[RTC_ACTION_FIRST..RTC_ACTION_LAST] of cardinal =
(1, 1, 1, 1);
{ Used by all Connection components internaly,
to tell the traffic limiter they want to start an action.
@exclude }
function rtcStartAction(Thr: TRtcThread; action:cardinal): boolean;
{ Used by all connection components internaly,
to tell the traffic limiter they just completed the last action.
@exclude }
procedure rtcCloseAction(Thr: TRtcThread);
implementation
type
TRtcWaitData=record
WaitList:TXList; // action-based waiting list
Thr_WorkCount:cardinal; // number of threads working with this action
end;
TRtcTimeoutObject=class(TRtcObject)
public
Timer:TRtcTimer;
procedure Kill; override;
end;
TRtcTimeoutJob=class(TRtcJob)
public
procedure Run(Thr:TRtcThread); override;
procedure Kill; override;
end;
var
CS:TRtcCritSec;
WorkList:TBinList; // global working threads list
TimeList:TBinList; // timeout list for working threads
PauseList:TBinList; // global paused threads list
Data:array[RTC_ACTION_FIRST..RTC_ACTION_LAST] of TRtcWaitData;
Message_LimitTimeout:TRtcTimeoutJob=nil;
{ TRtcTimeoutObject }
procedure TRtcTimeoutObject.Kill;
begin
TRtcTimer.Stop(Timer);
Free;
end;
{ TRtcTimeoutJob }
procedure TRtcTimeoutJob.Run(Thr:TRtcThread);
begin
if RTC_LIMIT_CONN and assigned(Thr) then
rtcCloseAction(Thr);
end;
procedure TRtcTimeoutJob.Kill;
begin
// do not free. This object will be used for all Threads.
end;
{ --- }
procedure RunPaused(action:integer);
var
TC:longword;
wrk:cardinal;
Thr:TRtcThread;
Obj:TRtcTimeoutObject;
begin
with Data[action] do
begin
wrk:=WaitList.First;
WaitList.removeFirst; // remove from waiting list
Inc(Thr_WorkCount);
PauseList.remove(wrk); // remove from paused list
WorkList.insert(wrk, action); // add to working list
TC:=RTC_LIMIT_CONN_MAXREPEAT[action];
if TC=0 then TC:=RTC_LIMIT_MAX_REPEAT;
TimeList.insert(wrk,TC);
Thr:=TRtcThread(wrk);
if RTC_LIMIT_CONN_TIMEOUT[action]>0 then
begin
obj:=TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]);
if obj=nil then
begin
obj:=TRtcTimeoutObject.Create;
obj.Timer:=TRtcTimer.Create(True);
Thr.Info.Obj[RTC_THREAD_INFO_INDEX]:=Obj;
end;
TRtcTimer.Enable(Obj.Timer,
RTC_LIMIT_CONN_TIMEOUT[action]*1000,
Thr,Message_LimitTimeout,
True);
end;
Thr.Resume;
end;
end;
function rtcStartAction(Thr: TRtcThread; action:cardinal): boolean;
var
act:cardinal;
TC:longword;
Obj:TRtcTimeoutObject;
begin
if not RTC_LIMIT_CONN then
Result:=True
else
begin
Result:=False;
CS.Enter;
try
if not assigned(WorkList) then
begin
PauseList:=tBinList.Create(128);
WorkList:=tBinList.Create(128);
TimeList:=tBinList.Create(128);
end;
act:=WorkList.search(longword(Thr));
if (act>0) and (act<>action) then // action changing
begin
with Data[act] do
begin
// remove from working list ...
WorkList.remove(longword(Thr));
TimeList.remove(longword(Thr));
Dec(Thr_WorkCount);
// Disable timeout
if assigned(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]) then
TRtcTimer.Disable(TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]).Timer);
if WaitList.Count>0 then // other threads waiting
RunPaused(act);
act:=0;
end;
end;
with Data[action] do
begin
if act>0 then // active
begin
TC:=TimeList.search(longword(Thr));
if TC>0 then // can keep working
begin
// Reset timeout
if assigned(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]) then
TRtcTimer.Reset(TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]).Timer);
// continue ...
if TC<RTC_LIMIT_MAX_REPEAT then
begin
Dec(TC);
TimeList.change(longword(Thr),TC);
end;
Result:=True;
end
else // exceeding allowed time limit
begin
if WaitList.Count=0 then
begin
// Reset timeout
if assigned(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]) then
TRtcTimer.Reset(TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]).Timer);
// continue ...
Result:=True;
end
else
begin
// Disable timeout
if assigned(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]) then
TRtcTimer.Disable(TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]).Timer);
// remove from working list ...
WorkList.remove(longword(Thr));
TimeList.remove(longword(Thr));
Dec(Thr_WorkCount);
RunPaused(action);
// add to waiting list ...
Thr.Pause;
PauseList.insert(longword(Thr),action);
WaitList.addLast(longword(Thr));
end;
end;
end
else if PauseList.search(longword(Thr))=0 then // not waiting
begin
if not assigned(WaitList) then
begin
WaitList:=tXList.Create(128);
Thr_WorkCount:=0;
end;
if RTC_LIMIT_CONN_COUNT[action]=0 then
begin
// no limit, continue ...
Result:=True;
end
else if Thr_WorkCount<RTC_LIMIT_CONN_COUNT[action] then // theres place for another thread
begin
if WaitList.Count=0 then // nobody waiting
begin
// start timeout timer ...
if RTC_LIMIT_CONN_TIMEOUT[action]>0 then
begin
Obj:=TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]);
if Obj=nil then
begin
Obj:=TRtcTimeoutObject.Create;
Obj.Timer:=TRtcTimer.Create(True);
Thr.Info.Obj[RTC_THREAD_INFO_INDEX]:=Obj;
end;
TRtcTimer.Enable(Obj.Timer,
RTC_LIMIT_CONN_TIMEOUT[action]*1000,
Thr,Message_LimitTimeout,
True);
end;
// start thread ...
WorkList.insert(longword(Thr),action);
if RTC_LIMIT_CONN_MAXREPEAT[action]>0 then
TC:=RTC_LIMIT_CONN_MAXREPEAT[action]-1
else
TC:=RTC_LIMIT_MAX_REPEAT;
TimeList.insert(longword(Thr),TC);
Inc(Thr_WorkCount);
Result:=True;
end
else
begin
RunPaused(action); // activate one
// add to waiting list ...
Thr.Pause;
PauseList.insert(longword(Thr),action);
WaitList.addLast(longword(Thr));
end;
end
else
begin
// add to waiting list ...
Thr.Pause;
PauseList.insert(longword(Thr),action);
WaitList.addLast(longword(Thr));
end;
end;
end;
finally
CS.Leave;
end;
end;
end;
procedure rtcCloseAction(Thr: TRtcThread);
var
act:cardinal;
begin
if not RTC_LIMIT_CONN then Exit;
CS.Enter;
try
if not assigned(WorkList) then
begin
PauseList:=tBinList.Create(128);
WorkList:=tBinList.Create(128);
TimeList:=tBinList.Create(128);
end;
act:=WorkList.search(longword(Thr));
if act>0 then // active
begin
// Disable timeout
if assigned(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]) then
TRtcTimer.Disable(TRtcTimeoutObject(Thr.Info.Obj[RTC_THREAD_INFO_INDEX]).Timer);
with Data[act] do
begin
// remove from working list ...
WorkList.remove(longword(Thr));
TimeList.remove(longword(Thr));
Dec(Thr_WorkCount);
if WaitList.Count>0 then // other threads waiting
RunPaused(act);
end;
end
else
begin
act:=PauseList.search(longword(Thr));
if act>0 then
begin
with Data[act] do
begin
// remove from waiting list and resume
PauseList.remove(longword(Thr));
WaitList.removeThis(longword(Thr));
Thr.Resume;
end;
end;
end;
finally
CS.Leave;
end;
end;
procedure _Init;
var
a:integer;
begin
CS:=TRtcCritSec.Create;
Message_LimitTimeout:=TRtcTimeoutJob.Create;
PauseList:=nil;
WorkList:=nil;
TimeList:=nil;
for a:=Low(Data) to High(Data) do
with Data[a] do
begin
WaitList:=nil;
Thr_WorkCount:=0;
end;
end;
procedure _Free;
var
a:integer;
begin
CS.Enter;
try
if assigned(PauseList) then
begin
PauseList.Free;
PauseList:=nil;
end;
if assigned(WorkList) then
begin
WorkList.Free;
WorkList:=nil;
end;
if assigned(TimeList) then
begin
TimeList.Free;
TimeList:=nil;
end;
for a:=Low(Data) to High(Data) do
if assigned(Data[a].WaitList) then
begin
Data[a].WaitList.Free;
Data[a].WaitList:=nil;
Data[a].Thr_WorkCount:=0;
end;
Garbage(Message_LimitTimeout);
finally
CS.Leave;
end;
Garbage(CS);
end;
initialization
_Init;
finalization
_Free;
end.
|
unit MD5;
interface
uses
Classes, Common;
type
TCheckSumFileMD5 = class(TCheckSumFile)
protected
Fmd5File: string;
public
constructor Create(AFileName: string); override;
procedure ToStringList(slOut: TStringList); override;
function SingleFileChecksum(AFileName: string): string; override;
function MergeLine(AFileName, ACheckSum: string): string; override;
end;
function md5file(const filename: string): string;
procedure MD5FileToStringList(amd5file: string; slOut: TStringList);
implementation
uses
SysUtils, IdHashMessageDigest, idHash, LongFilenameOperations;
function md5file(const filename: string): string;
var
IdMD5: TIdHashMessageDigest5;
FS: TFileStream;
begin
IdMD5 := TIdHashMessageDigest5.Create;
FS := TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite);
try
{$IFDEF UNICODE} // I actually do not know at which version of Delphi/Indy, this has changed.
Result := IdMD5.HashStreamAsHex(FS);
{$ELSE}
Result := IdMD5.AsHex(IdMD5.HashValue(FS));
{$ENDIF}
finally
FS.Free;
IdMD5.Free;
end;
end;
procedure MD5FileToStringList(amd5file: string; slOut: TStringList);
var
sLine: string;
originalFilename: string;
expectedChecksum: string;
fil: THandle;
csum: TChecksum;
firstLinePassed: boolean;
forceUTF8: boolean;
begin
if not FileExists(amd5file) then
exit;
MyAssignFile(fil, amd5file);
try
MyReset(fil);
firstLinePassed := false;
forceUTF8 := false;
while not MyEOF(fil) do
begin
MyReadLn(fil, sLine);
{$REGION 'Try UTF8 decode'}
if not firstLinePassed and (length(sLine)>2) and (sLine[1]=#$EF) and (sLine[2]=#$BB) and (sLine[3]=#$BF) then
begin
delete(sLine,1,3); // Remove BOM
forceUTF8 := true;
end;
firstLinePassed := true;
if forceUTF8 or (Pos(#$FFFD, Utf8ToString(RawByteString(sLine))) = 0) then
sLine := Utf8ToString(RawByteString(sLine));
{$ENDREGION}
if Copy(Trim(sLine),1,1) = ';' then continue;
// 25bfdef2651071efdd08bb3404797384 *Example.doc
sLine := Trim(sLine);
if sLine = '' then
continue;
expectedChecksum := Copy(sLine, 1, 32);
Delete(sLine, 1, 32);
sLine := Trim(sLine);
if Copy(sLine, 1, 1) = '*' then
Delete(sLine, 1, 1);
sLine := Trim(sLine);
originalFilename := sLine;
//slOut.Values[originalFilename] := expectedChecksum; // <-- with this, files cannot have an equal sign
slOut.OwnsObjects := true;
csum := TChecksum.Create;
csum.checksum := expectedChecksum;
slOut.AddObject(originalFilename, csum);
end;
finally
MyCloseFile(fil);
end;
end;
{ TCheckSumFileMD5 }
constructor TCheckSumFileMD5.Create(AFileName: string);
begin
inherited;
fmd5File := AFileName;
if not SameText(ExtractFileExt(AFileName),'.md5') then
raise Exception.Create('Invalid checksum file extension.');
end;
function TCheckSumFileMD5.MergeLine(AFileName, ACheckSum: string): string;
begin
result := ACheckSum + ' *' + AFileName;
end;
function TCheckSumFileMD5.SingleFileChecksum(AFileName: string): string;
begin
result := LowerCase(md5file(AFileName));
end;
procedure TCheckSumFileMD5.ToStringList(slOut: TStringList);
begin
inherited;
MD5FileToStringList(fmd5File, slOut);
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 2016-01-28 ¿ÀÀü 9:00:25
//
unit W_Main_Class;
interface
uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect;
type
TServerMethods1Client = class(TDSAdminClient)
private
FEchoStringCommand: TDBXCommand;
FReverseStringCommand: TDBXCommand;
FInsert_QrtCommand: TDBXCommand;
FInsert_W_QrtCommand: TDBXCommand;
Fbtn_HereMeet_ClickCommand: TDBXCommand;
FChat_LogCommand: TDBXCommand;
FCreate_RoomCommand: TDBXCommand;
FJoin_MemberCommand: TDBXCommand;
FbroadcastCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
procedure Insert_Qrt(Name: string; Lat: string; Lng: string; channel: string);
procedure Insert_W_Qrt(Name: string; Address: string; channel: string);
procedure btn_HereMeet_Click(channel: string);
procedure Chat_Log(chat: string; channel: string);
procedure Create_Room(Room: string);
procedure Join_Member(Name: string; channel: string);
function broadcast(Value: TJSONObject; channel: string): Boolean;
end;
implementation
function TServerMethods1Client.EchoString(Value: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FDBXConnection.CreateCommand;
FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FEchoStringCommand.Text := 'TServerMethods1.EchoString';
FEchoStringCommand.Prepare;
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.ExecuteUpdate;
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethods1Client.ReverseString(Value: string): string;
begin
if FReverseStringCommand = nil then
begin
FReverseStringCommand := FDBXConnection.CreateCommand;
FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FReverseStringCommand.Text := 'TServerMethods1.ReverseString';
FReverseStringCommand.Prepare;
end;
FReverseStringCommand.Parameters[0].Value.SetWideString(Value);
FReverseStringCommand.ExecuteUpdate;
Result := FReverseStringCommand.Parameters[1].Value.GetWideString;
end;
procedure TServerMethods1Client.Insert_Qrt(Name: string; Lat: string; Lng: string; channel: string);
begin
if FInsert_QrtCommand = nil then
begin
FInsert_QrtCommand := FDBXConnection.CreateCommand;
FInsert_QrtCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsert_QrtCommand.Text := 'TServerMethods1.Insert_Qrt';
FInsert_QrtCommand.Prepare;
end;
FInsert_QrtCommand.Parameters[0].Value.SetWideString(Name);
FInsert_QrtCommand.Parameters[1].Value.SetWideString(Lat);
FInsert_QrtCommand.Parameters[2].Value.SetWideString(Lng);
FInsert_QrtCommand.Parameters[3].Value.SetWideString(channel);
FInsert_QrtCommand.ExecuteUpdate;
end;
procedure TServerMethods1Client.Insert_W_Qrt(Name: string; Address: string; channel: string);
begin
if FInsert_W_QrtCommand = nil then
begin
FInsert_W_QrtCommand := FDBXConnection.CreateCommand;
FInsert_W_QrtCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsert_W_QrtCommand.Text := 'TServerMethods1.Insert_W_Qrt';
FInsert_W_QrtCommand.Prepare;
end;
FInsert_W_QrtCommand.Parameters[0].Value.SetWideString(Name);
FInsert_W_QrtCommand.Parameters[1].Value.SetWideString(Address);
FInsert_W_QrtCommand.Parameters[2].Value.SetWideString(channel);
FInsert_W_QrtCommand.ExecuteUpdate;
end;
procedure TServerMethods1Client.btn_HereMeet_Click(channel: string);
begin
if Fbtn_HereMeet_ClickCommand = nil then
begin
Fbtn_HereMeet_ClickCommand := FDBXConnection.CreateCommand;
Fbtn_HereMeet_ClickCommand.CommandType := TDBXCommandTypes.DSServerMethod;
Fbtn_HereMeet_ClickCommand.Text := 'TServerMethods1.btn_HereMeet_Click';
Fbtn_HereMeet_ClickCommand.Prepare;
end;
Fbtn_HereMeet_ClickCommand.Parameters[0].Value.SetWideString(channel);
Fbtn_HereMeet_ClickCommand.ExecuteUpdate;
end;
procedure TServerMethods1Client.Chat_Log(chat: string; channel: string);
begin
if FChat_LogCommand = nil then
begin
FChat_LogCommand := FDBXConnection.CreateCommand;
FChat_LogCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FChat_LogCommand.Text := 'TServerMethods1.Chat_Log';
FChat_LogCommand.Prepare;
end;
FChat_LogCommand.Parameters[0].Value.SetWideString(chat);
FChat_LogCommand.Parameters[1].Value.SetWideString(channel);
FChat_LogCommand.ExecuteUpdate;
end;
procedure TServerMethods1Client.Create_Room(Room: string);
begin
if FCreate_RoomCommand = nil then
begin
FCreate_RoomCommand := FDBXConnection.CreateCommand;
FCreate_RoomCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FCreate_RoomCommand.Text := 'TServerMethods1.Create_Room';
FCreate_RoomCommand.Prepare;
end;
FCreate_RoomCommand.Parameters[0].Value.SetWideString(Room);
FCreate_RoomCommand.ExecuteUpdate;
end;
procedure TServerMethods1Client.Join_Member(Name: string; channel: string);
begin
if FJoin_MemberCommand = nil then
begin
FJoin_MemberCommand := FDBXConnection.CreateCommand;
FJoin_MemberCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FJoin_MemberCommand.Text := 'TServerMethods1.Join_Member';
FJoin_MemberCommand.Prepare;
end;
FJoin_MemberCommand.Parameters[0].Value.SetWideString(Name);
FJoin_MemberCommand.Parameters[1].Value.SetWideString(channel);
FJoin_MemberCommand.ExecuteUpdate;
end;
function TServerMethods1Client.broadcast(Value: TJSONObject; channel: string): Boolean;
begin
if FbroadcastCommand = nil then
begin
FbroadcastCommand := FDBXConnection.CreateCommand;
FbroadcastCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FbroadcastCommand.Text := 'TServerMethods1.broadcast';
FbroadcastCommand.Prepare;
end;
FbroadcastCommand.Parameters[0].Value.SetJSONValue(Value, FInstanceOwner);
FbroadcastCommand.Parameters[1].Value.SetWideString(channel);
FbroadcastCommand.ExecuteUpdate;
Result := FbroadcastCommand.Parameters[2].Value.GetBoolean;
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TServerMethods1Client.Destroy;
begin
FEchoStringCommand.DisposeOf;
FReverseStringCommand.DisposeOf;
FInsert_QrtCommand.DisposeOf;
FInsert_W_QrtCommand.DisposeOf;
Fbtn_HereMeet_ClickCommand.DisposeOf;
FChat_LogCommand.DisposeOf;
FCreate_RoomCommand.DisposeOf;
FJoin_MemberCommand.DisposeOf;
FbroadcastCommand.DisposeOf;
inherited;
end;
end.
|
unit TestConverter;
{ AFS 18 Jan 2003
Processor that can specify just one process, not all
to run
}
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestConverter, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses StringsConverter, BaseVisitor;
type
TTestConverter = class(TStringsConverter)
private
fbRunAll: boolean;
fcSingleProcess: TTreeNodeVisitorType;
protected
procedure ApplyProcesses;
public
constructor Create;
property RunAll: boolean Read fbRunAll Write fbRunAll;
property SingleProcess: TTreeNodeVisitorType
Read fcSingleProcess Write fcSingleProcess;
end;
implementation
uses VisitSetXY, VisitSetNesting, TreeWalker;
constructor TTestConverter.Create;
begin
inherited;
RunAll := True;
fcSingleProcess := nil;
end;
procedure TTestConverter.ApplyProcesses;
var
lcProcess: TBaseTreeNodeVisitor;
lcTreeWalker: TTreeWalker;
begin
if RunAll then
inherited
else
begin
lcTreeWalker := TTreeWalker.Create;
// apply a visit setXY first
lcProcess := TVisitSetXY.Create;
try
lcTreeWalker.Visit(GetRoot, lcProcess);
finally
lcProcess.Free;
end;
// and set up nesting levels
lcProcess := TVisitSetNestings.Create;
try
lcTreeWalker.Visit(GetRoot, lcProcess);
finally
lcProcess.Free;
end;
// then apply the process
lcProcess := SingleProcess.Create;
try
lcTreeWalker.Visit(GetRoot, lcProcess);
finally
lcProcess.Free;
end;
lcTreeWalker.Free;
end;
end;
end.
|
Program Tiny;
{ Program to compress .COM programs }
{$I-}
Uses
Dos,
Crt;
Const
mdStoreB = 1;
mdStoreW = 2;
mdDupB = 3;
mdDupW = 4;
mdDupWord = 5;
mdIncB = 6;
mdIncW = 7;
mdDecB = 8;
mdDecW = 9;
mdSkipOne = 10;
mdCopy = 11;
mdSpaceB = 12;
mdSpaceW = 13;
Const
DupBase = 4;
DupWordBase = 3;
IncBase = 5;
IncWordBase = 4;
DecBase = 6;
DecWordBase = 4;
SkipBase = 3;
CopyBase = 5;
SpaceBase = 0;
Const
ProgId = 'TINY V1.0 (C) Copyright June 1993, by Mike Wiering';
Max = $FFFF;
MaxMethods = 13;
MethodsUsed: Byte = 0;
TotalProcLength: Word = 0;
Const
Safe = $10;
Type
BufferPtr = ^Buffer;
Buffer = Array[1..Max] of Char;
Type
MethodRec = Record
Number: Byte;
UnpackProc: Pointer;
ProcLength: Word;
end;
Var
Prog,
NewProg: BufferPtr;
Filename, Oldname: String;
OrigSize,
ProgSize,
NewSize,
NewProgSize,
MaxBytes,
MaxGain: Word;
InputFile,
OutputFile: File;
Percent,
OldPercent,
MaxMethod, LastMethod: Byte;
M: Array[1..MaxMethods] of MethodRec;
StartSize, DoneSize: Byte;
Procedure StartUnpack; Assembler;
asm
mov si, 0000 { Program offset }
mov di, 0000 { Unpack buffer }
mov ax, 0000 { Program size }
mov bx, 0000 { Adderss UnpackDone }
mov dx, 0000 { Procedure tabel }
mov bp, di
push ax
push bx
cld
@1: lodsb
mov ah, 0
shl al, 1
jnc @2
ret
db 0
db 'TINY'
db 0
@2: mov bx, ax
add bx, dx
lodsb
mov cx, ax
call Word Ptr [bx]
jmp @1
ret
end;
Procedure UnpackDone; Assembler;
asm
pop cx
mov si, bp
mov di, 100h
push di
rep
movsb
ret
end;
Procedure UnpackMoveB; Assembler;
asm
rep
movsb
ret
end;
Procedure UnpackMoveW; Assembler;
asm
lodsb
mov ch, al
rep
movsb
ret
end;
Procedure UnpackDupB; Assembler;
asm
lodsb
rep
stosb
ret
end;
Procedure UnpackDupW; Assembler;
asm
lodsb
mov ch, al
lodsb
rep
stosb
ret
end;
Procedure UnpackDupWord; Assembler;
asm
lodsw
rep
stosw
ret
end;
Procedure UnpackIncB; Assembler;
asm
lodsb
@1: stosb
inc al
loop @1
ret
end;
Procedure UnpackIncW; Assembler;
asm
lodsw
@1: stosw
inc ax
loop @1
ret
end;
Procedure UnpackDecB; Assembler;
asm
lodsb
@1: stosb
dec al
loop @1
ret
end;
Procedure UnpackDecW; Assembler;
asm
lodsw
@1: stosw
dec ax
loop @1
ret
end;
Procedure UnpackSkip; Assembler;
asm
lodsb
@1: stosb
movsb
loop @1
ret
end;
Procedure UnpackCopy; Assembler;
asm
lodsw
push si
mov si, bp
add si, ax
rep
movsb
pop si
ret
end;
Procedure UnpackSpaceB; Assembler;
asm
@1: lodsb
cmp al, 7Fh
jnz @2
movsb
jmp @4
@2: test al, 80h
jz @3
and al, 7Fh
stosb
mov al, ' '
@3: stosb
@4: loop @1
ret
end;
Procedure UnpackSpaceW; Assembler;
asm
lodsb
mov ch, al
@1: lodsb
cmp al, 7Fh
jnz @2
movsb
jmp @4
@2: test al, 80h
jz @3
and al, 7Fh
stosb
mov al, ' '
@3: stosb
@4: loop @1
ret
end;
Procedure Error(Msg: String);
begin
WriteLn(Msg);
Halt;
end;
Procedure ShowInformation;
begin
WriteLn(#13#10 +
ProgId + #13#10 +
'Program to compress COM-programs'#13#10 +
#13#10 +
'Syntax: TINY filename');
Halt;
end;
Procedure ReadFile;
begin
Assign(InputFile, Filename);
Reset(InputFile, 1);
if IOresult <> 0 then
Error('Cannot open ' + Filename);
BlockRead(InputFile, Prog^[1], SizeOf(Buffer), OrigSize);
Close(InputFile);
if OrigSize > $E000 then
Error(#13'Sorry, program too large.');
end;
Function CountLength(var P): Word;
Var
Len: Word;
begin
asm
push ds
lds si, P
xor cx, cx
cld
@1: lodsw
dec si
inc cx
cmp ax, 0C3C3h
jnz @1
mov Len, cx
pop ds
end;
CountLength := Len;
end;
Procedure InitMethods;
Var
i: Byte;
begin
for i := 1 to MaxMethods do
M[i].Number := $FF;
M[mdStoreB].UnpackProc := @UnpackMoveB;
M[mdStoreW].UnpackProc := @UnpackMoveW;
M[mdDupB].UnpackProc := @UnpackDupB;
M[mdDupW].UnpackProc := @UnpackDupW;
M[mdDupWord].UnpackProc := @UnpackDupWord;
M[mdIncB].UnpackProc := @UnpackIncB;
M[mdIncW].UnpackProc := @UnpackIncW;
M[mdDecB].UnpackProc := @UnpackDecB;
M[mdDecW].UnpackProc := @UnpackDecW;
M[mdSkipOne].UnpackProc := @UnpackSkip;
M[mdCopy].UnpackProc := @UnpackCopy;
M[mdSpaceB].UnpackProc := @UnpackSpaceB;
M[mdSpaceW].UnpackProc := @UnpackSpaceW;
for i := 1 to MaxMethods do
M[i].ProcLength := CountLength(M[i].UnpackProc^);
end;
Procedure Init;
begin
if ParamCount < 1 then
ShowInformation;
if MaxAvail < 2 * SizeOf(Buffer) then
Error('Not enough memory');
GetMem(Prog, SizeOf(Buffer));
GetMem(NewProg, SizeOf(Buffer));
Filename := ParamStr(1);
if Pos('.', Filename) = 0 then
Filename := Filename + '.COM';
StartSize := CountLength(@StartUnpack^) - 1;
DoneSize := CountLength(@UnpackDone^);
ReadFile;
Move(@UnpackDone^, Prog^[OrigSize + 1], DoneSize);
ProgSize := OrigSize + DoneSize;
NewSize := 0;
OldPercent := $FF;
InitMethods;
end;
Function WordStr(W: Word): String;
begin
WordStr := Chr(Lo(W)) + Chr(Hi(W));
end;
Procedure CompressProgram;
Var
Pos,
Address,
StoreNumberPos,
StoreNumber: Word;
PosChar,
NextChar: Char;
Procedure CompressText;
Const
MaxText = 10000;
Var
Start, i, j, NumSpaces, SpecialChars: Word;
N: Byte;
Cmds: Integer;
FirstTime, Special: Boolean;
Buffer: Array[1..MaxText] of Char;
begin
if (LastMethod = mdStoreB) and (StoreNumber = 255) then Exit;
Start := StoreNumberPos + 1 + Byte(LastMethod = mdStoreW);
NumSpaces := 0;
SpecialChars := 0;
for i := Start to NewSize do
Case NewProg^[i] of
#127..#255: Inc(SpecialChars);
' ': Inc(NumSpaces);
end;
if NumSpaces > SpaceBase + 2 * SpecialChars then
begin
Cmds := 0;
SpecialChars := 0;
j := 1;
Special := False;
for i := Start to NewSize do
if (NewProg^[i] = ' ') and (j > 1) and
(Buffer[j - 1] < #128) and (not Special) then
begin
Buffer[j - 1] := Chr(Ord(Buffer[j - 1]) + $80);
end
else
if (NewProg^[i] in [#127..#255]) then
begin
Buffer[j] := #127;
Buffer[j + 1] := NewProg^[i];
Inc(j, 2);
Inc(SpecialChars);
Inc(Cmds);
Special := True;
end
else
begin
Buffer[j] := NewProg^[i];
Inc(j);
Inc(Cmds);
Special := False;
end;
Move(Buffer[1], NewProg^[Start], j);
NewSize := NewSize + Cmds + SpecialChars - StoreNumber;
if LastMethod = mdStoreB then N := mdSpaceB else N := mdSpaceW;
LastMethod := N;
FirstTime := (M[N].Number = $FF);
if FirstTime then
begin
M[N].Number := MethodsUsed;
Inc(MethodsUsed);
Inc(TotalProcLength, M[N].ProcLength);
end;
NewProg^[StoreNumberPos - 1] := Chr(M[N].Number);
StoreNumber := Cmds;
NewProg^[StoreNumberPos] := Chr(Lo(StoreNumber));
if N = mdSpaceW then
NewProg^[StoreNumberPos + 1] := Chr(Hi(StoreNumber));
end;
end;
Procedure StartNewMethod(N: Byte);
begin
if LastMethod in [mdStoreB, mdStoreW] then
CompressText;
LastMethod := N;
if M[N].Number <> $FF then Exit;
M[N].Number := MethodsUsed;
Inc(MethodsUsed);
Inc(TotalProcLength, M[N].ProcLength);
end;
Procedure WriteToProg(S: String);
Var
i: Word;
begin
for i := 1 to Length(S) do
NewProg^[NewSize + i] := S[i];
Inc(NewSize, Length(S));
end;
Procedure StartNewNumber;
begin
StartNewMethod(mdStoreB);
WriteToProg(Chr(M[mdStoreB].Number));
WriteToProg(#0);
StoreNumberPos := NewSize;
StoreNumber := 0;
end;
Procedure JustStoreChar(C: Char);
Var
i: Word;
begin
WriteToProg(C);
if StoreNumber = 255 then
begin
StartNewMethod(mdStoreW);
For i := NewSize DownTo StoreNumberPos + 1 do
NewProg^[i + 1] := NewProg^[i];
NewProg^[StoreNumberPos - 1] := Chr(M[mdStoreW].Number);
Inc(NewSize);
end;
Inc(StoreNumber);
NewProg^[StoreNumberPos] := Chr(Lo(StoreNumber));
if StoreNumber > 255 then
NewProg^[StoreNumberPos + 1] := Chr(Hi(StoreNumber));
end;
Procedure StopStore;
begin
if StoreNumber = 0 then
begin
Dec(NewSize, 2);
LastMethod := $FF;
end;
end;
Procedure CheckDup;
Var
Count: Word;
begin
Count := 0;
While (Prog^[Pos + Count] = PosChar) and (Pos + Count < ProgSize) do
Inc(Count);
if Count > MaxGain + DupBase then
begin
if Count > 255 then
MaxMethod := mdDupW
else
MaxMethod := mdDupB;
MaxBytes := Count;
MaxGain := Count - DupBase;
end;
end;
Procedure CheckDupWord;
Var
Count: Word;
begin
Count := 0;
While (Prog^[Pos + (2 * Count)] = PosChar) and
(Prog^[Pos + (2 * Count) + 1] = NextChar) and
(Count < $FF) and (Pos + (2 * Count) + 1 < ProgSize) do
Inc(Count);
if Count > MaxGain + DupWordBase then
begin
MaxMethod := mdDupWord;
MaxBytes := Count;
MaxGain := (Count - DupWordBase) * 2;
end;
end;
Procedure CheckIncByte;
Var
Count: Word;
Ch: Byte;
begin
Count := 0;
Ch := Ord(PosChar);
While (Prog^[Pos + Count] = Chr(Ch)) and (Count < $FF)
and (Pos + Count < ProgSize) do
begin
Inc(Count);
Inc(Ch);
end;
if Count > MaxGain + IncBase then
begin
MaxMethod := mdIncB;
MaxBytes := Count;
MaxGain := Count - IncBase;
end;
end;
Procedure CheckDecByte;
Var
Count: Word;
Ch: Byte;
begin
Count := 0;
Ch := Ord(PosChar);
While (Prog^[Pos + Count] = Chr(Ch)) and (Count < $FF)
and (Pos + Count < ProgSize) do
begin
Inc(Count);
Dec(Ch);
end;
if Count > MaxGain + DecBase then
begin
MaxMethod := mdDecB;
MaxBytes := Count;
MaxGain := Count - DecBase;
end;
end;
Procedure CheckIncWord;
Var
Count: Word;
W: Word;
begin
Count := 0;
W := Ord(PosChar) + Ord(NextChar) * $100;
While (Prog^[Pos + 2 * Count] = Chr(Lo(W))) and
(Prog^[Pos + 2 * Count + 1] = Chr(Hi(W))) and
(Count < $FF) and (Pos + 2 * Count + 1 < ProgSize) do
begin
Inc(Count);
Inc(W);
end;
if Count > MaxGain + IncWordBase then
begin
MaxMethod := mdIncW;
MaxBytes := Count;
MaxGain := (Count - IncWordBase) * 2;
end;
end;
Procedure CheckDecWord;
Var
Count: Word;
W: Word;
begin
Count := 0;
W := Ord(PosChar) + Ord(NextChar) * $100;
While (Prog^[Pos + 2 * Count] = Chr(Lo(W))) and
(Prog^[Pos + 2 * Count + 1] = Chr(Hi(W))) and
(Count < $FF) and (Pos + 2 * Count + 1 < ProgSize) do
begin
Inc(Count);
Dec(W);
end;
if Count > MaxGain + DecWordBase then
begin
MaxMethod := mdDecW;
MaxBytes := Count;
MaxGain := (Count - DecWordBase) * 2;
end;
end;
Procedure CheckSkip;
Var
Count: Word;
i: Byte;
begin
Count := 0;
i := 0;
While (Prog^[Pos + 2 * Count] = PosChar) and (Count < $FF)
and (i < DupWordBase) and (Pos + 2 * Count + 2 < ProgSize) do
begin
Inc(Count);
if (Count > 0) and (Prog^[Pos + 2 * Count - 1] = Prog^[Pos + 2 * Count - 3]) then
Inc(i)
else
i := 0;
end;
if (i >= DupWordBase) then
if Count > i then
Dec(Count, i)
else
Count := 0;
if Count > MaxGain + SkipBase then
begin
MaxMethod := mdSkipOne;
MaxBytes := Count;
MaxGain := Count - SkipBase;
end;
end;
Procedure CheckCopy;
Var
S: String;
StrLen: Byte Absolute S;
MaxLen, i: Word;
j: Byte;
begin
Move(Prog^[Pos], S[1], SizeOf(S) - 1);
StrLen := 255;
if Pos + 255 > ProgSize then
StrLen := ProgSize - Pos + 1;
if StrLen > Pos - 1 then StrLen := Pos - 1;
if StrLen < CopyBase then Exit;
MaxLen := 0;
for i := 1 to Pos - 1 do
begin
j := 0;
While (S[j + 1] = Prog^[i + j]) and (j < StrLen) and (i + j < Pos) do
Inc(j);
if j > MaxLen then
begin
MaxLen := j;
Address := i;
end;
end;
if MaxLen > MaxGain + CopyBase then
begin
MaxMethod := mdCopy;
MaxBytes := MaxLen;
MaxGain := MaxLen - CopyBase;
end;
end;
Procedure StoreDup;
begin
if MaxBytes <= 255 then
begin
StartNewMethod(mdDupB);
WriteToProg(Chr(M[mdDupB].Number));
WriteToProg(Chr(MaxBytes));
end
else
begin
StartNewMethod(mdDupW);
WriteToProg(Chr(M[mdDupW].Number));
WriteToProg(WordStr(MaxBytes));
end;
WriteToProg(PosChar);
end;
Procedure StoreDupWord;
begin
StartNewMethod(mdDupWord);
WriteToProg(Chr(M[mdDupWord].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar + NextChar);
Inc(Pos, MaxBytes);
end;
Procedure StoreIncB;
begin
StartNewMethod(mdIncB);
WriteToProg(Chr(M[mdIncB].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar);
end;
Procedure StoreDecB;
begin
StartNewMethod(mdDecB);
WriteToProg(Chr(M[mdDecB].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar);
end;
Procedure StoreIncW;
begin
StartNewMethod(mdIncW);
WriteToProg(Chr(M[mdIncW].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar + NextChar);
Inc(Pos, MaxBytes);
end;
Procedure StoreDecW;
begin
StartNewMethod(mdDecW);
WriteToProg(Chr(M[mdDecW].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar + NextChar);
Inc(Pos, MaxBytes);
end;
Procedure StoreSkip;
Var
i: Word;
begin
StartNewMethod(mdSkipOne);
WriteToProg(Chr(M[mdSkipOne].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(PosChar);
for i := 0 to MaxBytes - 1 do
WriteToProg(Prog^[Pos + 1 + 2 * i]);
Inc(Pos, MaxBytes);
end;
Procedure StoreCopy;
begin
StartNewMethod(mdCopy);
WriteToProg(Chr(M[mdCopy].Number));
WriteToProg(Chr(MaxBytes));
WriteToProg(WordStr(Address - 1));
end;
begin
Pos := 0;
OldPercent := $FF;
StartNewNumber;
repeat
MaxMethod := 0;
MaxBytes := 0;
MaxGain := 0;
Inc(Pos);
PosChar := Prog^[Pos];
NextChar := Prog^[Pos + 1];
Percent := Byte((LongInt(Pos) * 100) div ProgSize);
if Percent <> OldPercent then
begin
Write(#13, Percent, '%');
OldPercent := Percent;
end;
CheckDup;
CheckDupWord;
CheckIncByte;
CheckDecByte;
CheckIncWord;
CheckDecWord;
CheckSkip;
CheckCopy;
if MaxGain = 0 then
JustStoreChar(Prog^[Pos])
else
begin
StopStore;
Case MaxMethod of
mdDupB,
mdDupW: StoreDup;
mdDupWord: StoreDupWord;
mdIncB: StoreIncB;
mdDecB: StoreDecB;
mdIncW: StoreIncW;
mdDecW: StoreDecW;
mdSkipOne: StoreSkip;
mdCopy: StoreCopy;
end;
Inc(Pos, MaxBytes - 1);
StartNewNumber;
end;
if ProgSize + NewSize + $1000 > Max then
Error(#13'Sorry, program too large.');
until Pos >= ProgSize;
StopStore;
if LastMethod in [mdStoreB, mdStoreW] then
CompressText;
WriteToProg(#$FF);
end;
Procedure WriteProg;
Var
Buf: Array[0..1000] of Char;
W: String[2];
i, j: Integer;
Count: Word;
begin
Assign(OutputFile, 'TINY.$$$');
ReWrite(OutputFile, 1);
Move(@StartUnpack^, Buf[1], StartSize);
W := WordStr($0100 + StartSize + MethodsUsed * 2 + TotalProcLength);
Buf[2] := W[1];
Buf[3] := W[2];
W := WordStr($0100 + StartSize + MethodsUsed * 2 + TotalProcLength +
NewSize);
Buf[5] := W[1];
Buf[6] := W[2];
W := WordStr(OrigSize);
Buf[8] := W[1];
Buf[9] := W[2];
W := WordStr($0100 + StartSize + MethodsUsed * 2 + TotalProcLength +
NewSize + OrigSize);
Buf[11] := W[1];
Buf[12] := W[2];
W := WordStr($0100 + StartSize);
Buf[14] := W[1];
Buf[15] := W[2];
BlockWrite(OutputFile, Buf[1], StartSize);
Count := $0100 + StartSize + MethodsUsed * 2;
for i := 0 to MaxMethods - 1 do
for j := 1 to MaxMethods do
if M[j].Number = i then
begin
W := WordStr(Count);
BlockWrite(OutputFile, W[1], 2);
Inc(Count, M[j].ProcLength);
end;
for i := 0 to MaxMethods - 1 do
for j := 1 to MaxMethods do
if M[j].Number = i then
begin
BlockWrite(OutputFile, M[j].UnpackProc^, M[j].ProcLength);
end;
BlockWrite(OutputFile, NewProg^[1], NewSize);
Close(OutputFile);
end;
Procedure Done;
begin
FreeMem(Prog, SizeOf(Buffer));
end;
begin
Init;
WriteLn(ProgId);
Filename := FExpand(Filename);
WriteLn('Compressing ' + Filename);
CompressProgram;
NewProgSize := StartSize + MethodsUsed * 2 + TotalProcLength + NewSize;
Write(#13'Old size: ', OrigSize, ' New size: ', NewProgSize,
' Gain: ', LongInt(OrigSize) - NewProgSize, ' (');
WriteLn(((LongInt(OrigSize) - NewProgSize) / OrigSize) * 100:1:2, '%)');
if OrigSize > NewProgSize then
begin
WriteProg;
if Pos('.', Filename) = 0 then
OldName := Filename + '.OLD'
else
OldName := Copy(Filename, 1, Pos('.', Filename) - 1) + '.OLD';
Rename(InputFile, Oldname);
Rename(OutputFile, Filename);
end
else
begin
WriteLn('Sorry, this program cannot be compressed.');
end;
Done;
end.
|
unit uFormBuscaProduto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIForm, uniDBNavigator, uniLabel, uniEdit, uniPanel,
uniGUIBaseClasses, uniImageList, uniBasicGrid, uniDBGrid, uniButton,
uniBitBtn, Data.DB, UniFSButton, uFrCadProdutos ;
type
TformBuscaProduto = class(TUniForm)
dsProduto: TDataSource;
UniDBGrid1: TUniDBGrid;
UniNativeImageList1: TUniNativeImageList;
UniPanel1: TUniPanel;
UniPanel2: TUniPanel;
UniLabel8: TUniLabel;
EdPesquisar: TUniEdit;
ubtSair: TUniFSButton;
btCancelar: TUniFSButton;
procedure UniFormCreate(Sender: TObject);
procedure UniDBGrid1DblClick(Sender: TObject);
procedure EdPesquisarChange(Sender: TObject);
procedure ubtSairClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function formBuscaProduto: TformBuscaProduto;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication, uDados, Main, uFrCaixa, uFuncoes;
function formBuscaProduto: TformBuscaProduto;
begin
Result := TformBuscaProduto(UniMainModule.GetFormInstance(TformBuscaProduto));
end;
procedure TformBuscaProduto.btCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TformBuscaProduto.EdPesquisarChange(Sender: TObject);
begin
// pesquisa dinamica na tabela Usuario
dmDados.QueryProduto.SQL.Clear;
dmDados.QueryProduto.SQL.Add('select * from PRODUTOS where');
dmDados.QueryProduto.SQL.Add('(DESCRICAO LIKE '+QuotedStr('%'+EdPesquisar.Text+'%') );
dmDados.QueryProduto.SQL.Add('or ID LIKE '+QuotedStr('%'+EdPesquisar.Text+'%') );
dmDados.QueryProduto.SQL.Add(')order by ID ');
dmDados.QueryProduto.Open;
end;
//
procedure TformBuscaProduto.ubtSairClick(Sender: TObject);
var
xDescricao : string;
begin
end;
procedure TformBuscaProduto.UniDBGrid1DblClick(Sender: TObject);
begin
ubtSairClick(Sender);
end;
procedure TformBuscaProduto.UniFormCreate(Sender: TObject);
begin
dmDados.QueryProduto.Close;
EdPesquisar.Text := '';
end;
end.
|
unit VA508AccessibilityManagerEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.CheckLst, Vcl.ImgList, Vcl.ComCtrls,
Vcl.ToolWin,
Vcl.StdCtrls, Vcl.ExtCtrls, VA508AccessibilityManager, ColnEdit;
type
Tva508CollectionEditor = class(TForm)
pnlLeft: TPanel;
pnlRight: TPanel;
splMain: TSplitter;
chkDefault: TCheckBox;
cmbAccessLbl: TComboBox;
cmbAccessProp: TComboBox;
memAccessTxt: TMemo;
lbCtrllList: TLabel;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ImageList1: TImageList;
lblAccLbl: TLabel;
lblAccProp: TLabel;
lnlAccTxt: TLabel;
pnlLstView: TPanel;
lstAccessCol: TCheckListBox;
lblAccColumns: TLabel;
lstCtrls: TListView;
StatusBar1: TStatusBar;
lblHeader: TLabel;
procedure lstCtrlsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure memAccessTxtChange(Sender: TObject);
procedure cmbAccessLblChange(Sender: TObject);
procedure cmbAccessPropChange(Sender: TObject);
procedure chkDefaultClick(Sender: TObject);
procedure lstAccessColClickCheck(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fInternal: Boolean;
fCollection: TVA508AccessibilityCollection;
fOwnerCtrl: TVA508AccessibilityManager;
fOldHint: TNotifyEvent;
procedure MyHint(Sender: TObject);
procedure ClearAll;
Function GetAccessItem: TVA508AccessibilityItem;
procedure SetAccessData(Sender: TObject; AccessItem: TVA508AccessibilityItem);
procedure ClearControl(aObj: TObject; aEvent: String; AccessItem: TVA508AccessibilityItem);
public
{ Public declarations }
procedure FillOutList(aCollection: TVA508AccessibilityCollection;
aOwnerCtrl: TVA508AccessibilityManager);
// constructor Create(AOwner: TComponent); override;
// destructor Destroy; override;
// property Collection: TVA508AccessibilityCollection read fCollection write fCollection;
// property OwnerForm: TComponent read fOwnerForm write fOwnerForm;
end;
var
va508CollectionEditor: Tva508CollectionEditor;
implementation
uses
system.TypInfo;
const
HeaderTxt = 'Settings for %s';
{$R *.dfm}
procedure Tva508CollectionEditor.MyHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
Function Tva508CollectionEditor.GetAccessItem: TVA508AccessibilityItem;
begin
Result := nil;
if lstCtrls.ItemIndex > -1 then
Result := TVA508AccessibilityItem(lstCtrls.Items[lstCtrls.ItemIndex].Data);
end;
procedure Tva508CollectionEditor.ClearAll;
begin
lblHeader.Caption := '';
ClearControl(chkDefault, 'OnClick', nil);
ClearControl(cmbAccessLbl, 'OnChange', nil);
ClearControl(cmbAccessProp, 'OnChange', nil);
ClearControl(memAccessTxt, 'OnChange', nil);
pnlLstView.Visible := false;
lstAccessCol.Clear;
end;
procedure Tva508CollectionEditor.lstCtrlsSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var
EdtItem: TVA508AccessibilityItem;
I, tmpIdx: integer;
tmpObj: TColumnList;
begin
if (not Assigned(Item.Data)) or (not Selected) then
exit;
ClearAll;
EdtItem := Item.Data;
fOwnerCtrl.GetProperties(EdtItem.Component, cmbAccessProp.Items);
// Fill out the fields
chkDefault.Checked := EdtItem.UseDefault;
lblHeader.Caption := Format(HeaderTxt, [EdtItem.DisplayName]);
if Assigned(EdtItem.AccessLabel) then
cmbAccessLbl.ItemIndex := cmbAccessLbl.Items.IndexOf
(EdtItem.AccessLabel.Name);
cmbAccessProp.ItemIndex := cmbAccessProp.Items.IndexOf
(EdtItem.AccessProperty);
memAccessTxt.Text := EdtItem.AccessText;
if EdtItem.Component is TListView then
begin
pnlLstView.Visible := true;
//Build the list
tmpObj := EdtItem.AccessColumns;
if Assigned(tmpObj) then
begin
for I := 0 to TListView(EdtItem.Component).Columns.Count - 1 do
begin
tmpIdx := lstAccessCol.Items.Add(TListView(EdtItem.Component).Column[i].Caption);
lstAccessCol.Checked[tmpIdx] := tmpObj.ColumnValues[I];
end;
end;
end;
end;
procedure Tva508CollectionEditor.ClearControl(aObj: TObject; aEvent: String; AccessItem: TVA508AccessibilityItem);
const
NILEvnt: TMethod = (Code: NIL; Data: NIL);
var
fMethodHwnd: TMethod;
begin
fMethodHwnd := GetMethodProp(aObj, aEvent);
SetMethodProp(aObj, aEvent, NILEvnt);
try
if aObj = chkDefault then
begin
chkDefault.Checked := false;
if Assigned(AccessItem) then
AccessItem.UseDefault := false;
end;
if aObj = cmbAccessLbl then
begin
cmbAccessLbl.ItemIndex := -1;
if Assigned(AccessItem) then
AccessItem.AccessLabel := nil;
end;
if aObj = cmbAccessProp then
begin
cmbAccessProp.ItemIndex := -1;
if Assigned(AccessItem) then
AccessItem.AccessProperty := '';
end;
if aObj = memAccessTxt then
begin
memAccessTxt.text := '';
if Assigned(AccessItem) then
AccessItem.AccessText := '';
end;
finally
SetMethodProp(aObj, aEvent, fMethodHwnd);
end;
end;
procedure Tva508CollectionEditor.SetAccessData(Sender: TObject; AccessItem: TVA508AccessibilityItem);
var
SelTxt: String;
SelLabel: TComponent;
begin
if Sender = chkDefault then
begin
AccessItem.UseDefault := chkDefault.Checked;
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
ClearControl(memAccessTxt, 'OnChange', AccessItem);
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
end else if Sender = cmbAccessLbl then
begin
if cmbAccessLbl.ItemIndex > -1 then
begin
SelTxt := cmbAccessLbl.Items.Strings[cmbAccessLbl.ItemIndex];
SelLabel := fOwnerCtrl.Owner.FindComponent(SelTxt);
AccessItem.AccessLabel := TLabel(SelLabel);
ClearControl(chkDefault, 'OnClick', AccessItem);
ClearControl(memAccessTxt, 'OnChange', AccessItem);
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
end else
AccessItem.AccessLabel := nil;
end else if Sender = cmbAccessLbl then
begin
AccessItem.AccessProperty := cmbAccessProp.Items.Strings[cmbAccessProp.ItemIndex];
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
ClearControl(memAccessTxt, 'OnChange', AccessItem);
ClearControl(chkDefault, 'OnClick', AccessItem);
end else if Sender = memAccessTxt then
begin
AccessItem.AccessText := memAccessTxt.Text;
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
ClearControl(chkDefault, 'OnClick', AccessItem);
ClearControl(cmbAccessLbl, 'OnChange', AccessItem);
end;
end;
procedure Tva508CollectionEditor.lstAccessColClickCheck(Sender: TObject);
var
AccessItem: TVA508AccessibilityItem;
tmpObj: TColumnList;
ColNum: Integer;
begin
AccessItem := GetAccessItem;
if Assigned(AccessItem) then
begin
tmpObj := AccessItem.AccessColumns;
ColNum := lstAccessCol.ItemIndex;
tmpObj.ColumnValues[ColNum] := lstAccessCol.Checked[lstAccessCol.ItemIndex];
// AccessItem.AccessColumns := tmpObj;
end;
end;
procedure Tva508CollectionEditor.chkDefaultClick(Sender: TObject);
var
AccessItem: TVA508AccessibilityItem;
begin
AccessItem := GetAccessItem;
if Assigned(AccessItem) then
SetAccessData(chkDefault, AccessItem);
end;
procedure Tva508CollectionEditor.memAccessTxtChange(Sender: TObject);
var
AccessItem: TVA508AccessibilityItem;
begin
AccessItem := GetAccessItem;
if Assigned(AccessItem) then
SetAccessData(memAccessTxt, AccessItem);
end;
procedure Tva508CollectionEditor.cmbAccessLblChange(Sender: TObject);
var
AccessItem: TVA508AccessibilityItem;
begin
AccessItem := GetAccessItem;
if Assigned(AccessItem) then
SetAccessData(cmbAccessLbl, AccessItem);
end;
procedure Tva508CollectionEditor.cmbAccessPropChange(Sender: TObject);
var
AccessItem: TVA508AccessibilityItem;
begin
AccessItem := GetAccessItem;
if Assigned(AccessItem) then
SetAccessData(cmbAccessProp, AccessItem);
end;
procedure Tva508CollectionEditor.FillOutList(aCollection
: TVA508AccessibilityCollection; aOwnerCtrl: TVA508AccessibilityManager);
var
aItem: TListItem;
I: integer;
tmpStrLst: TStringList;
begin
lstCtrls.Clear;
fCollection := aCollection;
fOwnerCtrl := aOwnerCtrl;
for I := 0 to fCollection.Count - 1 do
begin
aItem := lstCtrls.Items.Add;
aItem.Caption := fCollection.Items[I].Component.Name;
aItem.Data := fCollection.Items[I];
end;
// Prefill the available label list
tmpStrLst := TStringList.Create;
try
fOwnerCtrl.GetLabelStrings(tmpStrLst);
cmbAccessLbl.Items.Assign(tmpStrLst);
finally
tmpStrLst.Free;
end;
fInternal := false;
end;
procedure Tva508CollectionEditor.FormCreate(Sender: TObject);
begin
fOldHint := Application.OnHint;
Application.OnHint := MyHint;
end;
procedure Tva508CollectionEditor.FormDestroy(Sender: TObject);
begin
Application.OnHint := fOldHint;
end;
{
constructor Tva508CollectionEditor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor Tva508CollectionEditor.Destroy;
begin
inherited Destroy;
end; }
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright (c) 2000-2001, Borland Software Corporation }
{ }
{*******************************************************}
unit ReqFiles;
interface
uses SysUtils, Classes, Contnrs, HTTPApp;
type
{ TWebRequestFile }
TWebRequestFile = class(TAbstractWebRequestFile)
private
FFieldName: string;
FFileName: string;
FStream: TStream;
FContentType: string;
protected
function GetFieldName: string; override;
function GetFileName: string; override;
function GetStream: TStream; override;
function GetContentType: string; override;
public
constructor Create(const AFieldName, AFileName, AContentType: string;
AContent: Pointer; AContentLength: Integer);
destructor Destroy; override;
end;
{ TWebRequestFiles }
TWebRequestFiles = class(TAbstractWebRequestFiles)
private
FList: TObjectList;
protected
function GetCount: Integer; override;
function GetItem(I: Integer): TAbstractWebRequestFile; override;
public
constructor Create;
destructor Destroy; override;
procedure Add(const AName, AFileName, AContentType: string; AContent: Pointer; AContentLength: Integer); overload;
procedure Add(AFile: TWebRequestFile); overload;
end;
TWebRequestFileStream = class(TCustomMemoryStream)
public
constructor Create(ABuffer: Pointer; Size: Integer);
function Write(const Buffer; Count: Longint): Longint; override;
end;
implementation
uses WebConst, WebComp, BrkrConst;
{ TWebRequestFiles }
procedure TWebRequestFiles.Add(const AName, AFileName, AContentType: string;
AContent: Pointer; AContentLength: Integer);
begin
Add(TWebRequestFile.Create(AName, AFileName, AContentType,
AContent, AContentLength));
end;
procedure TWebRequestFiles.Add(AFile: TWebRequestFile);
begin
FList.Add(AFile);
end;
constructor TWebRequestFiles.Create;
begin
FList := TObjectList.Create(True {Owned});
inherited Create;
end;
destructor TWebRequestFiles.Destroy;
begin
inherited;
FList.Free;
end;
function TWebRequestFiles.GetCount: Integer;
begin
Result := FList.Count;
end;
function TWebRequestFiles.GetItem(I: Integer): TAbstractWebRequestFile;
begin
Result := FList[I] as TAbstractWebRequestFile;
end;
{ TWebRequestFile }
constructor TWebRequestFile.Create(const AFieldName, AFileName, AContentType: string;
AContent: Pointer; AContentLength: Integer);
begin
FFieldName := AFieldName;
FFileName := AFileName;
FContentType := AContentType;
FStream := TWebRequestFileStream.Create(AContent, AContentLength);
inherited Create;
end;
destructor TWebRequestFile.Destroy;
begin
inherited;
FStream.Free;
end;
function TWebRequestFile.GetContentType: string;
begin
Result := FContentType;
end;
function TWebRequestFile.GetFieldName: string;
begin
Result := FFieldName;
end;
function TWebRequestFile.GetFileName: string;
begin
Result := FFileName;
end;
function TWebRequestFile.GetStream: TStream;
begin
Result := FStream;
end;
{ TWebRequestFileStream }
constructor TWebRequestFileStream.Create(ABuffer: Pointer; Size: Integer);
begin
SetPointer(ABuffer, Size);
inherited Create;
end;
function TWebRequestFileStream.Write(const Buffer;
Count: Integer): Longint;
begin
// Write not supported
Assert(False);
Result := 0;
end;
end.
|
unit uTestuGraphicPrimitive;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Windows, uExceptionCodes, uExceptions, GdiPlus, Classes, SysUtils,
uDrawingSupport, Graphics, uBase, uEventModel, uGraphicPrimitive;
type
// Test methods for class TGraphicPrimitive
TestTGraphicPrimitive = class(TTestCase)
strict private
FGraphicPrimitive: TGraphicPrimitive;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestDraw;
procedure TestRemoveAllChildren;
procedure TestDelChild;
procedure TestDelChild1;
procedure TestParent;
procedure TestIndexColor;
procedure TestPoints;
procedure TestFirstPoint;
procedure TestSecondPoint;
procedure TestBackground;
procedure TestName;
end;
TestTBackground = class(TTestCase)
private
FBackground : TBackground;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestDraw;
end;
TestTSelect = class(TTestCase)
private
FSelect : TSelect;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestDraw;
end;
TestTBox = class(TTestCase)
private
FBox : TBox;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestDraw;
procedure TestInitCoord;
end;
implementation
procedure TestTGraphicPrimitive.SetUp;
begin
FGraphicPrimitive := TGraphicPrimitive.Create( nil );
end;
procedure TestTGraphicPrimitive.TearDown;
begin
FGraphicPrimitive.Free;
FGraphicPrimitive := nil;
end;
procedure TestTGraphicPrimitive.TestDraw;
var
aGraphics: IGPGraphics;
begin
// TODO: Setup method call parameters
FGraphicPrimitive.DrawNormal(aGraphics);
FGraphicPrimitive.DrawIndex(aGraphics);
// TODO: Validate method results
end;
procedure TestTGraphicPrimitive.TestFirstPoint;
begin
FGraphicPrimitive.FirstPoint := TPoint.Create( 11, 12 );
Check( FGraphicPrimitive.FirstPoint.X = 11 );
Check( FGraphicPrimitive.FirstPoint.Y = 12 );
end;
procedure TestTGraphicPrimitive.TestIndexColor;
var
c : TColor;
i, j : integer;
Prm, RPrm : TGraphicPrimitive;
arr : array[0..1000] of TColor;
begin
RPrm := TGraphicPrimitive.Create(nil);
Prm := RPrm;
for I := low(arr) to length(arr) - 1 do begin
Prm := TGraphicPrimitive.Create( Prm );
arr[i] := Prm.IndexColor;
end;
for I := low(arr) to length( arr ) - 1 do begin
c := arr[i];
for j := i + 1 to length( arr ) - 1 do begin
check( c <> arr[j] );
end;
end;
end;
procedure TestTGraphicPrimitive.TestName;
begin
FGraphicPrimitive.Name := 'aaa';
Check( FGraphicPrimitive.Name = 'aaa' );
end;
procedure TestTGraphicPrimitive.TestParent;
var
PrimP, PrimC : TGraphicPrimitive;
begin
PrimP := TGraphicPrimitive.Create(nil);
PrimC := TGraphicPrimitive.Create( PrimP );
try
Check( PrimC.Parent = PrimP );
Check( PrimP.ChildCount = 1 );
Check( PrimP.Child[0] = PrimC );
finally
PrimP.Free;
end;
end;
procedure TestTGraphicPrimitive.TestPoints;
var
P : TPoint;
begin
FGraphicPrimitive.Points.Add( 10, 11 );
P := FGraphicPrimitive.Points.Point[0];
Check( P.X = 10 );
Check( P.Y = 11 );
P := FGraphicPrimitive.Points.Point[1];
end;
procedure TestTGraphicPrimitive.TestRemoveAllChildren;
var
i, j : integer;
begin
randomize;
for I := 0 to 100 do begin
for j := 0 to random(100) do begin
TGraphicPrimitive.Create( FGraphicPrimitive );
end;
FGraphicPrimitive.RemoveAllChildren;
Check( FGraphicPrimitive.ChildCount = 0 );
end;
end;
procedure TestTGraphicPrimitive.TestSecondPoint;
begin
FGraphicPrimitive.FirstPoint := TPoint.Create( 11, 12 );
FGraphicPrimitive.SecondPoint := TPoint.Create( 13, 14 );
Check( FGraphicPrimitive.SecondPoint.X = 13 );
Check( FGraphicPrimitive.SecondPoint.Y = 14 );
end;
procedure TestTGraphicPrimitive.TestBackground;
begin
FGraphicPrimitive.BackgroundColor := clBlue;
end;
procedure TestTGraphicPrimitive.TestDelChild;
var
i, m : Integer;
begin
randomize;
m := random(100) + 10;
for i := 0 to m-1 do begin
TGraphicPrimitive.Create( FGraphicPrimitive );
end;
FGraphicPrimitive.DelChild( 0 );
Check( FGraphicPrimitive.ChildCount = m -1 );
dec( m );
FGraphicPrimitive.DelChild( m - 1 );
Check( FGraphicPrimitive.ChildCount = m -1 );
end;
procedure TestTGraphicPrimitive.TestDelChild1;
var
aPrimitive: TGraphicPrimitive;
m, i : integer;
begin
randomize;
m := random(100) + 10;
for i := 0 to m do begin
TGraphicPrimitive.Create( FGraphicPrimitive );
end;
aPrimitive := FGraphicPrimitive.Child[0];
FGraphicPrimitive.DelChild(aPrimitive);
for I := 0 to FGraphicPrimitive.ChildCount-1 do begin
Check( FGraphicPrimitive.Child[i] <> aPrimitive );
end;
end;
{ TestTBackground }
procedure TestTBackground.SetUp;
begin
FBackground := TBackground.Create( nil );
end;
procedure TestTBackground.TearDown;
begin
FBackground.Free;
FBackground := nil;
end;
procedure TestTBackground.TestDraw;
var
G : IGPGraphics;
begin
G := TGPGraphics.Create( GetDc(0) );
FBackground.FirstPoint := TPoint.Create( Low(integer), 0 );
FBackground.DrawNormal( G );
FBackground.DrawIndex( G );
FBackground.FirstPoint := TPoint.Create( 0, Low(integer) );
FBackground.DrawNormal( G );
FBackground.DrawIndex( G );
FBackground.FirstPoint := TPoint.Create( High(integer), Low(integer) );
FBackground.DrawNormal( G );
FBackground.DrawIndex( G );
{ Не проходит
FBackground.FirstPoint := TPoint.Create( 0, High(integer) );
FBackground.DrawNormal( G );
FBackground.DrawIndex( G );
}
FBackground.FirstPoint := TPoint.Create( 10, 10 );
FBackground.DrawNormal( G );
FBackground.DrawIndex( G );
end;
{ TestTSelect }
procedure TestTSelect.SetUp;
begin
inherited;
FSelect := TSelect.Create(nil);
FSelect.BorderColor := clGreen;
end;
procedure TestTSelect.TearDown;
begin
FSelect.Free;
FSelect := nil;
inherited;
end;
procedure TestTSelect.TestDraw;
var
G : IGPGraphics;
i, j : integer;
begin
G := TGPGraphics.Create( GetDc(0) );
//FSelect.DrawNormal( G );
for I := -10 to 10 do
for j := 10 downto -10 do begin
FSelect.FirstPoint := TPoint.Create( i, j );
FSelect.SecondPoint := TPoint.Create( j, i );
FSelect.DrawNormal( G );
end;
end;
{ TestTBox }
procedure TestTBox.SetUp;
begin
inherited;
FBox := TBox.Create( nil );
end;
procedure TestTBox.TearDown;
begin
FreeAndNil( FBox );
inherited;
end;
procedure TestTBox.TestDraw;
var
G : IGPGraphics;
i, j : integer;
begin
G := TGPGraphics.Create( GetDc(0) );
// FBox.DrawNormal( G );
for I := -10 to 10 do
for j := 10 downto -10 do begin
FBox.FirstPoint := TPoint.Create( i, j );
FBox.SecondPoint := TPoint.Create( j, i );
FBox.DrawNormal( G );
FBox.DrawIndex( G );
end;
end;
procedure TestTBox.TestInitCoord;
begin
FBox.InitCoord( 10, 10 );
FBox.InitCoord( -10, 100 );
FBox.InitCoord( 0, 10 );
FBox.InitCoord( 10, 0 );
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTGraphicPrimitive.Suite);
RegisterTest(TestTBackground.Suite);
RegisterTest(TestTSelect.Suite);
RegisterTest(TestTBox.Suite);
end.
|
unit gzIO;
(************************************************************************
Pascal unit based on gzio.c -- IO on .gz files
Copyright (C) 1995-1998 Jean-loup Gailly.
Define NO_DEFLATE to compile this file without the compression code
Pascal translation based on code contributed by Francisco Javier Crespo
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Aug 2000
- ZLIB 113 changes
Feb 2002
- allow variable windowbits/memlevel in gzopen
- gzsetparams and gzeof in interface part
- DEF_WBITS instead of MAX_WBITS for inflate
- Source code reformating/reordering
- global {$I-} because bracketing IO functions leaves {I+} on
- check IOResult after writing .gz header
- make code work under BP7/DPMI&Win
Mar 2005
- Code cleanup for WWW upload
May 2005
- gzopen: typecast Long(stream.avail_in)
- do_flush: written: unsigned;
- gzerror: missing exit if s=nil
Aug 2008
- gzopen: assign with fpath
Jul 2009
- D12 fixes
Sep 2015
- UNIT_SCOPE fixes
------------------------------------------------------------------------
*************************************************************************)
interface
{$x+}
{$i-} {*we 0202}
uses
ZLibH;
const
SEEK_SET = 0; {seek from beginning of file}
SEEK_CUR = 1; {seek from current position}
SEEK_END = 2;
var
GZ_windowBits : int; { = -MAX_WBITS;} {*we 0202}
GZ_memLevel : int; { = DEF_MEM_LEVEL;} {allow variable windowbits/memlevel in gzopen}
type
gzFile = voidp;
z_off_t = long;
function gzopen(const fpath, fmode: str255): gzFile;
{-Opens a gzip (.gz) file for reading or writing.}
function gzread(f: gzfile; buf: voidp; len: uInt): int;
{-Reads the given number of uncompressed bytes from the compressed file.}
function gzgetc(f: gzfile): int;
{-Reads one byte from the compressed file.}
function gzgets(f: gzfile; buf: PChar8; len: int): PChar8;
{-Read a string from the compressed file}
function gzseek(f: gzfile; offset: z_off_t; whence: int): z_off_t;
{-Sets the starting position for the next gzread/gzwrite on the compressed file.}
function gzclose(f: gzfile): int;
{-Flushes all pending output if necessary, closes the compressed file}
function gzerror(f: gzfile; var errnum: Int): str255;
{-Flushes all pending output if necessary, closes the compressed file}
function gzsetparams(f: gzfile; level: int; strategy: int): int;
{-Update the compression level and strategy.}
function gzeof(f: gzfile): boolean;
{-Returns true when EOF has previously been detected reading the given input stream, otherwise false.}
function gztell(f: gzfile): z_off_t;
{-Returns the starting position for the next gzread or gzwrite on the given compressed file.}
{$ifndef NO_DEFLATE}
function gzwrite(f: gzFile; buf: voidp; len: uInt): int;
{-Writes the given number of uncompressed bytes into the compressed file.}
function gzputc(f: gzfile; c: char8): int;
{-Writes c, converted to an unsigned char, into the compressed file.}
function gzputs(f: gzfile; s: PChar8): int;
{-Writes the given null-terminated string to the compressed file}
function gzflush(f: gzFile; flush: int): int;
{-Flushes all pending output into the compressed file.}
{$endif} {NO_DEFLATE}
implementation
{$I zconf.inc}
uses
{$ifndef MSDOS}
{$ifndef VER70} {*we 0202: Not for BP7/Win}
{$ifdef UNIT_SCOPE}
system.SysUtils,
{$else}
SysUtils,
{$endif}
{$endif}
{$endif}
zlib, zcrc32;
{$ifdef UNIT_SCOPE}
{Should use system.Ansistrings but then D17 does not know strlen}
{$warn UNIT_DEPRECATED OFF}
{$warn SYMBOL_DEPRECATED OFF}
{$endif}
const
Z_EOF = -1; {same value as in STDIO.H}
Z_BUFSIZE = 16384;
gz_magic : array[0..1] of byte = ($1F, $8B); {gzip magic header}
{gzip flag byte }
{ASCII_FLAG = $01;} {bit 0 set: file probably ascii text }
HEAD_CRC = $02; {bit 1 set: header CRC present }
EXTRA_FIELD = $04; {bit 2 set: extra field present }
ORIG_NAME = $08; {bit 3 set: original file name present}
COMMENT = $10; {bit 4 set: file comment present }
RESERVED = $E0; {bits 5..7: reserved }
type
gz_stream = record
stream : z_stream;
z_err : int; {error code for last stream operation }
zs_eof : boolean; {set if end of input file }
zfile : file; {.gz file }
inbuf : pBytef; {input buffer }
outbuf : pBytef; {output buffer }
crc : uLong; {crc32 of uncompressed data }
msg, {error message - limit 79 chars }
path : string[79]; {path name for debugging only - limit 79 chars }
transparent : boolean; {true if input file is not a .gz file }
mode : char8; {'w' or 'r' }
startpos : long; {start of compressed data in file (header skipped)}
end;
type
gz_streamp = ^gz_stream;
{---------------------------------------------------------------------------}
function get_byte(s: gz_streamp): int;
{-Read a byte from a gz_stream. Updates next_in and avail_in.}
{Returns EOF for end of file.}
{IN assertion: the stream s has been sucessfully opened for reading.}
begin
with s^ do begin
if zs_eof then begin
get_byte := Z_EOF;
exit;
end;
if stream.avail_in=0 then begin
blockread(zfile, inbuf^, Z_BUFSIZE, stream.avail_in);
if stream.avail_in=0 then begin
zs_eof := true;
if IOResult<>0 then z_err := Z_ERRNO;
get_byte := Z_EOF;
exit;
end;
stream.next_in := inbuf;
end;
dec(stream.avail_in);
get_byte := stream.next_in^;
inc(stream.next_in);
end;
end;
{---------------------------------------------------------------------------}
procedure check_header(s: gz_streamp);
{-Check the gzip header of a gz_stream opened for reading.}
{Set the stream mode to transparent if the gzip magic header is not present.
Set s^.err to Z_DATA_ERROR if the magic header is present but the rest of
the header is incorrect.
IN assertion: the stream s has already been created sucessfully;
s^.stream.avail_in is zero for the first time, but may be non-zero
for concatenated .gz files.}
var
method: int; {method byte}
flags : int; {flags byte}
len : uInt;
c : int;
begin
with s^ do begin
{Check the gzip magic header}
for len := 0 to 1 do begin
c := get_byte(s);
if c<>gz_magic[len] then begin
if len<>0 then begin
inc(stream.avail_in);
dec(stream.next_in);
end;
if c<>Z_EOF then begin
inc(stream.avail_in);
dec(stream.next_in);
transparent := true;
end;
if stream.avail_in<>0 then z_err := Z_OK else z_err := Z_STREAM_END;
exit;
end;
end;
method := get_byte(s);
flags := get_byte(s);
if (method <> Z_DEFLATED) or ((flags and RESERVED) <> 0) then begin
z_err := Z_DATA_ERROR;
exit;
end;
for len := 0 to 5 do get_byte(s); {Discard time, xflags and OS code}
if (flags and EXTRA_FIELD) <> 0 then begin {skip the extra field}
len := uInt(get_byte(s));
len := len + (uInt(get_byte(s)) shr 8);
{len is garbage if EOF but the loop below will quit anyway}
while (len <> 0) and (get_byte(s) <> Z_EOF) do dec(len);
end;
if (flags and ORIG_NAME)<>0 then begin {skip the original file name}
repeat
c := get_byte(s);
until (c = 0) or (c = Z_EOF);
end;
if (flags and COMMENT)<>0 then begin {skip the .gz file comment}
repeat
c := get_byte(s);
until (c=0) or (c=Z_EOF);
end;
if (flags and HEAD_CRC)<>0 then begin {skip the header crc}
get_byte(s);
get_byte(s);
end;
if zs_eof then z_err := Z_DATA_ERROR else z_err := Z_OK;
end;
end;
{---------------------------------------------------------------------------}
function destroy(var s: gz_streamp): int;
{-Cleanup then free the given gz_stream. Return a zlib error code.}
{Try freeing in the reverse order of allocations.}
begin
destroy := Z_OK;
if not Assigned(s) then begin
destroy := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
if stream.state <> nil then begin
if mode='w' then begin
{$ifdef NO_DEFLATE}
destroy := Z_STREAM_ERROR;
{$else}
destroy := deflateEnd(s^.stream);
{$endif}
end
else if mode='r' then begin
destroy := inflateEnd(stream);
end;
end;
if path<>'' then begin
close(zfile);
if IOResult<>0 then destroy := Z_ERRNO;
end;
if z_err<0 then destroy := z_err;
if Assigned(inbuf) then FreeMem(inbuf, Z_BUFSIZE);
if Assigned(outbuf) then FreeMem(outbuf, Z_BUFSIZE);
end;
FreeMem(s, sizeof(gz_stream));
end;
{---------------------------------------------------------------------------}
function gzopen(const fpath, fmode: str255): gzFile;
{-Opens a gzip (.gz) file for reading or writing.}
{As Pascal does not use file descriptors, the code has been changed
to accept only path names.
The fmode parameter defaults to BINARY read or write operations ('r' or 'w')
but can also include a compression level ('w9') or a strategy: Z_FILTERED
as in 'w6f' or Z_HUFFMAN_ONLY as in 'w1h'. (See the description of
deflateInit2 for more information about the strategy parameter.)
gzopen can be used to open a file which is not in gzip format; in this
case, gzread will directly read from the file without decompression.
gzopen returns nil if the file could not be opened (non-zero IOResult)
or if there was insufficient memory to allocate the (de)compression state
(zlib error is Z_MEM_ERROR).}
var
i : uInt;
err : int;
level : int; {compression level}
strategy: int; {compression strategy}
s : gz_streamp;
{$ifndef NO_DEFLATE}
gzheader : array [0..9] of byte;
{$endif}
begin
if (fpath='') or (fmode='') then begin
gzopen := Z_NULL;
exit;
end;
GetMem(s,sizeof(gz_stream));
if not Assigned(s) then begin
gzopen := Z_NULL;
exit;
end;
level := Z_DEFAULT_COMPRESSION;
strategy := Z_DEFAULT_STRATEGY;
with s^ do begin
stream.zalloc := nil; {(alloc_func)0}
stream.zfree := nil; {(free_func)0}
stream.opaque := nil; {(voidpf)0}
stream.next_in := Z_NULL;
stream.next_out := Z_NULL;
stream.avail_in := 0;
stream.avail_out := 0;
path := fpath; {limit to 255 chars}
z_err := Z_OK;
zs_eof := false;
inbuf := Z_NULL;
outbuf := Z_NULL;
crc := crc32(0, Z_NULL, 0);
msg := '';
transparent := false;
mode := #0;
for i:=1 to length(mode) do begin
case fmode[i] of
'r' : mode := 'r';
'w' : mode := 'w';
'0'..'9' : level := ord(fmode[i])-ord('0');
'f' : strategy := Z_FILTERED;
'h' : strategy := Z_HUFFMAN_ONLY;
end;
end;
if mode=chr(0) then begin
destroy(s);
gzopen := gzFile(Z_NULL);
exit;
end;
if mode='w' then begin
{$ifdef NO_DEFLATE}
err := Z_STREAM_ERROR;
{$else}
{*we 0202: allow variable windowbits/memlevel in gzopen}
{windowBits is passed < 0 to suppress zlib header}
err := deflateInit2(stream, level, Z_DEFLATED, -abs(GZ_windowBits), GZ_memLevel, strategy);
GetMem(outbuf, Z_BUFSIZE);
stream.next_out := outbuf;
{$endif}
if (err <> Z_OK) or (outbuf = Z_NULL) then begin
destroy(s);
gzopen := gzFile(Z_NULL);
exit;
end;
end
else begin
GetMem(inbuf, Z_BUFSIZE);
stream.next_in := inbuf;
{windowBits is passed < 0 to tell that there is no zlib header}
{*we 0202: DEF_WBITS instead of MAX_WBITS for inflate}
err := inflateInit2_(stream, -DEF_WBITS, ZLIB_VERSION, sizeof(z_stream));
if (err <> Z_OK) or (inbuf = Z_NULL) then begin
destroy(s);
gzopen := gzFile(Z_NULL);
exit;
end;
end;
stream.avail_out := Z_BUFSIZE;
{*WE Aug.2008: Use fpath in assign because the original paszlib code }
{ Assign(s^.gzfile, s^.path); truncates names with more than 79 chars}
system.assign(zfile, {$ifdef unicode} string {$endif}(fpath));
if mode='w' then rewrite(zfile,1) else reset(zfile,1);
if IOResult<>0 then begin
destroy(s);
gzopen := gzFile(Z_NULL);
exit;
end;
if mode = 'w' then begin {Write a very simple .gz header}
{$ifndef NO_DEFLATE}
fillchar(gzheader, sizeof(gzheader),0);
gzheader[0] := gz_magic [0];
gzheader[1] := gz_magic [1];
gzheader[2] := Z_DEFLATED; {method}
blockwrite(zfile, gzheader, 10);
{*we 0202: check IOResult after write .gz header}
if IOResult<>0 then begin
destroy(s);
gzopen := gzFile(Z_NULL);
exit;
end;
startpos := Long(10);
{$endif}
end
else begin
check_header(s); {skip the .gz header}
startpos := FilePos(zfile) - Long(stream.avail_in);
end;
end;
gzopen := gzFile(s);
end;
{---------------------------------------------------------------------------}
function gzsetparams(f: gzfile; level: int; strategy: int): int;
{-Update the compression level and strategy.}
var
s: gz_streamp;
written: integer;
begin
s := gz_streamp(f);
if (s=nil) or (s^.mode <> 'w') then begin
gzsetparams := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
{Make room to allow flushing}
if stream.avail_out=0 then begin
stream.next_out := outbuf;
blockwrite(zfile, outbuf^, Z_BUFSIZE, written);
if (written <> Z_BUFSIZE) then z_err := Z_ERRNO;
stream.avail_out := Z_BUFSIZE;
end;
gzsetparams := deflateParams(stream, level, strategy);
end;
end;
{*we 113}
{---------------------------------------------------------------------------}
function getLong(s: gz_streamp): uLong;
{-Reads a long in LSB order from the given gz_stream. Sets z_err in case of error.}
var
x: packed array [0..3] of byte;
c: int;
begin
{x := uLong(get_byte(s)); - you can't do this with TP, no unsigned long}
{the following assumes a little endian machine and TP}
x[0] := byte(get_byte(s));
x[1] := byte(get_byte(s));
x[2] := byte(get_byte(s));
c := get_byte(s);
x[3] := byte(c);
if c=Z_EOF then s^.z_err := Z_DATA_ERROR;
GetLong := uLong(longint(x));
end;
{---------------------------------------------------------------------------}
function gzread(f: gzfile; buf: voidp; len: uInt): int;
{-Reads the given number of uncompressed bytes from the compressed file.}
{If the input file was not in gzip format, gzread copies the given number
of bytes into the buffer.
gzread returns the number of uncompressed bytes actually read
(0 for end of file, -1 for error).}
var
s : gz_streamp;
start : pBytef;
next_out : pBytef;
n : uInt;
crclen : uInt; {Buffer length to update CRC32} {*we113: filecrc/len deleted}
bytes : integer; {bytes actually read in I/O blockread}
total_in : uLong;
total_out: uLong;
begin
s := gz_streamp(f);
start := pBytef(buf); {starting point for crc computation}
if (s=nil) or (s^.mode<>'r') then begin
gzread := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
if (z_err=Z_DATA_ERROR) or (z_err=Z_ERRNO) then begin
gzread := -1;
exit;
end;
if z_err=Z_STREAM_END then begin
gzread := 0; {EOF}
exit;
end;
stream.next_out := pBytef(buf);
stream.avail_out := len;
while stream.avail_out<>0 do begin
if transparent then begin
{Copy first the lookahead bytes:}
n := stream.avail_in;
if n>stream.avail_out then n := stream.avail_out;
if n>0 then begin
zmemcpy(stream.next_out, stream.next_in, n);
inc(stream.next_out, n);
inc(stream.next_in, n);
dec(stream.avail_out, n);
dec(stream.avail_in, n);
end;
if stream.avail_out>0 then begin
blockread (zfile, stream.next_out^, stream.avail_out, bytes);
dec(stream.avail_out, uInt(bytes));
end;
dec(len, stream.avail_out);
inc(stream.total_in, uLong(len));
inc(stream.total_out, uLong(len));
gzread := int(len);
exit;
end; {if transparent}
if (stream.avail_in=0) and (not zs_eof) then begin
blockread(zfile, inbuf^, Z_BUFSIZE, stream.avail_in);
if stream.avail_in=0 then begin
zs_eof := true;
if IOResult<>0 then begin
z_err := Z_ERRNO;
break;
end;
end;
stream.next_in := inbuf;
end;
z_err := inflate(stream, Z_NO_FLUSH);
if z_err=Z_STREAM_END then begin
crclen := 0;
next_out := stream.next_out;
while next_out<>start do begin
dec(next_out);
inc(crclen); {Hack because Pascal cannot substract pointers}
end;
{Check CRC and original size}
crc := crc32(crc, start, crclen);
start := stream.next_out;
if crc<>getLong(s) then z_err := Z_DATA_ERROR
else begin
{*we 113}
{The uncompressed length returned by above getlong() may}
{be different from s->stream.total_out) in case of }
{concatenated .gz files. Check for such files: }
getLong(s);
{Check for concatenated .gz files:}
check_header(s);
if z_err=Z_OK then begin
total_in := stream.total_in;
total_out := stream.total_out;
inflateReset(stream);
stream.total_in := total_in;
stream.total_out := total_out;
crc := crc32(0, Z_NULL, 0);
end;
end;
end;
if (z_err<>Z_OK) or zs_eof then break;
end; {while}
crclen := 0;
next_out := stream.next_out;
while next_out<>start do begin
dec(next_out);
inc(crclen); {Hack because Pascal cannot substract pointers}
end;
crc := crc32(crc, start, crclen);
gzread := int(len - stream.avail_out);
end;
end;
{---------------------------------------------------------------------------}
function gzgetc(f: gzfile): int;
{-Reads one byte from the compressed file.}
{gzgetc returns this byte or -1 in case of end of file or error.}
var
c: byte;
begin
if gzread(f,@c,1)=1 then gzgetc := c else gzgetc := -1;
end;
{---------------------------------------------------------------------------}
function gzgets(f: gzfile; buf: PChar8; len: int): PChar8;
{-Read a string from the compressed file}
{Reads bytes from the compressed file until len-1 characters are read}
{or a newline character is read and transferred to buf, or an end-of-file
condition is encountered. The string is then zero-terminated.
gzgets returns buf, or Z_NULL in case of error.
The current implementation is not optimized at all.}
var
b : PChar8; {start of buffer}
bytes : Int; {number of bytes read by gzread}
gzchar: char8; {char read by gzread}
begin
if (buf=Z_NULL) or (len<=0) then begin
gzgets := Z_NULL;
exit;
end;
b := buf;
repeat
dec(len);
bytes := gzread(f, buf, 1);
gzchar := buf^;
inc(buf);
until (len=0) or (bytes<>1) or (gzchar=chr(13));
buf^ := chr(0);
if (b=buf) and (len>0) then gzgets := Z_NULL else gzgets := b;
end;
{$ifndef NO_DEFLATE}
{---------------------------------------------------------------------------}
function gzwrite(f: gzfile; buf: voidp; len: uInt): int;
{-Writes the given number of uncompressed bytes into the compressed file.}
{gzwrite returns the number of uncompressed bytes actually written
(0 in case of error).}
var
s: gz_streamp;
written: integer;
begin
s := gz_streamp(f);
if (s=nil) or (s^.mode<>'w') then begin
gzwrite := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
stream.next_in := pBytef(buf);
stream.avail_in := len;
while stream.avail_in<>0 do begin
if stream.avail_out=0 then begin
stream.next_out := outbuf;
blockwrite(zfile, outbuf^, Z_BUFSIZE, written);
if written<>Z_BUFSIZE then begin
z_err := Z_ERRNO;
break;
end;
stream.avail_out := Z_BUFSIZE;
end;
z_err := deflate(stream, Z_NO_FLUSH);
if z_err<>Z_OK then break;
end; {while}
crc := crc32(crc, buf, len);
gzwrite := int(len - stream.avail_in);
end;
end;
{---------------------------------------------------------------------------}
function gzputc(f: gzfile; c: char8): int;
{-Writes c, converted to an unsigned char, into the compressed file.}
{gzputc returns the value that was written, or -1 in case of error.}
begin
if gzwrite(f,@c,1)=1 then begin
{$ifdef FPC}
gzputc := int(ord(c))
{$else}
gzputc := int(c)
{$endif}
end
else gzputc := -1;
end;
{---------------------------------------------------------------------------}
function gzputs(f: gzfile; s: PChar8): int;
{-Writes the given null-terminated string to the compressed file}
{the terminating null character is excluded}
{gzputs returns the number of characters written, or -1 in case of error.}
{$ifdef VER70}
function StrLen(PS: PChar8): Word; assembler;
asm
cld
les di,PS
mov cx,0ffffh
xor al,al
repne scasb
mov ax,0fffeh
sub ax,cx
end;
{$endif}
begin
gzputs := gzwrite(f, voidp(s), strlen(s));
end;
{---------------------------------------------------------------------------}
function do_flush(f: gzfile; flush: int): int;
{-Flushes all pending output into the compressed file.}
{The parameter flush is as in the zdeflate() function.}
var
len : uInt;
done : boolean;
s : gz_streamp;
written: unsigned; {*we May 2005}
begin
done := false;
s := gz_streamp(f);
if (s=nil) or (s^.mode<>'w') then begin
do_flush := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
stream.avail_in := 0; {should be zero already anyway}
while true do begin
len := Z_BUFSIZE - stream.avail_out;
if len<>0 then begin
blockwrite(zfile, outbuf^, len, written);
if written<>len then begin
z_err := Z_ERRNO;
do_flush := Z_ERRNO;
exit;
end;
stream.next_out := outbuf;
stream.avail_out := Z_BUFSIZE;
end;
if done then break;
z_err := deflate(stream, flush);
{Ignore the second of two consecutive flushes:}
if (len=0) and (z_err=Z_BUF_ERROR) then z_err := Z_OK;
{deflate has finished flushing only when it hasn't used up
all the available space in the output buffer:}
done := (stream.avail_out <> 0) or (z_err = Z_STREAM_END);
if (z_err<>Z_OK) and (z_err<>Z_STREAM_END) then break;
end; {while}
if z_err=Z_STREAM_END then do_flush:=Z_OK else do_flush := z_err;
end;
end;
{---------------------------------------------------------------------------}
function gzflush(f: gzfile; flush: int): int;
{-Flushes all pending output into the compressed file.}
{The parameter flush is as in the zdeflate() function.
The return value is the zlib error number (see function gzerror below).
gzflush returns Z_OK if the flush parameter is Z_FINISH and all output
could be flushed.
gzflush should be called only when strictly necessary because it can
degrade compression.}
var
err: int;
s : gz_streamp;
begin
s := gz_streamp(f);
err := do_flush(f, flush);
if err<>0 then begin
gzflush := err;
exit;
end;
if s^.z_err=Z_STREAM_END then gzflush := Z_OK else gzflush := s^.z_err;
end;
{$endif} {NO DEFLATE}
{---------------------------------------------------------------------------}
function gzrewind(f: gzfile): int;
{-Rewinds input file.}
var
s: gz_streamp;
begin
s := gz_streamp(f);
if (s=nil) or (s^.mode<>'r') then begin
gzrewind := -1;
exit;
end;
with s^ do begin
z_err := Z_OK;
zs_eof := false;
stream.avail_in := 0;
stream.next_in := inbuf;
crc := crc32(0, Z_NULL, 0); {*we 113}
if startpos=0 then begin {not a compressed file}
seek(zfile, 0);
gzrewind := 0;
exit;
end;
inflateReset(stream);
seek(zfile, startpos);
gzrewind := int(IOResult);
end;
end;
{---------------------------------------------------------------------------}
function gzseek(f: gzfile; offset: z_off_t; whence: int): z_off_t;
{-Sets the starting position for the next gzread/gzwrite on the compressed file.}
{The offset represents a number of bytes from the beginning
of the uncompressed stream.
gzseek returns the resulting offset, or -1 in case of error.
SEEK_END is not implemented, returns error.
In this version of the library, gzseek can be extremely slow.}
var
s: gz_streamp;
size: uInt;
begin
s := gz_streamp(f);
if (s=nil) or (whence=SEEK_END) or (s^.z_err=Z_ERRNO) or (s^.z_err=Z_DATA_ERROR) then begin
gzseek := z_off_t(-1);
exit;
end;
with s^ do begin
if mode='w' then begin
{$ifdef NO_DEFLATE}
gzseek := z_off_t(-1);
exit;
{$else}
if whence=SEEK_SET then dec(offset, stream.total_in); {*we 113}
if offset<0 then begin;
gzseek := z_off_t(-1);
exit;
end;
{At this point, offset is the number of zero bytes to write.}
if inbuf = Z_NULL then begin
GetMem(inbuf, Z_BUFSIZE);
zmemzero(inbuf, Z_BUFSIZE);
end;
while offset>0 do begin
size := Z_BUFSIZE;
if offset<Z_BUFSIZE then size := uInt(offset);
size := gzwrite(f, inbuf, size);
if size=0 then begin
gzseek := z_off_t(-1);
exit;
end;
dec(offset,size);
end;
gzseek := z_off_t(stream.total_in);
exit;
{$endif}
end;
{Rest of function is for reading only}
{compute absolute position}
if whence=SEEK_CUR then inc(offset, stream.total_out);
if offset<0 then begin
gzseek := z_off_t(-1);
exit;
end;
if transparent then begin
stream.avail_in := 0;
stream.next_in := inbuf;
seek(zfile, offset);
if IOResult<>0 then begin
gzseek := z_off_t(-1);
exit;
end;
stream.total_in := uLong(offset);
stream.total_out := uLong(offset);
gzseek := z_off_t(offset);
exit;
end;
{For a negative seek, rewind and use positive seek}
if uLong(offset) >= stream.total_out then dec(offset, stream.total_out)
else if (gzrewind(f) <> 0) then begin
gzseek := z_off_t(-1);
exit;
end;
{offset is now the number of bytes to skip.}
if (offset<>0) and (outbuf=Z_NULL) then GetMem(outbuf, Z_BUFSIZE);
while offset>0 do begin
size := Z_BUFSIZE;
if offset<Z_BUFSIZE then size := int(offset);
size := gzread(f, outbuf, size);
if size<=0 then begin
gzseek := z_off_t(-1);
exit;
end;
dec(offset, size);
end;
gzseek := z_off_t(stream.total_out);
end;
end;
{---------------------------------------------------------------------------}
function gztell(f: gzfile): z_off_t;
{Returns the starting position for the next gzread or gzwrite on the given compressed file.}
{This position represents a number of bytes in the uncompressed data stream.}
begin
gztell := gzseek(f, 0, SEEK_CUR);
end;
{---------------------------------------------------------------------------}
function gzeof(f: gzfile): boolean;
{-Returns true when EOF has previously been detected reading the given input stream, otherwise false.}
var
s: gz_streamp;
begin
s := gz_streamp(f);
if (s=nil) or (s^.mode<>'r') then gzeof := false else gzeof := s^.zs_eof;
end;
{---------------------------------------------------------------------------}
procedure putLong(var f: file; x: uLong);
{-Outputs a longint in LSB order to the given file}
var
n: int;
c: byte;
begin
for n:=0 to 3 do begin
c := x and $FF;
blockwrite(f, c, 1);
x := x shr 8;
end;
end;
{---------------------------------------------------------------------------}
function gzclose(f: gzfile): int;
{-Flushes all pending output if necessary, closes the compressed file}
{and deallocates all the (de)compression state.}
{The return value is the zlib error number (see function gzerror below)}
var
err: int;
s : gz_streamp;
begin
s := gz_streamp(f);
if s=nil then begin
gzclose := Z_STREAM_ERROR;
exit;
end;
with s^ do begin
if mode='w' then begin
{$ifdef NO_DEFLATE}
gzclose := Z_STREAM_ERROR;
exit;
{$else}
err := do_flush(f, Z_FINISH);
if err<>Z_OK then begin
gzclose := destroy(gz_streamp(f));
exit;
end;
putLong(zfile, crc);
putLong(zfile, stream.total_in);
{$endif}
end;
end;
gzclose := destroy(gz_streamp(f));
end;
{---------------------------------------------------------------------------}
function gzerror(f: gzfile; var errnum: int): str255;
{-Returns the error message for the last error which occured on the given compressed file.}
{errnum is set to zlib error number. If an error occured in the file system
and not in the compression library, errnum is set to Z_ERRNO and the
application may consult errno to get the exact error code.}
var
m : str255;
s : gz_streamp;
begin
s := gz_streamp(f);
if s=nil then begin
errnum := Z_STREAM_ERROR;
gzerror := zError(Z_STREAM_ERROR);
exit; {*we 05.2005}
end;
with s^ do begin
errnum := z_err;
if errnum=Z_OK then begin
gzerror := zError(Z_OK);
exit;
end;
m := stream.msg;
if errnum=Z_ERRNO then m := '';
if m='' then m := zError(z_err);
msg := path+': '+m;
gzerror := msg;
end;
end;
begin
GZ_windowBits := -MAX_WBITS; {*we 0202}
GZ_memLevel := DEF_MEM_LEVEL; {allow variable windowbits/memlevel in gzopen}
end.
|
UNIT heaps;
{$mode objfpc}{$H+}
INTERFACE
TYPE
{ T_binaryHeap }
GENERIC T_binaryHeap<T>=object
TYPE
T_entry=record prio:double; payload:T; end;
T_payloadArray=array of T;
F_calcPrio=FUNCTION(CONST entry:T):double;
F_compare =FUNCTION(CONST x,y:T):boolean;
private
items:array of T_entry;
fill:longint;
prioCalculator:F_calcPrio;
comparator:F_compare;
PROCEDURE bubbleUp;
PROCEDURE bubbleDown;
public
CONSTRUCTOR createWithNumericPriority(CONST prio:F_calcPrio);
CONSTRUCTOR createWithComparator(CONST comp:F_compare);
DESTRUCTOR destroy;
PROCEDURE insert(CONST v:T);
PROCEDURE insert(CONST v:T; CONST Priority:double);
FUNCTION extractHighestPrio:T;
PROPERTY size:longint read fill;
FUNCTION getAll:T_payloadArray;
end;
IMPLEMENTATION
{ T_binaryHeap }
PROCEDURE T_binaryHeap.bubbleUp;
VAR i,j:longint;
tmp:T_entry;
begin
i:=fill-1;
j:=(i-1) div 2;
if comparator=nil then begin
while (i>0) and (items[i].prio>items[j].prio) do begin
tmp:=items[i]; items[i]:=items[j]; items[j]:=tmp;
i:=j;
j:=(i-1) div 2;
end;
end else begin
while (i>0) and comparator(items[i].payload,items[j].payload) do begin
tmp:=items[i]; items[i]:=items[j]; items[j]:=tmp;
i:=j;
j:=(i-1) div 2;
end;
end;
end;
PROCEDURE T_binaryHeap.bubbleDown;
FUNCTION largerChildIndex(CONST index:longint):longint; inline;
VAR leftChildIndex,
rightChildIndex:longint;
begin
leftChildIndex :=(index shl 1)+1;
rightChildIndex:=leftChildIndex+1;
if leftChildIndex>fill then result:=index else
if rightChildIndex>fill then result:=leftChildIndex else
if comparator<>nil then begin
if comparator(items[leftChildIndex].payload,items[rightChildIndex].payload)
then result:=leftChildIndex
else result:=rightChildIndex;
end else begin
if items[leftChildIndex].prio>items[rightChildIndex].prio
then result:=leftChildIndex
else result:=rightChildIndex;
end;
end;
FUNCTION isValidParent(CONST index:longint):boolean;
VAR leftChildIndex,
rightChildIndex:longint;
begin
leftChildIndex :=(index shl 1)+1;
rightChildIndex:=leftChildIndex+1;
if (leftChildIndex>fill) then exit(true);
if comparator<>nil then begin
if not(comparator(items[index].payload,items[leftChildIndex].payload)) then exit(false);
result:=(rightChildIndex<=fill) and comparator(items[index].payload,items[rightChildIndex].payload);
end else begin
if not(items[index].prio>=items[leftChildIndex].prio) then exit(false);
result:=(rightChildIndex<=fill) and (items[index].prio>=items[rightChildIndex].prio);
end;
end;
VAR i:longint=0;
j:longint;
tmp:T_entry;
begin
while (i<=fill) and not isValidParent(i) do begin
j:=largerChildIndex(i);
tmp:=items[i]; items[i]:=items[j]; items[j]:=tmp;
i:=j;
end;
end;
CONSTRUCTOR T_binaryHeap.createWithNumericPriority(CONST prio: F_calcPrio);
begin
setLength(items,1);
fill:=0;
prioCalculator:=prio;
comparator:=nil;
end;
CONSTRUCTOR T_binaryHeap.createWithComparator(CONST comp: F_compare);
begin
assert(comp<>nil);
setLength(items,1);
fill:=0;
prioCalculator:=nil;
comparator:=comp;
end;
DESTRUCTOR T_binaryHeap.destroy;
begin
setLength(items,0);
end;
PROCEDURE T_binaryHeap.insert(CONST v: T);
begin
assert((prioCalculator<>nil) or (comparator<>nil));
//ensure space
if fill>=length(items) then setLength(items,1+(length(items)*5 shr 2));
//add item
items[fill].payload:=v;
//calculate priority if possible
if prioCalculator<>nil then items[fill].prio:=prioCalculator(v);
inc(fill);
if fill>1 then bubbleUp;
end;
PROCEDURE T_binaryHeap.insert(CONST v:T; CONST Priority:double);
begin
//ensure space
if fill>=length(items) then setLength(items,1+(length(items)*5 shr 2));
//add item
items[fill].payload:=v;
items[fill].prio :=Priority;
inc(fill);
if fill>1 then bubbleUp;
end;
FUNCTION T_binaryHeap.extractHighestPrio: T;
begin
assert(fill>0);
result:=items[0].payload;
dec(fill);
if fill>0 then begin
items[0]:=items[fill];
bubbleDown;
end;
end;
FUNCTION T_binaryHeap.getAll: T_payloadArray;
VAR i:longint;
begin
setLength(result,fill);
for i:=0 to fill-1 do result[i]:=items[i].payload;
end;
end.
|
{===================================================================
NPC Schematics 2016
Tutorial: Halo Schematics
by Baharuddin Aziz
September 4, 2016
===================================================================}
program halo_schematics;
{ DEKLARASI VARIABEL }
var
// input
N : integer; // jumlah pengulangan
// process
i : integer; // variabel utk pengulangan FOR
suku_kata_awal : string; // suku kata 'Halo Schema'
suku_kata_akhir : string; // suku kata 'tics'
temp : string; // menampung suku 'tics' sebelum digabung
// output
suku_kata_total : string; // hasil penggabungan
begin
{ INISIALISASI VARIABEL }
// inisialisasi masukan yg bukan dari user
suku_kata_awal := 'Halo Schema';
suku_kata_akhir := 'tics';
suku_kata_total := suku_kata_awal;
// membaca masukan user
read(N);
{ ALGORITMA }
// proses penggabungan
for i := 1 to N do
suku_kata_total := suku_kata_total + suku_kata_akhir;
// menuliskan hasil penggabungan
writeln(suku_kata_total);
end. |
unit TestFileParse;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestFileParse, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ test that all test files can parse }
uses
TestFrameWork;
type
TTestFileParse = class(TTestCase)
private
procedure TestParseFile(psInFileName: string; const piTokenCount: integer); overload;
protected
procedure SetUp; override;
published
procedure TestDirs;
procedure TestCreate;
{ one proc for each file,
as it's nice to have a tick for each test file }
procedure Empty1;
procedure fFormTest;
procedure fBracketProp;
procedure LittleTest1;
procedure LittleTest2;
procedure LittleTest3;
procedure LittleTest4;
procedure LittleTest5;
procedure LittleTest6;
procedure LittleTest7;
procedure LittleTest8;
procedure LittleTest9;
procedure LittleTest10;
procedure LittleTest11;
procedure LittleTest12;
procedure LittleTest13;
procedure LittleTest14;
procedure LittleTest15;
procedure LittleTest16;
procedure LittleTest17;
procedure LittleTest18;
procedure LittleTest19;
procedure LittleTest20;
procedure LittleTest21;
procedure LittleTest22;
procedure LittleTest23;
procedure LittleTest24;
procedure LittleTest25;
procedure LittleTest26;
procedure LittleTest27;
procedure LittleTest28;
procedure LittleTest29;
procedure LittleTest30;
procedure LittleTest31;
procedure LittleTest32;
procedure LittleTest33;
procedure LittleTest34;
procedure LittleTest35;
procedure LittleTest36;
procedure LittleTest37;
procedure LittleTest38;
procedure LittleTest39;
procedure LittleTest40;
procedure LittleTest41;
procedure LittleTest42;
procedure LittleTest43;
procedure LittleTest44;
procedure LittleTest45;
procedure LittleTest46;
procedure LittleTest47;
procedure LittleTest48;
procedure LittleTest49;
procedure LittleTest50;
procedure LittleTest51;
procedure LittleTest52;
procedure LittleTest53;
procedure LittleTest54;
procedure LittleTest55;
procedure LittleTest56;
procedure LittleTest57;
procedure LittleTest58;
procedure LittleTest59;
procedure LittleTest60;
procedure LittleTest61;
procedure LittleTest62;
procedure TestAbsolute;
procedure TestAlign;
procedure TestArray;
procedure TestAsm;
procedure TestAsmStructs;
procedure TestAtExpr;
procedure TestBlankLineRemoval;
procedure TestBogusDirectives;
procedure TestBogusTypes;
procedure TestCaseBlock;
procedure TestCaseIfFormat;
procedure TestSimpleCast;
procedure TestCast;
procedure TestCharLiterals;
procedure TestClassLines;
procedure TestCommentIndent;
procedure TestCommentIndent2;
procedure TestCondReturns;
procedure TestConstRecords;
procedure TestD6;
procedure TestDeclarations;
procedure TestDeclarations2;
procedure TestDefaultParams;
procedure TestDefines;
procedure TestDeref;
procedure TestEmptyCase;
procedure TestEmptyClass;
procedure TestEmptySquareBrackets;
procedure TestEndElse;
procedure TestEsotericKeywords;
procedure TestExclusion;
procedure TestExclusionFlags;
procedure TestExternal;
procedure TestForward;
procedure TestGoto;
procedure TestInheritedExpr;
procedure TestInitFinal;
procedure TestInline;
procedure TestInterfaceImplements;
procedure TestInterfaceMap;
procedure TestInterfaces;
procedure TestLayout;
procedure TestLayoutBare;
procedure TestLayoutBare2;
procedure TestLayoutBare3;
procedure TestLibExports;
procedure TestLineBreaking;
procedure TestLocalTypes;
procedure TestLongStrings;
procedure TestMarcoV;
procedure TestMixedModeCaps;
procedure TestMessages;
procedure TestMVB;
procedure TestNested;
procedure TestNestedRecords;
procedure TestOleParams;
procedure TestOperators;
procedure TestParams;
procedure TestParamSpaces;
procedure TestPointers;
procedure TestProgram;
procedure TestProperties;
procedure TestPropertyLines;
procedure TestPropertyInherited;
procedure TestRaise;
procedure TestRecords;
procedure TestReg;
procedure TestReint;
procedure TestReturnRemoval;
procedure TestReturns;
procedure TestRunOnConst;
procedure TestRunOnDef;
procedure TestRunOnLine;
procedure TestSimpleIfDef;
procedure TestSimpleIfDef2;
procedure TestSimpleIfDef3;
procedure TestSimpleIfDef4;
procedure TestSimpleIfDef5;
procedure TestSimpleIfDef6;
procedure TestTestMH;
procedure TestTPObjects;
procedure TestTry;
procedure TestTypeDefs;
procedure TestUnitPlatform;
procedure TestUnitAllDirectives;
procedure TestUnitDeprecated;
procedure TestUnitLibrary;
procedure TestUses;
procedure TestUsesChanges;
procedure TestWarnings;
procedure TestWarnDestroy;
procedure TestVarParam;
procedure TestWith;
procedure TestProcBlankLines;
procedure TestCondCompBreaks;
procedure TestCondCompBreaks2;
procedure TestAsmLabel;
procedure TestDephiNetUses;
procedure TestForIn;
procedure TestConstBug;
procedure TestDottedName;
procedure TestDelphiNetClass;
procedure TestDelphiNetConst;
procedure TestDelphiNetStatic;
procedure TestTestDotNetForm1;
procedure TestDelphiNetOperatorOverload;
procedure TestDelphiNetHelperClass;
procedure TestDelphiNetNestedType;
procedure TestDelphiNetNestedType2;
procedure TestDelphiNetRecordForward;
procedure TestDelphiNetWebService;
procedure TestDelphiNetWebService2;
procedure TestDelphiNetAttributes;
procedure TestDelphiNetKeywords;
procedure TestDelphiNetClassVar;
procedure TestDelphiNetSealedClass;
procedure TestDelphiNetFinalMethod;
procedure TestDelphiNetDottedType;
procedure TestDelphiNetAmpersandMethod;
procedure TestDelphiNetMulticast;
procedure TestDelphiNetDynamicArray;
procedure TestDelphiNetRecordProcs;
procedure TestTryExceptRaise;
procedure TestTrailingCommaParam;
procedure TestDprNoBegin;
procedure TestDLLIndex;
procedure TestIncAt;
procedure TestAsmAnd;
procedure TestVarArgs;
procedure TestCases;
procedure TestPackage;
end;
implementation
uses
{ delphi }
SysUtils, Windows,
{ JCL }
JclFileUtils,
{ local }
FileConverter, ConvertTypes, JcfSettings, JcfRegistrySettings,
TestConstants;
procedure TTestFileParse.Setup;
begin
inherited;
InitTestSettings;
end;
procedure TTestFileParse.TestParseFile(psInFileName: string;
const piTokenCount: integer);
var
lcConverter: TFileConverter;
lsSettingsFileName, lsOutFileName: string;
begin
{ does it have an file extension? }
if Pos('.', psInFileName) <= 0 then
psInFileName := psInFileName + '.pas';
if Pos(PathSeparator, psInFileName) <= 0 then
psInFileName := GetTestFilesDir + psInFileName;
Check(FileExists(psInFileName), 'input file ' + psInFileName + ' not found');
lcConverter := TFileConverter.Create;
try
lcConverter.YesAll := True;
lcConverter.GuiMessages := False;
{ see also TestFullClarify }
lsSettingsFileName := GetTestSettingsFileName;
Check(FileExists(lsSettingsFileName), 'Settings file ' +
lsSettingsFileName + ' not found');
JcfFormatSettings.ReadFromFile(lsSettingsFileName, True);
JcfFormatSettings.Obfuscate.Enabled := False;
lcConverter.SourceMode := fmSingleFile;
lcConverter.BackupMode := cmSeparateOutput;
GetRegSettings.OutputExtension := 'out';
lcConverter.Input := psInFileName;
lcConverter.Convert;
Check( not lcConverter.ConvertError, 'Convert failed for ' +
ExtractFileName(psInFileName));
lsOutFileName := lcConverter.OutFileName;
Check(lsOutFileName <> '', 'No output file');
Check(FileExists(lsOutFileName), 'output file ' + lsOutFileName + ' not found');
CheckEquals(piTokenCount, lcConverter.TokenCount, 'wrong number of tokens');
// clean up
SysUtils.DeleteFile(lsOutFileName);
finally
lcConverter.Free;
end;
end;
procedure TTestFileParse.TestCreate;
var
lcConverter: TFileConverter;
begin
lcConverter := TFileConverter.Create;
lcConverter.Free;
end;
procedure TTestFileParse.TestDirs;
begin
Check(DirectoryExists(GetTestFilesDir), 'Test files dir ' +
GetTestFilesDir + ' not found');
Check(DirectoryExists(GetRefOutFilesDir), 'Test files ref out dir ' +
GetTestFilesDir + ' not found');
end;
procedure TTestFileParse.Empty1;
begin
TestParseFile('EmptyTest1', 18);
end;
procedure TTestFileParse.fFormTest;
begin
TestParseFile('fFormTest', 150);
end;
procedure TTestFileParse.LittleTest1;
begin
TestParseFile('LittleTest1', 28);
end;
procedure TTestFileParse.LittleTest2;
begin
TestParseFile('LittleTest2', 29);
end;
procedure TTestFileParse.LittleTest3;
begin
TestParseFile('LittleTest3', 42);
end;
procedure TTestFileParse.LittleTest4;
begin
TestParseFile('LittleTest4', 45);
end;
procedure TTestFileParse.LittleTest5;
begin
TestParseFile('LittleTest5', 58);
end;
procedure TTestFileParse.LittleTest6;
begin
TestParseFile('LittleTest6', 78);
end;
procedure TTestFileParse.LittleTest7;
begin
TestParseFile('LittleTest7', 109);
end;
procedure TTestFileParse.LittleTest8;
begin
TestParseFile('LittleTest8', 41);
end;
procedure TTestFileParse.TestAbsolute;
begin
TestParseFile('TestAbsolute', 86);
end;
procedure TTestFileParse.TestAlign;
begin
TestParseFile('TestAlign', 662);
end;
procedure TTestFileParse.TestArray;
begin
TestParseFile('TestArray', 220);
end;
procedure TTestFileParse.TestAsm;
begin
TestParseFile('TestAsm', 828);
end;
procedure TTestFileParse.TestBlankLineRemoval;
begin
TestParseFile('TestBlankLineRemoval', 373);
end;
procedure TTestFileParse.TestBogusDirectives;
begin
TestParseFile('TestBogusDirectives', 456);
end;
procedure TTestFileParse.TestBogusTypes;
begin
TestParseFile('TestBogusTypes', 230);
end;
procedure TTestFileParse.TestCaseBlock;
begin
TestParseFile('TestCaseBlock', 3041);
end;
procedure TTestFileParse.TestCast;
begin
TestParseFile('TestCast', 654);
end;
procedure TTestFileParse.TestSimpleCast;
begin
TestParseFile('TestCastSimple', 843);
end;
procedure TTestFileParse.TestCharLiterals;
begin
TestParseFile('TestCharLiterals', 1035);
end;
procedure TTestFileParse.TestClassLines;
begin
TestParseFile('TestClassLines', 71);
end;
procedure TTestFileParse.TestCommentIndent;
begin
TestParseFile('TestCommentIndent', 549);
end;
procedure TTestFileParse.TestCommentIndent2;
begin
TestParseFile('TestCommentIndent2', 361);
end;
procedure TTestFileParse.TestConstRecords;
begin
TestParseFile('TestConstRecords', 945);
end;
procedure TTestFileParse.TestD6;
begin
TestParseFile('TestD6', 959);
end;
procedure TTestFileParse.TestDeclarations;
begin
TestParseFile('TestDeclarations', 1004);
end;
procedure TTestFileParse.TestDeclarations2;
begin
TestParseFile('TestDeclarations2', 362);
end;
procedure TTestFileParse.TestDefaultParams;
begin
TestParseFile('TestDefaultParams', 698);
end;
procedure TTestFileParse.TestEmptyClass;
begin
TestParseFile('TestEmptyClass', 244);
end;
procedure TTestFileParse.TestEsotericKeywords;
begin
TestParseFile('TestEsotericKeywords', 258);
end;
procedure TTestFileParse.TestExclusion;
begin
TestParseFile('TestExclusion', 431);
end;
procedure TTestFileParse.TestExclusionFlags;
begin
TestParseFile('TestExclusionFlags', 723);
end;
procedure TTestFileParse.TestExternal;
begin
TestParseFile('TestExternal', 259);
end;
procedure TTestFileParse.TestForward;
begin
TestParseFile('TestForward', 332);
end;
procedure TTestFileParse.TestGoto;
begin
TestParseFile('TestGoto', 503);
end;
procedure TTestFileParse.TestInitFinal;
begin
TestParseFile('TestInitFinal', 170);
end;
procedure TTestFileParse.TestInterfaceImplements;
begin
TestParseFile('TestInterfaceImplements', 225);
end;
procedure TTestFileParse.TestInterfaceMap;
begin
TestParseFile('TestInterfaceMap', 397);
end;
procedure TTestFileParse.TestInterfaces;
begin
TestParseFile('TestInterfaces', 648);
end;
procedure TTestFileParse.TestLayout;
begin
TestParseFile('TestLayout', 1227);
end;
procedure TTestFileParse.TestLayoutBare;
begin
TestParseFile('TestLayoutBare', 1555);
end;
procedure TTestFileParse.TestLayoutBare2;
begin
TestParseFile('TestLayoutBare2', 1013);
end;
procedure TTestFileParse.TestLayoutBare3;
begin
TestParseFile('TestLayoutBare3', 1178);
end;
procedure TTestFileParse.TestLibExports;
begin
TestParseFile('TestLibExports', 119);
end;
procedure TTestFileParse.TestLineBreaking;
begin
TestParseFile('TestLineBreaking', 6108);
end;
procedure TTestFileParse.TestLocalTypes;
begin
TestParseFile('TestLocalTypes', 297);
end;
procedure TTestFileParse.TestLongStrings;
begin
TestParseFile('TestLongStrings', 163);
end;
procedure TTestFileParse.TestMarcoV;
begin
TestParseFile('TestMarcoV', 241);
end;
procedure TTestFileParse.TestTestMH;
begin
TestParseFile('TestMH', 2956);
end;
procedure TTestFileParse.TestMixedModeCaps;
begin
TestParseFile('TestMixedModeCaps', 123);
end;
procedure TTestFileParse.TestMVB;
begin
TestParseFile('TestMVB', 835);
end;
procedure TTestFileParse.TestNested;
begin
TestParseFile('TestNested', 658);
end;
procedure TTestFileParse.TestNestedRecords;
begin
TestParseFile('TestNestedRecords', 1189);
end;
procedure TTestFileParse.TestOleParams;
begin
TestParseFile('TestOleParams', 160);
end;
procedure TTestFileParse.TestOperators;
begin
TestParseFile('TestOperators', 1233);
end;
procedure TTestFileParse.TestParams;
begin
TestParseFile('TestParams', 218);
end;
procedure TTestFileParse.TestParamSpaces;
begin
TestParseFile('TestParamSpaces', 159);
end;
procedure TTestFileParse.TestPointers;
begin
TestParseFile('TestPointers', 193);
end;
procedure TTestFileParse.TestProgram;
begin
TestParseFile('TestProgram', 1246);
end;
procedure TTestFileParse.TestProperties;
begin
TestParseFile('TestProperties', 751);
end;
procedure TTestFileParse.TestPropertyLines;
begin
TestParseFile('TestPropertyLines', 1186);
end;
procedure TTestFileParse.TestRecords;
begin
TestParseFile('TestRecords', 1455);
end;
procedure TTestFileParse.TestReg;
begin
TestParseFile('TestReg', 85);
end;
procedure TTestFileParse.TestReint;
begin
TestParseFile('TestReint', 159);
end;
procedure TTestFileParse.TestReturnRemoval;
begin
TestParseFile('TestReturnRemoval', 256);
end;
procedure TTestFileParse.TestReturns;
begin
TestParseFile('TestReturns', 141);
end;
procedure TTestFileParse.TestRunOnConst;
begin
TestParseFile('TestRunOnConst', 465);
end;
procedure TTestFileParse.TestRunOnDef;
begin
TestParseFile('TestRunOnDef', 363);
end;
procedure TTestFileParse.TestRunOnLine;
begin
TestParseFile('TestRunOnLine', 3668);
end;
procedure TTestFileParse.TestTPObjects;
begin
TestParseFile('TestTPObjects', 126);
end;
procedure TTestFileParse.TestTry;
begin
TestParseFile('TestTry', 939);
end;
procedure TTestFileParse.TestTypeDefs;
begin
TestParseFile('TestTypeDefs', 793);
end;
procedure TTestFileParse.TestUses;
begin
TestParseFile('TestUses', 64);
end;
procedure TTestFileParse.TestUsesChanges;
begin
TestParseFile('TestUsesChanges', 56);
end;
procedure TTestFileParse.TestWarnings;
begin
TestParseFile('TestWarnings', 702);
end;
procedure TTestFileParse.TestWith;
begin
TestParseFile('TestWith', 735);
end;
procedure TTestFileParse.TestCases;
begin
TestParseFile('Testcases.dpr', 1301);
end;
procedure TTestFileParse.TestPackage;
begin
TestParseFile('TestMe.dpk', 684);
end;
procedure TTestFileParse.TestProcBlankLines;
begin
TestParseFile('TestProcBlankLines', 64);
end;
procedure TTestFileParse.TestVarArgs;
begin
TestParseFile('TestVarArgs', 43);
end;
procedure TTestFileParse.TestVarParam;
begin
TestParseFile('TestVarParam', 116);
end;
procedure TTestFileParse.LittleTest9;
begin
TestParseFile('LittleTest9', 69);
end;
procedure TTestFileParse.TestDeref;
begin
TestParseFile('TestDeref', 584);
end;
procedure TTestFileParse.TestPropertyInherited;
begin
TestParseFile('TestPropertyInherited', 797);
end;
procedure TTestFileParse.TestMessages;
begin
TestParseFile('TestMessages', 130);
end;
procedure TTestFileParse.LittleTest10;
begin
TestParseFile('LittleTest10', 375);
end;
procedure TTestFileParse.TestInheritedExpr;
begin
TestParseFile('TestInheritedExpr', 301);
end;
procedure TTestFileParse.LittleTest11;
begin
TestParseFile('LittleTest11', 97);
end;
procedure TTestFileParse.LittleTest12;
begin
TestParseFile('LittleTest12', 54);
end;
procedure TTestFileParse.LittleTest13;
begin
TestParseFile('LittleTest13', 86);
end;
procedure TTestFileParse.LittleTest14;
begin
TestParseFile('LittleTest14', 37);
end;
procedure TTestFileParse.LittleTest15;
begin
TestParseFile('LittleTest15', 41);
end;
procedure TTestFileParse.LittleTest16;
begin
TestParseFile('LittleTest16', 102);
end;
procedure TTestFileParse.LittleTest17;
begin
TestParseFile('LittleTest17', 102);
end;
procedure TTestFileParse.LittleTest18;
begin
TestParseFile('LittleTest18', 103);
end;
procedure TTestFileParse.TestAtExpr;
begin
TestParseFile('TestAtExpr', 79);
end;
procedure TTestFileParse.TestAsmStructs;
begin
TestParseFile('TestAsmStructs', 358);
end;
procedure TTestFileParse.TestUnitAllDirectives;
begin
TestParseFile('TestUnitAllDirectives', 21);
end;
procedure TTestFileParse.TestUnitDeprecated;
begin
TestParseFile('TestUnitDeprecated', 17);
end;
procedure TTestFileParse.TestUnitLibrary;
begin
TestParseFile('TestUnitLibrary', 17);
end;
procedure TTestFileParse.TestUnitPlatform;
begin
TestParseFile('TestUnitPlatform', 17);
end;
procedure TTestFileParse.LittleTest19;
begin
TestParseFile('LittleTest19', 168);
end;
procedure TTestFileParse.TestRaise;
begin
TestParseFile('TestRaise', 519);
end;
procedure TTestFileParse.LittleTest20;
begin
TestParseFile('LittleTest20', 62);
end;
procedure TTestFileParse.LittleTest21;
begin
TestParseFile('LittleTest21', 37);
end;
procedure TTestFileParse.LittleTest22;
begin
TestParseFile('LittleTest22', 53);
end;
procedure TTestFileParse.LittleTest23;
begin
TestParseFile('LittleTest23', 74);
end;
procedure TTestFileParse.LittleTest24;
begin
TestParseFile('LittleTest24', 69);
end;
procedure TTestFileParse.LittleTest25;
begin
TestParseFile('LittleTest25', 42);
end;
procedure TTestFileParse.LittleTest26;
begin
TestParseFile('LittleTest26', 97);
end;
procedure TTestFileParse.LittleTest27;
begin
TestParseFile('LittleTest27', 89);
end;
procedure TTestFileParse.TestEmptySquareBrackets;
begin
TestParseFile('TestEmptySquareBrackets', 66);
end;
procedure TTestFileParse.LittleTest28;
begin
TestParseFile('LittleTest28', 71);
end;
procedure TTestFileParse.LittleTest29;
begin
TestParseFile('LittleTest29', 141);
end;
procedure TTestFileParse.LittleTest30;
begin
TestParseFile('LittleTest30', 60);
end;
procedure TTestFileParse.LittleTest31;
begin
TestParseFile('LittleTest31', 58);
end;
procedure TTestFileParse.LittleTest32;
begin
TestParseFile('LittleTest32', 91);
end;
procedure TTestFileParse.LittleTest33;
begin
TestParseFile('LittleTest33', 45);
end;
procedure TTestFileParse.TestEmptyCase;
begin
TestParseFile('TestEmptyCase', 128);
end;
procedure TTestFileParse.TestCaseIfFormat;
begin
TestParseFile('TestCaseIfFormat', 294);
end;
procedure TTestFileParse.LittleTest34;
begin
TestParseFile('LittleTest34', 78);
end;
procedure TTestFileParse.LittleTest35;
begin
TestParseFile('LittleTest35', 38);
end;
procedure TTestFileParse.LittleTest36;
begin
TestParseFile('LittleTest36', 77);
end;
procedure TTestFileParse.LittleTest37;
begin
TestParseFile('LittleTest37', 76);
end;
procedure TTestFileParse.TestSimpleIfDef;
begin
TestParseFile('TestSimpleIfDef', 54);
end;
procedure TTestFileParse.TestSimpleIfDef2;
begin
TestParseFile('TestSimpleIfDef2', 33);
end;
procedure TTestFileParse.TestSimpleIfDef3;
begin
TestParseFile('TestSimpleIfDef3', 83);
end;
procedure TTestFileParse.TestSimpleIfDef4;
begin
TestParseFile('TestSimpleIfDef4', 92);
end;
procedure TTestFileParse.TestSimpleIfDef5;
begin
TestParseFile('TestSimpleIfDef5', 39);
end;
procedure TTestFileParse.LittleTest38;
begin
TestParseFile('LittleTest38', 53);
end;
procedure TTestFileParse.LittleTest39;
begin
TestParseFile('LittleTest39', 185);
end;
procedure TTestFileParse.LittleTest40;
begin
TestParseFile('LittleTest40', 143);
end;
procedure TTestFileParse.TestDefines;
begin
TestParseFile('TestDefines', 262);
end;
procedure TTestFileParse.LittleTest41;
begin
TestParseFile('LittleTest41', 47);
end;
procedure TTestFileParse.LittleTest42;
begin
TestParseFile('LittleTest42', 112);
end;
procedure TTestFileParse.LittleTest43;
begin
TestParseFile('LittleTest43', 413);
end;
procedure TTestFileParse.LittleTest44;
begin
TestParseFile('LittleTest44', 286);
end;
procedure TTestFileParse.LittleTest45;
begin
TestParseFile('LittleTest45', 177);
end;
procedure TTestFileParse.LittleTest46;
begin
TestParseFile('LittleTest46', 96);
end;
procedure TTestFileParse.LittleTest47;
begin
TestParseFile('LittleTest47', 268);
end;
procedure TTestFileParse.TestWarnDestroy;
begin
TestParseFile('TestWarnDestroy', 117);
end;
procedure TTestFileParse.LittleTest48;
begin
TestParseFile('LittleTest48', 204);
end;
procedure TTestFileParse.LittleTest49;
begin
TestParseFile('LittleTest49', 161);
end;
procedure TTestFileParse.LittleTest50;
begin
TestParseFile('LittleTest50', 135);
end;
procedure TTestFileParse.LittleTest51;
begin
TestParseFile('LittleTest51', 172);
end;
procedure TTestFileParse.LittleTest52;
begin
TestParseFile('LittleTest52', 39);
end;
procedure TTestFileParse.TestSimpleIfDef6;
begin
TestParseFile('TestSimpleIfDef6', 46);
end;
procedure TTestFileParse.LittleTest53;
begin
TestParseFile('LittleTest53', 60);
end;
procedure TTestFileParse.LittleTest54;
begin
TestParseFile('LittleTest54', 62);
end;
procedure TTestFileParse.LittleTest55;
begin
TestParseFile('LittleTest55', 66);
end;
procedure TTestFileParse.LittleTest56;
begin
TestParseFile('LittleTest56', 51);
end;
procedure TTestFileParse.LittleTest57;
begin
TestParseFile('LittleTest57', 204);
end;
procedure TTestFileParse.LittleTest58;
begin
TestParseFile('LittleTest58', 212);
end;
procedure TTestFileParse.LittleTest59;
begin
TestParseFile('LittleTest59', 61);
end;
procedure TTestFileParse.LittleTest60;
begin
TestParseFile('LittleTest60', 73);
end;
procedure TTestFileParse.LittleTest61;
begin
TestParseFile('LittleTest61', 24);
end;
procedure TTestFileParse.LittleTest62;
begin
TestParseFile('LittleTest62', 49);
end;
procedure TTestFileParse.TestInline;
begin
TestParseFile('TestInline', 92);
end;
procedure TTestFileParse.fBracketProp;
begin
TestParseFile('fBracketProp', 492);
end;
procedure TTestFileParse.TestEndElse;
begin
TestParseFile('TestEndElse', 106);
end;
procedure TTestFileParse.TestCondReturns;
begin
TestParseFile('TestCondReturns', 92);
end;
procedure TTestFileParse.TestDephiNetUses;
begin
TestParseFile('TestDelphiNetUses', 146);
end;
procedure TTestFileParse.TestConstBug;
begin
TestParseFile('TestConstBug', 157);
end;
procedure TTestFileParse.TestForIn;
begin
TestParseFile('TestForIn', 76);
end;
procedure TTestFileParse.TestDottedName;
begin
TestParseFile('test.dotted.name.pas', 23);
end;
procedure TTestFileParse.TestDelphiNetClass;
begin
TestParseFile('TestDelphiNetClass', 148);
end;
procedure TTestFileParse.TestDelphiNetConst;
begin
TestParseFile('TestDelphiNetConst', 125);
end;
procedure TTestFileParse.TestDelphiNetDottedType;
begin
TestParseFile('TestDelphiNetDottedType', 245);
end;
procedure TTestFileParse.TestDelphiNetDynamicArray;
begin
TestParseFile('TestDelphiNetDynamicArray', 797);
end;
procedure TTestFileParse.TestDelphiNetStatic;
begin
TestParseFile('TestDelphiNetStatic', 324);
end;
procedure TTestFileParse.TestTestDotNetForm1;
begin
TestParseFile('TestDotNetForm1', 356);
end;
procedure TTestFileParse.TestDelphiNetNestedType;
begin
TestParseFile('TestDelphiNetNestedType', 117);
end;
procedure TTestFileParse.TestDelphiNetNestedType2;
begin
TestParseFile('TestDelphiNetNestedType2', 174);
end;
procedure TTestFileParse.TestDelphiNetOperatorOverload;
begin
TestParseFile('TestDelphiNetOperatorOverload', 252);
end;
procedure TTestFileParse.TestDelphiNetHelperClass;
begin
TestParseFile('TestDelphiNetHelperClass', 158);
end;
procedure TTestFileParse.TestDelphiNetRecordForward;
begin
TestParseFile('TestDelphiNetRecordForward', 142);
end;
procedure TTestFileParse.TestDelphiNetRecordProcs;
begin
TestParseFile('TestDelphiNetRecordProcs', 698);
end;
procedure TTestFileParse.TestCondCompBreaks;
begin
TestParseFile('TestCondCompBreaks', 89);
end;
procedure TTestFileParse.TestCondCompBreaks2;
begin
TestParseFile('TestCondCompBreaks2', 88);
end;
procedure TTestFileParse.TestDelphiNetAmpersandMethod;
begin
TestParseFile('TestDelphiNetAmpersandMethod', 166);
end;
procedure TTestFileParse.TestDelphiNetAttributes;
begin
TestParseFile('TestDelphiNetAttributes', 247);
end;
procedure TTestFileParse.TestDelphiNetWebService;
begin
TestParseFile('TestDelphiNetWebService', 356);
end;
procedure TTestFileParse.TestDelphiNetWebService2;
begin
TestParseFile('TestDelphiNetWebService2', 432);
end;
procedure TTestFileParse.TestDelphiNetKeywords;
begin
TestParseFile('TestDelphiNetKeywords', 95);
end;
procedure TTestFileParse.TestDelphiNetMulticast;
begin
TestParseFile('TestDelphiNetMulticast', 65);
end;
procedure TTestFileParse.TestDelphiNetClassVar;
begin
TestParseFile('TestDelphiNetClassVar', 314);
end;
procedure TTestFileParse.TestTrailingCommaParam;
begin
TestParseFile('TestTrailingCommaParam', 189);
end;
procedure TTestFileParse.TestTryExceptRaise;
begin
TestParseFile('TestTryExceptRaise', 155);
end;
procedure TTestFileParse.TestDprNoBegin;
begin
TestParseFile('TestDprNoBegin.dpr', 168);
end;
procedure TTestFileParse.TestDLLIndex;
begin
TestParseFile('TestDLLIndex', 120);
end;
procedure TTestFileParse.TestIncAt;
begin
TestParseFile('TestIncAt', 53);
end;
procedure TTestFileParse.TestDelphiNetFinalMethod;
begin
TestParseFile('TestDelphiNetFinalMethod', 140);
end;
procedure TTestFileParse.TestDelphiNetSealedClass;
begin
TestParseFile('TestDelphiNetSealedClass', 200);
end;
procedure TTestFileParse.TestAsmAnd;
begin
TestParseFile('TestAsmAnd', 142);
end;
procedure TTestFileParse.TestAsmLabel;
begin
TestParseFile('TestAsmLabel', 52);
end;
initialization
TestFramework.RegisterTest(TTestFileParse.Suite);
end.
|
unit cosmobackground;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtDlgs, PluginTypes, LGPStruct, ExtCtrls, Math, FF7Types;
type
TfrmCosmoBackground = class(TForm)
Scroller: TScrollBox;
savBmp: TSaveDialog;
opnBmp: TOpenPictureDialog;
Image: TImage;
Panel1: TPanel;
cmbLayer: TComboBox;
btnExport: TBitBtn;
btnImport: TBitBtn;
btnSave: TBitBtn;
BitBtn1: TBitBtn;
procedure cmbLayerChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure btnImportClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSaveClick(Sender: TObject);
private
{ Private declarations }
Foreground, Background, Combine, Palette, Tiles: TBitmap;
RawLGP: TRawLGPFile;
CurFile: String;
Data: TMemoryStream;
procedure Cleanup;
procedure FillBitmaps;
procedure DoCombine;
public
{ Public declarations }
Plugin: TCosmoPlugin;
Rebuild: TCombinerFunc;
procedure OpenFile(FName:String);
end;
var
frmCosmoBackground: TfrmCosmoBackground;
implementation
{$R *.DFM}
procedure TfrmCosmoBackground.FillBitmaps;
var
K,J,TOffset,TDest,I,B3Off,BOff: Integer;
DCol,bgnsprites2,bgwidth,bgheight,bgnsprites: Word;
bgpsprites2,bgpsprites,psprite: PFF7BGSPRITE;
Col,Dest,Pal: PWord;
Source,Image,Comb,Picture,PB: PByte;
PI: PInteger;
Bmp: TBitmap;
begin
Data.Position := 2 + (8+1)*4;
Data.ReadBuffer(BOff,4); Inc(BOff,4);
Data.Position := 2 + (3+1)*4;
Data.ReadBuffer(B3Off,4); Inc(B3Off,4);
Data.Position := BOff + $28;
Data.ReadBuffer(bgwidth,2);
Data.Position := BOff + $2A;
Data.ReadBuffer(bgheight,2);
Data.Position := BOff + $2C;
Data.ReadBuffer(bgnsprites,2);
GetMem(bgpsprites,Sizeof(TFF7BGSPRITE)*bgnsprites);
Data.Position := BOff + $32;
Data.ReadBuffer(bgpsprites^,Sizeof(TFF7BGSPRITE)*bgnsprites);
Data.Position := BOff + bgnsprites*52+$39;
Data.ReadBuffer(bgnsprites2,2);
GetMem(bgpsprites2,Sizeof(TFF7BGSPRITE)*bgnsprites2);
Data.Position := BOff + $32 + bgnsprites*52 + $1B;
Data.ReadBuffer(bgpsprites2^,Sizeof(TFF7BGSPRITE)*bgnsprites2);
PB := Data.Memory;
Inc(PB,B3Off + $C);
Pal := Pointer(PB);
begin {Palette creation}
Palette := TBitmap.Create;
PB := Data.Memory;
Inc(PB,B3Off);
PI := Pointer(PB);
I := PI^ - $C;
Palette.Width := 256;
Palette.Height := (I div 2);
For J := 1 to (I div 2) do begin
Col := Pal;
Inc(Col,J-1);
K := ( (Col^ and $1F) shl 3 ) or ( ( (Col^ and $3E0) shr 5) shl 11) or ( ( (Col^ and $7C00) shr 10) shl 19);
Palette.Canvas.Brush.Color := K;
Palette.Canvas.Brush.Style := bsSolid;
Palette.Canvas.FillRect(Rect( (16*(J mod 16)),(16*(J div 16)),(16+16*(J mod 16)),(16+16*(J div 16))));
end;
end;
Picture := Data.Memory;
Inc(Picture,BOff + bgnsprites*52 + bgnsprites2*52 + $58);
GetMem(Image,bgwidth*bgheight*2);
{
Dest := Pointer(Image);
For I := 1 to bgwidth*bgheight do begin
Dest^ := $1F shl 5;
Inc(Dest);
end;
}
ZeroMemory(Image,bgwidth*bgheight*2);
For I := 0 to bgnsprites-1 do begin
PSprite := BGPSprites;
Inc(PSprite,I);
TOffset := (PSprite^.Page shl 16) or ( (PSprite^.SrcY shl 8) or (PSprite^.SrcX) ) + (PSprite^.Page+1)*6;
TDest := ((PSprite^.Y + (bgheight shr 1))*bgwidth)+(PSprite^.X+(bgwidth shr 1));
TDest := TDest shl 1;
If PSprite^.Sfx <> 0 then Continue;
For J := 0 to 15 do begin
Source := Picture;
If TOffset > Data.Size then Continue;
Inc(Source,TOffset);
PB := Image;
If TDest > (BGWidth*BGHeight*2) then Continue;
Inc(PB,TDest);
Dest := Pointer(PB);
For K := 0 to 15 do begin
If Source^=0 then begin
Inc(Source); Inc(Dest); Continue;
end;
If (Integer(Dest) > ( Integer(Image) + 2*BGHeight*BGWidth - 2 )) or (Integer(Dest) < Integer(Image)) then Continue;
Col := Pal;
Inc(Col, (PSprite^.Pal shl 8) + Source^ );
If Integer(Col) > ( Integer(Data.Memory) + Data.Size ) then Continue;
Inc(Source);
DCol := 0;
DCol := DCol or ( (Col^ and $1F) shl 10 );
DCol := DCol or (Col^ and $3E0);
DCol := DCol or ( (Col^ and $7C00) shr 10);
Dest^ := DCol;
Inc(Dest);
end;
TDest := TDest + (BGWidth shl 1);
Inc(TOffset,256);
end;
end;
Background := TBitmap.Create;
Background.PixelFormat := pf15Bit;
Background.Width := BGWidth;
Background.Height := BGHeight;
PB := Image;
For I := 0 to BGHeight-1 do begin
Source := Background.ScanLine[I];
CopyMemory(Source,PB,BGWidth*2);
Inc(PB,BGWidth*2);
end;
Dest := Pointer(Image);
For I := 1 to bgwidth*bgheight do begin
Dest^ := $1F shl 5;
Inc(Dest);
end;
For I := 0 to bgnsprites2-1 do begin
PSprite := BGPSprites2;
Inc(PSprite,I);
TOffset := (PSprite^.Page shl 16) or ( (PSprite^.SrcY shl 8) or (PSprite^.SrcX) ) + (PSprite^.Page+1)*6;
TDest := ((PSprite^.Y + (bgheight shr 1))*bgwidth)+(PSprite^.X+(bgwidth shr 1));
TDest := TDest shl 1;
If PSprite^.Sfx <> 0 then Continue;
For J := 0 to 15 do begin
Source := Picture;
If TOffset > Data.Size then Continue;
Inc(Source,TOffset);
PB := Image;
If TDest > (BGWidth*BGHeight*2) then Continue;
Inc(PB,TDest);
Dest := Pointer(PB);
For K := 0 to 15 do begin
If Source^=0 then begin
Inc(Source); Inc(Dest); Continue;
end;
If (Integer(Dest) > ( Integer(Image) + 2*BGHeight*BGWidth - 2 )) or (Integer(Dest) < Integer(Image)) then Continue;
Col := Pal;
Inc(Col, (PSprite^.Pal shl 8) + Source^ );
Inc(Source);
DCol := 0;
DCol := DCol or ( (Col^ and $1F) shl 10 );
DCol := DCol or (Col^ and $3E0);
DCol := DCol or ( (Col^ and $7C00) shr 10);
Dest^ := DCol; //!!!
Inc(Dest);
end;
TDest := TDest + (BGWidth shl 1);
Inc(TOffset,256);
end;
end;
Foreground := TBitmap.Create;
Foreground.PixelFormat := pf15Bit;
Foreground.Width := BGWidth;
Foreground.Height := BGHeight;
PB := Image;
For I := 0 to BGHeight-1 do begin
Source := Foreground.ScanLine[I];
CopyMemory(Source,PB,BGWidth*2);
Inc(PB,BGWidth*2);
end;
FreeMem(Image);
FreeMem(BGPSprites);
FreeMem(BGPSprites2);
end;
procedure TfrmCosmoBackground.cmbLayerChange(Sender: TObject);
begin
btnImport.Enabled := (cmbLayer.ItemIndex<>2);
Case cmbLayer.ItemIndex of
0: Image.Picture.Assign(Background);
1: Image.Picture.Assign(Foreground);
2: Image.Picture.Assign(Combine);
3: Image.Picture.Assign(Palette);
4: Image.Picture.Assign(Tiles);
end;
end;
procedure TfrmCosmoBackground.FormCreate(Sender: TObject);
begin
Foreground := nil; Background := nil; RawLGP := nil; Data := nil;
Combine := nil; Palette := nil; Tiles := nil; Rebuild := nil;
end;
procedure TfrmCosmoBackground.Cleanup;
begin
If Foreground<>nil then Foreground.Free; Foreground := nil;
If Background<>nil then Background.Free; Background := nil;
If Combine<>nil then Combine.Free; Combine := nil;
If Palette<>nil then Palette.Free; Palette := nil;
If Tiles<>nil then Tiles.Free; Tiles := nil;
If RawLGP<>nil then RawLGP.Free; RawLGP := nil;
If Data<>nil then Data.Free; Data := nil;
end;
procedure TfrmCosmoBackground.FormDestroy(Sender: TObject);
begin
Cleanup;
end;
procedure TfrmCosmoBackground.OpenFile(FName:String);
var
I: Integer;
LGP,Fil: String;
Tmp: TMemoryStream;
begin
Cleanup;
CurFile := FName;
I := Pos('?',CurFile);
Tmp := TMemoryStream.Create;
If I=0 then begin
Tmp.LoadFromFile(CurFile);
end else begin
LGP := Copy(CurFile,1,I-1);
Fil := Copy(CurFile,I+1,Length(CurFile));
RawLGP := TRawLGPFile.CreateFromFile(LGP);
For I := 0 to RawLGP.NumEntries-1 do
If Uppercase(RawLGP.TableEntry[I].Filename)=Uppercase(Fil) then begin
RawLGP.Extract(I,Tmp);
Break;
end;
end;
If Tmp.Size=0 then Cleanup else begin
Data := Plugin.LZS_Decompress(Tmp);
FillBitmaps;
DoCombine;
end;
Tmp.Free;
@Rebuild := Plugin.GetProcedure('FF7Ed_BackgroundRebuilder');
end;
procedure TfrmCosmoBackground.DoCombine;
var
PW1,PW2: PWord;
I,J: Integer;
begin
Combine := TBitmap.Create;
Combine.Width := Background.Width;
Combine.Height := Background.Height;
Combine.PixelFormat := pf15Bit;
For I := 0 to Background.Height-1 do begin
PW1 := Background.ScanLine[I];
PW2 := Combine.ScanLine[I];
For J := 0 to Background.Width-1 do begin
PW2^ := PW1^;
Inc(PW1); Inc(PW2);
end;
end;
For I := 0 to Foreground.Height-1 do begin
PW1 := Foreground.ScanLine[I];
PW2 := Combine.ScanLine[I];
For J := 0 to Foreground.Width-1 do begin
If PW1^<>($1F shl 5) then PW2^ := PW1^;
Inc(PW1); Inc(PW2);
end;
end;
end;
procedure TfrmCosmoBackground.btnExportClick(Sender: TObject);
begin
If savBMP.Execute then
Image.Picture.Bitmap.SaveToFile(savBMP.Filename);
end;
procedure TfrmCosmoBackground.btnImportClick(Sender: TObject);
var
Bmp: TBitmap;
Tmp: TMemoryStream;
PI: PInteger;
PB: PByte;
Colr,I,OldNum,NewNum,Siz: Integer;
W: Word;
begin
If Not opnBMP.Execute then Exit;
Bmp := TBitmap.Create;
Bmp.LoadFromFile(opnBMP.Filename);
Bmp.PixelFormat := pf15Bit;
If cmbLayer.ItemIndex<2 then
If (Bmp.Height<>Background.Height) or (Bmp.Width<>Background.Width) then begin
ShowMessage(Format('Bitmap is wrong size (should be %dx%d)',[Background.Width,Background.Height]));
Bmp.Free; Exit;
end;
Case cmbLayer.ItemIndex of
0: begin Background.Free; Background := Bmp; end;
1: begin Foreground.Free; Foreground := Bmp; end;
3: begin
Bmp.Free; Palette.LoadFromFile(opnBMP.Filename);
PB := Data.Memory; Inc(PB,2+(3+1)*4);
PI := Pointer(PB); Siz := PI^;
PB := Data.Memory; Inc(PB,Siz);
PI := Pointer(PB);
OldNum := (PI^ - $C) div 2;
NewNum := (Palette.Width div 16) * (Palette.Height div 16);
If OldNum>NewNum then ShowMessage('Warning! New palette is smaller than old one. This may cause problems.');
Tmp := TMemoryStream.Create;
Data.Position := 0;
Tmp.CopyFrom(Data,Siz);
I := NewNum*2 + $C;
Tmp.Position := Siz;
Tmp.WriteBuffer(I,4);
Tmp.WriteBuffer(I,4);
Data.Position := Siz+8;
Data.ReadBuffer(I,4);
Tmp.WriteBuffer(I,4);
For I := 0 to (NewNum-1) do begin
Colr := Palette.Canvas.Pixels[ (I mod 16)*16+8, (I div 16)*16+8];
W := ((Colr and $FF) shr 3) or ((Colr and $F800) shr 6) or ((Colr and $F80000) shr 9);
Tmp.WriteBuffer(W,2);
end;
Data.Position := Siz + PI^;
Tmp.CopyFrom(Data,Data.Size-Data.Position);
PB := Data.Memory;
Inc(PB,22);
PI := Pointer(PB);
Dec(PB,20);
For I := 1 to PB^ do begin
PI^ := PI^ + (NewNum-OldNum)*2;
Inc(PI);
end;
Data.Free;
Data := Tmp;
FillBitmaps;
end;
end;
DoCombine;
cmbLayerChange(Sender);
end;
procedure TfrmCosmoBackground.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Cleanup;
end;
procedure TfrmCosmoBackground.btnSaveClick(Sender: TObject);
var
I: Integer;
LGP,Fil:String;
Tmp: TMemoryStream;
begin
ShowMessage('This will only save *palette* changes at the moment, sorry...');
I := Pos('?',CurFile);
Tmp := Plugin.LZS_Compress(Data);
If I=0 then begin
Tmp.SaveToFile(CurFile);
Tmp.Free;
end else begin
LGP := Copy(CurFile,1,I-1);
Fil := Copy(CurFile,I+1,Length(CurFile));
For I := 0 to RawLGP.NumEntries-1 do
If Uppercase(RawLGP.TableEntry[I].Filename)=Uppercase(Fil) then begin
RawLGP.UpdateFile(I,Tmp);
Break;
end;
end;
end;
end.
|
unit UFrmAssets;
interface
uses
WinApi.Windows, Classes, Generics.Collections, SuperXMLParser, SuperObject,
Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UDownloader, Winapi.ActiveX, WinApi.UrlMon,
Vcl.Controls, XmlDoc, XMLDom, IdBaseComponent, IdComponent, UFileUtilities,
IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdSSL, IdSSLOpenSSL;
const
MC_RESOURCES_URL = 'https://s3.amazonaws.com/Minecraft.Resources/';
type
TFrmAssets = class(TForm)
BtnDownloadAll: TButton;
IdHTTP1: TIdHTTP;
IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
procedure BtnDownloadAllClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
type
TBindStatusCallback = class(TInterfacedObject, IDownloadCallback)
v:TFrmAssets;
protected
function OnStartBinding( dwReserved: DWORD; pib: IBinding ): HResult; stdcall;
function GetPriority( out nPriority ): HResult; stdcall;
function OnLowResource( reserved: DWORD ): HResult; stdcall;
function OnProgress( ulProgress, ulProgressMax, ulStatusCode: ULONG;
szStatusText: LPCWSTR): HResult; stdcall;
function OnStopBinding( hresult: HResult; szError: LPCWSTR ): HResult; stdcall;
function GetBindInfo( out grfBINDF: DWORD; var bindinfo: TBindInfo ): HResult; stdcall;
function OnDataAvailable( grfBSCF: DWORD; dwSize: DWORD; formatetc: PFormatEtc;
stgmed: PStgMedium ): HResult; stdcall;
function OnObjectAvailable( const iid: TGUID; punk: IUnknown ): HResult; stdcall;
procedure OnStatus(status:string);
public
constructor Create(v:TFrmAssets);
end;
private
d: TDownloader;
doc: ISuperObject;
cb: TBindStatusCallBack;
procedure ParseXML(xml:string);
public
end;
var
FrmAssets: TFrmAssets;
implementation
{$R *.dfm}
constructor TFrmAssets.TBindStatusCallback.Create(v: TFrmAssets);
begin
Self.v := v;
end;
function TFrmAssets.TBindStatusCallback.GetBindInfo( out grfBINDF: DWORD; var bindinfo: TBindInfo ): HResult;
begin
result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.GetPriority( out nPriority ): HResult;
begin
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnDataAvailable( grfBSCF, dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium ): HResult;
begin
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnLowResource( reserved: DWORD ): HResult;
begin
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnObjectAvailable( const iid: TGUID; punk: IInterface ): HResult;
begin
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnStartBinding( dwReserved: DWORD; pib: IBinding ): HResult;
begin
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnStopBinding( hresult: HResult; szError: LPCWSTR ): HResult;
var s:String;
begin
s := TFileUtilities.ReadToEnd('resources.xml');
v.ParseXML(s);
Result := S_OK;
end;
function TFrmAssets.TBindStatusCallback.OnProgress( ulProgress, ulProgressMax, ulStatusCode: ULONG;szStatusText: LPCWSTR): HResult;
begin
end;
procedure TFrmAssets.TBindStatusCallBack.OnStatus(status: string);
begin
end;
procedure TFrmAssets.ParseXML(xml:string);
var i: Integer;
item: TSuperObjectIter;
begin
doc := XMLParseString(xml);
ShowMessage(XML);
if ObjectFindFirst(doc, item) then
repeat
ShowMessage(item.val.AsJSon);
until ObjectFindNext(item);
end;
procedure TFrmAssets.BtnDownloadAllClick(Sender: TObject);
begin
cb := TBindStatusCallback.Create(self);
d := TDownloader.Create(MC_RESOURCES_URL);
d.DownFileAsync('resources.xml', cb);
end;
procedure TFrmAssets.FormCreate(Sender: TObject);
begin
Idhttp1.IOHandler := Self.IdSSLIOHandlerSocketOpenSSL1;
Idhttp1.Request.ContentType := 'application/x-www-form-urlencoded';
Idhttp1.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)';
end;
end. |
{***************************************************************************}
{ Copyright 2021 Google LLC }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ https://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 Render;
interface
uses QR, Crt, Dos;
const
ScreenWidth = 80;
ScreenHeight = 25;
ScreenBufferSize = ScreenWidth*ScreenHeight*2;
type
ScreenBuffer = array [0..ScreenBufferSize-1] of Word;
Renderer = object
constructor Init;
procedure Render(qrPtr: QRCodePtr; invert: Boolean); virtual;
end;
RendererPtr = ^Renderer;
TextRenderer = object(Renderer)
OrigScreen: ScreenBuffer;
constructor Init;
procedure Render(qrPtr: QRCodePtr; invert: Boolean); virtual;
procedure DisplayNormal(qrPtr: QRCodePtr; invert: Boolean);
procedure SaveScreenState;
procedure RestoreScreenState;
end;
TextRendererPtr = ^TextRenderer;
implementation
const
NormalAttr = $7;
InverseAttr = $7 shl 4;
var
Screen: ScreenBuffer Absolute $B800 : $0000;
procedure HideCursor;
var
regs : Registers;
begin
with regs do
begin
AX := $0100;
CH := $20;
CL := $20;
Intr($10, regs);
end;
end;
procedure ShowCursor;
var
regs : Registers;
begin
with regs do
begin
AX := $0100;
CH := $06;
CL := $07;
Intr($10, regs);
end;
end;
constructor Renderer.Init;
begin
end;
procedure Renderer.Render(qrPtr: QRCodePtr; invert: Boolean);
begin
WriteLn('Implement me: Renderer.Render');
end;
constructor TextRenderer.Init;
begin
Renderer.Init;
end;
procedure TextRenderer.DisplayNormal(qrPtr: QRCodePtr; invert: Boolean);
var
row, col: Integer;
val: Module;
bits: Byte;
originX, originY: Integer;
k: Char;
fill: Word;
attr: Word;
begin
HideCursor;
if invert then
attr := InverseAttr
else
attr := NormalAttr;
originX := (ScreenWidth - qrPtr^.QRSize) div 2;
originY := (ScreenHeight - qrPtr^.QRSize div 2) div 2;
{ Clean area with borders for QR }
for row := originY - 1 to originY + qrPtr^.QRSize div 2 + 1 do
for col := originX - 2 to originX + qrPtr^.QRSize + 1 do
if ((row >= 0) and (row < ScreenHeight)) and
((col >= 0) and (col < ScreenWidth)) then
Screen[row*ScreenWidth + col] := (attr shl 8) or 219;
row := 0;
while row <= qrPtr^.QRSize - 1 do
begin
for col := 0 to qrPtr^.QRSize - 1 do
begin
if qrPtr^.GetModule(row, col) = Light then
bits := 2
else
bits := 0;
if qrPtr^.GetModule(row + 1, col) = Light then
bits := bits or 1;
case bits of
0: fill := $20;
1: fill := 220;
2: fill := 223;
3: fill := 219;
end;
Screen[(originY + row div 2) * ScreenWidth + (originX + col)] :=
fill or (attr shl 8);
end;
row := row + 2;
end;
k := ReadKey;
ShowCursor;
end;
procedure TextRenderer.SaveScreenState;
begin
Move(Screen, OrigScreen, SizeOf(Screen));
end;
procedure TextRenderer.RestoreScreenState;
begin
Move(OrigScreen, Screen, SizeOf(Screen));
end;
procedure TextRenderer.Render(qrPtr: QRCodePtr; invert: Boolean);
begin
SaveScreenState;
DisplayNormal(qrPtr, invert);
RestoreScreenState;
end;
begin
end.
|
unit CreateBasicColors;
interface
type
TColorQueue = (green, red, blue);
TRecordCust = record
green,red,blue:Integer;
end;
procedure creatingBasicColors(var MassOfStandart: array of TRecordCust; var N:integer; shift: Integer);
implementation
procedure Succa(var Clr: TColorQueue);
begin
clr := succ(clr);
if( ord(Clr) > 2 ) then
Clr := green;
end;
procedure SuccBool(var boolTemp:Boolean);
begin
if boolTemp then
boolTemp := False
else
boolTemp := True;
end;
function LessThen255(ColorT: TColorQueue; var K: TRecordCust): boolean;
begin
case ColorT of
blue: Result:= K.blue < 255;
green: Result:= K.green < 255;
red: Result:= K.red < 255
end;
end;
function MoreThen0(ColorT: TColorQueue; K: TRecordCust): boolean;
begin
case ColorT of
blue: Result:= K.blue > 0;
green: Result:= K.green > 0;
red: Result:= K.red > 0
end;
end;
procedure IncKColorT(ColorT: TColorQueue; var K: TRecordCust);
begin
case ColorT of
blue: Inc(K.blue);
green: Inc(K.green);
red: Inc(K.red);
end;
end;
procedure DecKColorT(ColorT: TColorQueue; var K: TRecordCust);
begin
case ColorT of
blue: Dec(K.blue);
green: Dec(K.green);
red: Dec(K.red);
end;
end;
procedure creatingBasicColors(var MassOfStandart: array of TRecordCust; var N:integer; shift: Integer);
var
trg_plus, exitbool: Boolean;
i:Byte;
deltaShift: Integer;
colorT: TColorQueue;
K: TRecordCust;
begin
K.red := 255;
K.green := 0;
K.blue := 0;
MassOfStandart[1].green := K.green;
MassOfStandart[1].red := K.red;
MassOfStandart[1].blue := K.blue;
trg_plus := true;
colorT := green;
for i:=2 to N do
begin
exitbool := false;
deltaShift := shift;
while not(exitbool) do
begin
case trg_plus of
true:
begin
while LessThen255(colorT, K) and (deltaShift <> 0) do
begin
IncKColorT(colorT, K);
dec(deltaShift);
end;
end
else
begin
while MoreThen0(colorT, K) and (deltaShift <> 0) do
begin
DecKColorT(colorT, K);
dec(deltaShift);
end;
end;
end;
if (deltaShift = 0) then
begin
MassOfStandart[i].green := K.green;
MassOfStandart[i].red := K.red;
MassOfStandart[i].blue := K.blue;
exitbool:=true;
end
else
begin
Succbool(trg_plus);
SuccA(colorT);
end;
end;
end;
end;
end.
|
PROGRAM Hello(INPUT, OUTPUT);
BEGIN REPEAT WRITELN('Hello world!');
UNTIL FALSE;END. |
unit ShapeMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, ADODB, Grids, DBGrids, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
Customers: TADODataSet;
Orders: TADODataSet;
CustSource: TDataSource;
OrderSource: TDataSource;
DBGrid1: TDBGrid;
DBGrid2: TDBGrid;
CustomersCustNo: TFloatField;
CustomersCompany: TWideStringField;
CustomersAddr1: TWideStringField;
CustomersAddr2: TWideStringField;
CustomersCity: TWideStringField;
CustomersState: TWideStringField;
CustomersZip: TWideStringField;
CustomersCountry: TWideStringField;
CustomersPhone: TWideStringField;
CustomersFAX: TWideStringField;
CustomersTaxRate: TFloatField;
CustomersContact: TWideStringField;
CustomersLastInvoiceDate: TDateField;
CustomersOrders: TDataSetField;
OrdersOrderNo: TFloatField;
OrdersCustNo: TFloatField;
OrdersSaleDate: TDateField;
OrdersShipDate: TDateField;
OrdersEmpNo: TIntegerField;
OrdersShipToContact: TWideStringField;
OrdersShipToAddr1: TWideStringField;
OrdersShipToAddr2: TWideStringField;
OrdersShipToCity: TWideStringField;
OrdersShipToState: TWideStringField;
OrdersShipToZip: TWideStringField;
OrdersShipToCountry: TWideStringField;
OrdersShipToPhone: TWideStringField;
OrdersShipVIA: TWideStringField;
OrdersPO: TWideStringField;
OrdersTerms: TWideStringField;
OrdersPaymentMethod: TWideStringField;
OrdersItemsTotal: TFloatField;
OrdersTaxRate: TFloatField;
OrdersFreight: TFloatField;
OrdersAmountPaid: TFloatField;
Panel1: TPanel;
ProviderLabel: TLabel;
DataProviderLabel: TLabel;
DataSourceLabel: TLabel;
Label4: TLabel;
Provider: TEdit;
DataProvider: TEdit;
DataSource: TEdit;
OpenButton: TButton;
procedure OpenButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.OpenButtonClick(Sender: TObject);
const
ConnStr = 'Provider=%s;Data Provider=%s;Data Source=%s';
begin
if not ADOConnection1.Connected then
ADOConnection1.ConnectionString := Format(ConnStr, [Provider.Text,
DataProvider.Text, DataSource.Text]);
Customers.Open;
Orders.Open;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : FRTextureEdit<p>
Basic editing frame for TGLTexture<p>
<b>Historique : </b><font size=-1><ul>
<li>05/10/08 - DanB - Removed Kylix support
<li>24/03/08 - DaStr - Moved TGLMinFilter and TGLMagFilter from GLUtils.pas
to GLGraphics.pas (BugTracker ID = 1923844)
<li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585)
<li>19/12/06 - DaStr - SBEditImageClick() now calls DoOnChange
TRTextureEdit.CBImageClassChange - TGLTextureImageClass(tic).Create()
now gets the correct variable as its owner (BugTracker ID = 1603743)
All comboboxes get their Items using RTTI
(thanks to dikoe Kenguru for the reminder and Roman Ganz for the code)
<li>03/07/04 - LR - Make change for Linux
<li>17/03/00 - Egg - Added ImageAlpha combo
<li>13/03/00 - Egg - Creation
</ul></font>
}
{ TODO : Replace STImageClass with a dropdown (polymorphism) }
unit FRTextureEdit;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils, System.TypInfo, VCL.Forms, VCL.StdCtrls,
VCL.Buttons, VCL.Controls,
GLGraphics, GLTextureFormat, GLTexture, GLState, GLTextureImageEditors;
type
TRTextureEdit = class(TFrame)
Label2: TLabel;
SBEditImage: TSpeedButton;
CBMagFilter: TComboBox;
Label3: TLabel;
Label4: TLabel;
CBMinFilter: TComboBox;
CBTextureMode: TComboBox;
Label1: TLabel;
Label5: TLabel;
CBTextureWrap: TComboBox;
CBDisabled: TCheckBox;
CBImageClass: TComboBox;
CBImageAlpha: TComboBox;
Label6: TLabel;
CBFilteringQuality: TComboBox;
Label7: TLabel;
procedure CBMagFilterChange(Sender: TObject);
procedure CBMinFilterChange(Sender: TObject);
procedure CBTextureModeChange(Sender: TObject);
procedure CBTextureWrapChange(Sender: TObject);
procedure CBDisabledClick(Sender: TObject);
procedure SBEditImageClick(Sender: TObject);
procedure CBImageClassChange(Sender: TObject);
procedure CBImageAlphaChange(Sender: TObject);
procedure CBFilteringQualityChange(Sender: TObject);
private
{ Private declarations }
FTexture: TGLTexture;
FOnChange: TNotifyEvent;
Changeing: Boolean;
protected
{ Protected declarations }
procedure SetTexture(const val: TGLTexture);
procedure DoOnChange; dynamic;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Texture: TGLTexture read FTexture write SetTexture;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{$R *.dfm}
// Create
//
constructor TRTextureEdit.Create(AOwner: TComponent);
var
I: Integer;
begin
inherited;
FTexture := TGLTexture.Create(Self);
SetTexture(FTexture);
SetGLTextureImageClassesToStrings(CBImageClass.Items);
for I := 0 to Integer( High(TGLTextureImageAlpha)) do
CBImageAlpha.Items.Add(GetEnumName(TypeInfo(TGLTextureImageAlpha), I));
for I := 0 to Integer( High(TGLMagFilter)) do
CBMagFilter.Items.Add(GetEnumName(TypeInfo(TGLMagFilter), I));
for I := 0 to Integer( High(TGLMinFilter)) do
CBMinFilter.Items.Add(GetEnumName(TypeInfo(TGLMinFilter), I));
for I := 0 to Integer( High(TGLTextureFilteringQuality)) do
CBFilteringQuality.Items.Add
(GetEnumName(TypeInfo(TGLTextureFilteringQuality), I));
for I := 0 to Integer( High(TGLTextureMode)) do
CBTextureMode.Items.Add(GetEnumName(TypeInfo(TGLTextureMode), I));
for I := 0 to Integer( High(TGLTextureWrap)) do
CBTextureWrap.Items.Add(GetEnumName(TypeInfo(TGLTextureWrap), I));
end;
// Destroy
//
destructor TRTextureEdit.Destroy;
begin
FTexture.Free;
inherited;
end;
// SetTexture
//
procedure TRTextureEdit.SetTexture(const val: TGLTexture);
begin
FTexture.Assign(val);
changeing := True;
try
with CBImageClass do
ItemIndex := Items.IndexOfObject(Pointer(FTexture.Image.ClassType));
CBImageAlpha.ItemIndex := Integer(FTexture.ImageAlpha);
CBMagFilter.ItemIndex := Integer(FTexture.MagFilter);
CBMinFilter.ItemIndex := Integer(FTexture.MinFilter);
CBFilteringQuality.ItemIndex := Integer(FTexture.FilteringQuality);
CBTextureMode.ItemIndex := Integer(FTexture.TextureMode);
CBTextureWrap.ItemIndex := Integer(FTexture.TextureWrap);
CBDisabled.Checked := FTexture.Disabled;
finally
Changeing := False;
DoOnChange;
end;
end;
// DoOnChange
//
procedure TRTextureEdit.DoOnChange;
begin
if (not changeing) and Assigned(FOnChange) then
OnChange(Self);
end;
// CBImageClassChange
//
procedure TRTextureEdit.CBImageClassChange(Sender: TObject);
var
tic: TGLTextureImageClass;
ti: TGLTextureImage;
begin
if not changeing then
begin
with CBImageClass do
tic := TGLTextureImageClass(Items.Objects[ItemIndex]);
if FTexture.Image.ClassType <> tic then
begin
ti := TGLTextureImageClass(tic).Create(FTexture);
FTexture.Image := ti;
ti.Free;
end;
DoOnChange;
end;
end;
// CBImageAlphaChange
//
procedure TRTextureEdit.CBImageAlphaChange(Sender: TObject);
begin
FTexture.ImageAlpha := TGLTextureImageAlpha(CBImageAlpha.ItemIndex);
DoOnChange;
end;
// CBMagFilterChange
//
procedure TRTextureEdit.CBMagFilterChange(Sender: TObject);
begin
FTexture.MagFilter := TGLMagFilter(CBMagFilter.ItemIndex);
DoOnChange;
end;
// CBMinFilterChange
//
procedure TRTextureEdit.CBMinFilterChange(Sender: TObject);
begin
FTexture.MinFilter := TGLMinFilter(CBMinFilter.ItemIndex);
DoOnChange;
end;
// CBTextureModeChange
//
procedure TRTextureEdit.CBTextureModeChange(Sender: TObject);
begin
FTexture.TextureMode := TGLTextureMode(CBTextureMode.ItemIndex);
DoOnChange;
end;
// CBTextureWrapChange
//
procedure TRTextureEdit.CBTextureWrapChange(Sender: TObject);
begin
FTexture.TextureWrap := TGLTextureWrap(CBTextureWrap.ItemIndex);
DoOnChange;
end;
// CBDisabledClick
//
procedure TRTextureEdit.CBDisabledClick(Sender: TObject);
begin
FTexture.Disabled := CBDisabled.Checked;
DoOnChange;
end;
// SBEditImageClick
//
procedure TRTextureEdit.SBEditImageClick(Sender: TObject);
begin
EditGLTextureImage(FTexture.Image);
DoOnChange;
end;
procedure TRTextureEdit.CBFilteringQualityChange(Sender: TObject);
begin
FTexture.FilteringQuality := TGLTextureFilteringQuality(CBFilteringQuality.ItemIndex);
DoOnChange;
end;
end.
|
unit uRestApp;
interface
uses REST.Client, System.SysUtils, System.Classes, REST.Types, System.JSON;
type TRestApp = class
private
_Client : TRESTClient;
_Response : TRESTResponse;
_Request : TRESTRequest;
Fcharset: string;
Fservice: string;
Fhost: string;
Fencoding: string;
Faccept: string;
FResponseCode: Integer;
FResponseMessage: String;
procedure Setaccept(const Value: string);
procedure Setcharset(const Value: string);
procedure Setencoding(const Value: string);
procedure Sethost(const Value: string);
procedure Setservice(const Value: string);
public
property responseCode : Integer read FResponseCode;
property responseMessage : String read FResponseMessage;
property host : string read Fhost write Sethost;
property service : string read Fservice write Setservice;
property accept : string read Faccept write Setaccept;
property charset : string read Fcharset write Setcharset;
property encoding: string read Fencoding write Setencoding;
function executarServico(AMethod: TRESTRequestMethod = rmGET): TJSONValue;
constructor create; overload;
constructor create(ABaseUrl, AResource: String); overload;
destructor destroy;
end;
implementation
{ TRestApp }
uses Forms, Vcl.Controls;
constructor TRestApp.create;
begin
_Client := TRESTClient.Create(Application.MainForm);
_Response := TRESTResponse.Create(nil);
_Request := TRESTRequest.Create(nil);
_Request.Response := _Response;
_Request.Client := _Client;
_Client.Accept := 'application/json';
_Client.AcceptCharset := 'UTF-8';
end;
constructor TRestApp.create(ABaseUrl, AResource: String);
begin
create;
_Client.BaseURL := ABaseUrl;
_Request.Resource := AResource;
end;
destructor TRestApp.destroy;
begin
FreeAndNil(_Response);
FreeAndNil(_Request);
FreeAndNil(_Client);
end;
function TRestApp.executarServico(AMethod: TRESTRequestMethod): TJSONValue;
begin
try
_Request.Method := AMethod;
_Request.Execute;
FResponseMessage := _Response.StatusText;
FResponseCode := _Response.StatusCode;
Result := _Response.JSONValue;
except
on e : Exception do
begin
FResponseMessage := _Response.StatusText;
FResponseCode := _Response.StatusCode;
end;
end;
end;
procedure TRestApp.Setaccept(const Value: string);
begin
Faccept := Value;
_Client.Accept := Value;
end;
procedure TRestApp.Setcharset(const Value: string);
begin
Fcharset := Value;
_Client.AcceptCharset := charset;
end;
procedure TRestApp.Setencoding(const Value: string);
begin
Fencoding := Value;
end;
procedure TRestApp.Sethost(const Value: string);
begin
Fhost := Value;
_Client.BaseURL := Value;
end;
procedure TRestApp.Setservice(const Value: string);
begin
Fservice := Value;
_Request.Resource := Value;
end;
end.
|
unit intf_1;
interface
implementation
uses System;
type
II1 = interface
procedure AAA;
end;
TT1 = class(TObject, II1)
procedure AAA;
end;
var G: Int32;
procedure TT1.AAA;
begin
G := 12;
end;
var T: TT1;
I: II1;
procedure Test;
begin
T := TT1.Create();
I := T;
I.AAA();
end;
initialization
Test();
finalization
Assert(G = 12);
end. |
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit Config5;
interface
procedure cfgMsgAreaEditor;
implementation
uses Dos,
Global, Strings, Config, Output, Input, Menus, Files, Misc, bbsInit,
MsgArea, Logs;
var maF : file of tMsgAreaRec;
procedure cfgInsertMsgArea;
var I,X,Z,B : Byte;
begin
oDnLn(2);
if numMsgArea >= maxMsgArea then
begin
oCWriteLn('|U0You may only have a maximum of '+St(maxMsgArea)+' message areas.');
oDnLn(2);
oPromptKey;
Exit;
end;
oCWrite('|U1Insert before which message area? |U5[|U61|U5-|U6'+St(numMsgArea+1)+'|U5]: |U3');
I := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (I > numMsgArea+1) or (I < 1) then Exit;
oCWrite('|U1Number of areas to insert |U5[|U61|U5-|U6'+St(maxMsgArea-numMsgArea)+'|U5]: |U3');
X := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (X > maxMsgArea-numMsgArea) or (X < 1) then X := 1;
Dec(I);
Reset(maF);
for b := 1 to x do
begin
for Z := FileSize(maF)-1 downto I do
begin
Seek(maF,Z);
Read(maF,mArea^);
Write(maF,mArea^);
end;
maReset;
Seek(maF,I);
Write(maF,mArea^);
end;
numMsgArea := FileSize(maF);
Close(maF);
maUpdateScanFile;
end;
procedure cfgMoveMsgArea;
var K,X,Y,I,B : Word; J : Integer;
mTemp : ^tMsgAreaRec;
begin
oDnLn(2);
if numMsgArea <= 1 then
begin
oCWriteLn('|U0There is only one message area, no need to move it.');
oDnLn(2);
oPromptKey;
Exit;
end;
oCWrite('|U1Move which message area? |U5[|U61|U5-|U6'+St(numMsgArea)+'|U5]: |U3');
X := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (X > numMsgArea) or (X < 1) then Exit;
oCWrite('|U1Move before which message area? |U5[|U61|U5-|U6'+St(numMsgArea+1)+'|U5]: |U3');
Y := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (Y > numMsgArea+1) or (Y < 1) then Exit;
Dec(I,1);
New(mTemp);
Reset(maF);
K := Y;
if (Y > X) then Dec(Y);
Dec(X);
Dec(Y);
Seek(maF,X);
Read(maF,mTemp^);
I := X;
if (X > Y) then J := -1 else J := 1;
while (I <> Y) do
begin
if (I+J < FileSize(maF)) then
begin
Seek(maF,I+J);
Read(maF,mArea^);
Seek(maF,I);
Write(maF,mArea^);
end;
Inc(I,J);
end;
Seek(maF,Y);
Write(maF,mTemp^);
Inc(X);
Inc(Y);
{y:=k;}
Close(maF);
Dispose(mTemp);
{
if ((I >= 0) and (I <= FileSize(maF))) and (numMsgArea < maxMsgArea) then
begin
for Z := FileSize(maF)-1 downto I do
begin
Seek(maF,Z);
Read(maF,mArea^);
Write(maF,mArea^);
end;
maReset;
Seek(maF,I);
Write(maF,mArea^);
Inc(numMsgArea,1);
end;}
maUpdateScanFile;
end;
procedure cfgDeleteMsgArea;
var I,X,Z,B : Byte;
begin
oDnLn(2);
if numMsgArea <= 1 then
begin
oCWriteLn('|U0You must have at least one message area!');
oDnLn(2);
oPromptKey;
Exit;
end;
oCWrite('|U1Delete which message area? |U5[|U61|U5-|U6'+St(numMsgArea)+'|U5]: |U3');
I := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (I > numMsgArea) or (I < 1) then Exit;
Dec(I);
Reset(maF);
if (I >= 0) and (I <= FileSize(maF)-2) then
for Z := I to FileSize(maF)-2 do
begin
Seek(maF,Z+1);
Read(maF,mArea^);
Seek(maF,Z);
Write(maF,mArea^);
end;
Seek(maF,FileSize(maF)-1);
Truncate(maF);
Dec(numMsgArea,1);
Close(maF);
if (fExists(Cfg^.pathMsgs+mArea^.Filename+extMsgData)) or
(fExists(Cfg^.pathMsgs+mArea^.Filename+extMsgHead)) or
(fExists(Cfg^.pathMsgs+mArea^.Filename+extMsgScan)) then
begin
oCWrite('|U1Delete this message area''s data files? ');
if iYesNo(False) then
begin
fDeleteFile(Cfg^.pathMsgs+mArea^.Filename+extMsgData);
fDeleteFile(Cfg^.pathMsgs+mArea^.Filename+extMsgHead);
fDeleteFile(Cfg^.pathMsgs+mArea^.Filename+extMsgScan);
end;
end;
end;
procedure cfgEditMsgArea;
var optAreaType : array[1..2] of String;
An, Anum, T : Byte; B : Boolean; Fil : String; optNet : array[1..maxAddress] of String;
begin
optAreaType[1] := 'Local message area';
optAreaType[2] := 'EchoMail area';
Anum := User^.curMsgArea;
oDnLn(2);
for T := 1 to maxAddress do optNet[T] := '#'+St(T)+' ('+St(Cfg^.Address[T].Zone)+
':'+St(Cfg^.Address[T].Net)+'/'+St(Cfg^.Address[T].Node)+'.'+St(Cfg^.Address[T].Point)+')';
if numMsgArea = 0 then
begin
oCWriteLn('|U0Can''t continue. No message areas exist');
oDnLn(2);
oPromptKey;
Exit;
end;
oCWrite('|U1Begin edit with which message area? |U5[|U61|U5-|U6'+St(numMsgArea)+'|U5]: |U3');
An := StrToInt(iReadString('',inUpper,chNumeric,'',3));
if (An > numMsgArea) or (An < 1) then Exit;
User^.curMsgArea := An;
maLoad;
cfgOver := False;
cfgDraw := True;
repeat
cfgInit(bbsTitle+' Message Area Editor');
cfgCol := 20;
cfgItem('--Current area',10,St(An)+' of '+St(numMsgArea),'');
cfgItem('A Description',40,mArea^.Name,
'This message area''s description (shown in message area lists, etc).');
cfgItem('B Filename',8,mArea^.Filename,
'This is the file that the actual messages for this area will be stored in.');
cfgItem('C Msg area type',20,cfgOption(optAreaType,mArea^.areaType),
'Type of message area.');
if mArea^.areaType = mareaEchoMail then
cfgItem('D Echomail path',40,mArea^.MsgPath,
'Directory which incoming/outgoing echomail will be stored in, until processed.');
if mArea^.areaType = mareaEchoMail then
cfgItem('E Origin line #',58,Resize(St(mArea^.Origin)+' ('+Cfg^.Origin[mArea^.Origin],40)+'...)',
'Which origin line (defined in system configuration) to append to messages.');
if mArea^.areaType = mareaEchoMail then
cfgItem('F Net address',20,cfgOption(optNet,mArea^.Address),
'Network address this area uses.');
cfgItem('G Area sponsor',36,mArea^.Sponsor,
'Creator or manager of this message area (Usually the SysOp).');
cfgItem('H Access ACS',20,mArea^.ACS,
'ACS required to access or read messages in this area.');
cfgItem('I Post ACS',20,mArea^.PostACS,
'ACS required to post messages in this area.');
cfgItem('J Max messages',4,St(mArea^.MaxMsgs),
'Maximum messages this area can contain before being packed (0 = unlimited).');
cfgItem('K Password',20,mArea^.Password,
'Password required to access or read messages in this message Area.');
cfgItem('L QWK name',16,mArea^.qwkName,
'Shortened message area name (max 16 characters) for QWK indexing');
cfgItem('M Messages',5,st(mArea^.Msgs),
'Number of messages currently in area (do not change unless necessary)');
cfgItem('1 Unhidden',3,B2St(maUnhidden in mArea^.Flag),
'Display this area under any circumstances?');
cfgItem('2 Real Names',3,B2St(maRealName in mArea^.Flag),
'Force use of user''s REAL name when posting in this area?');
cfgItem('3 Private',3,B2St(maPrivate in mArea^.Flag),
'Allow private messages to be posted in this area?');
cfgSrt := 40;
cfgCol := 60;
Dec(cfgLn,2);
cfgItem('4 Mandatory',3,B2St(maMandatory in mArea^.Flag),
'Force user to read all new messages in this area?');
cfgItem('5 Anonymous',3,B2St(maAnonymous in mArea^.Flag),
'Allow anonymous messages to be posted in this area?');
cfgSrt := 1;
cfgCol := 20;
if cfgDraw then Dec(cfgbot,2);
cfgItem('[ Previous Area',0,'','');
cfgItem('] Next Area',0,'','');
cfgBar;
cfgDrawAllItems;
cfgPromptCommand;
case cfgKey of
'A' : begin
cfgReadInfo(mArea^.Name,inNormal,chNormal,'',False);
mArea^.Name := cfgRead;
cfgSetItem(mArea^.Name);
end;
'B' : begin
Fil := mArea^.Filename;
cfgReadInfo(mArea^.Filename,inUpper,chFileNoExt,'',True);
mArea^.Filename := cfgRead;
cfgSetItem(mArea^.Filename);
fRenameFile(Cfg^.pathMsgs+Fil+extMsgData,Cfg^.pathMsgs+mArea^.Filename+extMsgData);
fRenameFile(Cfg^.pathMsgs+Fil+extMsgHead,Cfg^.pathMsgs+mArea^.Filename+extMsgHead);
fRenameFile(Cfg^.pathMsgs+Fil+extMsgScan,Cfg^.pathMsgs+mArea^.Filename+extMsgScan);
if UpStr(mArea^.qwkName) = Fil then
begin
mArea^.qwkName := strMixed(mArea^.Filename);
cfgDraw := True;
cfgOver := True;
end;
end;
'C' : begin
T := mArea^.areaType;
cfgReadOption(optAreaType,2,mArea^.areaType);
cfgSetItem(cfgOption(optAreaType,mArea^.areaType));
cfgDraw := T <> mArea^.areaType;
end;
'D' : begin
cfgReadInfo(mArea^.MsgPath,inUpper,chDirectory,'',True);
mArea^.MsgPath := cfgRead;
if mArea^.MsgPath[Length(mArea^.MsgPath)] <> '\' then
mArea^.MsgPath := mArea^.MsgPath+'\';
cfgSetItem(mArea^.MsgPath);
cfgAskCreate(mArea^.MsgPath);
end;
'E' : begin
cfgSetItem('');
cfgReadInfo(St(mArea^.Origin),inUpper,chNumeric,'',True);
mArea^.Origin := mClip(StrToInt(cfgRead),1,maxOrigin);
cfgSetItem(Resize(St(mArea^.Origin)+' ('+Cfg^.Origin[mArea^.Origin],40)+'...)');
end;
'F' : begin
cfgReadOption(optNet,maxAddress,mArea^.Address);
cfgSetItem(cfgOption(optNet,mArea^.Address));
end;
'G' : begin
cfgReadInfo(mArea^.Sponsor,inNormal,chNormal,'',False);
mArea^.Sponsor := cfgRead;
cfgSetItem(mArea^.Sponsor);
end;
'H' : begin
cfgReadInfo(mArea^.ACS,inLower,chNormal,'',False);
mArea^.ACS := cfgRead;
cfgSetItem(mArea^.ACS);
end;
'I' : begin
cfgReadInfo(mArea^.PostACS,inLower,chNormal,'',False);
mArea^.PostACS := cfgRead;
cfgSetItem(mArea^.PostACS);
end;
'J' : begin
cfgReadInfo(St(mArea^.MaxMsgs),inUpper,chNumeric,'',True);
mArea^.MaxMsgs := mClip(StrToInt(cfgRead),0,9999);
cfgSetItem(St(mArea^.MaxMsgs));
end;
'K' : begin
cfgReadInfo(mArea^.Password,inUpper,chNormal,'',False);
mArea^.Password := cfgRead;
cfgSetItem(mArea^.Password);
end;
'L' : begin
cfgReadInfo(mArea^.qwkName,inNormal,chNormal,'',False);
mArea^.qwkName := cfgRead;
cfgSetItem(mArea^.qwkName);
end;
'M' : begin
cfgReadInfo(St(mArea^.Msgs),inUpper,chNumeric,'',True);
mArea^.Msgs := mClip(StrToInt(cfgRead),0,64000);
cfgSetItem(St(mArea^.Msgs));
end;
'1' : begin
B := maUnhidden in mArea^.Flag;
cfgReadBoolean(B);
if not B then mArea^.Flag := mArea^.Flag - [maUnhidden] else
mArea^.Flag := mArea^.Flag + [maUnhidden];
cfgSetItem(B2St(B));
end;
'2' : begin
B := maRealName in mArea^.Flag;
cfgReadBoolean(B);
if not B then mArea^.Flag := mArea^.Flag - [maRealName] else
mArea^.Flag := mArea^.Flag + [maRealName];
cfgSetItem(B2St(B));
end;
'3' : begin
B := maPrivate in mArea^.Flag;
cfgReadBoolean(B);
if not B then mArea^.Flag := mArea^.Flag - [maPrivate] else
mArea^.Flag := mArea^.Flag + [maPrivate];
cfgSetItem(B2St(B));
end;
'4' : begin
B := maMandatory in mArea^.Flag;
cfgReadBoolean(B);
if not B then mArea^.Flag := mArea^.Flag - [maMandatory] else
mArea^.Flag := mArea^.Flag + [maMandatory];
cfgSetItem(B2St(B));
end;
'5' : begin
B := maAnonymous in mArea^.Flag;
cfgReadBoolean(B);
if not B then mArea^.Flag := mArea^.Flag - [maAnonymous] else
mArea^.Flag := mArea^.Flag + [maAnonymous];
cfgSetItem(B2St(B));
end;
'[' : begin
T := mArea^.areaType;
User^.curMsgArea := An;
maSave;
if An = 1 then An := numMsgArea else Dec(An,1);
User^.curMsgArea := An;
maLoad;
cfgDraw := T <> mArea^.areaType;
cfgOver := not cfgDraw;
if cfgOver then cfgDraw := True;
end;
']' : begin
T := mArea^.areaType;
User^.curMsgArea := An;
maSave;
if An = numMsgArea then An := 1 else Inc(An,1);
User^.curMsgArea := An;
maLoad;
cfgDraw := T <> mArea^.areaType;
cfgOver := not cfgDraw;
if cfgOver then cfgDraw := True;
end;
end;
until (HangUp) or (cfgDone);
cfgDone := False;
User^.curMsgArea := An;
maSave;
User^.curMsgArea := Anum;
if UserOn then maLoad;
end;
procedure cfgMsgAreaEditor;
var cmdMaEdit : array[1..5] of String;
oldArea : Word;
begin
cmdMaEdit[1] := 'I nsert';
cmdMaEdit[2] := 'D elete';
cmdMaEdit[3] := 'E dit';
cmdMaEdit[4] := 'M ove';
cmdMaEdit[5] := 'Esc Quit';
cfgDone := False;
logWrite('*Message area edit.');
oldArea := User^.curMsgArea;
repeat
oClrScr;
cfgDraw := True;
cfgOver := False;
PausePos := 1;
PauseAbort := False;
oSetCol(colText);
oWriteLn(' Num Description Filename ACS pACS Max Sponsor');
{ 4 26 9 6 6 4 16}
oSetCol(colBorder);
oWriteLn(sRepeat('Ä',79));
oUpPause(2);
numMsgArea := 0;
Assign(maF,Cfg^.pathData+fileMsgArea);
{$I-}
Reset(maF);
{$I+}
if ioResult <> 0 then
begin
maReset;
Rewrite(maF);
Write(maF,mArea^);
Close(maF);
Reset(maF);
end;
while (not PauseAbort) and (not Eof(maF)) do
begin
Read(maF,mArea^);
Inc(numMsgArea,1);
oSetCol(colInfo);
oCWriteLn(' '+Resize(St(numMsgArea),4)+
' '+Resize(mArea^.Name,26)+
' '+Resize(mArea^.Filename,9)+
' '+Resize(mArea^.ACS,6)+
' '+Resize(mArea^.PostACS,6)+
' '+Resize(St(mArea^.MaxMsgs),4)+
' '+strSquish(mArea^.Sponsor,16));
oUpPause(1);
end;
numMsgArea := FileSize(maF);
Close(maF);
if numMsgArea = 0 then oWriteLn('No message areas currently exist.');
oSetCol(colBorder);
oWriteLn(sRepeat('Ä',79));
oUpPause(1);
PausePos := 0;
cfgPrompt(cmdMaEdit,5);
repeat
cfgKey := UpCase(iReadkey);
until (HangUp) or (cfgKey in ['I','D','E','M',#27]);
if cfgKey = #27 then oWrite('Quit') else oWriteChar(cfgKey);
case cfgKey of
'I' : cfgInsertMsgArea;
'D' : cfgDeleteMsgArea;
'E' : cfgEditMsgArea;
'M' : cfgMoveMsgArea;
#27 : cfgDone := True;
end;
until (HangUp) or (cfgDone);
maUpdateAllScanFiles;
User^.curMsgArea := oldArea;
maLoad;
end;
end. |
unit adot.Alg.IntegralImage;
interface
uses
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils;
type
{ Summed area table. Precalculates sums for very fast calculation of SUM of any area [x1,y1,x2,y2].
https://en.wikipedia.org/wiki/Summed_area_table}
TIntegralImageInt64 = record
private
procedure BuildLine(ADst: PInt64Array);
function GetLine(y: integer): PInt64Array;
function GetSum(x1, y1, x2, y2: integer): int64;
function GetAvg(x1, y1, x2, y2: integer): int64;
public
Image: TArray<int64>;
Width,Height: integer;
procedure Init;
procedure SetSize(AWidth,AHeight: integer);
procedure Build;
{ release memory etc }
procedure Clear;
{ usefull to fill with initial values }
property Lines[y: integer]: PInt64Array read GetLine;
{ Fastest, no range checks etc }
property Sum[x1,y1,x2,y2: integer]:int64 read GetSum;
{ positions are adjusted to be inside of the image }
property Avg[x1,y1,x2,y2: integer]:int64 read GetAvg; default;
end;
TInterpolation_Int64Custom = class
public
type
TPt = record
X,Y: int64;
end;
protected
FPoints: TArray<TPt>;
FUpdateCnt: integer;
FComparer: IComparer<TPt>;
procedure DoBeginUpdate; virtual;
procedure DoEndUpdate; virtual;
function DoGetValue(const X: int64):int64; virtual; abstract;
function GetPointCount: integer;
function GetPoint(i: integer): TPt;
procedure SetPoint(i: integer; const Value: TPt);
public
constructor Create(PointCount: integer); virtual;
procedure BeginUpdate;
procedure EndUpdate;
property PointCount: integer read GetPointCount;
property Points[i: integer]: TPt read GetPoint write SetPoint;
property Values[const x: int64]: int64 read DoGetValue; default;
end;
TLinearInterpolation_Int64 = class(TInterpolation_Int64Custom)
protected
function DoGetValue(const X: int64):int64; override;
end;
implementation
{ TIntegralImageInt64 }
procedure TIntegralImageInt64.Init;
begin
Self := Default(TIntegralImageInt64);
end;
procedure TIntegralImageInt64.SetSize(AWidth, AHeight: integer);
begin
Width := AWidth;
Height := AHeight;
SetLength(Image, 0);
SetLength(Image, Width*Height);
end;
procedure TIntegralImageInt64.Build;
var
x,y: Integer;
begin
for x := 1 to Width-1 do
Inc(Image[x],Image[x-1]);
for y := 1 to Height-1 do
Inc(Image[y*Width],Image[(y-1)*Width]);
for y := 1 to Height-1 do
BuildLine(@Image[y*Width+1]);
end;
(*
#####
# #
####?
*)
procedure TIntegralImageInt64.BuildLine(ADst: PInt64Array);
var
x: Integer;
begin
for x := 0 to Width-2 do
inc(ADst[x], ADst[x-1]+ADst[x-Width]-ADst[x-Width-1]);
end;
procedure TIntegralImageInt64.Clear;
begin
SetSize(0,0);
end;
function TIntegralImageInt64.GetLine(y: integer): PInt64Array;
begin
result := @Image[y*Width];
end;
function TIntegralImageInt64.GetSum(x1, y1, x2, y2: integer): int64;
begin
Result := Image[x2+y2*Width];
if x1>0 then
begin
if y1>0 then
Inc(Result, Image[x1-1+(y1-1)*Width]);
dec(Result, Image[x1-1+y2*Width]);
end;
if y1>0 then
dec(Result, Image[x2+(y1-1)*Width]);
end;
function TIntegralImageInt64.GetAvg(x1, y1, x2, y2: integer): int64;
begin
assert((x2>=x1) and (y2>=y1));
if x2-x1+1>width then
x2 := x1+width-1;
if y2-y1+1>height then
y2 := y1+height-1;
if x1<0 then
begin
dec(x2, x1);
x1 := 0;
end;
if y1<0 then
begin
dec(y2, y1);
y1 := 0;
end;
if x2>=width then
begin
dec(x1,x2-width+1);
x2 := width-1;
end;
if y2>=height then
begin
dec(y1,y2-height+1);
y2 := height-1;
end;
result := Sum[x1,y1,x2,y2] div ((x2-x1+1)*(y2-y1+1));
end;
{ TInterpolation_Int64Custom }
constructor TInterpolation_Int64Custom.Create(PointCount: integer);
begin
SetLength(FPoints, PointCount);
FComparer := TDelegatedComparer<TPt>.Create(
function (const A, B: TPt): integer
begin
if A.X < B.X then result := -1 else
if A.X = B.X then result := 0 else
result := 1;
end);
end;
procedure TInterpolation_Int64Custom.BeginUpdate;
begin
inc(FUpdateCnt);
if FUpdateCnt=1 then
DoBeginUpdate;
end;
procedure TInterpolation_Int64Custom.EndUpdate;
begin
dec(FUpdateCnt);
if FUpdateCnt=0 then
DoEndUpdate;
end;
procedure TInterpolation_Int64Custom.DoBeginUpdate;
begin
end;
procedure TInterpolation_Int64Custom.DoEndUpdate;
var
I: Integer;
begin
{ reorder if necessary }
for I := 0 to High(FPoints)-1 do
if FPoints[I].X > FPoints[I+1].X then
begin
TArray.Sort<TPt>(FPoints, FComparer);
Break;
end;
{ It is not allowed to have Xi=Xj for any i<>j,
items are ordered, so we can check it eficiently. }
for I := 0 to High(FPoints)-1 do
if FPoints[I].X=FPoints[I+1].X then
raise Exception.Create('Error');
end;
function TInterpolation_Int64Custom.GetPoint(i: integer): TPt;
begin
result := FPoints[i];
end;
procedure TInterpolation_Int64Custom.SetPoint(i: integer; const Value: TPt);
begin
Assert((FUpdateCnt>0) and (i>=0) and (i<=High(FPoints)));
FPoints[i] := Value;
end;
function TInterpolation_Int64Custom.GetPointCount: integer;
begin
result := Length(FPoints);
end;
{ TLinearInterpolation_Int64 }
function TLinearInterpolation_Int64.DoGetValue(const X: int64): int64;
var
Item: TPt;
FoundIndex: Integer;
begin
Assert(Length(FPoints)>0);
Item.X := X;
Item.Y := 0;
if TArray.BinarySearch<TPt>(FPoints, Item, FoundIndex, FComparer) then
result := FPoints[FoundIndex].Y
else
{ If not found, FoundIndex contains the index of the first entry larger than Item }
if FoundIndex = 0 then result := FPoints[0].Y else
if FoundIndex > High(FPoints) then result := FPoints[High(FPoints)].Y else
{ Xi<>Xj for any i<>j (check DoEndUpdate), so div by zero is not possible here. }
result := FPoints[FoundIndex-1].Y +
(X-FPoints[FoundIndex-1].X) *
(FPoints[FoundIndex].Y-FPoints[FoundIndex-1].Y) div
(FPoints[FoundIndex].X-FPoints[FoundIndex-1].X);
end;
end.
|
unit JAList;
{$mode objfpc}{$H+}
{$i JA.inc}
interface
uses
JATypes;
type
PJAListItem = ^TJAListItem;
TJAListItem = record
Data : pointer;
Previous : PJAListItem;
Next : PJAListItem;
end;
TJAListItemCallback = function(AItem : PJAListItem) : boolean;
{ TJAList }
TJAList = record
Head : PJAListItem;
Tail : PJAListItem;
Count : SInt32;
end;
PJAList = ^TJAList;
function JAListItemCreate : PJAListItem; {creates memory for item}
function JAListItemDestroy(AItem : PJAListItem) : boolean; {frees memory of item}
function JAListItemCopy(AItem : PJAListItem) : PJAListItem; {creates memory for a new item and copies existing item to it}
function JAListCreate : PJAList;
function JAListDestroy(AList : PJAList) : boolean;
{Item routines}
function JAListInsertBefore(AList : PJAList; AItem, ABeforeItem : PJAListItem) : PJAListItem; {Insert Item Before Item, Return AItem or NIL on Error}
function JAListInsertAfter(AList : PJAList; AItem, AAfterItem : PJAListItem) : PJAListItem; {Insert Item After Item, Return AItem or NIL on Error}
function JAListPushHead(AList : PJAList; AItem : PJAListItem) : PJAListItem; {Push AItem to Head, Return AItem or NIL on Error}
function JAListPushTail(AList : PJAList; AItem : PJAListItem) : PJAListItem; {Push AItem to Tail, Return AItem or NIL on Error}
function JAListPopHead(AList : PJAList) : PJAListItem; {Unlink Head Item, Return Item or NIL on Error}
function JAListPopTail(AList : PJAList) : PJAListItem; {Unlink Tail Item, Return Item or NIL on Error}
function JAListPeekHead(AList : PJAList) : PJAListItem; {Return Head Item or NIL on Error}
function JAListPeekTail(AList : PJAList) : PJAListItem; {Return Tail Item or NIL on Error}
function JAListExtract(AList : PJAList; AItem : PJAListItem) : PJAListItem; {Unlink AItem, Return AItem or NIL on Error}
{List interacions}
function JAListInsertListBefore(AList, AListSource : PJAList; ABeforeItem : PJAListItem) : PJAList; {Insert List Before Item, Reset Source, Return Self or NIL on Error}
function JAListInsertListAfter(AList, AListSource : PJAList; AAfterItem : PJAListItem) : PJAList; {Insert List After Item, Reset Source, Return Self or NIL on Error}
function JAListPushListHead(AList, AListSource : PJAList) : PJAList; {Push List to Head, Reset Source, Return Self or NIL on Error}
function JAListPushListTail(AList, AListSource : PJAList) : PJAList; {Push List to Tail, Reset Source, Return Self or NIL on Error}
function JAListPushListCopyHead(AList, AListSource : PJAList) : PJAList; {Push a copy of the List to Head, Return Self or NIL on Error}
function JAListPushListCopyTail(AList, AListSource : PJAList) : PJAList; {Push a copy of the List to Tail, Return Self or NIL on Error}
function JAListClear(AList : PJAList) : PJAList; {Destroy All Items, Reset to default state, return Self or NIL on Error}
{callback routines}
procedure JAListCallbackHeadToTail(AList : PJAList; ACallBack : TJAListItemCallback); {Callback Head To Tail}
procedure JAListCallbackTailToHead(AList : PJAList; ACallBack : TJAListItemCallback); {Callback Tail to Head}
implementation
function JAListItemCreate() : PJAListItem;
begin
Result := JAMemGet(SizeOf(TJAListItem));
Result^.Data := nil;
Result^.Previous := nil;
Result^.Next := nil;
end;
function JAListItemDestroy(AItem : PJAListItem) : boolean;
begin
//if (AItem^.Previous<>nil) then AItem^.Previous^.Next := nil;
//if (AItem^.Next<>nil) then AItem^.Next^.Previous := nil;
JAMemFree(AItem, SizeOf(TJAListItem));
Result := true;
end;
function JAListItemCopy(AItem : PJAListItem) : PJAListItem;
begin
Result := JAMemGet(SizeOf(TJAListItem));
Result^.Data := AItem^.Data;
Result^.Previous := AItem^.Previous;
Result^.Next := AItem^.Next;
end;
function JAListCreate() : PJAList;
begin
Result := JAMemGet(SizeOf(TJAList));
Result^.Count := 0;
{Create Dummy Head and Tail}
Result^.Head := JAListItemCreate();
Result^.Tail := JAListItemCreate();
{Setup Initial links}
Result^.Head^.Next := Result^.Tail;
Result^.Tail^.Previous := Result^.Head;
end;
function JAListDestroy(AList : PJAList) : boolean;
begin
{must destroy all items and dummy items}
JAListClear(AList);
JAListItemDestroy(AList^.Head);
JAListItemDestroy(AList^.Tail);
JAMemFree(AList, SizeOf(TJAList));
end;
function JAListClear(AList : PJAList) : PJAList;
var
CurrentItem : PJAListItem;
begin
Result := AList;
if (AList^.Count=0) then exit;
CurrentItem := AList^.Head^.Next;
while (CurrentItem <> AList^.Tail) do
begin
CurrentItem := CurrentItem^.Next;
JAListItemDestroy(CurrentItem^.Previous);
end;
AList^.Head^.Next := AList^.Tail;
AList^.Tail^.Previous := AList^.Head;
AList^.Count := 0;
end;
function JAListInsertBefore(AList : PJAList; AItem, ABeforeItem : PJAListItem) : PJAListItem;
begin
Result := nil;
if (AItem=nil) or (ABeforeItem=nil) then exit;
AItem^.Previous := ABeforeItem^.Previous;
AItem^.Next := ABeforeItem;
ABeforeItem^.Previous^.Next := AItem;
ABeforeItem^.Previous := AItem;
AList^.Count += 1;
Result := AItem;
end;
function JAListInsertAfter(AList : PJAList; AItem, AAfterItem : PJAListItem) : PJAListItem;
begin
Result := nil;
if (AItem=nil) or (AAfterItem=nil) then exit;
AItem^.Previous := AAfterItem;
AItem^.Next := AAfterItem^.Next;
AAfterItem^.Next^.Previous := AItem;
AAfterItem^.Next := AItem;
AList^.Count += 1;
Result := AItem;
end;
function JAListPushHead(AList : PJAList; AItem : PJAListItem) : PJAListItem;
begin
Result := JAListInsertAfter(AList, AItem, AList^.Head);
end;
function JAListPushTail(AList : PJAList; AItem : PJAListItem) : PJAListItem;
begin
Result := JAListInsertBefore(AList, AItem, AList^.Tail);
end;
function JAListPopHead(AList : PJAList) : PJAListItem;
begin
if (AList^.Count>0) then
begin
Result := AList^.Head^.Next;
AList^.Head^.Next := Result^.Next;
AList^.Head^.Next^.Previous := AList^.Head;
Result^.Previous := nil;
Result^.Next := nil;
AList^.Count -= 1;
end else Result := nil;
end;
function JAListPopTail(AList : PJAList) : PJAListItem;
begin
if (AList^.Count>0) then
begin
Result := AList^.Tail^.Previous;
AList^.Tail^.Previous := Result^.Previous;
AList^.Tail^.Previous^.Next := AList^.Tail;
Result^.Previous := nil;
Result^.Next := nil;
AList^.Count -= 1;
end else Result := nil;
end;
function JAListPeekHead(AList : PJAList) : PJAListItem;
begin
if (AList^.Count>0) then Result := AList^.Head^.Next
else Result := nil;
end;
function JAListPeekTail(AList : PJAList) : PJAListItem;
begin
if (AList^.Count>0) then Result := AList^.Tail^.Previous
else Result := nil;
end;
function JAListExtract(AList : PJAList; AItem : PJAListItem) : PJAListItem;
begin
Result := nil;
if (AItem=nil) then exit;
AItem^.Previous^.Next := AItem^.Next;
AItem^.Next^.Previous := AItem^.Previous;
AList^.Count -= 1;
Result := AItem;
end;
function JAListInsertListBefore(AList, AListSource : PJAList; ABeforeItem : PJAListItem) : PJAList;
begin
Result := nil;
if (AListSource=nil) or (ABeforeItem=nil) or (AListSource=AList) then exit;
if (AListSource^.Count=0) then exit;
{Insert List}
JAListPeekTail(AListSource)^.Next := ABeforeItem;
JAListPeekHead(AListSource)^.Previous := ABeforeItem^.Previous;
ABeforeItem^.Previous^.Next := JAListPeekHead(AListSource);
ABeforeItem^.Previous := JAListPeekTail(AListSource);
AList^.Count += AListSource^.Count;
{Set Source List to Default State}
AListSource^.Head^.Next := AListSource^.Tail;
AListSource^.Tail^.Previous := AListSource^.Head;
AListSource^.Count := 0;
Result := AList;
end;
function JAListInsertListAfter(AList, AListSource : PJAList; AAfterItem : PJAListItem) : PJAList;
begin
Result := nil;
if (AListSource=nil) or (AAfterItem=nil) or (AListSource=AList) then exit;
if (AListSource^.Count=0) then exit;
{Insert List}
JAListPeekTail(AListSource)^.Next := AAfterItem^.Next;
JAListPeekHead(AListSource)^.Previous := AAfterItem;
AAfterItem^.Next^.Previous := JAListPeekTail(AListSource);
AAfterItem^.Next := JAListPeekTail(AListSource);
AList^.Count += AListSource^.Count;
{Set Source List to Default State}
AListSource^.Head^.Next := AListSource^.Tail;
AListSource^.Tail^.Previous := AListSource^.Head;
AListSource^.Count := 0;
Result := AList;
end;
function JAListPushListHead(AList, AListSource : PJAList) : PJAList;
begin
Result := JAListInsertListAfter(AList, AListSource, AList^.Head);
end;
function JAListPushListTail(AList, AListSource : PJAList) : PJAList;
begin
Result := JAListInsertListBefore(AList, AListSource, AList^.Tail);
end;
function JAListPushListCopyHead(AList, AListSource : PJAList) : PJAList;
var
CurrentItem : PJAListItem;
begin
Result := nil;
if (AListSource=nil) then exit;
CurrentItem := JAListPeekTail(AListSource);
While (CurrentItem<>AListSource^.Head) do
begin
JAListPushHead(AList, JAListItemCopy(CurrentItem));
CurrentItem := CurrentItem^.Previous;
end;
Result := AList;
end;
function JAListPushListCopyTail(AList, AListSource : PJAList) : PJAList;
var
CurrentItem : PJAListItem;
begin
Result := nil;
if (AListSource=nil) then exit;
CurrentItem := JAListPeekHead(AListSource);
While (CurrentItem<>AListSource^.Tail) do
begin
JAListPushTail(AList, JAListItemCopy(CurrentItem));
CurrentItem := CurrentItem^.Next;
end;
Result := AList;
end;
procedure JAListCallbackHeadToTail(AList : PJAList; ACallBack : TJAListItemCallback);
var
CurrentItem : PJAListItem;
begin
if (AList^.Count=0) then exit;
CurrentItem := AList^.Head^.Next;
while (CurrentItem<>AList^.Tail) do
begin
ACallBack(CurrentItem);
CurrentItem := CurrentItem^.Next;
end;
end;
procedure JAListCallbackTailToHead(AList : PJAList; ACallBack : TJAListItemCallback);
var
CurrentItem : PJAListItem;
begin
if (AList^.Count=0) then exit;
CurrentItem := AList^.Tail^.Previous;
while (CurrentItem<>AList^.Head) do
begin
ACallBack(CurrentItem);
CurrentItem := CurrentItem^.Previous;
end;
end;
end.
|
unit Filter1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, DB;
type
TfmFilterFrm = class(TForm)
Label1: TLabel;
Label2: TLabel;
ListBox1: TListBox;
ListBox2: TListBox;
Label3: TLabel;
Memo1: TMemo;
GroupBox1: TGroupBox;
cbCaseSensitive: TCheckBox;
cbNoPartialCompare: TCheckBox;
ComboBox1: TComboBox;
Label4: TLabel;
BtnApplyFilter: TButton;
BtnClear: TButton;
BtnClose: TButton;
procedure AddFieldName(Sender: TObject);
procedure ListBox2DblClick(Sender: TObject);
procedure ApplyFilter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure cbCaseSensitiveClick(Sender: TObject);
procedure cbNoPartialCompareClick(Sender: TObject);
procedure SBtnClearClick(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure SBtnCloseClick(Sender: TObject);
end;
var
fmFilterFrm: TfmFilterFrm;
implementation
uses DM, CustView;
{$R *.DFM}
{ Adds current listbox field name to memo. }
procedure TfmFilterFrm.AddFieldName(Sender: TObject);
begin
if Memo1.Text <> '' then
Memo1.Text := Memo1.Text + ' ';
Memo1.Text := Memo1.Text + ListBox1.Items[ListBox1.ItemIndex];
end;
{ Adds current Filter operator to memo. }
procedure TfmFilterFrm.ListBox2DblClick(Sender: TObject);
begin
if Memo1.Text <> '' then
Memo1.Text := Memo1.Text + ' '+ ListBox2.Items[ListBox2.ItemIndex];
end;
procedure TfmFilterFrm.ApplyFilter(Sender: TObject);
begin
with DM1.CustomerSource.Dataset do
begin
if ComboBox1.Text <> '' then
begin
Filter := ComboBox1.Text;
Filtered := True;
fmCustView.Caption := 'Customers - Filtered';
end
else begin
Filter := '';
Filtered := False;
fmCustView.Caption := 'Customers - Unfiltered'
end;
end;
end;
{ Populate the ListBox1 with available fields from the Customer Dataset. }
procedure TfmFilterFrm.FormCreate(Sender: TObject);
var
I: Integer;
begin
for I := 0 to DM1.CustomerSource.Dataset.FieldCount - 1 do
ListBox1.Items.Add(DM1.Customer.Fields[I].FieldName);
{ Add date dependent Query ComboBox1. }
ComboBox1.Items.Add('LastInvoiceDate >= ''' +
DateToStr(EncodeDate(1994, 09, 30)) + '''');
ComboBox1.Items.Add('Country = ''US'' and LastInvoiceDate > ''' +
DateToStr(EncodeDate(1994, 06, 30)) + '''');
end;
{ Since the Filter property is a TStrings and the Memo field
is a TMemo, convert the Memo's wrapped text to a string,
which is then used when the user presses Apply. }
procedure TfmFilterFrm.Memo1Change(Sender: TObject);
var
I: Integer;
begin
ComboBox1.Text := Memo1.Lines[0];
for I := 1 to Memo1.Lines.Count - 1 do
ComboBox1.Text := ComboBox1.Text + ' ' + Memo1.Lines[I];
end;
{ Set the Customer's Dataset Case Sensitive Filter Option. }
procedure TfmFilterFrm.cbCaseSensitiveClick(Sender: TObject);
begin
with DM1.CustomerSource.Dataset do
if cbCaseSensitive.checked then
FilterOptions := FilterOptions - [foCaseInSensitive]
else
FilterOptions := FilterOptions + [foCaseInsensitive];
end;
{ Set the Customer Partial Compare Filter Option. }
procedure TfmFilterFrm.cbNoPartialCompareClick(Sender: TObject);
begin
with DM1.CustomerSource.Dataset do
if cbNoPartialCompare.checked then
FilterOptions := FilterOptions + [foNoPartialCompare]
else
FilterOptions := FilterOptions - [foNoPartialCompare];
end;
{ Add User-Entered filters into list box at runtime. }
procedure TfmFilterFrm.SBtnClearClick(Sender: TObject);
var
st: string;
begin
Memo1.Lines.Clear;
st := ComboBox1.Text;
ComboBox1.Text := '';
if ComboBox1.Items.IndexOf(st) = -1 then
ComboBox1.Items.Add(st);
end;
{ Reset the Memo field when the Filter ComboBox changes. }
procedure TfmFilterFrm.ComboBox1Change(Sender: TObject);
begin
Memo1.Lines.Clear;
Memo1.Lines.Add(ComboBox1.Text);
end;
{ Close the Filter Form. }
procedure TfmFilterFrm.SBtnCloseClick(Sender: TObject);
begin
Close;
end;
end.
|
unit Devices.ModbusBase;
interface
uses Windows, GMGlobals, SysUtils, GMConst, StrUtils, Math;
const MODBUS_TCP_ANSWER_DATA_START = 9;
MODBUS_RTU_ANSWER_DATA_START = 3;
procedure Modbus_CRC(var buf: array of Byte; Len: int);
procedure Modbus_LRC(var buf: array of Byte; Len: int);
function Modbus_CheckCRC(buf: array of Byte; Len: int): bool;
function Modbus_ReadWord(buf: array of Byte; dataAddr: int): int;
function Modbus_ResultTypeLength(resultType: int): int;
implementation
function Modbus_ResultTypeLength(resultType: int): int;
begin
Result := 1;
if resultType in [MODBUS_RESULT_DOUBLE_BIG_ENDIAN, MODBUS_RESULT_DOUBLE_LITTLE_ENDIAN] then
Inc(Result, 3)
else
if resultType in [MODBUS_RESULT_LONG_BIG_ENDIAN..MODBUS_RESULT_SINGLE_LITTLE_ENDIAN] then
Inc(Result);
end;
function Modbus_CRC_Calc(var buf: array of Byte; Len: int): WORD;
var i, j: int;
CRC: WORD;
begin
CRC := $FFFF;
if Len < High(CRC) then
for i := 0 to Len - 1 do
begin
CRC := (CRC xor buf[i]) and $FFFF;
for j := 0 to 7 do
if (CRC and 1) = 1 then
CRC := ((CRC shr 1) xor $A001) and $FFFF
else
CRC := (CRC shr 1) and $FFFF;
end;
Result := CRC;
end;
procedure Modbus_LRC(var buf: array of Byte; Len: int);
var i: int;
lrc: byte;
begin
lrc := 0;
for i := 1 to Len - 1 do
lrc := (lrc + StrToInt('$' + AnsiChar(buf[i])) * IfThen(Odd(i), 16, 1)) and $FF;
lrc := ($100 - lrc) and $FF;
buf[Len] := ord(AnsiString(IntToHex(lrc, 2))[1]);
buf[Len + 1] := ord(AnsiString(IntToHex(lrc, 2))[2]);
end;
procedure Modbus_CRC(var buf: array of Byte; Len: int);
var CRC: WORD;
begin
CRC := Modbus_CRC_Calc(buf, Len);
buf[Len] := CRC mod 256;
buf[Len + 1] := CRC div 256;
end;
function Modbus_CheckCRC(buf: array of Byte; Len: int): bool;
var CRC: WORD;
begin
if Len < 3 then
begin
Result := false;
Exit;
end;
CRC := Modbus_CRC_Calc(buf, Len - 2);
Result := (buf[Len - 2] = CRC mod 256) and (buf[Len - 1] = CRC div 256);
end;
function Modbus_ReadWord(buf: array of Byte; dataAddr: int): int;
begin
Result := 0;
// 6 - это номер устройства, код ф-и, к-во слов в ответе, CRC и второй байт искомого слова
// addr нумеруются с 0
if dataAddr * 2 + 6 >= Length(buf) then Exit;
Result := buf[dataAddr * 2 + 3] * 256 + buf[dataAddr * 2 + 4];
end;
end.
|
unit Ntapi.ntseapi;
{$WARN SYMBOL_PLATFORM OFF}
{$MINENUMSIZE 4}
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntrtl;
const
TOKEN_ASSIGN_PRIMARY = $0001;
TOKEN_DUPLICATE = $0002;
TOKEN_IMPERSONATE = $0004;
TOKEN_QUERY = $0008;
TOKEN_QUERY_SOURCE = $0010;
TOKEN_ADJUST_PRIVILEGES = $0020;
TOKEN_ADJUST_GROUPS = $0040;
TOKEN_ADJUST_DEFAULT = $0080;
TOKEN_ADJUST_SESSIONID = $0100;
TOKEN_ALL_ACCESS_P = STANDARD_RIGHTS_REQUIRED or
TOKEN_ASSIGN_PRIMARY or TOKEN_DUPLICATE or TOKEN_IMPERSONATE or
TOKEN_QUERY or TOKEN_QUERY_SOURCE or TOKEN_ADJUST_PRIVILEGES or
TOKEN_ADJUST_GROUPS or TOKEN_ADJUST_DEFAULT;
TOKEN_ALL_ACCESS = TOKEN_ALL_ACCESS_P or TOKEN_ADJUST_SESSIONID;
TokenAccessMapping: array [0..8] of TFlagName = (
(Value: TOKEN_DUPLICATE; Name: 'Duplicate'),
(Value: TOKEN_QUERY; Name: 'Query'),
(Value: TOKEN_QUERY_SOURCE; Name: 'Query source'),
(Value: TOKEN_IMPERSONATE; Name: 'Impersonate'),
(Value: TOKEN_ASSIGN_PRIMARY; Name: 'Assign primary'),
(Value: TOKEN_ADJUST_DEFAULT; Name: 'Adjust defaults'),
(Value: TOKEN_ADJUST_PRIVILEGES; Name: 'Adjust privileges'),
(Value: TOKEN_ADJUST_GROUPS; Name: 'Adjust groups'),
(Value: TOKEN_ADJUST_SESSIONID; Name: 'Adjust session ID')
);
TokenAccessType: TAccessMaskType = (
TypeName: 'token';
FullAccess: TOKEN_ALL_ACCESS;
Count: Length(TokenAccessMapping);
Mapping: PFlagNameRefs(@TokenAccessMapping);
);
// Filtration flags
DISABLE_MAX_PRIVILEGE = $1;
SANDBOX_INERT = $2;
LUA_TOKEN = $4;
WRITE_RESTRICTED = $8;
SE_MIN_WELL_KNOWN_PRIVILEGE = 2;
SE_MAX_WELL_KNOWN_PRIVILEGE = 36;
// Win 8+
NtCurrentProcessToken: THandle = THandle(-4);
NtCurrentThreadToken: THandle = THandle(-5);
NtCurrentEffectiveToken: THandle = THandle(-6);
type
{$MINENUMSIZE 1}
TSeWellKnownPrivilege = (
SE_RESERVED_LUID_0 = 0,
SE_RESERVED_LUID_1 = 1,
SE_CREATE_TOKEN_PRIVILEGE = 2,
SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE = 3,
SE_LOCK_MEMORY_PRIVILEGE = 4,
SE_INCREASE_QUOTA_PRIVILEGE = 5,
SE_MACHINE_ACCOUNT_PRIVILEGE = 6,
SE_TCB_PRIVILEGE = 7,
SE_SECURITY_PRIVILEGE = 8,
SE_TAKE_OWNERSHIP_PRIVILEGE = 9,
SE_LOAD_DRIVER_PRIVILEGE = 10,
SE_SYSTEM_PROFILE_PRIVILEGE = 11,
SE_SYSTEMTIME_PRIVILEGE = 12,
SE_PROFILE_SINGLE_PROCESS_PRIVILEGE = 13,
SE_INCREASE_BASE_PRIORITY_PRIVILEGE = 14,
SE_CREATE_PAGEFILE_PRIVILEGE = 15,
SE_CREATE_PERMANENT_PRIVILEGE = 16,
SE_BACKUP_PRIVILEGE = 17,
SE_RESTORE_PRIVILEGE = 18,
SE_SHUTDOWN_PRIVILEGE = 19,
SE_DEBUG_PRIVILEGE = 20,
SE_AUDIT_PRIVILEGE = 21,
SE_SYSTEM_ENVIRONMENT_PRIVILEGE = 22,
SE_CHANGE_NOTIFY_PRIVILEGE = 23,
SE_REMOTE_SHUTDOWN_PRIVILEGE = 24,
SE_UNDOCK_PRIVILEGE = 25,
SE_SYNC_AGENT_PRIVILEGE = 26,
SE_ENABLE_DELEGATION_PRIVILEGE = 27,
SE_MANAGE_VOLUME_PRIVILEGE = 28,
SE_IMPERSONATE_PRIVILEGE = 29,
SE_CREATE_GLOBAL_PRIVILEGE = 30,
SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE = 31,
SE_RELABEL_PRIVILEGE = 32,
SE_INCREASE_WORKING_SET_PRIVILEGE = 33,
SE_TIME_ZONE_PRIVILEGE = 34,
SE_CREATE_SYMBOLIC_LINK_PRIVILEGE = 35,
SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE = 36
);
{$MINENUMSIZE 4}
// WinNt.10661
TTokenInformationClass = (
TokenInfoTPad = 0, // [Required to generate TypeInfo]
TokenUser = 1, // q: TSidAndAttributes
TokenGroups = 2, // q: TTokenGroups
TokenPrivileges = 3, // q: TTokenPrivileges
TokenOwner = 4, // q, s: TTokenOwner
TokenPrimaryGroup = 5, // q, s: TTokenPrimaryGroup
TokenDefaultDacl = 6, // q, s: TTokenDefaultDacl
TokenSource = 7, // q: TTokenSource
TokenType = 8, // q: TTokenType
TokenImpersonationLevel = 9, // q: TSecurityImpersonationLevel
TokenStatistics = 10, // q: TTokenStatistics
TokenRestrictedSids = 11, // q: TTokenGroups
TokenSessionId = 12, // q, s: Cardinal
TokenGroupsAndPrivileges = 13, // q: TTokenGroupsAndPrivileges
TokenSessionReference = 14, // s: LongBool
TokenSandBoxInert = 15, // q: LongBool
TokenAuditPolicy = 16, // q, s: TTokenAuditPolicy
TokenOrigin = 17, // q, s: TLuid
TokenElevationType = 18, // q: TTokenElevationType
TokenLinkedToken = 19, // q, s: THandle
TokenElevation = 20, // q: LongBool
TokenHasRestrictions = 21, // q: LongBool
TokenAccessInformation = 22, // q: TTokenAccessInformation
TokenVirtualizationAllowed = 23, // q, s: LongBool
TokenVirtualizationEnabled = 24, // q, s: LongBool
TokenIntegrityLevel = 25, // q, s: TSidAndAttributes
TokenUIAccess = 26, // q, s: LongBool
TokenMandatoryPolicy = 27, // q, s: Cardinal
TokenLogonSid = 28, // q: TTokenGroups
TokenIsAppContainer = 29, // q: LongBool
TokenCapabilities = 30, // q: TTokenGroups
TokenAppContainerSid = 31, // q: TTokenAppContainer
TokenAppContainerNumber = 32, // q: Cardinal
TokenUserClaimAttributes = 33, // q: TClaimSecurityAttributes
TokenDeviceClaimAttributes = 34, // q: TClaimSecurityAttributes
TokenRestrictedUserClaimAttributes = 35, // q:
TokenRestrictedDeviceClaimAttributes = 36, // q:
TokenDeviceGroups = 37, // q: TTokenGroups
TokenRestrictedDeviceGroups = 38, // q: TTokenGroups
TokenSecurityAttributes = 39, // q, s:
TokenIsRestricted = 40, // q: LongBool
TokenProcessTrustLevel = 41, // q:
TokenPrivateNameSpace = 42, // q, s: LongBool
TokenSingletonAttributes = 43, // q:
TokenBnoIsolation = 44, // q:
TokenChildProcessFlags = 45, // q, s: LongBool
TokenIsLessPrivilegedAppContainer = 46 // q:
);
function NtCreateToken(out TokenHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes; TokenType: TTokenType;
var AuthenticationId: TLuid; var ExpirationTime: TLargeInteger;
const User: TSidAndAttributes; Groups: PTokenGroups;
Privileges: PTokenPrivileges; Owner: PTokenOwner;
var PrimaryGroup: TTokenPrimaryGroup; DefaultDacl: PTokenDefaultDacl;
const Source: TTokenSource): NTSTATUS; stdcall; external ntdll;
// Win 8+
function NtCreateLowBoxToken(out TokenHandle: THandle;
ExistingTokenHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes; PackageSid: PSID;
CapabilityCount: Cardinal; Capabilities: TArray<TSidAndAttributes>;
HandleCount: Cardinal; Handles: TArray<THandle>): NTSTATUS; stdcall;
external ntdll delayed;
function NtOpenProcessTokenEx(ProcessHandle: THandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal;
out TokenHandle: THandle): NTSTATUS; stdcall; external ntdll;
function NtOpenThreadTokenEx(ThreadHandle: THandle;
DesiredAccess: TAccessMask; OpenAsSelf: Boolean; HandleAttributes: Cardinal;
out TokenHandle: THandle): NTSTATUS; stdcall; external ntdll;
function NtDuplicateToken(ExistingTokenHandle: THandle;
DesiredAccess: TAccessMask; ObjectAttributes: PObjectAttributes;
EffectiveOnly: LongBool; TokenType: TTokenType; out NewTokenHandle: THandle)
: NTSTATUS; stdcall; external ntdll;
function NtQueryInformationToken(TokenHandle: THandle;
TokenInformationClass: TTokenInformationClass; TokenInformation: Pointer;
TokenInformationLength: Cardinal; out ReturnLength: Cardinal): NTSTATUS;
stdcall; external ntdll;
function NtSetInformationToken(TokenHandle: THandle;
TokenInformationClass: TTokenInformationClass;
TokenInformation: Pointer; TokenInformationLength: Cardinal): NTSTATUS;
stdcall; external ntdll;
function NtAdjustPrivilegesToken(TokenHandle: THandle;
DisableAllPrivileges: Boolean; NewState: PTokenPrivileges;
BufferLength: Cardinal; PreviousState: PTokenPrivileges;
ReturnLength: PCardinal): NTSTATUS; stdcall; external ntdll;
function NtAdjustGroupsToken(TokenHandle: THandle; ResetToDefault: Boolean;
NewState: PTokenGroups; BufferLength: Cardinal; PreviousState:
PTokenPrivileges; ReturnLength: PCardinal): NTSTATUS; stdcall; external ntdll;
function NtFilterToken(ExistingTokenHandle: THandle; Flags: Cardinal;
SidsToDisable: PTokenGroups; PrivilegesToDelete: PTokenPrivileges;
RestrictedSids: PTokenGroups; out NewTokenHandle: THandle): NTSTATUS;
stdcall; external ntdll;
function NtCompareTokens(FirstTokenHandle: THandle; SecondTokenHandle: THandle;
out Equal: LongBool): NTSTATUS; stdcall; external ntdll;
function NtImpersonateAnonymousToken(ThreadHandle: THandle): NTSTATUS;
stdcall; external ntdll;
implementation
end.
|
program CaeserCipher;
//function to encrypt the string
procedure encrypt(var input: string);
var i: integer;
BEGIN
//for the length of the string, shift each character
for i := 1 to length(input) do
case input[i] of
//If character is between A and Z, get its alphabetical value by subtracting it from char A and adding an offset to encrypt.
//Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char A's value to get the actual character
'A'..'Z': input[i] := chr(ord('A') + (ord(input[i]) - ord('A') + 16) mod 26);
//If character is between a and z, get its alphabetical value by subtracting it from char a and adding an offset to encrypt.
//Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char a's value to get the actual character
'a'..'z': input[i] := chr(ord('a') + (ord(input[i]) - ord('a') + 16) mod 26);
END;
END;
//function to decrypt the string
procedure decrypt(var input: string);
var i: integer;
BEGIN
//for the length of the string, shift each character
for i := 1 to length(input) do
case input[i] of
//If character is between A and Z, get its alphabetical value by subtracting it from char A and adding 26 minus the offset to decrypt.
//Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char A's value to get the actual character
'A'..'Z': input[i] := chr(ord('A') + (ord(input[i]) - ord('A') + 10) mod 26);
//If character is between a and z, get its alphabetical value by subtracting it from char a and adding 26 minus the offset to decrypt.
//Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char a's value to get the actual character
'a'..'z': input[i] := chr(ord('a') + (ord(input[i]) - ord('a') + 10) mod 26);
END;
END;
//function to print every possible shift value and result for input string
procedure solve(var input: string);
var i: integer;
var j: integer;
BEGIN
for j := 1 to 25 do
BEGIN
for i := 1 to length(input) do
case input[i] of
//If character is between A and Z, get its alphabetical value by subtracting it from char A and adding an iterating j offset to get
//every possible combination. Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char A's value to get the
// actual character
'A'..'Z': input[i] := chr(ord('A') + (ord(input[i]) - ord('A') + j) mod 26);
//If character is between a and z, get its alphabetical value by subtracting it from char a and adding an iterating j offset to get
//every possible combination. Then, modulus it by 26 to make sure it stays between 1 and 26. Last, re-add char a's value to get the
// actual character
'a'..'z': input[i] := chr(ord('a') + (ord(input[i]) - ord('a') + j) mod 26);
END;
//print the offset and the solved string
writeln(j, ': ', input);
END;
END;
var input: string;
//begin actual program
BEGIN
//set input string, print its encrypted, decrypted, and solved values
input := 'Wibbly wobbly timey wimey';
encrypt(input);
writeln('Encrypted input: ', input);
decrypt(input);
writeln('Decrypted input: ', input);
writeln('Solved input: ');
solve(input);
END. |
unit uOrder;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils;
type
// 1 订单调整
TSQLOrderAdjustment = class(TSQLRecord)
private
fOrderAdjustmentType: TSQLOrderAdjustmentTypeID;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
fComments: RawUTF8;
fDescription: RawUTF8;
fAmount: Currency;
fRecurringAmount: Currency;
fAmountAlreadyIncluded: Currency;
fProductPromo: TSQLProductPromoID;
fProductPromoRule: TSQLProductPromoRuleID;
fProductPromoActionSeq: Integer;
fProductFeature: Integer;
fCorrespondingProduct: Integer;
fTaxAuthorityRateSeq: TSQLTaxAuthorityRateProductID;
fSourceReference: Integer;
fSourcePercentage: Double;
fCustomerReference: Integer;
fPrimaryGeo: TSQLGeoID;
fSecondaryGeo: TSQLGeoID;
fExemptAmount: Currency;
fTaxAuthGeo: Integer;
fTaxAuthParty: Integer;
fOverrideGlAccount: TSQLGlAccountID;
fIncludeInTax: Boolean;
fIncludeInShipping: Boolean;
fIsManual: Boolean;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
fOriginalAdjustment: TSQLOrderAdjustmentID;
published
property OrderAdjustmentType: TSQLOrderAdjustmentTypeID read fOrderAdjustmentType write fOrderAdjustmentType;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property Comments: RawUTF8 read fComments write fComments;
property Description: RawUTF8 read fDescription write fDescription;
property Amount: Currency read fAmount write fAmount;
property RecurringAmount: Currency read fRecurringAmount write fRecurringAmount;
property AmountAlreadyIncluded: Currency read fAmountAlreadyIncluded write fAmountAlreadyIncluded;
property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo;
property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule;
property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq;
property ProductFeature: Integer read fProductFeature write fProductFeature;
property CorrespondingProduct: Integer read fCorrespondingProduct write fCorrespondingProduct;
property TaxAuthorityRateSeq: TSQLTaxAuthorityRateProductID read fTaxAuthorityRateSeq write fTaxAuthorityRateSeq;
property SourceReference: Integer read fSourceReference write fSourceReference;
property SourcePercentage: Double read fSourcePercentage write fSourcePercentage;
property CustomerReference: Integer read fCustomerReference write fCustomerReference;
property PrimaryGeo: TSQLGeoID read fPrimaryGeo write fPrimaryGeo;
property SecondaryGeo: TSQLGeoID read fSecondaryGeo write fSecondaryGeo;
property ExemptAmount: Currency read fExemptAmount write fExemptAmount;
property TaxAuthGeo: Integer read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: Integer read fTaxAuthParty write fTaxAuthParty;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property IncludeInTax: Boolean read fIncludeInTax write fIncludeInTax;
property IncludeInShipping: Boolean read fIncludeInShipping write fIncludeInShipping;
property IsManual: Boolean read fIsManual write fIsManual;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
property OriginalAdjustment: TSQLOrderAdjustmentID read fOriginalAdjustment write fOriginalAdjustment;
end;
// 2 订单调整属性
TSQLOrderAdjustmentAttribute = class(TSQLRecord)
private
fOrderAdjustment: TSQLOrderAdjustmentID;
fAttrName: TSQLOrderAdjustmentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property OrderAdjustment: TSQLOrderAdjustmentID read fOrderAdjustment write fOrderAdjustment;
property AttrName: TSQLOrderAdjustmentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 3
TSQLOrderAdjustmentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLOrderAdjustmentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLOrderAdjustmentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 4
TSQLOrderAdjustmentBilling = class(TSQLRecord)
private
fOrderAdjustment: TSQLOrderAdjustmentID;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fAmount: Currency;
published
property OrderAdjustment: TSQLOrderAdjustmentID read fOrderAdjustment write fOrderAdjustment;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property Amount: Currency read fAmount write fAmount;
end;
// 5
TSQLOrderAdjustmentTypeAttr = class(TSQLRecord)
private
fOrderAdjustmentType: TSQLOrderAdjustmentTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property OrderAdjustmentType: TSQLOrderAdjustmentTypeID read fOrderAdjustmentType write fOrderAdjustmentType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 6
TSQLOrderAttribute = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 7
TSQLOrderBlacklist = class(TSQLRecord)
private
fBlacklistString: RawUTF8;
fOrderBlacklistType: TSQLOrderBlacklistTypeID;
published
property BlacklistString: RawUTF8 read fBlacklistString write fBlacklistString;
property OrderBlacklistType: TSQLOrderBlacklistTypeID read fOrderBlacklistType write fOrderBlacklistType;
end;
// 8
TSQLOrderBlacklistType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 9
TSQLCommunicationEventOrder = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fCommunicationEvent: TSQLCommunicationEventID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
end;
// 10
TSQLOrderContactMech = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
fContactMech: TSQLContactMechID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
end;
// 11
TSQLOrderContent = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fContent: TSQLContentID;
fOrderContentType: TSQLOrderContentTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Content: TSQLContentID read fContent write fContent;
property OrderContentType: TSQLOrderContentTypeID read fOrderContentType write fOrderContentType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 12
TSQLOrderContentType = class(TSQLRecord)
private
fParent: TSQLOrderContentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLOrderContentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 13
TSQLOrderDeliverySchedule = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fEstimatedReadyDate: TDateTime;
fCartons: Integer;
fSkidsPallets: Integer;
fUnitsPieces: Double;
fTotalCubicSize: Double;
fTotalCubicUom: TSQLUomID;
fTotalWeight: Double;
fTotalWeightUom: TSQLUomID;
fStatus: TSQLStatusItemID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property EstimatedReadyDate: TDateTime read fEstimatedReadyDate write fEstimatedReadyDate;
property Cartons: Integer read fCartons write fCartons;
property SkidsPallets: Integer read fSkidsPallets write fSkidsPallets;
property UnitsPieces: Double read fUnitsPieces write fUnitsPieces;
property TotalCubicSize: Double read fTotalCubicSize write fTotalCubicSize;
property TotalCubicUom: TSQLUomID read fTotalCubicUom write fTotalCubicUom;
property TotalWeight: Double read fTotalWeight write fTotalWeight;
property TotalWeightUom: TSQLUomID read fTotalWeightUom write fTotalWeightUom;
property Status: TSQLStatusItemID read fStatus write fStatus;
end;
// 14
TSQLOrderHeader = class(TSQLRecord)
private
fOrderType: TSQLOrderTypeID;
fOrderName: RawUTF8;
fExternalId: Integer;
fSalesChannelEnum: TSQLEnumerationID;
fOrderDate: TDateTime;
fPriority: Boolean;
fEntryDate: TDateTime;
fPickSheetPrintedDate: TDateTime;
fVisit: Integer;
fStatus: TSQLStatusItemID;
fCreatedBy: TSQLUserLoginID;
fFirstAttemptOrder: Integer;
fCurrencyUom: TSQLUomID;
fAyncStatus: TSQLStatusItemID;
fBillingAccount: TSQLBillingAccountID;
fOriginFacility: TSQLFacilityID;
fWebSite: TSQLWebSiteID;
fProductStore: TSQLProductStoreID;
fTerminalId: RawUTF8;
fTransactionId: Integer;
fAutoOrderShoppingList: TSQLShoppingListID;
fNeedsInventoryIssuance: Boolean;
fIsRushOrder: Boolean;
fInternalCode: Integer;
fRemainingSubTotal: Currency;
fGrandTotal: Currency;
fIsViewed: Boolean;
fInvoicePerShipment: Boolean;
published
property OrderType: TSQLOrderTypeID read fOrderType write fOrderType;
property OrderName: RawUTF8 read fOrderName write fOrderName;
property ExternalId: Integer read fExternalId write fExternalId;
property SalesChannelEnum: TSQLEnumerationID read fSalesChannelEnum write fSalesChannelEnum;
property OrderDate: TDateTime read fOrderDate write fOrderDate;
property Priority: Boolean read fPriority write fPriority;
property EntryDate: TDateTime read fEntryDate write fEntryDate;
property PickSheetPrintedDate: TDateTime read fPickSheetPrintedDate write fPickSheetPrintedDate;
property Visit: Integer read fVisit write fVisit;
property Status: TSQLStatusItemID read fStatus write fStatus;
property CreatedBy: TSQLUserLoginID read fCreatedBy write fCreatedBy;
property FirstAttemptOrder: Integer read fFirstAttemptOrder write fFirstAttemptOrder;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property AyncStatus: TSQLStatusItemID read fAyncStatus write fAyncStatus;
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property OriginFacility: TSQLFacilityID read fOriginFacility write fOriginFacility;
property WebSite: TSQLWebSiteID read fWebSite write fWebSite;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property TerminalId: RawUTF8 read fTerminalId write fTerminalId;
property TransactionId: Integer read fTransactionId write fTransactionId;
property AutoOrderShoppingList: TSQLShoppingListID read fAutoOrderShoppingList write fAutoOrderShoppingList;
property NeedsInventoryIssuance: Boolean read fNeedsInventoryIssuance write fNeedsInventoryIssuance;
property IsRushOrder: Boolean read fIsRushOrder write fIsRushOrder;
property InternalCode: Integer read fInternalCode write fInternalCode;
property RemainingSubTotal: Currency read fRemainingSubTotal write fRemainingSubTotal;
property GrandTotal: Currency read fGrandTotal write fGrandTotal;
property IsViewed: Boolean read fIsViewed write fIsViewed;
property InvoicePerShipment: Boolean read fInvoicePerShipment write fInvoicePerShipment;
end;
// 15
TSQLOrderHeaderNote = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fNote: TSQLNoteDataID;
fInternalNote: Boolean;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property Note: TSQLNoteDataID read fNote write fNote;
property InternalNote: Boolean read fInternalNote write fInternalNote;
end;
// 16
TSQLOrderHeaderWorkEffort = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fWorkEffort: TSQLWorkEffortID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
// 17
TSQLOrderItem = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fExternalId: Integer;
fOrderItemType: TSQLOrderItemTypeID;
fOrderItemGroupSeq: Integer;
fIsItemGroupPrimary: Boolean;
fFromInventoryItem: TSQLInventoryItemID;
fBudgetId: Integer;
fBudgetItemSeq: Integer;
fProduct: TSQLProductID;
fSupplierProduct: Integer;
fProductFeature: Integer;
fProdCatalog: Integer;
fProductCategory: Integer;
fIsPromo: Boolean;
fQuote: TSQLQuoteItemID;
fQuoteItemSeq: Integer;
fShoppingList: TSQLShoppingListItemID;
fShoppingListItemSeq: Integer;
fSubscription: Integer;
fDeployment: Integer;
fQuantity: Double;
fCancelQuantity: Double;
fSelectedAmount: Double;
fUnitPrice: Currency;
fUnitListPrice: Currency;
fUnitAverageCost: Currency;
fUnitRecurringPrice: Currency;
fIsModifiedPrice: Boolean;
fRecurringFreqUom: TSQLUomID;
fItemDescription: RawUTF8;
fComments: RawUTF8;
fCorrespondingPo: Integer;
fStatus: TSQLStatusItemID;
fSyncStatus: TSQLStatusItemID;
fEstimatedShipDate: TDateTime;
fEstimatedDeliveryDate: TDateTime;
fAutoCancelDate: TDateTime;
fDontCancelSetDate: TDateTime;
fDontCancelSetUserLogin: TSQLUserLoginID;
fShipBeforeDate: TDateTime;
fShipAfterDate: TDateTime;
fCancelBackOrderDate: TDateTime;
fOverrideGlAccount: TSQLGlAccountID;
fSalesOpportunity: TSQLSalesOpportunityID;
fChangeByUserLogin: TSQLUserLoginID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ExternalId: Integer read fExternalId write fExternalId;
property OrderItemType: TSQLOrderItemTypeID read fOrderItemType write fOrderItemType;
property OrderItemGroupSeq: Integer read fOrderItemGroupSeq write fOrderItemGroupSeq;
property IsItemGroupPrimary: Boolean read fIsItemGroupPrimary write fIsItemGroupPrimary;
property FromInventoryItem: TSQLInventoryItemID read fFromInventoryItem write fFromInventoryItem;
property BudgetId: Integer read fBudgetId write fBudgetId;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property Product: TSQLProductID read fProduct write fProduct;
property SupplierProduct: Integer read fSupplierProduct write fSupplierProduct;
property ProductFeature: Integer read fProductFeature write fProductFeature;
property ProdCatalog: Integer read fProdCatalog write fProdCatalog;
property ProductCategory: Integer read fProductCategory write fProductCategory;
property IsPromo: Boolean read fIsPromo write fIsPromo;
property Quote: TSQLQuoteItemID read fQuote write fQuote;
property QuoteItemSeq: Integer read fQuoteItemSeq write fQuoteItemSeq;
property ShoppingList: TSQLShoppingListItemID read fShoppingList write fShoppingList;
property ShoppingListItemSeq: Integer read fShoppingListItemSeq write fShoppingListItemSeq;
property Subscription: Integer read fSubscription write fSubscription;
property Deployment: Integer read fDeployment write fDeployment;
property Quantity: Double read fQuantity write fQuantity;
property CancelQuantity: Double read fCancelQuantity write fCancelQuantity;
property SelectedAmount: Double read fSelectedAmount write fSelectedAmount;
property UnitPrice: Currency read fUnitPrice write fUnitPrice;
property UnitListPrice: Currency read fUnitListPrice write fUnitListPrice;
property UnitAverageCost: Currency read fUnitAverageCost write fUnitAverageCost;
property UnitRecurringPrice: Currency read fUnitRecurringPrice write fUnitRecurringPrice;
property IsModifiedPrice: Boolean read fIsModifiedPrice write fIsModifiedPrice;
property RecurringFreqUom: TSQLUomID read fRecurringFreqUom write fRecurringFreqUom;
property ItemDescription: RawUTF8 read fItemDescription write fItemDescription;
property Comments: RawUTF8 read fComments write fComments;
property CorrespondingPo: Integer read fCorrespondingPo write fCorrespondingPo;
property Status: TSQLStatusItemID read fStatus write fStatus;
property SyncStatus: TSQLStatusItemID read fSyncStatus write fSyncStatus;
property EstimatedShipDate: TDateTime read fEstimatedShipDate write fEstimatedShipDate;
property EstimatedDeliveryDate: TDateTime read fEstimatedDeliveryDate write fEstimatedDeliveryDate;
property AutoCancelDate: TDateTime read fAutoCancelDate write fAutoCancelDate;
property DontCancelSetDate: TDateTime read fDontCancelSetDate write fDontCancelSetDate;
property DontCancelSetUserLogin: TSQLUserLoginID read fDontCancelSetUserLogin write fDontCancelSetUserLogin;
property ShipBeforeDate: TDateTime read fShipBeforeDate write fShipBeforeDate;
property ShipAfterDate: TDateTime read fShipAfterDate write fShipAfterDate;
property CancelBackOrderDate: TDateTime read fCancelBackOrderDate write fCancelBackOrderDate;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property SalesOpportunity: TSQLSalesOpportunityID read fSalesOpportunity write fSalesOpportunity;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 18
TSQLOrderItemAssoc = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
fToOrder: TSQLOrderHeaderID;
fToOrderItemSeq: Integer;
fToShipGroupSeq: Integer;
fOrderItemAssocType: TSQLOrderItemAssocTypeID;
fQuantity: Double;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property ToOrder: TSQLOrderHeaderID read fToOrder write fToOrder;
property ToOrderItemSeq: Integer read fToOrderItemSeq write fToOrderItemSeq;
property ToShipGroupSeq: Integer read fToShipGroupSeq write fToShipGroupSeq;
property OrderItemAssocType: TSQLOrderItemAssocTypeID read fOrderItemAssocType write fOrderItemAssocType;
property Quantity: Double read fQuantity write fQuantity;
end;
// 19
TSQLOrderItemAssocType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLOrderItemAssocTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLOrderItemAssocTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 20
TSQLOrderItemAttribute = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 21
TSQLOrderItemBilling = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fItemIssuance: TSQLItemIssuanceID;
fShipmentReceipt: TSQLShipmentReceiptID;
fQuantity: Double;
fAmount: Currency;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property ItemIssuance: TSQLItemIssuanceID read fItemIssuance write fItemIssuance;
property ShipmentReceipt: TSQLShipmentReceiptID read fShipmentReceipt write fShipmentReceipt;
property Quantity: Double read fQuantity write fQuantity;
property Amount: Currency read fAmount write fAmount;
end;
// 22
TSQLOrderItemChange = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fChangeTypeEnum: TSQLEnumerationID;
fChangeDatetime: TDateTime;
fQuantity: Double;
fCancelQuantity: Double;
fUnitPrice: Currency;
fItemDescription: RawUTF8;
fReasonEnum: TSQLEnumerationID;
fChangeComments: RawUTF8;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ChangeTypeEnum: TSQLEnumerationID read fChangeTypeEnum write fChangeTypeEnum;
property ChangeDatetime: TDateTime read fChangeDatetime write fChangeDatetime;
property Quantity: Double read fQuantity write fQuantity;
property CancelQuantity: Double read fCancelQuantity write fCancelQuantity;
property UnitPrice: Currency read fUnitPrice write fUnitPrice;
property ItemDescription: RawUTF8 read fItemDescription write fItemDescription;
property ReasonEnum: TSQLEnumerationID read fReasonEnum write fReasonEnum;
property ChangeComments: RawUTF8 read fChangeComments write fChangeComments;
end;
// 23
TSQLOrderItemContactMech = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
fContactMech: TSQLContactMechID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
end;
// 24
TSQLOrderItemGroup = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemGroupSeq: Integer;
fParentGroupSeq: TSQLOrderItemGroupID;
fGroupName: RawUTF8;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemGroupSeq: Integer read fOrderItemGroupSeq write fOrderItemGroupSeq;
property ParentGroupSeq: TSQLOrderItemGroupID read fParentGroupSeq write fParentGroupSeq;
property GroupName: RawUTF8 read fGroupName write fGroupName;
end;
// 25
TSQLOrderItemGroupOrder = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fGroupOrder: TSQLProductGroupOrderID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property GroupOrder: TSQLProductGroupOrderID read fGroupOrder write fGroupOrder;
end;
// 26
TSQLOrderItemPriceInfo = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fProductPriceRule: TSQLProductPriceRuleID;
fProductPriceActionSeq: Integer;
fModifyAmount: Currency;
fDescription: RawUTF8;
fRateCode: RawUTF8;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ProductPriceRule: TSQLProductPriceRuleID read fProductPriceRule write fProductPriceRule;
property ProductPriceActionSeq: Integer read fProductPriceActionSeq write fProductPriceActionSeq;
property ModifyAmount: Currency read fModifyAmount write fModifyAmount;
property Description: RawUTF8 read fDescription write fDescription;
property RateCode: RawUTF8 read fRateCode write fRateCode;
end;
// 27
TSQLOrderItemRole = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 28
TSQLOrderItemShipGroup = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fShipGroupSeq: Integer;
fShipmentMethodType: TSQLShipmentMethodTypeID;
fSupplierParty: TSQLPartyID;
fVendorParty: TSQLPartyID;
fCarrierParty: TSQLPartyID;
fCarrierRoleType: TSQLRoleTypeID;
fFacility: TSQLFacilityID;
fContactMech: TSQLContactMechID;
fTelecomContactMech: TSQLTelecomNumberID;
fTrackingNumber: RawUTF8;
fShippingInstructions: RawUTF8;
fMaySplit: Boolean;
fGiftMessage: TSQLRawBlob;
fIsGift: Boolean;
fShipAfterDate: TDateTime;
fShipByDate: TDateTime;
fEstimatedShipDate: TDateTime;
fEstimatedDeliveryDate: TDateTime;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType;
property SupplierParty: TSQLPartyID read fSupplierParty write fSupplierParty;
property VendorParty: TSQLPartyID read fVendorParty write fVendorParty;
property CarrierParty: TSQLPartyID read fCarrierParty write fCarrierParty;
property CarrierRoleType: TSQLRoleTypeID read fCarrierRoleType write fCarrierRoleType;
property Facility: TSQLFacilityID read fFacility write fFacility;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property TelecomContactMech: TSQLTelecomNumberID read fTelecomContactMech write fTelecomContactMech;
property TrackingNumber: RawUTF8 read fTrackingNumber write fTrackingNumber;
property ShippingInstructions: RawUTF8 read fShippingInstructions write fShippingInstructions;
property MaySplit: Boolean read fMaySplit write fMaySplit;
property GiftMessage: TSQLRawBlob read fGiftMessage write fGiftMessage;
property IsGift: Boolean read fIsGift write fIsGift;
property ShipAfterDate: TDateTime read fShipAfterDate write fShipAfterDate;
property ShipByDate: TDateTime read fShipByDate write fShipByDate;
property EstimatedShipDate: TDateTime read fEstimatedShipDate write fEstimatedShipDate;
property EstimatedDeliveryDate: TDateTime read fEstimatedDeliveryDate write fEstimatedDeliveryDate;
end;
// 29
TSQLOrderItemShipGroupAssoc = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
fQuantity: Double;
fCancelQuantity: Double;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property Quantity: Double read fQuantity write fQuantity;
property CancelQuantity: Double read fCancelQuantity write fCancelQuantity;
end;
// 30
TSQLOrderItemShipGrpInvRes = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fShipGroupSeq: Integer;
fInventoryItem: TSQLInventoryItemID;
fReserveOrderEnum: Integer;
fQuantity: Double;
fQuantityNotAvailable: Double;
fReservedDatetime: TDateTime;
fCreatedDatetime: TDateTime;
fPromisedDatetime: TDateTime;
fCurrentPromisedDate: TDateTime;
fPriority: Boolean;
fSequence: Integer;
fOldPickStartDate: TDateTime;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem;
property ReserveOrderEnum: Integer read fReserveOrderEnum write fReserveOrderEnum;
property Quantity: Double read fQuantity write fQuantity;
property QuantityNotAvailable: Double read fQuantityNotAvailable write fQuantityNotAvailable;
property ReservedDatetime: TDateTime read fReservedDatetime write fReservedDatetime;
property CreatedDatetime: TDateTime read fCreatedDatetime write fCreatedDatetime;
property PromisedDatetime: TDateTime read fPromisedDatetime write fPromisedDatetime;
property CurrentPromisedDate: TDateTime read fCurrentPromisedDate write fCurrentPromisedDate;
property Priority: Boolean read fPriority write fPriority;
property Sequence: Integer read fSequence write fSequence;
property OldPickStartDate: TDateTime read fOldPickStartDate write fOldPickStartDate;
end;
// 31
TSQLOrderItemType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLOrderItemTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLOrderItemTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 32
TSQLOrderItemTypeAttr = class(TSQLRecord)
private
fOrderItemType: TSQLOrderItemTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property OrderItemType: TSQLOrderItemTypeID read fOrderItemType write fOrderItemType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 33
TSQLOrderNotification = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fEmailType: TSQLEnumerationID;
fComments: RawUTF8;
fNotificationDate: TDateTime;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property EmailType: TSQLEnumerationID read fEmailType write fEmailType;
property Comments: RawUTF8 read fComments write fComments;
property NotificationDate: TDateTime read fNotificationDate write fNotificationDate;
end;
// 34
TSQLOrderPaymentPreference = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
fProductPricePurpose: TSQLProductPricePurposeID;
fPaymentMethodType: TSQLPaymentMethodTypeID;
fPaymentMethod: TSQLPaymentMethodID;
fFinAccount: TSQLFinAccountID;
fSecurityCode: RawUTF8;
fTrack2: RawUTF8;
fPresentFlag: Boolean;
fSwipedFlag: Boolean;
fOverflowFlag: Boolean;
fMaxAmount: Currency;
fProcessAttempt: Double;
fBillingPostalCode: RawUTF8;
fManualAuthCode: RawUTF8;
fManualRefNum: RawUTF8;
fStatus: TSQLStatusItemID;
fNeedsNsfRetry: Boolean;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property ProductPricePurpose: TSQLProductPricePurposeID read fProductPricePurpose write fProductPricePurpose;
property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType;
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property SecurityCode: RawUTF8 read fSecurityCode write fSecurityCode;
property Track2: RawUTF8 read fTrack2 write fTrack2;
property PresentFlag: Boolean read fPresentFlag write fPresentFlag;
property SwipedFlag: Boolean read fSwipedFlag write fSwipedFlag;
property OverflowFlag: Boolean read fOverflowFlag write fOverflowFlag;
property MaxAmount: Currency read fMaxAmount write fMaxAmount;
property ProcessAttempt: Double read fProcessAttempt write fProcessAttempt;
property BillingPostalCode: RawUTF8 read fBillingPostalCode write fBillingPostalCode;
property ManualAuthCode: RawUTF8 read fManualAuthCode write fManualAuthCode;
property ManualRefNum: RawUTF8 read fManualRefNum write fManualRefNum;
property Status: TSQLStatusItemID read fStatus write fStatus;
property NeedsNsfRetry: Boolean read fNeedsNsfRetry write fNeedsNsfRetry;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 35
TSQLOrderProductPromoCode = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fProductPromoCode: TSQLProductPromoCodeID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property ProductPromoCode: TSQLProductPromoCodeID read fProductPromoCode write fProductPromoCode;
end;
// 36
TSQLOrderRole = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 37
TSQLOrderShipment = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
fShipment: TSQLShipmentID;
fShipmentItemSeq: Integer;
fQuantity: Double;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property Shipment: TSQLShipmentID read fShipment write fShipment;
property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq;
property Quantity: Double read fQuantity write fQuantity;
end;
// 38
TSQLOrderStatus = class(TSQLRecord)
private
fStatus: TSQLStatusItemID;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fOrderPaymentPreference: TSQLOrderPaymentPreferenceID;
fStatusDatetime: TDateTime;
fStatusUserLogin: TSQLUserLoginID;
fChangeReason: RawUTF8;
published
property Status: TSQLStatusItemID read fStatus write fStatus;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property OrderPaymentPreference: TSQLOrderPaymentPreferenceID read fOrderPaymentPreference write fOrderPaymentPreference;
property StatusDatetime: TDateTime read fStatusDatetime write fStatusDatetime;
property StatusUserLogin: TSQLUserLoginID read fStatusUserLogin write fStatusUserLogin;
property ChangeReason: RawUTF8 read fChangeReason write fChangeReason;
end;
// 39
TSQLOrderSummaryEntry = class(TSQLRecord)
private
fEntryDate: TDateTime;
fProduct: TSQLProductID;
fFacility: TSQLFacilityID;
fTotalQuantity: Double;
fGrossSales: Currency;
fProductCost: Currency;
published
property EntryDate: TDateTime read fEntryDate write fEntryDate;
property Product: TSQLProductID read fProduct write fProduct;
property Facility: TSQLFacilityID read fFacility write fFacility;
property TotalQuantity: Double read fTotalQuantity write fTotalQuantity;
property GrossSales: Currency read fGrossSales write fGrossSales;
property ProductCost: Currency read fProductCost write fProductCost;
end;
// 40
TSQLOrderTerm = class(TSQLRecord)
private
fTermType: TSQLTermTypeID;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fTermValue: Currency;
fTermDays: Integer;
fTextValue: RawUTF8;
fDescription: RawUTF8;
fUom: TSQLUomID;
published
property TermType: TSQLTermTypeID read fTermType write fTermType;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property TermValue: Currency read fTermValue write fTermValue;
property TermDays: Integer read fTermDays write fTermDays;
property TextValue: RawUTF8 read fTextValue write fTextValue;
property Description: RawUTF8 read fDescription write fDescription;
property Uom: TSQLUomID read fUom write fUom;
end;
// 41
TSQLOrderTermAttribute = class(TSQLRecord)
private
fTermType: Integer;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property TermType: Integer read fTermType write fTermType;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 42
TSQLOrderType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLOrderTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLOrderTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 43
TSQLOrderTypeAttr = class(TSQLRecord)
private
fOrderType: TSQLOrderTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property OrderType: TSQLOrderTypeID read fOrderType write fOrderType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 44
TSQLProductOrderItem = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fEngagementId: TSQLOrderHeaderID;
fEngagementItemSeq: Integer;
fProduct: TSQLProductID;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property EngagementId: TSQLOrderHeaderID read fEngagementId write fEngagementId;
property EngagementItemSeq: Integer read fEngagementItemSeq write fEngagementItemSeq;
property Product: TSQLProductID read fProduct write fProduct;
end;
// 45
TSQLWorkOrderItemFulfillment = class(TSQLRecord)
private
fWorkEffort: TSQLWorkEffortID;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fShipGroupSeq: Integer;
published
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
end;
// 46
TSQLQuote = class(TSQLRecord)
private
fQuoteType: TSQLQuoteTypeID;
fParty: TSQLPartyID;
fIssueDate: TDateTime;
fStatus: TSQLStatusItemID;
fCurrencyUom: TSQLUomID;
fProductStore: TSQLProductStoreID;
fSalesChannelEnum: TSQLEnumerationID;
fValidFromDate: TDateTime;
fValidThruDate: TDateTime;
fQuoteName: RawUTF8;
fDescription: RawUTF8;
published
property QuoteType: TSQLQuoteTypeID read fQuoteType write fQuoteType;
property Party: TSQLPartyID read fParty write fParty;
property IssueDate: TDateTime read fIssueDate write fIssueDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property SalesChannelEnum: TSQLEnumerationID read fSalesChannelEnum write fSalesChannelEnum;
property ValidFromDate: TDateTime read fValidFromDate write fValidFromDate;
property ValidThruDate: TDateTime read fValidThruDate write fValidThruDate;
property QuoteName: RawUTF8 read fQuoteName write fQuoteName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 47
TSQLQuoteAttribute = class(TSQLRecord)
private
fQuote: TSQLQuoteID;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Quote: TSQLQuoteID read fQuote write fQuote;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 48
TSQLQuoteCoefficient = class(TSQLRecord)
private
fQuote: TSQLQuoteID;
fCoeffName: RawUTF8;
fCoeffValue: Double;
published
property Quote: TSQLQuoteID read fQuote write fQuote;
property CoeffName: RawUTF8 read fCoeffName write fCoeffName;
property CoeffValue: Double read fCoeffValue write fCoeffValue;
end;
// 49
TSQLQuoteItem = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fProduct: TSQLProductID;
fProductFeature: TSQLProductFeatureID;
fDeliverableType: TSQLDeliverableTypeID;
fSkillType: TSQLSkillTypeID;
fUom: TSQLUomID;
fWorkEffort: TSQLWorkEffortID;
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fQuantity: Double;
fSelectedAmount: Double;
fQuoteUnitPrice: Currency;
fReservStart: TDateTime;
fReservLength: Double;
fReservPersons: Integer;
fConfigId: Integer;
fEstimatedDeliveryDate: TDateTime;
fComments: RawUTF8;
fIsPromo: Boolean;
fLeadTimeDays: Integer;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Product: TSQLProductID read fProduct write fProduct;
property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature;
property DeliverableType: TSQLDeliverableTypeID read fDeliverableType write fDeliverableType;
property SkillType: TSQLSkillTypeID read fSkillType write fSkillType;
property Uom: TSQLUomID read fUom write fUom;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property Quantity: Double read fQuantity write fQuantity;
property SelectedAmount: Double read fSelectedAmount write fSelectedAmount;
property QuoteUnitPrice: Currency read fQuoteUnitPrice write fQuoteUnitPrice;
property ReservStart: TDateTime read fReservStart write fReservStart;
property ReservLength: Double read fReservLength write fReservLength;
property ReservPersons: Integer read fReservPersons write fReservPersons;
property ConfigId: Integer read fConfigId write fConfigId;
property EstimatedDeliveryDate: TDateTime read fEstimatedDeliveryDate write fEstimatedDeliveryDate;
property Comments: RawUTF8 read fComments write fComments;
property IsPromo: Boolean read fIsPromo write fIsPromo;
property LeadTimeDays: Integer read fLeadTimeDays write fLeadTimeDays;
end;
// 50
TSQLQuoteNote = class(TSQLRecord)
private
fQuote: TSQLQuoteID;
fNote: TSQLNoteDataID;
published
property Quote: TSQLQuoteID read fQuote write fQuote;
property Note: TSQLNoteDataID read fNote write fNote;
end;
// 51
TSQLQuoteRole = class(TSQLRecord)
private
fQuote: TSQLQuoteID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Quote: TSQLQuoteID read fQuote write fQuote;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 52
TSQLQuoteTerm = class(TSQLRecord)
private
fTermType: TSQLTermTypeID;
fQuote: TSQLQuoteID;
fQuoteItemSeq: Integer;
fTermValue: Integer;
fUom: Integer;
fTermDays: Integer;
fTextValue: RawUTF8;
fDescription: RawUTF8;
published
property TermType: TSQLTermTypeID read fTermType write fTermType;
property Quote: TSQLQuoteID read fQuote write fQuote;
property QuoteItemSeq: Integer read fQuoteItemSeq write fQuoteItemSeq;
property TermValue: Integer read fTermValue write fTermValue;
property Uom: Integer read fUom write fUom;
property TermDays: Integer read fTermDays write fTermDays;
property TextValue: RawUTF8 read fTextValue write fTextValue;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 53
TSQLQuoteTermAttribute = class(TSQLRecord)
private
fTermTypeId: Integer;
fQuoteId: Integer;
fQuoteItemSeqId: Integer;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property TermTypeId: Integer read fTermTypeId write fTermTypeId;
property QuoteId: Integer read fQuoteId write fQuoteId;
property QuoteItemSeqId: Integer read fQuoteItemSeqId write fQuoteItemSeqId;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 54
TSQLQuoteType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLQuoteTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLQuoteTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 55
TSQLQuoteTypeAttr = class(TSQLRecord)
private
fQuoteType: TSQLQuoteTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property QuoteType: TSQLQuoteTypeID read fQuoteType write fQuoteType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 56
TSQLQuoteWorkEffort = class(TSQLRecord)
private
fQuote: TSQLQuoteID;
fWorkEffort: TSQLWorkEffortID;
published
property Quote: TSQLQuoteID read fQuote write fQuote;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
// 57
TSQLQuoteAdjustment = class(TSQLRecord)
private
fOrderAdjustmentType: TSQLOrderAdjustmentTypeID;
fQuote: TSQLQuoteID;
fQuoteItemSeq: Integer;
fComments: RawUTF8;
fDescription: RawUTF8;
fAmount: Currency;
fProductPromo: TSQLProductPromoID;
fProductPromoRule: TSQLProductPromoRuleID;
fProductPromoActionSeq: Integer;
fProductFeature: Integer;
fCorrespondingProduct: Integer;
fSourceReference: Integer;
fSourcePercentage: Double;
fCustomerReference: Integer;
fPrimaryGeo: TSQLGeoID;
fSecondaryGeo: TSQLGeoID;
fExemptAmount: Currency;
fTaxAuthGeo: Integer;
fTaxAuthParty: Integer;
fOverrideGlAccount: TSQLGlAccountID;
fIncludeInTax: Boolean;
fIncludeInShipping: Boolean;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property OrderAdjustmentType: TSQLOrderAdjustmentTypeID read fOrderAdjustmentType write fOrderAdjustmentType;
property Quote: TSQLQuoteID read fQuote write fQuote;
property QuoteItemSeq: Integer read fQuoteItemSeq write fQuoteItemSeq;
property Comments: RawUTF8 read fComments write fComments;
property Description: RawUTF8 read fDescription write fDescription;
property Amount: Currency read fAmount write fAmount;
property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo;
property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule;
property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq;
property ProductFeature: Integer read fProductFeature write fProductFeature;
property CorrespondingProduct: Integer read fCorrespondingProduct write fCorrespondingProduct;
property SourceReference: Integer read fSourceReference write fSourceReference;
property SourcePercentage: Double read fSourcePercentage write fSourcePercentage;
property CustomerReference: Integer read fCustomerReference write fCustomerReference;
property PrimaryGeo: TSQLGeoID read fPrimaryGeo write fPrimaryGeo;
property SecondaryGeo: TSQLGeoID read fSecondaryGeo write fSecondaryGeo;
property ExemptAmount: Currency read fExemptAmount write fExemptAmount;
property TaxAuthGeo: Integer read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: Integer read fTaxAuthParty write fTaxAuthParty;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property IncludeInTax: Boolean read fIncludeInTax write fIncludeInTax;
property IncludeInShipping: Boolean read fIncludeInShipping write fIncludeInShipping;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 58
TSQLCustRequest = class(TSQLRecord)
private
fCustRequestType: TSQLCustRequestTypeID;
fCustRequestCategory: TSQLCustRequestCategoryID;
fStatus: TSQLStatusItemID;
fFromParty: TSQLPartyID;
fPriority: Integer;
fCustRequestDate: TDateTime;
fResponseRequiredDate: TDateTime;
fCustRequestName: RawUTF8;
fDescription: RawUTF8;
fMaximumAmountUom: TSQLUomID;
fProductStore: TSQLProductStoreID;
fSalesChannelEnum: TSQLEnumerationID;
fFulfillContactMech: TSQLContactMechID;
fCurrencyUom: TSQLUomID;
fOpenDateTime: TDateTime;
fClosedDateTime: TDateTime;
fInternalComment: RawUTF8;
fReason: RawUTF8;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property CustRequestType: TSQLCustRequestTypeID read fCustRequestType write fCustRequestType;
property CustRequestCategory: TSQLCustRequestCategoryID read fCustRequestCategory write fCustRequestCategory;
property Status: TSQLStatusItemID read fStatus write fStatus;
property FromParty: TSQLPartyID read fFromParty write fFromParty;
property Priority: Integer read fPriority write fPriority;
property CustRequestDate: TDateTime read fCustRequestDate write fCustRequestDate;
property ResponseRequiredDate: TDateTime read fResponseRequiredDate write fResponseRequiredDate;
property CustRequestName: RawUTF8 read fCustRequestName write fCustRequestName;
property Description: RawUTF8 read fDescription write fDescription;
property MaximumAmountUom: TSQLUomID read fMaximumAmountUom write fMaximumAmountUom;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property SalesChannelEnum: TSQLEnumerationID read fSalesChannelEnum write fSalesChannelEnum;
property FulfillContactMech: TSQLContactMechID read fFulfillContactMech write fFulfillContactMech;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property OpenDateTime: TDateTime read fOpenDateTime write fOpenDateTime;
property ClosedDateTime: TDateTime read fClosedDateTime write fClosedDateTime;
property InternalComment: RawUTF8 read fInternalComment write fInternalComment;
property Reason: RawUTF8 read fReason write fReason;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 59
TSQLCustRequestAttribute = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 60
TSQLCustRequestCategory = class(TSQLRecord)
private
fCustRequestType: TSQLCustRequestTypeID;
fName: RawUTF8;
fDescription: RawUTF8;
published
property CustRequestType: TSQLCustRequestTypeID read fCustRequestType write fCustRequestType;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 61
TSQLCustRequestCommEvent = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fCommunicationEvent: TSQLCommunicationEventID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
end;
// 62
TSQLCustRequestContent = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fContent: TSQLContentID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property Content: TSQLContentID read fContent write fContent;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 63
TSQLCustRequestItem = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fCustRequestResolution: TSQLCustRequestResolutionID;
fStatus: TSQLStatusItemID;
fPriority: Integer;
fSequenceNum: Integer;
fRequiredByDate: TDateTime;
fProduct: TSQLProductID;
fQuantity: Double;
fSelectedAmount: Double;
fMaximumAmount: Currency;
fReservStart: TDateTime;
fReservLength: Double;
fReservPersons: Integer;
fConfigId: Integer;
fDescription: RawUTF8;
fStory: RawUTF8;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property CustRequestResolution: TSQLCustRequestResolutionID read fCustRequestResolution write fCustRequestResolution;
property Status: TSQLStatusItemID read fStatus write fStatus;
property Priority: Integer read fPriority write fPriority;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
property RequiredByDate: TDateTime read fRequiredByDate write fRequiredByDate;
property Product: TSQLProductID read fProduct write fProduct;
property Quantity: Double read fQuantity write fQuantity;
property SelectedAmount: Double read fSelectedAmount write fSelectedAmount;
property MaximumAmount: Currency read fMaximumAmount write fMaximumAmount;
property ReservStart: TDateTime read fReservStart write fReservStart;
property ReservLength: Double read fReservLength write fReservLength;
property ReservPersons: Integer read fReservPersons write fReservPersons;
property ConfigId: Integer read fConfigId write fConfigId;
property Description: RawUTF8 read fDescription write fDescription;
property Story: RawUTF8 read fStory write fStory;
end;
// 64
TSQLCustRequestNote = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fNote: TSQLNoteDataID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property Note: TSQLNoteDataID read fNote write fNote;
end;
// 65
TSQLCustRequestItemNote = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fNote: TSQLNoteDataID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property Note: TSQLNoteDataID read fNote write fNote;
end;
// 66
TSQLCustRequestItemWorkEffort = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fWorkEffort: TSQLWorkEffortID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
// 67
TSQLCustRequestResolution = class(TSQLRecord)
private
fEncode: RawUTF8;
fCustRequestTypeEncode: RawUTF8;
fCustRequestType: TSQLCustRequestTypeID;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property CustRequestTypeEncode: RawUTF8 read fCustRequestTypeEncode write fCustRequestTypeEncode;
property CustRequestType: TSQLCustRequestTypeID read fCustRequestType write fCustRequestType;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 68
TSQLCustRequestParty = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 69
TSQLCustRequestStatus = class(TSQLRecord)
private
fStatus: TSQLStatusItemID;
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fStatusDate: TDateTime;
fChangeByUserLogin: TSQLUserLoginID;
published
property Status: TSQLStatusItemID read fStatus write fStatus;
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 70
TSQLCustRequestType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLCustRequestTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
fParty: Integer;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLCustRequestTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
property Party: Integer read fParty write fParty;
end;
// 71
TSQLCustRequestTypeAttr = class(TSQLRecord)
private
fCustRequestType: TSQLCustRequestTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property CustRequestType: TSQLCustRequestTypeID read fCustRequestType write fCustRequestType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 72
TSQLCustRequestWorkEffort = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fWorkEffort: TSQLWorkEffortID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
// 73
TSQLRespondingParty = class(TSQLRecord)
private
fRespondingPartySeq: Integer;
fCustRequest: TSQLCustRequestID;
fParty: TSQLPartyID;
fContactMech: TSQLContactMechID;
fDateSent: TDateTime;
published
property RespondingPartySeq: Integer read fRespondingPartySeq write fRespondingPartySeq;
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property Party: TSQLPartyID read fParty write fParty;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property DateSent: TDateTime read fDateSent write fDateSent;
end;
// 74
TSQLDesiredFeature = class(TSQLRecord)
private
fRequirement: TSQLRequirementID;
fProductFeature: TSQLProductFeatureID;
fOptionalInd: Boolean;
published
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature;
property OptionalInd: Boolean read fOptionalInd write fOptionalInd;
end;
// 75
TSQLOrderRequirementCommitment = class(TSQLRecord)
private
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fRequirement: TSQLRequirementID;
fQuantity: Double;
published
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property Quantity: Double read fQuantity write fQuantity;
end;
// 76
TSQLRequirement = class(TSQLRecord)
private
fRequirementType: TSQLRequirementTypeID;
fFacility: TSQLFacilityID;
fDeliverable: TSQLDeliverableID;
fFixedAsset: TSQLFixedAssetID;
fProduct: TSQLProductID;
fStatus: TSQLStatusItemID;
fDescription: RawUTF8;
fRequirementStartDate: TDateTime;
fRequiredByDate: TDateTime;
fEstimatedBudget: Currency;
fQuantity: Double;
fUseCase: RawUTF8;
fReason: RawUTF8;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property RequirementType: TSQLRequirementTypeID read fRequirementType write fRequirementType;
property Facility: TSQLFacilityID read fFacility write fFacility;
property Deliverable: TSQLDeliverableID read fDeliverable write fDeliverable;
property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset;
property Product: TSQLProductID read fProduct write fProduct;
property Status: TSQLStatusItemID read fStatus write fStatus;
property Description: RawUTF8 read fDescription write fDescription;
property RequirementStartDate: TDateTime read fRequirementStartDate write fRequirementStartDate;
property RequiredByDate: TDateTime read fRequiredByDate write fRequiredByDate;
property EstimatedBudget: Currency read fEstimatedBudget write fEstimatedBudget;
property Quantity: Double read fQuantity write fQuantity;
property UseCase: RawUTF8 read fUseCase write fUseCase;
property Reason: RawUTF8 read fReason write fReason;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 77
TSQLRequirementAttribute = class(TSQLRecord)
private
fRequirement: TSQLRequirementID;
fAttrName: TSQLOrderAdjustmentTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property AttrName: TSQLOrderAdjustmentTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 78
TSQLRequirementBudgetAllocation = class(TSQLRecord)
private
fBudget: TSQLBudgetID;
fBudgetItemSeq: Integer;
fRequirement: TSQLRequirementID;
fAmount: Currency;
published
property Budget: TSQLBudgetID read fBudget write fBudget;
property BudgetItemSeq: Integer read fBudgetItemSeq write fBudgetItemSeq;
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property Amount: Currency read fAmount write fAmount;
end;
// 79
TSQLRequirementCustRequest = class(TSQLRecord)
private
fCustRequest: TSQLCustRequestID;
fCustRequestItemSeq: Integer;
fRequirement: TSQLRequirementID;
published
property CustRequest: TSQLCustRequestID read fCustRequest write fCustRequest;
property CustRequestItemSeq: Integer read fCustRequestItemSeq write fCustRequestItemSeq;
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
end;
// 80
TSQLRequirementRole = class(TSQLRecord)
private
fRequirement: TSQLRequirementID;
fParty: TSQLPartyID;
fRoleType: Integer;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: Integer read fRoleType write fRoleType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 81
TSQLRequirementStatus = class(TSQLRecord)
private
fRequirement: TSQLRequirementID;
fStatus: TSQLStatusItemID;
fStatusDate: TDateTime;
fChangeByUserLogin: TSQLUserLoginID;
published
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 82
TSQLRequirementType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLRequirementTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLRequirementTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 83
TSQLRequirementTypeAttr = class(TSQLRecord)
private
fRequirementType: TSQLRequirementTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property RequirementType: TSQLRequirementTypeID read fRequirementType write fRequirementType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 84
TSQLWorkReqFulfType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 85
TSQLWorkRequirementFulfillment = class(TSQLRecord)
private
fRequirement: TSQLRequirementID;
fWorkEffort: TSQLWorkEffortID;
fWorkReqFulfType: TSQLWorkReqFulfTypeID;
published
property Requirement: TSQLRequirementID read fRequirement write fRequirement;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
property WorkReqFulfType: TSQLWorkReqFulfTypeID read fWorkReqFulfType write fWorkReqFulfType;
end;
// 86
TSQLReturnAdjustment = class(TSQLRecord)
private
fReturnAdjustmentType: TSQLReturnAdjustmentTypeID;
fReturn: TSQLReturnHeaderID;
fReturnItemSeq: Integer;
fShipGroupSeq: Integer;
fComments: RawUTF8;
fDescription: RawUTF8;
fReturnType: TSQLReturnTypeID;
fOrderAdjustment: TSQLOrderAdjustmentID;
fAmount: Currency;
fProductPromo: TSQLProductPromoID;
fProductPromoRule: TSQLProductPromoRuleID;
fProductPromoActionSeq: Integer;
fProductFeature: Integer;
fCorrespondingProduct: Integer;
fTaxAuthorityRateSeq: Integer;
fSourceReference: Integer;
fSourcePercentage: Double;
fCustomerReference: Integer;
fPrimaryGeo: TSQLGeoID;
fSecondaryGeo: TSQLGeoID;
fExemptAmount: Currency;
fTaxAuthGeo: TSQLGeoID;
fTaxAuthParty: Integer;
fOverrideGlAccount: TSQLGlAccountID;
fIncludeInTax: Boolean;
fIncludeInShipping: Boolean;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property ReturnAdjustmentType: TSQLReturnAdjustmentTypeID read fReturnAdjustmentType write fReturnAdjustmentType;
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property ReturnItemSeq: Integer read fReturnItemSeq write fReturnItemSeq;
property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq;
property Comments: RawUTF8 read fComments write fComments;
property Description: RawUTF8 read fDescription write fDescription;
property ReturnType: TSQLReturnTypeID read fReturnType write fReturnType;
property OrderAdjustment: TSQLOrderAdjustmentID read fOrderAdjustment write fOrderAdjustment;
property Amount: Currency read fAmount write fAmount;
property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo;
property ProductPromoRule: TSQLProductPromoRuleID read fProductPromoRule write fProductPromoRule;
property ProductPromoActionSeq: Integer read fProductPromoActionSeq write fProductPromoActionSeq;
property ProductFeature: Integer read fProductFeature write fProductFeature;
property CorrespondingProduct: Integer read fCorrespondingProduct write fCorrespondingProduct;
property TaxAuthorityRateSeq: Integer read fTaxAuthorityRateSeq write fTaxAuthorityRateSeq;
property SourceReference: Integer read fSourceReference write fSourceReference;
property SourcePercentage: Double read fSourcePercentage write fSourcePercentage;
property CustomerReference: Integer read fCustomerReference write fCustomerReference;
property PrimaryGeo: TSQLGeoID read fPrimaryGeo write fPrimaryGeo;
property SecondaryGeo: TSQLGeoID read fSecondaryGeo write fSecondaryGeo;
property ExemptAmount: Currency read fExemptAmount write fExemptAmount;
property TaxAuthGeo: TSQLGeoID read fTaxAuthGeo write fTaxAuthGeo;
property TaxAuthParty: Integer read fTaxAuthParty write fTaxAuthParty;
property OverrideGlAccount: TSQLGlAccountID read fOverrideGlAccount write fOverrideGlAccount;
property IncludeInTax: Boolean read fIncludeInTax write fIncludeInTax;
property IncludeInShipping: Boolean read fIncludeInShipping write fIncludeInShipping;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 87
TSQLReturnAdjustmentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLReturnAdjustmentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLReturnAdjustmentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 88
TSQLReturnHeader = class(TSQLRecord)
private
fReturnHeaderType: TSQLReturnHeaderTypeID;
fStatus: TSQLStatusItemID;
fCreatedBy: TSQLUserLoginID;
fFromParty: TSQLPartyID;
fToParty: TSQLPartyID;
fPaymentMethod: TSQLPaymentMethodID;
fFinAccount: TSQLFinAccountID;
fBillingAccount: TSQLBillingAccountID;
fEntryDate: TDateTime;
fOriginContactMech: TSQLContactMechID;
fDestinationFacility: TSQLFacilityID;
fNeedsInventoryReceive: Boolean;
fCurrencyUom: TSQLUomID;
fSupplierRma: Integer;
published
property ReturnHeaderType: TSQLReturnHeaderTypeID read fReturnHeaderType write fReturnHeaderType;
property Status: TSQLStatusItemID read fStatus write fStatus;
property CreatedBy: TSQLUserLoginID read fCreatedBy write fCreatedBy;
property FromParty: TSQLPartyID read fFromParty write fFromParty;
property ToParty: TSQLPartyID read fToParty write fToParty;
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property FinAccount: TSQLFinAccountID read fFinAccount write fFinAccount;
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property EntryDate: TDateTime read fEntryDate write fEntryDate;
property OriginContactMech: TSQLContactMechID read fOriginContactMech write fOriginContactMech;
property DestinationFacility: TSQLFacilityID read fDestinationFacility write fDestinationFacility;
property NeedsInventoryReceive: Boolean read fNeedsInventoryReceive write fNeedsInventoryReceive;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property SupplierRma: Integer read fSupplierRma write fSupplierRma;
end;
// 89
TSQLReturnHeaderType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLReturnHeaderTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLReturnHeaderTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 90
TSQLReturnItem = class(TSQLRecord)
private
fReturn: TSQLReturnHeaderID;
fFeturnItemSeq: Integer;
fReturnReason: TSQLReturnReasonID;
fReturnType: TSQLReturnTypeID;
fReturnItemType: TSQLReturnItemTypeID;
fProduct: TSQLProductID;
fDescription: RawUTF8;
fOrderId: TSQLOrderHeaderID;
fOrderItemSeq: Integer;
fStatus: TSQLStatusItemID;
fExpectedItemStatus: TSQLStatusItemID;
fReturnQuantity: Double;
fReceivedQuantity: Double;
fReturnPrice: Currency;
fReturnItemResponse: TSQLReturnItemResponseID;
published
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property FeturnItemSeq: Integer read fFeturnItemSeq write fFeturnItemSeq;
property ReturnReason: TSQLReturnReasonID read fReturnReason write fReturnReason;
property ReturnType: TSQLReturnTypeID read fReturnType write fReturnType;
property ReturnItemType: TSQLReturnItemTypeID read fReturnItemType write fReturnItemType;
property Product: TSQLProductID read fProduct write fProduct;
property Description: RawUTF8 read fDescription write fDescription;
property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId;
property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq;
property Status: TSQLStatusItemID read fStatus write fStatus;
property ExpectedItemStatus: TSQLStatusItemID read fExpectedItemStatus write fExpectedItemStatus;
property ReturnQuantity: Double read fReturnQuantity write fReturnQuantity;
property ReceivedQuantity: Double read fReceivedQuantity write fReceivedQuantity;
property ReturnPrice: Currency read fReturnPrice write fReturnPrice;
property ReturnItemResponse: TSQLReturnItemResponseID read fReturnItemResponse write fReturnItemResponse;
end;
// 91
TSQLReturnItemResponse = class(TSQLRecord)
private
fOrderPaymentPreference: TSQLOrderPaymentPreferenceID;
fReplacementOrder: TSQLOrderHeaderID;
fPayment: TSQLPaymentID;
fBillingAccount: TSQLBillingAccountID;
fFinAccountTrans: TSQLFinAccountTransID;
fResponseAmount: Currency;
fResponseDate: TDateTime;
published
property OrderPaymentPreference: TSQLOrderPaymentPreferenceID read fOrderPaymentPreference write fOrderPaymentPreference;
property ReplacementOrder: TSQLOrderHeaderID read fReplacementOrder write fReplacementOrder;
property Payment: TSQLPaymentID read fPayment write fPayment;
property BillingAccount: TSQLBillingAccountID read fBillingAccount write fBillingAccount;
property FinAccountTrans: TSQLFinAccountTransID read fFinAccountTrans write fFinAccountTrans;
property ResponseAmount: Currency read fResponseAmount write fResponseAmount;
property ResponseDate: TDateTime read fResponseDate write fResponseDate;
end;
// 92
TSQLReturnItemType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLReturnItemTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLReturnItemTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 93
TSQLReturnItemTypeMap = class(TSQLRecord)
private
fReturnHeaderTypeEncode: RawUTF8;
fReturnItemTypeEncode: RawUTF8;
fReturnItemMapKey: RawUTF8;
fReturnHeaderType: TSQLReturnHeaderTypeID;
fReturnItemType: TSQLReturnAdjustmentTypeID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property ReturnHeaderTypeEncode: RawUTF8 read fReturnHeaderTypeEncode write fReturnHeaderTypeEncode;
property ReturnItemTypeEncode: RawUTF8 read fReturnItemTypeEncode write fReturnItemTypeEncode;
property ReturnItemMapKey: RawUTF8 read fReturnItemMapKey write fReturnItemMapKey;
property ReturnHeaderType: TSQLReturnHeaderTypeID read fReturnHeaderType write fReturnHeaderType;
property ReturnItemType: TSQLReturnAdjustmentTypeID read fReturnItemType write fReturnItemType;
end;
// 94
TSQLReturnReason = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
fSequence: Integer;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property Sequence: Integer read fSequence write fSequence;
end;
// 95
TSQLReturnStatus = class(TSQLRecord)
private
fStatus: TSQLStatusItemID;
fReturn: TSQLReturnHeaderID;
fReturnItemSeq: Integer;
fChangeByUserLogin: TSQLUserLoginID;
fStatusDatetime: TDateTime;
published
property Status: TSQLStatusItemID read fStatus write fStatus;
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property ReturnItemSeq: Integer read fReturnItemSeq write fReturnItemSeq;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
property StatusDatetime: TDateTime read fStatusDatetime write fStatusDatetime;
end;
// 96
TSQLReturnType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
fSequence: Integer;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property Sequence: Integer read fSequence write fSequence;
end;
// 97
TSQLReturnItemBilling = class(TSQLRecord)
private
fReturn: TSQLReturnHeaderID;
fReturnItemSeq: Integer;
fInvoice: TSQLInvoiceID;
fInvoiceItemSeq: Integer;
fShipmentReceipt: TSQLShipmentReceiptID;
fQuantity: Double;
fAmount: Currency;
published
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property ReturnItemSeq: Integer read fReturnItemSeq write fReturnItemSeq;
property Invoice: TSQLInvoiceID read fInvoice write fInvoice;
property InvoiceItemSeq: Integer read fInvoiceItemSeq write fInvoiceItemSeq;
property ShipmentReceipt: TSQLShipmentReceiptID read fShipmentReceipt write fShipmentReceipt;
property Quantity: Double read fQuantity write fQuantity;
property Amount: Currency read fAmount write fAmount;
end;
// 98
TSQLReturnItemShipment = class(TSQLRecord)
private
fReturn: TSQLReturnHeaderID;
fReturnItemSeq: Integer;
fShipment: TSQLShipmentID;
fShipmentItemSeq: Integer;
fQuantity: Double;
published
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property ReturnItemSeq: Integer read fReturnItemSeq write fReturnItemSeq;
property Shipment: TSQLShipmentID read fShipment write fShipment;
property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq;
property Quantity: Double read fQuantity write fQuantity;
end;
// 99
TSQLReturnContactMech = class(TSQLRecord)
private
fReturn: TSQLReturnHeaderID;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
fContactMech: TSQLContactMechID;
published
property Return: TSQLReturnHeaderID read fReturn write fReturn;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
end;
// 100
TSQLCartAbandonedLine = class(TSQLRecord)
private
fVisit: Integer;
fCartAbandonedLineSeq: Integer;
fProduct: TSQLProductID;
fProdCatalog: TSQLProdCatalogID;
fQuantity: Double;
fReservStart: TDateTime;
fReservLength: Double;
fReservPersons: Integer;
fUnitPrice: Currency;
fReserv2ndPPPerc: Double;
fReservNthPPPerc: Double;
fConfigId: Integer;
fTotalWithAdjustments: Currency;
fWasReserved: Boolean;
published
property Visit: Integer read fVisit write fVisit;
property CartAbandonedLineSeq: Integer read fCartAbandonedLineSeq write fCartAbandonedLineSeq;
property Product: TSQLProductID read fProduct write fProduct;
property ProdCatalog: TSQLProdCatalogID read fProdCatalog write fProdCatalog;
property Quantity: Double read fQuantity write fQuantity;
property ReservStart: TDateTime read fReservStart write fReservStart;
property ReservLength: Double read fReservLength write fReservLength;
property ReservPersons: Integer read fReservPersons write fReservPersons;
property UnitPrice: Currency read fUnitPrice write fUnitPrice;
property Reserv2ndPPPerc: Double read fReserv2ndPPPerc write fReserv2ndPPPerc;
property ReservNthPPPerc: Double read fReservNthPPPerc write fReservNthPPPerc;
property ConfigId: Integer read fConfigId write fConfigId;
property TotalWithAdjustments: Currency read fTotalWithAdjustments write fTotalWithAdjustments;
property WasReserved: Boolean read fWasReserved write fWasReserved;
end;
// 101
TSQLShoppingList = class(TSQLRecord)
private
fShoppingListType: TSQLShoppingListTypeID;
fParentShoppingList: TSQLShoppingListID;
fProductStore: TSQLProductStoreID;
fVisitorId: Integer;
fParty: TSQLPartyID;
fListName: RawUTF8;
fDescription: RawUTF8;
fIsPublic: Boolean;
fIsActive: Boolean;
fCurrencyUom: TSQLUomID;
fShipmentMethodType: Integer;
fCarrierParty: Integer;
fCarrierRoleType: Integer;
fContactMech: TSQLContactMechID;
fPaymentMethod: TSQLPaymentMethodID;
fRecurrenceInfo: TSQLRecurrenceInfoID;
fLastOrderedDate: TDateTime;
fLastAdminModified: TDateTime;
fProductPromoCode: TSQLProductPromoCodeID;
published
property ShoppingListType: TSQLShoppingListTypeID read fShoppingListType write fShoppingListType;
property ParentShoppingList: TSQLShoppingListID read fParentShoppingList write fParentShoppingList;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property VisitorId: Integer read fVisitorId write fVisitorId;
property Party: TSQLPartyID read fParty write fParty;
property ListName: RawUTF8 read fListName write fListName;
property Description: RawUTF8 read fDescription write fDescription;
property IsPublic: Boolean read fIsPublic write fIsPublic;
property IsActive: Boolean read fIsActive write fIsActive;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property ShipmentMethodType: Integer read fShipmentMethodType write fShipmentMethodType;
property CarrierParty: Integer read fCarrierParty write fCarrierParty;
property CarrierRoleType: Integer read fCarrierRoleType write fCarrierRoleType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property PaymentMethod: TSQLPaymentMethodID read fPaymentMethod write fPaymentMethod;
property RecurrenceInfo: TSQLRecurrenceInfoID read fRecurrenceInfo write fRecurrenceInfo;
property LastOrderedDate: TDateTime read fLastOrderedDate write fLastOrderedDate;
property LastAdminModified: TDateTime read fLastAdminModified write fLastAdminModified;
property ProductPromoCode: TSQLProductPromoCodeID read fProductPromoCode write fProductPromoCode;
end;
// 102
TSQLShoppingListItem = class(TSQLRecord)
private
fShoppingList: TSQLShoppingListID;
fShoppingListItemSeq: Integer;
fProduct: TSQLProductID;
fQuantity: Double;
fModifiedPrice: Currency;
fReservStart: TDateTime;
fReservLength: Double;
fReservPersons: Double;
fQuantityPurchased: Double;
fConfigId: Integer;
published
property ShoppingList: TSQLShoppingListID read fShoppingList write fShoppingList;
property ShoppingListItemSeq: Integer read fShoppingListItemSeq write fShoppingListItemSeq;
property Product: TSQLProductID read fProduct write fProduct;
property Quantity: Double read fQuantity write fQuantity;
property ModifiedPrice: Currency read fModifiedPrice write fModifiedPrice;
property ReservStart: TDateTime read fReservStart write fReservStart;
property ReservLength: Double read fReservLength write fReservLength;
property ReservPersons: Double read fReservPersons write fReservPersons;
property QuantityPurchased: Double read fQuantityPurchased write fQuantityPurchased;
property ConfigId: Integer read fConfigId write fConfigId;
end;
// 103
TSQLShoppingListItemSurvey = class(TSQLRecord)
private
fShoppingList: TSQLShoppingListID;
fShoppingListItemSeq: Integer;
fSurveyResponse: TSQLSurveyResponseID;
published
property ShoppingList: TSQLShoppingListID read fShoppingList write fShoppingList;
property ShoppingListItemSeq: Integer read fShoppingListItemSeq write fShoppingListItemSeq;
property SurveyResponse: TSQLSurveyResponseID read fSurveyResponse write fSurveyResponse;
end;
// 104
TSQLShoppingListType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 105
TSQLShoppingListWorkEffort = class(TSQLRecord)
private
fShoppingList: TSQLShoppingListID;
fWorkEffort: TSQLWorkEffortID;
published
property ShoppingList: TSQLShoppingListID read fShoppingList write fShoppingList;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
implementation
uses
Classes, SysUtils;
// 1
class procedure TSQLCustRequestType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCustRequestType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCustRequestType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CustRequestType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CustRequestType set parent=(select c.id from CustRequestType c where c.Encode=CustRequestType.ParentEncode);');
Server.Execute('update CustRequestResolution set CustRequestType=(select c.id from CustRequestType c where c.Encode=CustRequestResolution.CustRequestTypeEncode);');
finally
Rec.Free;
end;
end;
// 2
class procedure TSQLCustRequestResolution.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCustRequestResolution;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCustRequestResolution.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CustRequestResolution.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CustRequestResolution set CustRequestType=(select c.id from CustRequestType c where c.Encode=CustRequestResolution.CustRequestTypeEncode);');
finally
Rec.Free;
end;
end;
// 3
class procedure TSQLOrderAdjustmentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLOrderAdjustmentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLOrderAdjustmentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','OrderAdjustmentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update OrderAdjustmentType set parent=(select c.id from OrderAdjustmentType c where c.Encode=OrderAdjustmentType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 4
class procedure TSQLOrderBlacklistType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLOrderBlacklistType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLOrderBlacklistType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','OrderBlacklistType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 5
class procedure TSQLOrderItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLOrderItemType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLOrderItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','OrderItemType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update OrderItemType set parent=(select c.id from OrderItemType c where c.Encode=OrderItemType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 6
class procedure TSQLOrderType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLOrderType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLOrderType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','OrderType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update OrderType set parent=(select c.id from OrderType c where c.Encode=OrderType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 7
class procedure TSQLOrderItemAssocType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLOrderItemAssocType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLOrderItemAssocType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','OrderItemAssocType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update OrderItemAssocType set parent=(select c.id from OrderItemAssocType c where c.Encode=OrderItemAssocType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 8
class procedure TSQLQuoteType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLQuoteType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLQuoteType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','QuoteType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update QuoteType set parent=(select c.id from QuoteType c where c.Encode=QuoteType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 9
class procedure TSQLRequirementType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLRequirementType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLRequirementType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','RequirementType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update RequirementType set parent=(select c.id from RequirementType c where c.Encode=RequirementType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 10
class procedure TSQLShoppingListType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLShoppingListType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLShoppingListType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShoppingListType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 11
class procedure TSQLReturnAdjustmentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnAdjustmentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnAdjustmentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnAdjustmentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ReturnAdjustmentType set parent=(select c.id from ReturnAdjustmentType c where c.Encode=ReturnAdjustmentType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 12
class procedure TSQLReturnHeaderType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnHeaderType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnHeaderType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnHeaderType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ReturnHeaderType set parent=(select c.id from ReturnHeaderType c where c.Encode=ReturnHeaderType.ParentEncode);');
Server.Execute('update ReturnItemTypeMap set ReturnHeaderType=(select c.id from ReturnHeaderType c where c.Encode=ReturnItemTypeMap.ReturnHeaderTypeEncode);');
finally
Rec.Free;
end;
end;
// 13
class procedure TSQLReturnItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnItemType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnItemType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ReturnItemType set parent=(select c.id from ReturnItemType c where c.Encode=ReturnItemType.ParentEncode);');
Server.Execute('update ReturnItemTypeMap set ReturnItemType=(select c.id from ReturnItemType c where c.Encode=ReturnItemTypeMap.ReturnItemTypeEncode);');
finally
Rec.Free;
end;
end;
// 14
class procedure TSQLReturnItemTypeMap.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnItemTypeMap;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnItemTypeMap.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnItemTypeMap.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ReturnItemTypeMap set ReturnHeaderType=(select c.id from ReturnHeaderType c where c.Encode=ReturnItemTypeMap.ReturnHeaderTypeEncode);');
Server.Execute('update ReturnItemTypeMap set ReturnItemType=(select c.id from ReturnItemType c where c.Encode=ReturnItemTypeMap.ReturnItemTypeEncode);');
finally
Rec.Free;
end;
end;
// 15
class procedure TSQLReturnReason.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnReason;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnReason.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnReason.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 16
class procedure TSQLReturnType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLReturnType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLReturnType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ReturnType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 17
class procedure TSQLWorkReqFulfType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLWorkReqFulfType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLWorkReqFulfType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','WorkReqFulfType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit crpt_create_doc_data;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, JSONObjects, AbstractSerializationObjects;
type
{ TCRPTCreateDocumentData }
TCRPTCreateDocumentData = class(TJSONSerializationObject)
private
FDocumentFormat: string;
FDocumentType: string;
FProductDocument: string;
FSignature: string;
procedure SetDocumentFormat(AValue: string);
procedure SetDocumentType(AValue: string);
procedure SetProductDocument(AValue: string);
procedure SetSignature(AValue: string);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create; override;
destructor Destroy; override;
procedure LoadProductDocument(AStream:TStream);
procedure LoadSignature(AStream:TStream);
published
property DocumentFormat:string read FDocumentFormat write SetDocumentFormat;
property ProductDocument:string read FProductDocument write SetProductDocument;
property DocumentType:string read FDocumentType write SetDocumentType;
property Signature:string read FSignature write SetSignature;
end;
implementation
uses base64;
function EncodeStringBase64W(const S:TStream):String;
var
OutStream : TStringStream;
Encoder : TBase64EncodingStream;
begin
if not Assigned(S) then
Exit('');
OutStream:=TStringStream.Create('');
try
Encoder:=TBase64EncodingStream.create(OutStream);
try
Encoder.CopyFrom(S, S.Size);
finally
Encoder.Free;
end;
Result:=OutStream.DataString;
finally
OutStream.free;
end;
end;
{ TCRPTCreateDocumentData }
procedure TCRPTCreateDocumentData.SetDocumentFormat(AValue: string);
begin
if FDocumentFormat=AValue then Exit;
CheckLockupValue('DocumentFormat', AValue);
FDocumentFormat:=AValue;
ModifiedProperty('DocumentFormat');
end;
procedure TCRPTCreateDocumentData.SetDocumentType(AValue: string);
begin
if FDocumentType=AValue then Exit;
FDocumentType:=AValue;
ModifiedProperty('DocumentType');
end;
procedure TCRPTCreateDocumentData.SetProductDocument(AValue: string);
begin
if FProductDocument=AValue then Exit;
FProductDocument:=AValue;
ModifiedProperty('ProductDocument');
end;
procedure TCRPTCreateDocumentData.SetSignature(AValue: string);
begin
if FSignature=AValue then Exit;
FSignature:=AValue;
ModifiedProperty('Signature');
end;
procedure TCRPTCreateDocumentData.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('DocumentFormat', 'document_format', [], '', -1, -1);
P.ValidList.Add('MANUAL');
P.ValidList.Add('XML');
P.ValidList.Add('CSV');
RegisterProperty('ProductDocument', 'product_document', [], '', -1, -1);
RegisterProperty('DocumentType', 'type', [], '', -1, -1);
RegisterProperty('Signature', 'signature', [], '', -1, -1);
end;
procedure TCRPTCreateDocumentData.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
constructor TCRPTCreateDocumentData.Create;
begin
inherited Create;
end;
destructor TCRPTCreateDocumentData.Destroy;
begin
inherited Destroy;
end;
procedure TCRPTCreateDocumentData.LoadProductDocument(AStream: TStream);
begin
ProductDocument:=EncodeStringBase64W(AStream)
end;
procedure TCRPTCreateDocumentData.LoadSignature(AStream: TStream);
var
S: String;
begin
//Signature:=EncodeStringBase64W(AStream)
Signature:='';
if not Assigned(AStream) then Exit;
if (AStream.Size > 0) then
begin
S:='';
SetLength(S, AStream.Size);
AStream.Read(S[1], AStream.Size);
Signature:=S;
end;
end;
end.
|
unit UnContaCorrenteListaRegistrosModelo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FMTBcd, DB, DBClient, Provider, SqlExpr,
{ helsonsant }
Util, DataUtil, UnModelo, Dominio;
type
TContaCorrenteListaRegistrosModelo = class(TModelo)
protected
function GetSql: TSql; override;
end;
var
ContaCorrenteListaRegistrosModelo: TContaCorrenteListaRegistrosModelo;
implementation
{$R *.dfm}
{ TContaCorrenteListaRegistrosModelo }
function TContaCorrenteListaRegistrosModelo.GetSql: TSql;
var
_exibirRegistrosExcluidos: Boolean;
_configuracao: string;
begin
_exibirRegistrosExcluidos := False;
_configuracao := Self.FConfiguracoes.Ler('ExibirRegistrosExcluidos');
if _configuracao = '1' then
_exibirRegistrosExcluidos := True;
if Self.FDominio = nil then
begin
Self.FDominio := TDominio.Create('BancoPesquisaModelo');
Self.FDominio.Sql
.Select('CCOR_OID, CCOR_COD, CCOR_DES')
.From('CCOR')
.Where(Self.FUtil
.iff(not _exibirRegistrosExcluidos, Format('REC_STT = %s', [IntToStr(Ord(srAtivo))]), ''))
.Order('CCOR_OID')
.MetaDados('CCOR_OID IS NULL');
Self.FDominio.Campos
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CCOR_COD', 'Código', 15))
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CCOR_DES', 'Conta Corrente', 100))
end;
Result := Self.FDominio.Sql;
end;
initialization
RegisterClass(TContaCorrenteListaRegistrosModelo);
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc: HGLRC;
procedure PrepareImage;
procedure Idle (Sender:TObject;var Done:boolean);
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
Angle : GLfloat = 0.0;
time : LongInt;
implementation
uses DGLUT;
{$R *.DFM}
procedure TfrmGL.Idle (Sender:TObject;var Done:boolean);
begin
With frmGL do begin
Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000;
If Angle >= 360.0 then Angle := 0.0;
time := GetTickCount;
Done := False;
InvalidateRect(Handle, nil, False);
end;
end;
{======================================================================
Подготовка текстуры}
procedure TfrmGL.PrepareImage;
type
PPixelArray = ^TPixelArray;
TPixelArray = array [0..0] of Byte;
var
Bitmap : TBitmap;
Data : PPixelArray;
BMInfo : TBitmapInfo;
I, ImageSize : Integer;
Temp : Byte;
MemDC : HDC;
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile ('spheremap.bmp');
with BMinfo.bmiHeader do begin
FillChar (BMInfo, SizeOf(BMInfo), 0);
biSize := sizeof (TBitmapInfoHeader);
biBitCount := 24;
biWidth := Bitmap.Width;
biHeight := Bitmap.Height;
ImageSize := biWidth * biHeight;
biPlanes := 1;
biCompression := BI_RGB;
MemDC := CreateCompatibleDC (0);
GetMem (Data, ImageSize * 3);
try
GetDIBits (MemDC, Bitmap.Handle, 0, biHeight, Data, BMInfo, DIB_RGB_COLORS);
For I := 0 to ImageSize - 1 do begin
Temp := Data [I * 3];
Data [I * 3] := Data [I * 3 + 2];
Data [I * 3 + 2] := Temp;
end;
glTexImage2d(GL_TEXTURE_2D, 0, 3, biWidth,
biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);
finally
FreeMem (Data);
DeleteDC (MemDC);
Bitmap.Free;
end;
end;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(2 * Angle, 0.0, 1.0, 0.0);
glRotatef(Angle, 0.0, 0.0, 1.0);
glEnable(GL_TEXTURE_2D);
glutSolidTeapot (1.0);
glDisable(GL_TEXTURE_2D);
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat(DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glClearColor (1.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);// разрешаем тест глубины
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glEnable (GL_TEXTURE_GEN_S);
glEnable (GL_TEXTURE_GEN_T);
PrepareImage;
time := GetTickCount;
Application.OnIdle := Idle;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewPort (0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(18.0, ClientWidth / ClientHeight, 7.0, 13.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -9.0);
glRotatef(60.0, 1.0, 0.0, 1.0);
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit SelfSaved;
interface
uses Classes, ClassInheritIDs;
type
TPropHeaderRec = record
ClassInheritID: Byte;
PropVersionNum: Byte
end;
TSelfSavedComponent = class(TComponent)
private
procedure ReadData(Reader: TReader);
class procedure ReadInheritChain(
const Reader: TReader;
const AnObject: TSelfSavedComponent
);
class procedure ReadPropHeader(const Reader: TReader;
out PropHeaderRec: TPropHeaderRec
);
procedure WriteData(Writer: TWriter);
class procedure WriteInheritChain(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); virtual;
class procedure WritePropHeader(const Writer: TWriter); virtual;
protected
class function IsClassInheritIDValid(
const ClassInheritID: Byte
): Boolean; virtual;
class function GetPropHeaderRec: TPropHeaderRec; virtual;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); virtual;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); virtual;
public
procedure DefineProperties(Filer: TFiler); override;
end;
TSelfSavedComponents = class of TSelfSavedComponent;
implementation
{ TSelfSavedComponent }
class function TSelfSavedComponent.IsClassInheritIDValid(
const ClassInheritID: Byte): Boolean;
begin
if ClassInheritID = GetPropHeaderRec.ClassInheritID then
Result := True else Result := False;
end;
procedure TSelfSavedComponent.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty(' ', ReadData, WriteData, True)
end;
class function TSelfSavedComponent.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := SelfSavedInheritID;
Result.PropVersionNum := SelfSavedCurVerNum;
end;
procedure TSelfSavedComponent.ReadData(Reader: TReader);
begin
with Reader do
begin
ReadListBegin;
ReadInheritChain(Reader, Self);
ReadListEnd;
end;
end;
class procedure TSelfSavedComponent.ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
);
begin
end;
class procedure TSelfSavedComponent.ReadPropHeader(const Reader: TReader;
out PropHeaderRec: TPropHeaderRec);
begin
with Reader, PropHeaderRec do
begin
ClassInheritID := ReadInteger;
PropVersionNum := ReadInteger;
end;
end;
procedure TSelfSavedComponent.WriteData(Writer: TWriter);
begin
with Writer do
begin
WriteListBegin;
WriteInheritChain(Writer, Self);
WriteListEnd;
end;
end;
class procedure TSelfSavedComponent.WriteInheritChain(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
);
var CurClassType: TSelfSavedComponents;
begin
CurClassType := TSelfSavedComponents(AnObject.ClassType);
repeat
with CurClassType do
begin
WritePropHeader(Writer);
WriteProperties(Writer, AnObject);
end;
CurClassType := TSelfSavedComponents(CurClassType.ClassParent);
until CurClassType = TSelfSavedComponent.ClassParent;
end;
class procedure TSelfSavedComponent.WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
);
begin
end;
class procedure TSelfSavedComponent.WritePropHeader(const Writer: TWriter);
var PropHeaderRec: TPropHeaderRec;
begin
PropHeaderRec := GetPropHeaderRec;
with Writer, PropHeaderRec do
begin
WriteInteger(ClassInheritID);
WriteInteger(PropVersionNum);
end;
end;
class procedure TSelfSavedComponent.ReadInheritChain(
const Reader: TReader;
const AnObject: TSelfSavedComponent
);
var PropHeaderRec: TPropHeaderRec;
CurClassType: TSelfSavedComponents;
begin
while not Reader.EndOfList do
begin
ReadPropHeader(Reader, PropHeaderRec);
CurClassType := TSelfSavedComponents(AnObject.ClassType);
repeat
with CurClassType do
if IsClassInheritIDValid(PropHeaderRec.ClassInheritID) then
begin
ReadProperties(Reader, PropHeaderRec, AnObject);
Break;
end;
CurClassType := TSelfSavedComponents(CurClassType.ClassParent);
until CurClassType = TSelfSavedComponent.ClassParent;
end;
end;
end.
|
unit uControleConfiguracoes;
interface
// a Unit do Controle conhece a View e conhece o Modelo (neste caso uEmpresa)
uses
Contnrs, StdCtrls , SysUtils , Grids,
MVCInterfaces, uViewConfiguracoes, uViewInclusao,uEmpresa, uSped,
uIndicadorOperacoes,uRegistro,UI010, UI100, UI200, UCST, uValidar,uExcecao,
UNumeroCampo, uTipoDetalhamento, uContaContabil;
type
TControle = class(TInterfacedObject, IControle)
private
fView : TViewConfiguracoes;
fViewInclusao : TViewInclusao;
fModelo : TEmpresa;
fModeloSped : TSped;
fModeloIndicadorOperacoes : TIndicadorOperacoes;
fModeloI010 : TI010;
fModeloI100 : TI100;
fModeloCST : TCST;
fModeloI200 : TI200;
fModeloNumeroCampo : TNumeroCampo;
fModeloTipoDetalhamento : TTipoDetalhamento;
fModeloContaContabil : TContaContabil;
public
constructor Create; reintroduce;
destructor Destroy; override;
procedure Initialize;
procedure ListaEmpresas;
procedure ListaSped;
procedure ListaI100;
procedure ListaI200;
procedure TelaIncluiI010;
procedure TelaIncluiI100;
procedure TelaIncluiI200;
procedure Salvar;
procedure SalvarI100;
procedure SalvarI200;
procedure CopiaObjectList(lObjectList : TObjectList;lComboBox : TComboBox; lClasse : TClass);
procedure LimpaStringGrid(lStringGrid : TStringGrid);
procedure MontaTelaIncluiI010;
procedure MontaTelaIncluiI100;
procedure MontaTelaIncluiI200;
Procedure MontaCamposTelaIncluiI010(var fcbIdentificadorOperacao : TComboBox; flIdentificadorOperacao : TLabel );
Procedure MontaCamposTelaIncluiI100(var fcbCST : TComboBox; flCST : TLabel );
Procedure MontaCamposTelaIncluiI200(var fcbNumeroCampo: TComboBox; flNumeroCampo : TLabel;
var fcbTipoDetalhamento: TComboBox; flTipoDetalhamento : Tlabel; flContaContabil : Tlabel;
fedCodigoContaContabil : Tedit; fedDescricaoContaContabil : Tedit);
Procedure SelecionouComboBoxNumeroCampo(Sender: TObject);
Procedure ProcuraContaContabil(Sender: TObject);
end;
implementation
procedure TControle.ListaEmpresas;
var
lEmpresas : TObjectList;
begin
lEmpresas := TObjectlist.create;
lEmpresas := fModelo.Todos;
fView.cbEmpresa.Clear;
CopiaObjectList(lEmpresas,fView.cbEmpresa, TEmpresa);
end;
constructor TControle.Create;
begin
fModelo := TEmpresa.Create;
fModeloSped := TSped.create;
fModeloI010 := TI010.create;
fModeloI100 := TI100.create;
fModeloI200 := TI200.create;
FView := TViewConfiguracoes.Create(nil);
end;
destructor TControle.Destroy;
begin
FView.Free;
inherited;
end;
procedure TControle.Initialize;
begin
FView.Modelo := fModelo;
fView.ModeloI010 := fModeloI010;
fModelo.OnModeloMudou := FView.ModeloMudou;
FView.DoLista := ListaSped;
FView.DoListaI100 := ListaI100;
fView.IncluiI010 := TelaIncluiI010;
fView.IncluiI100 := TelaIncluiI100;
fView.IncluiI200 := TelaIncluiI200;
fView.DOListaI200 := ListaI200;
ListaEmpresas;
FView.Initialize;
FView.ShowModal;
fView.Free;
fView := nil;
// precisa estudar para saber se assim esta correto como limpar a memoria
end;
procedure TControle.CopiaObjectList(lObjectList: TObjectList; lComboBox: TComboBox; lClasse : TClass );
var
x : Integer;
begin
lComboBox.Clear;
x := 0;
while (x < (lObjectList.Count) ) do begin
if lClasse = TEmpresa then
lComboBox.AddItem( TEmpresa( lObjectList.Items[x] ).nome , (TEmpresa(lObjectList.Items[x]) ) );
if lClasse = TIndicadorOperacoes then
lComboBox.AddItem( TIndicadorOperacoes(lObjectList.Items[x]).Descricao , (TIndicadorOperacoes(lObjectList.Items[x]) ) );
if lClasse = TCST then
lComboBox.AddItem( TCST(lObjectList.Items[x]).Descricao , (TCST(lObjectList.Items[x]) ) );
if lClasse = TNumeroCampo then
lComboBox.AddItem( TNumeroCampo(lObjectList.Items[x]).Descricao , (TNumeroCampo(lObjectList.Items[x]) ) );
if lClasse = TTipoDetalhamento then
lComboBox.AddItem( TTipoDetalhamento(lObjectList.Items[x]).Descricao , (TTipoDetalhamento(lObjectList.Items[x]) ) );
inc(x);
end;
lComboBox.ItemIndex := 0;
end;
procedure TControle.ListaSped;
var
lSpeds, lI010s : TObjectList;
I : Integer;
begin
fModeloSped.Empresa.ID := ( TEmpresa( fView.cbEmpresa.Items.Objects[fView.cbEmpresa.ItemIndex]).ID);
lSpeds := TobjectList.create;
lSpeds := fModeloSped.TodosDaEmpresa;
LimpaStringGrid(fView.sgI010);
// Teremos sempre somente um objeto SPED embora a arquitetura permita uma lista
if ( Assigned(lSpeds)) then begin
fView.lSpedID.Caption := 'Sped ID ' + inttostr( TSped(lSpeds[0]).ID);
fModeloSped.ID := TSped(lSpeds[0]).ID;
lI010s := TobjectList.create ;
I := 0;
lI010s := TSped(lSpeds[0]).I010s ;
if ( Assigned(lI010s)) then begin
fView.sgI010.Cells[0,0] := ' Indicador de Operações ';
while (I < ( lI010s.Count) ) do begin
fView.sgI010.Cells[0,1+I] := TI010(lI010s[I]).IndicadorOperacoes.Descricao ;
fView.sgI010.Objects[0,1+I] := TI010(lI010s[I]);
inc(I);
END;
end;
// lI010s.Free;
// lI010s := nil;
End;
lSpeds.free;
lSpeds := nil;
end;
procedure TControle.LimpaStringGrid(lStringGrid: TStringGrid);
var
i : integer;
begin
for I := 0 to lStringGrid.RowCount -1 do
lStringGrid.Rows[I].Clear;
end;
procedure TControle.TelaIncluiI010;
var
cbIdentificadorOperacao : TComboBox;
lIdentificadorOperacao : TLabel;
lIndicadorOperacoes : TObjectList;
begin
fModeloI010.Empresa.ID := fModeloSped.Empresa.ID;
MontaTelaIncluiI010;
MontaCamposTelaIncluiI010(cbIdentificadorOperacao,lIdentificadorOperacao);
fModeloIndicadorOperacoes := TIndicadorOperacoes.create;
lIndicadorOperacoes := TObjectlist.create;
lIndicadorOperacoes := fModeloIndicadorOperacoes.Todos;
cbIdentificadorOperacao.Clear;
CopiaObjectList(lIndicadorOperacoes,cbIdentificadorOperacao,TIndicadorOperacoes );
fViewInclusao.ShowModal;
fViewInclusao.Free ;
fViewInclusao := nil;
end;
procedure TControle.Salvar;
var
IndiceSelecionado : integer;
lSpeds : TObjectList;
begin
IndiceSelecionado := (fViewInclusao.FindComponent('cbIdentificadorOperacao') as TComboBox).ItemIndex;
fModeloIndicadorOperacoes := ( TIndicadorOperacoes ( (fViewInclusao.FindComponent('cbIdentificadorOperacao') as TComboBox).Items.Objects[IndiceSelecionado]));
fModeloI010.IndicadorOperacoes := fModeloIndicadorOperacoes;
fModeloI010.Sped := fModeloSped.ID;
// Verificar se o SPED da Empresa esta gravado
if (not Assigned(fModeloSped.Procurar() ) )then begin
fModeloSped.inserir();
end;
fModeloI010.Inserir();
end;
procedure TControle.MontaTelaIncluiI010;
begin
fViewInclusao := TViewInclusao.Create(nil);
fViewInclusao.Initialize;
fViewInclusao.Salvar := Salvar;
fViewInclusao.Height := 270;
fViewInclusao.reTitulo.Clear;
fViewInclusao.reTitulo.Lines.Add('Registro I010');
fViewInclusao.reTitulo.Lines.Add('I010 - Identificação do Estabelecimento');
end;
procedure TControle.MontaCamposTelaIncluiI010(
var fcbIdentificadorOperacao: TComboBox; flIdentificadorOperacao: TLabel);
begin
flIdentificadorOperacao := Tlabel.Create (fViewInclusao);
flIdentificadorOperacao.Parent := fViewInclusao.Panel3;
flIdentificadorOperacao.Left := 40;
flIdentificadorOperacao.Top := 55;
flIdentificadorOperacao.Caption := 'Identificador de Operações realizadas no período';
fcbIdentificadorOperacao := TComboBox.Create(fViewInclusao);
fcbIdentificadorOperacao.Name := 'cbIdentificadorOperacao';
fcbIdentificadorOperacao.Parent := fViewInclusao.Panel3;
fcbIdentificadorOperacao.Left := 288;
fcbIdentificadorOperacao.Top := 52;
fcbIdentificadorOperacao.Width := 470;
end;
procedure TControle.ListaI100;
var
I : Integer;
lI100s : TObjectList;
begin
// fView.fLinhaSg010 é uma variável na VIEW para passar
// a linha selecionada não sei se é correto mas não consegui implementar de outra maneira
FModeloI010 := TI010( fView.sgI010.Objects [0,fView.fLinhaSg010] );
fView.Label1.Caption := inttostr( TI010( fView.sgI010.Objects[0,fView.fLinhaSg010] ).Empresa.id );
lI100s := TobjectList.create;
LimpaStringGrid(fView.sgI100);
fModeloI100.I010.ID := fModeloI010.ID;
lI100s := fModeloI100.GetTodosdoI010;
if ( Assigned(lI100s)) then begin
fView.sgI100.Cells[0,0] := ' C.S. ';
I := 0;
while (I < ( lI100s.Count) ) do begin
fView.sgI100.Cells[0,1+I] := TI100(lI100s[I]).CST.Descricao;
fView.sgI100.Objects[0,1+I] := TI100(lI100s[I]);
inc(I);
end;
end;
end;
procedure TControle.TelaIncluiI100;
var
cbCST : TComboBox;
lCST : TLabel;
lCSTs : TObjectList;
begin
fModeloI100.Empresa.ID := fModeloSped.Empresa.ID;
MontaTelaIncluiI100;
MontaCamposTelaIncluiI100(cbCST,lCST);
fModeloCST := TCST.create;
lCSTs := TObjectlist.create;
lCSTs := fModeloCST.Todos;
cbCST.Clear;
CopiaObjectList(lCSTs,cbCST,TCST );
fViewInclusao.ShowModal;
fViewInclusao.Free ;
fViewInclusao := nil;
end;
procedure TControle.MontaTelaIncluiI100;
begin
fViewInclusao := TViewInclusao.Create(nil);
fViewInclusao.Initialize;
fViewInclusao.Salvar := SalvarI100;
fViewInclusao.Height := 270;
fViewInclusao.reTitulo.Clear;
fViewInclusao.reTitulo.Lines.Add('Registro I100');
fViewInclusao.reTitulo.Lines.Add('I100 - Consolidação das Operações do Período');
end;
Procedure TControle.MontaCamposTelaIncluiI100(var fcbCST : TComboBox; flCST : TLabel );
var
flAliquotaPIS : Tlabel;
flAliquotaCOFINS : Tlabel;
feditAliquotaPIS : TEdit;
feditAliquotaCOFINS : TEdit;
begin
flCST := Tlabel.Create (fViewInclusao);
flCST.Parent := fViewInclusao.Panel3;
flCST.Left := 32;
flCST.Top := 30;
flCST.Caption := 'Código de Situação Tributária';
fcbCST := TComboBox.Create(fViewInclusao);
fcbCST.Name := 'cbCST';
fcbCST.Parent := fViewInclusao.Panel3;
fcbCST.Left := 184;
fcbCST.Top := 24;
fcbCST.Width := 470;
flAliquotaPIS := Tlabel.Create (fViewInclusao);
flAliquotaPIS.Parent := fViewInclusao.Panel3;
flAliquotaPIS.Left := 32;
flAliquotaPIS.Top := 80;
flAliquotaPIS.Caption := 'Alíquota do PIS/PASEP (em percentual)';
feditAliquotaPIS := Tedit.Create(fViewInclusao);
feditAliquotaPIS.Parent := fViewInclusao.Panel3;
feditAliquotaPIS.Left := 235;
feditAliquotaPIS.Top := 75;
feditAliquotaPIS.Width := 90;
feditAliquotaPIS.Name := 'editAliquotaPIS';
feditAliquotaPIS.text := '';
flAliquotaCOFINS := Tlabel.Create (fViewInclusao);
flAliquotaCOFINS.Parent := fViewInclusao.Panel3;
flAliquotaCOFINS.Left := 344;
flAliquotaCOFINS.Top := 80;
flAliquotaCOFINS.Caption := 'Alíquota da COFINS (em percentual)';
feditAliquotaCOFINS := Tedit.Create(fViewInclusao);
feditAliquotaCOFINS.Parent := fViewInclusao.Panel3;
feditAliquotaCOFINS.Left := 530;
feditAliquotaCOFINS.Top := 75;
feditAliquotaCOFINS.Width := 90;
feditAliquotaCOFINS.Name := 'editAliquotaCOFINS';
feditAliquotaCOFINS.Text := '';
end;
procedure TControle.SalvarI100;
var
IndiceSelecionado : integer;
fValidar : Tvalidar;
begin
try
TValidar.CampoObrigatorio((fViewInclusao.FindComponent('editAliquotaPIS') as TEdit).text,True,'Campo Aliquota PIS obrigatório!', (fViewInclusao.FindComponent('editAliquotaPIS') as TEdit));
TValidar.CampoObrigatorio((fViewInclusao.FindComponent('editAliquotaCOFINS') as TEdit).text,True,'Campo Aliquota COFINS obrigatório!', (fViewInclusao.FindComponent('editAliquotaCOFINS') as TEdit));
TValidar.CampoExtend((fViewInclusao.FindComponent('editAliquotaPIS') as TEdit).text,True,'Erro no preenchimento do campo Aliquota PIS!', (fViewInclusao.FindComponent('editAliquotaPIS') as TEdit));
TValidar.CampoExtend((fViewInclusao.FindComponent('editAliquotaCOFINS') as TEdit).text,True,'Erro no preenchimento co campo Aliquota COFINS!', (fViewInclusao.FindComponent('editAliquotaCOFINS') as TEdit));
fModeloI100.I010.ID := fModeloI010.ID;
IndiceSelecionado := (fViewInclusao.FindComponent('cbCST') as TComboBox).ItemIndex;
fModeloCST := ( TCST ( (fViewInclusao.FindComponent('cbCST') as TComboBox).Items.Objects[IndiceSelecionado]));
fModeloI100.CST := fModeloCST;
fModeloI100.AliquotaPIS := StrToFloat ( (fViewInclusao.FindComponent('editAliquotaPIS') as TEdit).text );
fModeloI100.AliquotaCOFINS := StrToFloat ( (fViewInclusao.FindComponent('editAliquotaCOFINS') as TEdit).text );
fModeloI100.Inserir();
except
on e:TConGeralExcecao do
Raise
end;
end;
procedure TControle.ListaI200;
var
I : Integer;
begin
FModeloI100 := TI100( fView.sgI100.Objects [0,fView.fLinhasgI100] );
end;
procedure TControle.SalvarI200;
begin
end;
procedure TControle.TelaIncluiI200;
var
cbNumeroCampo : TComboBox;
lNumeroCampo : TLabel;
lNumeroSCampos : TObjectList;
cbTipoDetalhamento : TComboBox;
lTipoDetalhamento : TLabel;
lTiposDetalhamentos : TObjectList;
lContaContabil : TLabel;
edCodigoContaContabil : TEdit;
edDescricaoContaContabil : TEdit;
begin
fModeloI200.I100.ID := fModeloI100.ID;
fModeloContaContabil := TContaContabil.create;
MontaTelaIncluiI200;
MontaCamposTelaIncluiI200(cbNumeroCampo,lNumeroCampo,cbTipoDetalhamento,lTipoDetalhamento,
lContaContabil,edCodigoContaContabil,edDescricaoContaContabil);
fModeloNumeroCampo := TNumeroCampo.create;
lNumeroSCampos := TObjectlist.create;
lNumeroSCampos := fModeloNumeroCampo.Todos;
cbNumeroCampo.Clear;
CopiaObjectList(lNumeroSCampos,cbNumeroCampo,TNumeroCampo );
cbNumeroCampo.ItemIndex := 0;
SelecionouComboBoxNumeroCampo(cbNumeroCampo);
fViewInclusao.ShowModal;
fViewInclusao.Free ;
fViewInclusao := nil;
end;
procedure TControle.MontaTelaIncluiI200;
begin
fViewInclusao := TViewInclusao.Create(nil);
fViewInclusao.Initialize;
fViewInclusao.Salvar := SalvarI200;
fViewInclusao.Height := 300;
fViewInclusao.reTitulo.Clear;
fViewInclusao.reTitulo.Lines.Add('Registro I200');
fViewInclusao.reTitulo.Lines.Add('I200 - Detalhamento das Receitas Deduções e/ou Exclusões do Período');
end;
Procedure TControle.MontaCamposTelaIncluiI200(var fcbNumeroCampo: TComboBox; flNumeroCampo : TLabel;
var fcbTipoDetalhamento: TComboBox; flTipoDetalhamento : Tlabel ; flContaContabil : Tlabel;
fedCodigoContaContabil : Tedit; fedDescricaoContaContabil : Tedit);
begin
flNumeroCampo := Tlabel.Create (fViewInclusao);
flNumeroCampo.Parent := fViewInclusao.Panel3;
flNumeroCampo.Left := 32;
flNumeroCampo.Top := 30;
flNumeroCampo.Caption := 'Número do Campo';
fcbNumeroCampo := TComboBox.Create(fViewInclusao);
fcbNumeroCampo.Name := 'cbNumeroCampo';
fcbNumeroCampo.Parent := fViewInclusao.Panel3;
fcbNumeroCampo.Left := 170;
fcbNumeroCampo.Top := 24;
fcbNumeroCampo.Width := 470;
fcbNumeroCampo.OnSelect := SelecionouComboBoxNumeroCampo;
flTipoDetalhamento := Tlabel.Create (fViewInclusao);
flTipoDetalhamento.Parent := fViewInclusao.Panel3;
flTipoDetalhamento.Left := 32;
flTipoDetalhamento.Top := 80;
flTipoDetalhamento.Caption := 'Tipo Detalhamento';
fcbTipoDetalhamento := TComboBox.Create(fViewInclusao);
fcbTipoDetalhamento.Name := 'cbTipoDetalhamento';
fcbTipoDetalhamento.Parent := fViewInclusao.Panel3;
fcbTipoDetalhamento.Left := 170;
fcbTipoDetalhamento.Top := 74;
fcbTipoDetalhamento.Width := 470;
flContaContabil := Tlabel.Create (fViewInclusao);
flContaContabil.Parent := fViewInclusao.Panel3;
flContaContabil.Left := 32;
flContaContabil.Top := 120;
flContaContabil.Caption := 'Conta Contábil';
fedCodigoContaContabil := Tedit.Create (fViewInclusao);
fedCodigoContaContabil.Parent := fViewInclusao.Panel3;
fedCodigoContaContabil.Top := 120;
fedCodigoContaContabil.Left := 180;
fedCodigoContaContabil.OnExit := ProcuraContaContabil;
fedDescricaoContaContabil := Tedit.Create (fViewInclusao);
fedDescricaoContaContabil.Parent := fViewInclusao.Panel3;
fedDescricaoContaContabil.Top := 120;
fedDescricaoContaContabil.Left := 320;
end;
procedure TControle.SelecionouComboBoxNumeroCampo(Sender: TObject);
var
fcombobox : TComboBox;
fNumeroCampo : TNumeroCampo;
fTiposDetalhamentos : TObjectList;
begin
fNumeroCampo := TNumeroCampo.create;
fNumeroCampo.ID := ( TNumeroCampo( TComboBox(sender).Items.Objects[ TComboBox(sender).ItemIndex]).ID);
fcombobox := (fViewInclusao.FindComponent('cbTipoDetalhamento') as TComboBox);
fcombobox.Clear;
fModeloTipoDetalhamento := TTipoDetalhamento.create();
fTiposDetalhamentos := TObjectlist.create;
fModeloTipoDetalhamento.NumeroCampo.ID := fNumeroCampo.ID;
fTiposDetalhamentos := fModeloTipoDetalhamento.TodosDoNumeroCampo;
CopiaObjectList(fTiposDetalhamentos,fcombobox,TTipoDetalhamento );
end;
procedure TControle.ProcuraContaContabil(Sender: TObject);
begin
fModeloContaContabil.CodigoReduzido := ( TEdit(sender).text);
//fModeloContaContabil :=
fModeloContaContabil.Procurar();
fViewInclusao.btFechar.Caption := fModeloContaContabil.Descricao;
end;
end.
|
unit MemoAuto;
{ This unit implements TMemoApp, the Application automation object class for
the MemoEdit application. TMemoApp is registered as a Single Instance
automation class, thus causing a new copy of the application to be run each
time an OLE Automation controller asks for an instance of the "Memo.MemoApp"
OLE class name. TMemoApp implements the following automated methods and properties:
function NewMemo: OleVariant;
Creates a new editor window and returns the window's automation object.
function OpenMemo(const FileName: WideString): OleVariant;
Loads an existing file into a new editor window and returns the window's
automation object.
procedure TileWindows;
Tiles all open editor windows.
procedure CascadeWindows;
Cascades all open editor windows.
property MemoCount: Integer;
Number of open editor windows.
property Memos[Index: Integer]: OleVariant;
Array of automation objects for the currently open editor windows. }
interface
uses
ComObj, Memo_TLB;
type
TMemoApp = class(TAutoObject, IMemoApp)
protected
function Get_MemoCount: Integer; safecall;
function Get_Memos(MemoIndex: Integer): OleVariant; safecall;
function NewMemo: OleVariant; safecall;
function OpenMemo(const MemoFileName: WideString): OleVariant; safecall;
procedure CascadeWindows; safecall;
procedure TileWindows; safecall;
end;
implementation
uses ComServ, MainFrm, EditFrm;
function TMemoApp.Get_MemoCount: Integer;
begin
Result := MainForm.MDIChildCount;
end;
function TMemoApp.Get_Memos(MemoIndex: Integer): OleVariant;
begin
Result := TEditForm(MainForm.MDIChildren[MemoIndex]).OleObject;
end;
function TMemoApp.NewMemo: OleVariant;
begin
Result := MainForm.CreateMemo('').OleObject;
end;
function TMemoApp.OpenMemo(const MemoFileName: WideString): OleVariant;
begin
Result := MainForm.CreateMemo(MemoFileName).OleObject;
end;
procedure TMemoApp.CascadeWindows;
begin
MainForm.Cascade;
end;
procedure TMemoApp.TileWindows;
begin
MainForm.Tile;
end;
initialization
TAutoObjectFactory.Create(ComServer, TMemoApp, Class_MemoApp, ciSingleInstance);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.FramePush;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, System.JSON, System.Generics.Collections, FMX.ListView.Types,
FMX.ListView, FMX.Memo, RSConsole.Types, RSConsole.DlgPushWhereU,
FMX.Controls.Presentation, FMX.ScrollBox, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base;
type
TPushFrame = class(TFrame)
Layout1: TLayout;
ButtonPushData: TButton;
ButtonTargetChannels: TButton;
ButtonTargetWhere: TButton;
SendButton: TButton;
Layout2: TLayout;
LayoutPushData: TLayout;
DataMemo: TMemo;
TitleLabel: TLabel;
LayoutPushTarget: TLayout;
TargetMemo: TMemo;
Label4: TLabel;
Splitter1: TSplitter;
Layout3: TLayout;
ListView1: TListView;
ToolBar1: TToolBar;
Label1: TLabel;
ClearButton: TButton;
procedure ClearButtonClick(Sender: TObject);
procedure ButtonPushDataClick(Sender: TObject);
procedure ButtonTargetChannelsClick(Sender: TObject);
procedure ButtonTargetWhereClick(Sender: TObject);
procedure SendButtonClick(Sender: TObject);
procedure ListView1Change(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
public type
TSendStatus = record
private
FIOSCount: Integer;
FAndroidCount: Integer;
public
constructor Create(AIOSCount, AAndroidCount: Integer);
end;
THistoryItem = class
private
FSendTime: TDateTime;
FPayload: TJSONObject;
FTarget: TJSONObject;
FSendStatus: TSendStatus;
FMessage: string;
public
constructor Create(ASendTime: TDateTime; const AMessage: string;
const APayload, ATarget: TJSONObject; const ASendStatus: TSendStatus);
function ToString: string; override;
property Payload: TJSONObject read FPayload;
property Target: TJSONObject read FTarget;
end;
private
{ Private declarations }
FItems: TList<THistoryItem>;
FOnSelect: TNotifyEvent;
FAdding: Boolean;
function GetSelected: THistoryItem;
procedure UpdateList;
procedure AddListItem(const AItem: THistoryItem);
procedure GetDevices(out ADevices: TDlgPushWhere.TDevices);
procedure GetChannels(out AChannels: TArray<string>);
procedure OnHistorySelect(ASender: TObject);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Add(const AItem: THistoryItem);
procedure Clear;
property Selected: THistoryItem read GetSelected;
property OnSelect: TNotifyEvent read FOnSelect write FOnSelect;
end;
implementation
uses
REST.JSON, RSConsole.ModuleBackend, REST.Backend.EMSApi,
REST.Backend.PushTypes, RSConsole.Consts,
REST.Backend.EMSProvider, RSConsole.DlgPushDataU,
RSConsole.DlgPushChannelsU, RSConsole.Form, RSConsole.FrameViews;
{$R *.fmx}
constructor TPushFrame.Create(AOwner: TComponent);
begin
inherited;
FItems := TList<THistoryItem>.Create;
OnSelect := OnHistorySelect;
end;
destructor TPushFrame.Destroy;
begin
FItems.Free;
inherited;
end;
procedure TPushFrame.GetChannels(out AChannels: TArray<string>);
var
LEMSClientAPI: TEMSClientAPI;
begin
LEMSClientAPI := (BackendDM.BackendPush1.ProviderService as IGetEMSApi).EMSApi;
AChannels := LEMSClientAPI.RetrieveInstallationsChannelNames;
end;
procedure TPushFrame.GetDevices(out ADevices: TDlgPushWhere.TDevices);
var
LJSONArray: TJSONArray;
LJSONValue: TJSONValue;
I: Integer;
LDevice: TDlgPushWhere.TDevice;
LEMSClientAPI: TEMSClientAPI;
begin
LJSONArray := TJSONArray.Create;
try
LEMSClientAPI := (BackendDM.BackendPush1.ProviderService as IGetEMSApi).EMSApi;
LEMSClientAPI.QueryInstallations([], LJSONArray);
SetLength(ADevices, LJSONArray.Count);
for I := 0 to LJSONArray.Count - 1 do
begin
LJSONValue := LJSONArray.Items[I];
LDevice := TDlgPushWhere.TDevice.Create
(LJSONValue.GetValue<string>('deviceToken', ''),
LJSONValue.GetValue<string>('deviceType', ''), []);
ADevices[I] := LDevice;
end;
finally
LJSONArray.Free;
end;
end;
function TPushFrame.GetSelected: THistoryItem;
begin
if ListView1.ItemIndex >= 0 then
Result := FItems[ListView1.ItemIndex]
else
Result := nil;
end;
procedure TPushFrame.ListView1Change(Sender: TObject);
begin
if not FAdding then
if Assigned(FOnSelect) then
FOnSelect(Self);
end;
procedure TPushFrame.OnHistorySelect(ASender: TObject);
var
LItem: TPushFrame.THistoryItem;
begin
LItem := Selected;
if LItem <> nil then
begin
if LItem.Payload <> nil then
DataMemo.Text := LItem.Payload.Format
else
DataMemo.Text := '';
if LItem.Target <> nil then
TargetMemo.Text := LItem.Target.Format
else
TargetMemo.Text := '';
end;
end;
procedure TPushFrame.SendButtonClick(Sender: TObject);
var
LPushData: TPushData;
LTarget: TJSONValue;
LData: TJSONValue;
LTargetText: string;
LDataText: string;
LErrorMessage: string;
LPushStatus: TEMSClientAPI.TPushStatus;
LJSONPushData: TJSONObject;
LEMSClientAPI: TEMSClientAPI;
LMessages: string;
begin
LTarget := nil;
LData := nil;
LPushData := nil;
try
LTargetText := Trim(TargetMemo.Text);
if LTargetText <> '' then
begin
LTarget := TJSONObject.ParseJSONValue(LTargetText);
if not (LTarget is TJSONObject) then
raise Exception.Create(strTargetNotJSONObject);
end;
LDataText := Trim(DataMemo.Text);
LData := TJSONObject.ParseJSONValue(LDataText);
if not (LData is TJSONObject) then
raise Exception.Create(strTargetNotJSONObject);
LPushData := TPushData.Create;
try
LPushData.Load(TJSONObject(LData));
try
LJSONPushData := BackendDM.BackendPush1.PushAPI.PushDataAsJSON(LPushData);
try
LEMSClientAPI := (BackendDM.BackendPush1.ProviderService as IGetEMSApi).EMSApi;
LEMSClientAPI.PushToTarget(LJSONPushData, TJSONObject(LTarget), LPushStatus);
finally
LJSONPushData.Free;
end;
except
on E: Exception do
begin
LErrorMessage := E.Message;
raise;
end;
end;
finally
LMessages := ' - Message: ''' + LPushData.Message + ''' - APS.Alert: ''' +
LPushData.APS.Alert + ''' - GCM.Message: ''' + LPushData.GCM.Message + '''';
Add(THistoryItem.Create(Now, LMessages, TJSONObject(LData),
TJSONObject(LTarget), TSendStatus.Create(LPushStatus.QueuedIOS,
LPushStatus.QueuedAndroid)));
end;
finally
LPushData.Free;
LTarget.Free;
LData.Free;
end;
end;
procedure TPushFrame.UpdateList;
var
LItem: THistoryItem;
begin
ListView1.BeginUpdate;
try
for LItem in FItems do
AddListItem(LItem);
finally
ListView1.EndUpdate;
end;
end;
procedure TPushFrame.Add(const AItem: THistoryItem);
begin
FItems.Add(AItem);
AddListItem(AItem);
end;
procedure TPushFrame.AddListItem(const AItem: THistoryItem);
begin
FAdding := True;
try
ListView1.Items.Add.Text := AItem.ToString;
ListView1.ItemIndex := ListView1.Items.Count - 1;
finally
FAdding := False;
end;
end;
procedure TPushFrame.ButtonPushDataClick(Sender: TObject);
var
LJSONData: TJSONValue;
LDlg: TDlgPushData;
LData: string;
begin
LJSONData := nil;
try
LData := Trim(DataMemo.Text);
if LData <> '' then
begin
LJSONData := TJSONObject.ParseJSONValue(LData);
if LJSONData = nil then
raise Exception.Create(strDataNotJSON);
if not (LJSONData is TJSONObject) then
raise Exception.Create(strDataNotJSONObject);
end;
LDlg := TDlgPushData.Create(Self);
try
if LJSONData <> nil then
LDlg.JSONData := TJSONObject(LJSONData);
if LDlg.ShowModal = mrOk then
begin
FreeAndNil(LJSONData);
LJSONData := LDlg.JSONData.Clone as TJSONValue;
DataMemo.Text := LJSONData.Format;
end;
finally
LDlg.Free;
end;
finally
LJSONData.Free;
end;
end;
procedure TPushFrame.ButtonTargetChannelsClick(Sender: TObject);
var
LJSONData: TJSONValue;
LDlg: TDlgPushChannels;
LTarget: string;
LChannels: TArray<string>;
begin
if BackendDM.EMSProvider.BaseURL <> '' then
begin
LJSONData := nil;
try
LTarget := Trim(TargetMemo.Text);
if LTarget <> '' then
begin
LJSONData := TJSONObject.ParseJSONValue(LTarget);
if LJSONData = nil then
raise Exception.Create(strTargetNotJSON);
if not (LJSONData is TJSONObject) then
raise Exception.Create(strTargetNotJSONObject);
end;
if LJSONData = nil then
LJSONData := TJSONObject.Create;
LDlg := TDlgPushChannels.Create(Self);
try
GetChannels(LChannels);
LDlg.Channels := LChannels;
LDlg.Load(TJSONObject(LJSONData));
if LDlg.ShowModal = mrOk then
begin
LDlg.Save(TJSONObject(LJSONData));
TargetMemo.Text := LJSONData.Format;
end;
finally
LDlg.Free;
end;
finally
LJSONData.Free;
end;
end
else
raise Exception.Create(strURLBlank);
end;
procedure TPushFrame.ButtonTargetWhereClick(Sender: TObject);
var
LJSONData: TJSONValue;
LDlg: TDlgPushWhere;
LTarget: string;
LDevices: TDlgPushWhere.TDevices;
begin
if BackendDM.EMSProvider.BaseURL <> '' then
begin
LJSONData := nil;
try
LTarget := Trim(TargetMemo.Text);
if LTarget <> '' then
begin
LJSONData := TJSONObject.ParseJSONValue(LTarget);
if LJSONData = nil then
raise Exception.Create(strTargetNotJSON);
if not (LJSONData is TJSONObject) then
raise Exception.Create(strTargetNotJSONObject);
end;
if LJSONData = nil then
LJSONData := TJSONObject.Create;
LDlg := TDlgPushWhere.Create(Self);
try
GetDevices(LDevices);
LDlg.Devices := LDevices;
LDlg.Load(TJSONObject(LJSONData));
if LDlg.ShowModal = mrOk then
begin
LDlg.Save(TJSONObject(LJSONData));
TargetMemo.Text := LJSONData.Format;
end;
finally
LDlg.Free;
end;
finally
LJSONData.Free;
end;
end
else
raise Exception.Create(strURLBlank);
end;
procedure TPushFrame.Clear;
begin
ListView1.Items.Clear;
FItems.Clear;
UpdateList;
end;
procedure TPushFrame.ClearButtonClick(Sender: TObject);
begin
Clear;
end;
procedure TPushFrame.CloseButtonClick(Sender: TObject);
begin
Clear;
Visible := False;
TMainForm(Root).ViewsFrame.Visible := True;
DataMemo.Text := '';
TargetMemo.Text := '';
end;
{ TFrame1.TSendStatus }
constructor TPushFrame.TSendStatus.Create(AIOSCount, AAndroidCount: Integer);
begin
FIOSCount := AIOSCount;
FAndroidCount := AAndroidCount;
end;
{ TFrame1.THistoryItem }
constructor TPushFrame.THistoryItem.Create(ASendTime: TDateTime;
const AMessage: string; const APayload, ATarget: TJSONObject;
const ASendStatus: TSendStatus);
begin
FMessage := AMessage;
FSendTime := ASendTime;
if APayload <> nil then
FPayload := APayload.Clone as TJSONObject;
if ATarget <> nil then
FTarget := ATarget.Clone as TJSONObject;
FSendStatus := ASendStatus;
end;
function TPushFrame.THistoryItem.ToString: string;
begin
Result := TimeToStr(FSendTime) + Format(strMessageQueued,
[FMessage, FSendStatus.FAndroidCount, FSendStatus.FIOSCount]);
end;
end.
|
{***************************************************************
*
* Project : TFTPClient
* Unit Name: Main
* Purpose : Simple demo of TidFTPClient
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:39:10
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit Main;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient,
IdTrivialFTP;
type
TfrmMain = class(TForm)
edtRemoteFile: TEdit;
btnUpload: TButton;
edtHost: TEdit;
Label1: TLabel;
Label2: TLabel;
edtLocalFile: TEdit;
Label3: TLabel;
btnDownload: TButton;
TrivialFTP: TIdTrivialFTP;
procedure btnUploadClick(Sender: TObject);
procedure btnDownloadClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TfrmMain.btnUploadClick(Sender: TObject);
var
s: string;
begin
s := edtRemoteFile.Text;
if s = '' then
s := ExtractFileName(edtLocalFile.Text);
with TrivialFTP do
begin
Host := edtHost.Text;
Put(edtLocalFile.Text, s);
end;
end;
procedure TfrmMain.btnDownloadClick(Sender: TObject);
var
strm: TFileStream;
s: string;
begin
s := edtLocalFile.Text;
if s = '' then
s := ExtractFileName(edtRemoteFile.Text);
strm := TFileStream.Create(s, fmCreate);
with TrivialFTP do
try
Host := edtHost.Text;
Get(edtRemoteFile.Text, strm);
finally
strm.Free;
end;
end;
end.
|
unit ncaFrmConsumidor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, cxControls, cxContainer, cxEdit,
Vcl.StdCtrls, cxRadioGroup, cxLabel, cxButtons, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel;
type
TFrmConsumidor = class(TForm)
LMDSimplePanel5: TLMDSimplePanel;
btnSalvar: TcxButton;
btnCancelar: TcxButton;
LMDSimplePanel4: TLMDSimplePanel;
lbTit: TcxLabel;
rbRevenda: TcxRadioButton;
rbConsumo: TcxRadioButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSalvarClick(Sender: TObject);
private
{ Private declarations }
public
function Consumidor(var aConsumidor: Boolean): Boolean;
{ Public declarations }
end;
var
FrmConsumidor: TFrmConsumidor;
implementation
{$R *.dfm}
uses ncClassesBase, ncaDM;
procedure TFrmConsumidor.btnSalvarClick(Sender: TObject);
begin
if (not rbRevenda.Checked) and (not rbConsumo.Checked) then
raise Exception.Create('É necessário escolher uma das opções');
ModalResult := mrOk;
end;
procedure TFrmConsumidor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
function TFrmConsumidor.Consumidor(var aConsumidor: Boolean): Boolean;
begin
ShowModal;
if ModalResult=mrOk then begin
Result := True;
aConsumidor := rbConsumo.Checked;
end else
Result := False;
end;
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.ByteArrayUtils;
interface
uses
System.SysUtils;
function ConvertToByteArray(const pValue:Integer):TBytes; overload;
function ConvertToByteArray(const pValue:Int64):TBytes; overload;
function ByteArraysMatch(const pArray1, pArray2:TBytes):Boolean;
function ReverseByteArray(const pSource:TBytes):TBytes;
implementation
function ConvertToByteArray(const pValue:Integer):TBytes;
begin
SetLength(Result, SizeOf(Integer));
PInteger(@Result[0])^ := pValue;
end;
function ConvertToByteArray(const pValue:Int64):TBytes;
begin
SetLength(Result, SizeOf(Int64));
PInt64(@Result[0])^ := pValue;
end;
function ReverseByteArray(const pSource:TBytes):TBytes;
var
vArrayLength:Integer;
i:Integer;
begin
vArrayLength := Length(pSource);
SetLength(Result, vArrayLength);
if vArrayLength > 0 then
begin
for i := Low(pSource) to High(pSource) do
begin
Result[High(pSource) - i] := pSource[i];
end;
end;
end;
function ByteArraysMatch(const pArray1, pArray2:TBytes):Boolean;
var
vArrayLength:Integer;
begin
vArrayLength := Length(pArray1);
if vArrayLength = 0 then
begin
Result := Length(pArray2) = 0;
end
else
begin
Result := vArrayLength = Length(pArray2);
if Result then
begin
Result := CompareMem(@pArray1[0], @pArray2[0], vArrayLength);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.Consts;
interface
const
EMS_WOW64_REGISTRY_KEY = 'Software\Wow6432Node\Embarcadero\EMS';
EMS_REGISTRY_KEY = 'Software\Embarcadero\EMS';
EMS_CONFIG_NAME = 'ConfigFile';
EMS_STYLE_NAME = 'RSConsoleStyle';
ROOT_ITEM = 0;
USERS_ITEM = 1;
GROUPS_ITEM = 2;
INSTALLATIONS_ITEM = 3;
MODULES_ITEM = 4;
RESOURCES_ITEM = 5;
PUSH_ITEM = 6;
ENDPOINTS_ITEM = 7;
// DeviceTypes
striOS = 'ios';
strAndroid = 'android';
strWinrt = 'winrt';
strWinPhone = 'winphone';
strDonet = 'dotnet';
cAdd = 'Add';
cAddUsers = 'AddUsers';
cAddGroups = 'AddGroups';
cAddInstallations = 'AddInstallations';
cTab = 'Tab';
cAddTab = 'AddTab';
strRSP = '.rsp';
strEMSP = '.emsp';
resourcestring
strRSFormTitle = 'RAD Server Connection Profile: ';
strRestartStyle = 'Please restart the application for the new style.';
strSettingsPath = 'RSConsole';
// Styles
strLightStyle = 'Light';
strLightResName = 'LightStyle';
strDarkStyle = 'Dark';
strDarkResName = 'DarkStyle';
strViews = 'Views';
strUsers = 'Users';
strGroups = 'Groups';
strInstallations = 'Installations';
strChannels = 'Channels';
strEdgeModules = 'Modules';
strAllEdgeModule = 'All Modules';
strPush = 'Push';
strResources = 'Resources';
strEndpoints = 'Endpoints';
strLoggedIn = 'Logged In';
strLoggedOut = 'Logged Out';
strToken = 'Device Token';
strDevice = 'Device Type';
strNewProfile = 'New Profile';
// Add form
strClearData = 'Clear data';
strFieldName = 'Field Name';
strFieldValue = 'Field Value';
strGroupName = 'Group name';
strModUsers = 'Modify user';
strModGroup = 'Modify group';
strModInstall = 'Modify installation';
strAddChannels = 'Add channels';
strAddChannel = 'Add channel';
// Messages
strGroup = 'Group';
strUser = 'User';
strInstallation = 'Installation';
strEdgeModule = 'Module';
strResource = 'Resource';
strUserName = 'user name';
strDeviceWithToken = 'Device with Token';
strConnectionSucc = 'Successful connection';
strLoginSucc = 'Successful login';
strSaveProfileReg = 'Rename as';
strTypeProfName = 'Please type a name for your profile';
strFileExist = 'File already exists';
strReplaceIt = 'Do you want to replace it?';
strProfileFile = 'RAD Server Profile file';
strUserNotloggedIn = 'was not logged in';
strUserNotCreated = 'user was not created';
strInstallationNotCreated = 'installation was not created';
strNotUpdated = 'was not updated';
strGroupNotCreated = 'group was not created';
strNotAddedToGroup = ' was not added to group: ';
strNotAddedToGroupP = ' were not added to group: ';
strNotDeleted = ' was not deleted';
strNotRemovedFromGroup = ' was not removed from ';
strNotRemovedFromGroupP = ' were not removed from ';
strFileNotFound = 'File not found';
strDeviteTypeNeeded = 'A device type needs to be selected';
strMessage = 'Please enter a message';
strSendToChannel = 'Do you want to send a Push notification to the channel: ';
strChannelUser = 'Please select a Channel or a User';
strURLBlank = 'URL must not be blank. Please create a connection profile first.';
strTargetNotJSON = 'Target is not JSON';
strTargetNotJSONObject = 'Target is not a JSON object';
strDataNotJSON = 'Data is not JSON';
strDataNotJSONObject = 'Data is not a JSON object';
strMessageQueued = ', Message: "%s", Queued: %d Android, %d IOS';
strDeleteItem = 'You are about to delete item ';
strSelectModule = 'Select a module from the Modules tab.';
// Update
strYes = 'Yes';
strNo = 'No';
// Help URL
strURLtoHelp = '/en/RAD_Server_Management_Console_Application';
implementation
end.
|
{Ejercicio 3
Dadas las siguientes declaraciones:
CONST N = . . .;
. . .
TYPE
RangoN = 1..N;
Tabla = Array[RangoN] OF Integer;
Escriba un programa ContarMayores que, dado un entero ingresado por el usuario,
cuente e imprima la cantidad de valores almacenados en el arreglo que son mayores que el entero ingresado.
Escriba un programa HallaIndMax que encuentre e imprima el valor más grande de
un arreglo junto con el índice donde ocurre.
Escriba un programa Ordenado que determine si los elementos del arreglo se encuentran ordenados en
orden ascendente e imprima una salida con un mensaje indicando el resultado.
En los tres programas se deben obtener los valores del arreglo desde la entrada estándar en forma
previa a la resolución del problema solicitado.}
program ejercicio3;
const N = 10;
type
RangoN = 1..N;
Tabla = array[RangoN] of integer;
var arreglo : Tabla;
aux, i, entero, max, k, w : integer;
procedure Ingresoentero(var entero : integer);
begin
writeln('Ingrese un entero positivo.');
read(entero);
writeln('Ingrese ',N,' valores para el arreglo.');
end;
procedure LeerArreglo(var arreglo : Tabla);
begin
for i := 1 to N do
read(arreglo[i]);
end;
procedure Contar(var entero : integer; arreglo : Tabla);
begin
w := 0;
for i := 1 to N do
if entero < arreglo[i] then
w := w + 1;
writeln;
writeln(' ContarMayores ---> ',w);
end;
procedure HallaIndMax(var arreglo : Tabla);
begin
max:= arreglo[1]; (* hallar el maximo *)
for k:= 2 to N do
begin
if arreglo[k] > max then
begin
max:= arreglo[k];
aux := k;
end;
end;
writeln;
writeln(' Valor Maximo ---> ',max);
writeln('-------------------------<>-------------------------');
writeln;
writeln(' HallaIndMax ---> ',aux);
writeln('-------------------------<>-------------------------');
end;
procedure Orden(arreglo : Tabla);
var aux1, i : integer;
begin
i := 1;
while (i < N) and (arreglo[i] < arreglo[i+1]) do
i := i + 1;
if i < N then
writeln('Desordenado')
else
writeln('Ordenado');
end;
begin
Ingresoentero(entero);
LeerArreglo(arreglo);
writeln('-------------------------<>-------------------------');
Contar(entero,arreglo);
writeln('-------------------------<>-------------------------');
HallaIndMax(arreglo);
writeln('-------------------------<>-------------------------');
Orden(arreglo);
end. |
unit mRecon;
{
Monster Speech 1.1.0
written by Chen Yu (monster)
E-Mail: mftp@21cn.com ICQ UIN: 6740755
Homepage: http://homepages.msn.com/RedmondAve/mftp/
Suggestions and bug reports are warm welcomed.
This file used a Delphi translation of Speech API from
Project JEDI, and full package of this translation can
be found on JEDI's web page: http://www.delphi-jedi.org/
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComObj, ActiveX, Speech;
{$include mspeech.msg}
type
EMRecognitionException = class(Exception);
TMRecognition = class(TComponent)
private
FEngines: TStrings;
FEngineStarted: Boolean;
FIAMD: IAudioMultimediaDevice;
FIEnumSRShare: IEnumSRShare;
FInit: Boolean;
FISRCentral: ISRCentral;
FISREnum: ISREnum;
FVersion, DummyS: String;
PModeInfo: PSRModeInfo;
procedure Init;
procedure BeforeSelectEngine;
procedure PostSelectEngine;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SelectEngine(EngineName: String); overload;
procedure SelectEngine(EngineMode: SRModeInfo); overload;
property Engines: TStrings read FEngines;
published
property Version: String read FVersion write DummyS;
end;
implementation
{ TMRecognition: implementation of DirectSpeechRecognition }
{ construction/deconstruction }
constructor TMRecognition.Create(AOwner: TComponent);
begin
inherited;
FEngines := TStringList.Create;
FVersion := 'Monster Speech 1.1.0';
Init;
end;
destructor TMRecognition.Destroy;
begin
FInit := False;
FEngines.Free;
if Assigned(PModeInfo) then Dispose(PModeInfo);
inherited;
end;
procedure TMRecognition.Init;
var ModeInfo: SRModeInfo;
EngineCount: Integer;
begin
FInit := True;
FEngineStarted := False;
try
{ Enumerate engines }
OleCheck(CoCreateInstance(CLSID_SREnumerator, Nil, CLSCTX_ALL, IID_ISREnum, FISREnum));
OleCheck(CoCreateInstance(CLSID_SRShare, Nil, CLSCTX_ALL, IID_IEnumSRShare, FIEnumSRShare));
OleCheck(FISREnum.Reset);
OleCheck(FISREnum.Next(1, ModeInfo, @EngineCount));
while EngineCount > 0 do
begin
FEngines.Add(String(ModeInfo.szModeName));
OleCheck(FISREnum.Next(1, ModeInfo, @EngineCount));
end;
except
FInit := False;
end;
end;
procedure TMRecognition.BeforeSelectEngine;
begin
{ Check if audio device is available }
OleCheck(CoCreateInstance(CLSID_MMAudioSource, nil, CLSCTX_ALL,
IID_IAudioMultiMediaDevice, FIAMD));
end;
procedure TMRecognition.SelectEngine(EngineName: String);
var Index, EngineCount: Integer;
ModeInfo: SRModeInfo;
begin
if not FInit then
raise EMRecognitionException.Create(msgRENotInited);
Index := Engines.IndexOf(EngineName);
if Index < 0 then
raise EMRecognitionException.Create(msgRENotFound);
BeforeSelectEngine;
{ Select Engine }
FEngineStarted := True;
try
OleCheck(FISREnum.Reset);
OleCheck(FISREnum.Skip(Index));
OleCheck(FISREnum.Next(1, ModeInfo, @EngineCount));
if Assigned(PModeInfo) then Dispose(PModeInfo);
New(PModeInfo);
PModeInfo^ := ModeInfo;
OleCheck(FISREnum.Select(PModeInfo^.gModeID,
FISRCentral, IUnknown(FIAMD)));
PostSelectEngine;
except
FEngineStarted := False;
end;
end;
procedure TMRecognition.SelectEngine(EngineMode: SRModeInfo);
var FISRFind: ISRFind;
ModeInfo: SRModeInfo;
begin
if not FInit then
raise EMRecognitionException.Create(msgRENotInited);
BeforeSelectEngine;
FEngineStarted := True;
{ Find and Select Engine }
try
try
OleCheck(CoCreateInstance(CLSID_SREnumerator, Nil, CLSCTX_ALL, IID_ISRFind, FISRFind));
OleCheck(FISRFind.QueryInterface(IID_ISREnum, FISREnum));
OleCheck(FISRFind.Find(EngineMode, nil, ModeInfo));
if Assigned(PModeInfo) then Dispose(PModeInfo);
New(PModeInfo);
PModeInfo^ := ModeInfo;
OleCheck(FISRFind.Select(PModeInfo^.gModeID,
FISRCentral, IUnknown(FIAMD)));
PostSelectEngine;
except
FEngineStarted := False;
end;
finally
FISRFind._Release;
end;
end;
procedure TMRecognition.PostSelectEngine;
begin
end;
end.
|
//---------------------------------
//----------LOpLib 1.0-------------
//----------13.08.2017-------------
//-------Maximilian Eckert---------
//---------------------------------
unit LOpLib;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, GLU, GL, OpenGLContext;
procedure Setup(r, g, b: REAL);
procedure MakeSquare(width, height, r, g, b, layer: REAL);
procedure MakeCube(width, height, depth, r, g, b: REAL);
procedure MakePyramid(right, left, up, down, front, back, r, g, b: REAL);
implementation
//-----------SETUP----------
procedure Setup(r, g, b: REAL);
begin
glClearColor(r, g, b, 1.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glLoadIdentity;
GLMatrixMode(GL_MODELVIEW);
glEnable(GL_Depth_Test);
end;
//-----------SQUARE----------
procedure MakeSquare(width, height, r, g, b, layer: REAL);
var right, left, top, bottom: REAL;
begin
right := width / 2;
left := -(width / 2);
top := height / 2;
bottom := -(height / 2);
layer := -(layer / 100); //Maximum layer count
glColor3F(r, g, b);
glBegin(GL_POLYGON);
glVertex3f(left, top, layer); //left-top
glVertex3f(right, top, layer); //right-top
glVertex3f(right, bottom, layer); //right-bottom
glVertex3f(left, bottom, layer); //left-bottom
glEnd();
end;
//-----------CUBE----------
procedure MakeCube(width, height, depth, r, g, b: REAL);
var right, left, top, bottom, front, back: REAL;
begin
right := width / 2;
left := -(width / 2);
top := height / 2;
bottom := -(height / 2);
front := depth / 2;
back := -(depth / 2);
glBegin(GL_QUADS);
glColor3f(r, g, b);
glVertex3f(left, top, front); //front
glVertex3f(right, top, front);
glVertex3f(right, bottom, front);
glVertex3f(left, bottom, front);
glVertex3f(left, top, back); //back
glVertex3f(right, top, back);
glVertex3f(right, bottom, back);
glVertex3f(left, bottom, back);
glVertex3f(left, top, front); //left
glVertex3f(left, top, back);
glVertex3f(left, bottom, back);
glVertex3f(left, bottom, front);
glVertex3f(right, bottom, front); //right
glVertex3f(right, bottom, back);
glVertex3f(right, top, back);
glVertex3f(right, top, front);
glVertex3f(left, top, front); //up
glVertex3f(left, top, back);
glVertex3f(right, top, back);
glVertex3f(right, top, front);
glVertex3f(left, bottom, front); //down
glVertex3f(left, bottom, back);
glVertex3f(right, bottom, back);
glVertex3f(right, bottom, front);
glEnd;
end;
//---------PYRAMID----------
procedure MakePyramid(right, left, up, down, front, back, r, g, b: REAL);
begin
glbegin(GL_POLYGON);
glColor3f(r, g, b);
glVertex3f(left, down, front); //front
glVertex3f(right, down, front);
glVertex3f(0, up, 0);
glend;
glbegin(GL_POLYGON);
glVertex3f(left, down, back); //back
glVertex3f(right, down, back);
glVertex3f(0, up, 0);
glend;
glbegin(GL_POLYGON);
glVertex3f(right, down, front); //right
glVertex3f(right, down, back);
glVertex3f(0, up, 0);
glend;
glbegin(GL_POLYGON);
glVertex3f(left, down, front); //left
glVertex3f(left, down, back);
glVertex3f(0, up, 0);
glend;
glBegin(GL_QUADS);
glVertex3f(left, down, front); //bottom
glVertex3f(left, down, back);
glVertex3f(right, down, back);
glVertex3f(right, down, front);
glEnd;
end;
end.
|
unit PlotReaders;
interface
uses
Classes, SysUtils,
SpectrumTypes;
type
TByteSet = set of Byte;
TDecimalSeparator1 = (ds1Point, ds1Comma);
TOpenDialogKing = (odkSimple, odkTable);
TDataReader = class;
TDataReaderClass = class of TDataReader;
{
Параметры добавления графика на диаграмму.
Объект может создаваться где угодно (обработчик какого-либо экшена и т.п.),
затем передается в процедуру TPlot.AddGraph, которая является процедурой
верхнего уровня для создания графиков. Там параметры уточняются, передаются
в TGraph.Load(TGraphAppendParams), где и происходит реальное чтение данных
в соответствии с заданными параметрами. Затем объект-параметр уничтожается
(т.е. в том месте, где его создали, не нужно заботиться о его уничтожении).
При загрузке данных создается ридер, читающий данные, тип которого указан в
поле Reader, объект-график дополнительно уточняет параметры и предает их
созданному ридеру. Если же тип ридера не задан, то предполагается что данные
кем-то откуда-то уже прочитаны, указатели на них содержатся в полях ValuesX/Y
и никакой ридер использовать не нужно.
} (*
TGraphAppendParams = class
public
// Диаграмма, на которую добавляется график.
// В частности, может использоваться ридерами, создающими несколько графиков
// из одного источника (как TTableDataReader), для вызова TPlot.AddGraph
Plot: TObject;
// Способ чтения данных. Может не указываться, если заданы готовые
// массивы данных (указатели ValuesX/Y).
Reader: TDataReaderClass;
// Источник данных. Если задан поток, то это просто информация о том, из
// чего этот поток был создан. Иначе предполагается, что это имя файла, из
// которого нужно создать поток (в общем случае данные читаются из потока).
// В зависимости от типа ридера, может вообще не использоваться.
Source: String;
// Заголовок графика. Если не задано, то используется Source (см. TGraph.Load)
Title: String;
// Поток, из которого читаются данные. Передается графику, а потом и ридеру
// откуда-то извне или создается самим ридером (из файла указанного в Source
// или откуда угодно, в зависимости от типа ридера).
Stream: TStream;
// Указывыют ридеру, куда складывать считанные данные.
// Это либо указатели на аналогичные поля объекта-графика (TGraph), либо
// указатели на массивы, находящиеся в другом месте (см. TTableDataReader),
// которые после чтения (или вместо чтения) копируются в объект-график.
ValuesX: PValueArray;
ValuesY: PValueArray;
// Дополнтельный параметр, интерпретируется конкретным ридером.
// Например, при открытии RS-файла из архива, это - указатель на поток
// дополнительно открытого файла параметров спектра.
AuxParam: TObject;
// Если не задано ни одного параметра, то в процедуру создания графиков
// передаваются имена файлов и тип ридера определяется то типу файлов.
constructor Create(AReader: TDataReaderClass = nil;
const ASource: String = ''; AStream: TStream = nil); overload;
// Данные уже загружены и передаются графику в готовом виде.
constructor Create(AValuesX, AValuesY: PValueArray;
const ASource: String = ''; const ATitle: String = ''); overload;
// Способ создания данных определяется самим графиком по типу объекта.
constructor Create(AAuxParam: TObject); overload;
end; *)
TDataReader = class
const
ValueInc = 1000;
protected
FValueIndex: Integer;
FValueCount: Integer;
FLinesRead: Integer;
FValuesX: TValueArray;
FValuesY: TValueArray;
FResults: TGraphRecs;
procedure ResetResults;
procedure ResetValues;
procedure AddResult(var X, Y: TValueArray);
procedure CheckValuesSize; inline;
function GetResultCount: Integer;
function GetResult(Index: Integer): TGraphRec;
public
function Configure: Boolean; virtual;
procedure Read(const AFileName: String); virtual;
procedure Read(AStream: TStream); virtual; abstract;
property ResultCount: Integer read GetResultCount;
property Result[Index: Integer]: TGraphRec read GetResult;
class function IsMulti: Boolean; virtual;
class procedure FileFilters(Strings: TStrings); virtual;
class procedure FileExts(Strings: TStrings); virtual;
end;
// It's a holder for all TDataReaders that can read data from file.
// Use RegisterReader in initialization section to add a new reader
// to known file-readers list. Each file reader will be presented in
// its own line in filter list of 'Add Graph' open file dialog.
TFileReaders = class
private class var
FReaders: TList;
FFilters: TStringList;
private
class function GetReadersCount: Integer; static;
class function GetReader(Index: Integer): TDataReaderClass; static;
public
class function FileFilters: String;
class function ReaderByFilter(FilterIndex: Integer): TDataReaderClass;
class function ReaderByExt(const FileName: String): TDataReaderClass;
class procedure RegisterReader(AClass: TDataReaderClass);
class property ReadersCount: Integer read GetReadersCount;
class property Readers[Index: Integer]: TDataReaderClass read GetReader;
end;
TCSVDataReader = class(TDataReader)
const
StrInc = 256;
BufSize = 4096;
protected
FValDelimiters: TByteSet;
FFloatFmt: TFormatSettings;
FOneColumnX: TValue;
protected
procedure ProcessString(const Str: String); virtual;
procedure InitValueDelimiters; virtual;
procedure InitFloatFormat; virtual;
public
procedure Read(AStream: TStream); override;
end;
TCSVFileReader = class(TCSVDataReader)
public
class procedure FileFilters(Strings: TStrings); override;
class procedure FileExts(Strings: TStrings); override;
end;
(*
TTableGraph = record
ColumnX: Byte;
ColumnY: Byte;
Title: String;
OneColumnX: TValue;
ValueCount: Integer;
ValueIndex: Integer;
ValuesX: TValueArray;
ValuesY: TValueArray;
end;
TTableGraphs = array of TTableGraph;
TTableDataReader = class(TCSVDataReader)
protected
procedure ProcessString(const Str: String); override;
procedure InitValueDelimiters; override;
procedure InitFloatFormat; override;
public
//class var SkipFirstLines: Integer;
//class var DecSeparator: TDecimalSeparator1;
//class var ValueSeparators: String;
class var PreviewLineCount: Integer;
public
Graphs: TTableGraphs;
function Configure: Boolean; override;
procedure ReadValues; override;
class function IsMulti: Boolean; override;
end;
TTableFileReader = class(TTableDataReader)
public
//constructor Create(Params: TGraphAppendParams); override;
end;
TClipbrdDataReader = class(TCSVDataReader)
private
ValuesX: TValueArray;
ValuesY: TValueArray;
Props: TStringList;
ProcessingProps: Boolean;
procedure ProcessData;
protected
procedure ProcessString(const Str: String); override;
public
//constructor Create(Params: TGraphAppendParams); override;
destructor Destroy; override;
procedure ReadValues; override;
class function IsMulti: Boolean; override;
end;
TClipbrdTableReader = class(TTableDataReader)
public
//constructor Create(Params: TGraphAppendParams); override;
end;
function RefineOpener(AOpener: TDataReaderClass; const AFileName: String = ''): TDataReaderClass;
function FileIsRS(const AFileName: String): Boolean;
function FileIsArchive(const AFileName: String): Boolean;
const
CDefaultFolderFilter = '*.txt;*.dat';
*)
implementation
uses
{Controls,} Clipbrd,
OriStrings, OriUtils,
PlotReadersAux, SpectrumStrings, SpectrumSettings{, WinOpenTable};
(*
function RefineOpener(AOpener: TDataReaderClass; const AFileName: String = ''): TDataReaderClass;
begin
if FileIsRS(AFileName)
then Result := TRSFileReader
else Result := AOpener;
end;
function FileIsRS(const AFileName: String): Boolean;
var L: Integer;
begin
L := Length(AFileName);
Result := (L > 4) and (AFileName[L] in ['1','2','3','4']) and
(AFileName[L-1] in ['r','R']) and (AFileName[L-2] in ['t','T']) and (AFileName[L-3] = '.');
end;
function FileIsArchive(const AFileName: String): Boolean;
var
Ext: String;
begin
Ext := ExtractFileExt(AFileName);
Result := SameText(Ext, '.rar') or SameText(Ext, '.zip');
end;
{%region TGraphAppendParams}
constructor TGraphAppendParams.Create(AReader: TDataReaderClass; const ASource: String; AStream: TStream);
begin
Reader := AReader;
Source := ASource;
Stream := AStream;
end;
constructor TGraphAppendParams.Create(AValuesX, AValuesY: PValueArray; const ASource, ATitle: String);
begin
Title := ATitle;
Source := ASource;
ValuesX := AValuesX;
ValuesY := AValuesY;
end;
constructor TGraphAppendParams.Create(AAuxParam: TObject);
begin
AuxParam := AAuxParam;
end;
{%endregion}
*)
{%region TDataReader}
procedure TDataReader.Read(const AFileName: String);
var
S: TStream;
begin
S := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Read(S);
finally
S.Free;
end;
end;
function TDataReader.Configure: Boolean;
begin
Result := True;
end;
procedure TDataReader.ResetResults;
begin
FResults := nil;
end;
procedure TDataReader.ResetValues;
begin
FValueCount := 0;
FValueIndex := 0;
FLinesRead := 0;
FValuesX := nil;
FValuesY := nil;
end;
procedure TDataReader.AddResult(var X, Y: TValueArray);
var
L: Integer;
begin
L := Length(FResults);
SetLength(FResults, L+1);
FResults[L].X := X;
FResults[L].Y := Y;
end;
procedure TDataReader.CheckValuesSize;
begin
if FValueIndex = FValueCount then
begin
Inc(FValueCount, ValueInc);
SetLength(FValuesX, FValueCount);
SetLength(FValuesY, FValueCount);
end;
end;
class function TDataReader.IsMulti: Boolean;
begin
Result := False;
end;
function TDataReader.GetResultCount: Integer;
begin
Result := Length(FResults);
end;
function TDataReader.GetResult(Index: Integer): TGraphRec;
begin
Result := FResults[Index];
end;
class procedure TDataReader.FileFilters(Strings: TStrings);
begin
// do nothing
end;
class procedure TDataReader.FileExts(Strings: TStrings);
begin
// do nothing
end;
{%endregion}
{%region TCSVDataReader}
{function TCSVDataReader.ReadString: String;
var
I, J, L: Integer;
P: Int64;
Buf: array[0..255] of Char;
begin
I := 0;
L := 0;
P := Stream.Position; // backup pos
while Stream.Position < Stream.Size do
for J := 0 to Stream.Read(Buf, 255)-1 do
case Buf[J] of
// Вроде как ноль - стандартный детектор бинарного фйла; например, так
// определяет "бинарность" AkelPad. Но нулевые байты встречаются, например,
// в файлах samples\climate\*.per, а в остальном это нормальные текстовые файлы
// и как-то странно их не читать из-за этого нуля. Поэтому нуль-байт трактуем
// как конец строки, а бинарность определяем по наличию "малых" значений (< #9).
// #$0:
// raise ESpectrumError.CreateDK('Err_IllegalChar');
#$A, #$0:
begin
Stream.Position := P + Int64(I) + 1;
SetLength(Result, I);
Exit;
end;
#$D:
begin
Inc(P);
Continue;
end
else
begin
if Ord(Buf[J]) < 9 then
raise ESpectrumError.Create(Err_IllegalChar);
Inc(I);
if I > L then
begin
Inc(L, 256);
SetLength(Result, L);
end;
Result[I] := Buf[J];
end;
end;
SetLength(Result, I);
end; }
//procedure TCSVDataReader.SkipLines(Amount: Integer);
//var
// I: Integer;
//begin
// I := 0;
// while (I < Amount) and (Stream.Position < Stream.Size) do
// begin
// ReadString;
// Inc(I);
// end;
//end;
procedure TCSVDataReader.InitValueDelimiters;
var I: Integer;
begin
FValDelimiters := [];
for I := 1 to Length(Preferences.ValueSeparators) do
Include(FValDelimiters, Ord(Preferences.ValueSeparators[I]));
Include(FValDelimiters, $9);
Include(FValDelimiters, $20);
end;
procedure TCSVDataReader.InitFloatFormat;
begin
case Preferences.DecSeparator of
dsPoint: FFloatFmt.DecimalSeparator := '.';
dsComma: FFloatFmt.DecimalSeparator := ',';
else FFloatFmt.DecimalSeparator := DecimalSeparator;
end;
FFloatFmt.ThousandSeparator := #0;
end;
procedure TCSVDataReader.Read(AStream: TStream);
var
I: Integer;
Size, Pos: Int64;
BufRead: Longint;
InBuffer: array [0..BufSize-1] of Byte;
InByte: Byte;
InStr: String;
PrevSeparator: Boolean;
StrIndex, StrLen: Integer;
Stream: TStream;
begin
FOneColumnX := Preferences.OneColumnFirst;
Stream := AStream;
ResetResults;
ResetValues;
InitFloatFormat;
InitValueDelimiters;
// working line
FLinesRead := 0;
StrIndex := 0;
StrLen := StrInc;
SetLength(InStr, StrLen);
PrevSeparator := False;
Pos := 0;
Stream.Position := Pos;
Size := Stream.Size;
while Pos < Size do
begin
Stream.Position := Pos;
// Read next buffer
BufRead := Stream.Read(InBuffer, BufSize);
Inc(Pos, BufRead);
// Process buffer
for I := 0 to BufRead-1 do
begin
InByte := InBuffer[I];
// Process next byte
case InByte of
$A, $D, $0: // EOL founded
begin
// Working line is empty yet
if StrIndex = 0 then Continue;
// Part of working line (InStr) containing current line of file
// ends with double #0. Single #0 is used as values delimiter.
Inc(StrIndex);
InStr[StrIndex] := #0;
if StrIndex = StrLen then
begin
Inc(StrLen, StrInc);
SetLength(InStr, StrLen);
end;
InStr[StrIndex+1] := #0;
Inc(FLinesRead);
ProcessString(InStr);
PrevSeparator := False;
StrIndex := 0;
Continue;
end;
else // Meaning char - add to working line
begin
if Ord(InByte) < 9 then // May be file is binary
raise ESpectrumError.Create(Err_IllegalChar);
if InByte in FValDelimiters then
if not PrevSeparator then // Doubled delimiters is ignored
begin
if StrIndex > 0 then // Delimiter at the begining of line - throw it away
begin // All delimiters are replaced with zero to speed-up ProcessString
Inc(StrIndex);
InStr[StrIndex] := #0;
end;
PrevSeparator := True;
end
else Continue
else
begin
PrevSeparator := False;
Inc(StrIndex);
InStr[StrIndex] := Chr(InByte);
end;
end;
end; // Case InByte of
if StrIndex = StrLen then
begin
Inc(StrLen, StrInc);
SetLength(InStr, StrLen);
end;
end; // Process buffer
end; // Process stream
// Process the last line in file
if StrIndex > 0 then
begin
Inc(StrIndex);
InStr[StrIndex] := #0;
if StrIndex = StrLen then
begin
Inc(StrLen, StrInc);
SetLength(InStr, StrLen);
end;
InStr[StrIndex+1] := #0;
Inc(FLinesRead);
ProcessString(InStr);
end;
if FValuesX <> nil then SetLength(FValuesX, FValueIndex);
if FValuesY <> nil then SetLength(FValuesY, FValueIndex);
AddResult(FValuesX, FValuesY);
end;
procedure TCSVDataReader.ProcessString(const Str: String);
var
P, P1: PChar;
Value: Extended;
Value1, Value2: TValue;
ValueCount: Byte;
begin
if FLinesRead > Preferences.SkipFirstLines then
begin
ValueCount := 0;
P := PChar(Str);
P1 := P;
repeat
Inc(P);
if P^ = #0 then
begin
if not TextToFloat(P1, Value, fvExtended, FFloatFmt) then
if Preferences.DecSeparator = dsAuto then
begin // Toggle decimal separator
if FFloatFmt.DecimalSeparator = '.'
then FFloatFmt.DecimalSeparator := ','
else FFloatFmt.DecimalSeparator := '.';
if not TextToFloat(P1, Value, fvExtended, FFloatFmt)
then Exit; // Skip bad line
end else Exit; // Skip bad line
case ValueCount of
0:
begin
Value1 := Value;
Inc(ValueCount);
end;
1:
begin
Value2 := Value;
Inc(ValueCount);
Break;
end;
end;
P1 := P + 1;
end;
until P1^ = #0;
CheckValuesSize;
case ValueCount of
1:
begin
FValuesX[FValueIndex] := FOneColumnX;
FValuesY[FValueIndex] := Value1;
FOneColumnX := FOneColumnX + Preferences.OneColumnInc;
Inc(FValueIndex);
end;
2:
begin
FValuesX[FValueIndex] := Value1;
FValuesY[FValueIndex] := Value2;
Inc(FValueIndex);
end;
end;
end;
end;
{%endregion}
{%region TCSVFileReader}
class procedure TCSVFileReader.FileFilters(Strings: TStrings);
begin
Strings.Add(Filter_TXT);
Strings.Add(Filter_CSV);
Strings.Add(Filter_DAT);
Strings.Add(Filter_AllCSV);
end;
class procedure TCSVFileReader.FileExts(Strings: TStrings);
begin
Strings.Add('txt');
Strings.Add('dat');
Strings.Add('csv');
end;
{%endregion}
(*
{%region 'TTableDataReader'}
class function TTableDataReader.IsMulti: Boolean;
begin
Result := True;
end;
procedure TTableDataReader.InitValueDelimiters;
var I: Integer;
begin
FValDelimiters := [];
for I := 1 to Length(ValueSeparators) do
Include(FValDelimiters, Ord(ValueSeparators[I]));
Include(FValDelimiters, $9);
Include(FValDelimiters, $20);
end;
procedure TTableDataReader.InitFloatFormat;
begin
case DecSeparator of
dsComma: FFloatFmt.DecimalSeparator := ',';
else FFloatFmt.DecimalSeparator := '.';
end;
FFloatFmt.ThousandSeparator := #0;
end;
procedure TTableDataReader.ReadValues;
var i: Integer;
begin
for i := 0 to Length(Graphs)-1 do
Graphs[i].OneColumnX := OneColumnFirst;
inherited;
// TODO
//for i := 0 to Length(Graphs)-1 do
// with Graphs[i] do
// begin
// SetLength(ValuesX, ValueIndex);
// SetLength(ValuesY, ValueIndex);
// TPlot(FPlot).AddGraph(TGraphAppendParams.Create(
// @ValuesX, @ValuesY, FSource, Title));
// end;
end;
procedure TTableDataReader.ProcessString(const Str: String);
const
ValInc = 25;
var
i: Integer;
P, P1: PChar;
Parts: array of PChar;
ValueY, ValueX: Extended;
Index, Len: Byte;
begin
if FLinesRead > SkipFirstLines then
begin
Index := 0;
Len := ValInc;
SetLength(Parts, Len);
P := PChar(Str);
P1 := P;
repeat
Inc(P);
if P^ = #0 then
begin
Parts[Index] := P1;
Inc(Index);
if Index = Len then
begin
Inc(Len, ValInc);
SetLength(Parts, Len);
end;
P1 := P + 1;
end;
until P1^ = #0;
for i := 0 to Length(Graphs)-1 do
with Graphs[i] do
begin
if ValueIndex = ValueCount then
begin
Inc(ValueCount, ValueInc);
SetLength(ValuesX, ValueCount);
SetLength(ValuesY, ValueCount);
end;
if (ColumnX > Len) or (ColumnY > Len) then Continue;
if ColumnX = 0 then // не указана колонка для X
begin
ValueX := OneColumnX;
OneColumnX := OneColumnX + OneColumnInc;
end
else
begin
if ColumnX > Index then Continue;
if not TextToFloat(Parts[ColumnX-1], ValueX, fvExtended, FFloatFmt) then Continue;
end;
if (ColumnY < 1) or (ColumnY > Index) then Continue;
if not TextToFloat(Parts[ColumnY-1], ValueY, fvExtended, FFloatFmt) then Continue;
ValuesX[ValueIndex] := ValueX;
ValuesY[ValueIndex] := ValueY;
Inc(ValueIndex);
end;
end;
end;
function TTableDataReader.Configure: Boolean;
begin
Result := False; // TODO TwndOpenTable.Create(Self).ShowModal = mrOk;
end;
{%endregion}
{%region TTableFileReader}
//constructor TTableFileReader.Create(Params: TGraphAppendParams);
//begin
// inherited;
// OpenSourceAsFile;
//end;
{%endregion}
{%region TClipbrdDataReader}
//constructor TClipbrdDataReader.Create(Params: TGraphAppendParams);
//begin
// inherited;
//
// FValuesX := @ValuesX;
// FValuesY := @ValuesY;
//
// FStream := TStringStream.Create(Clipboard.AsText);
// FOwnedStream := True;
//end;
destructor TClipbrdDataReader.Destroy;
begin
Props.Free;
inherited;
end;
class function TClipbrdDataReader.IsMulti: Boolean;
begin
Result := True;
end;
procedure TClipbrdDataReader.ReadValues;
begin
inherited;
ProcessData;
end;
procedure TClipbrdDataReader.ProcessData;
//var
// Graph: TGraph;
begin
//if Length(ValuesX) > 0 then
//begin
// SetLength(ValuesX, FValueIndex);
// SetLength(ValuesY, FValueIndex);
// Graph := TPlot(FPlot).AddGraph(
// TGraphAppendParams.Create(FValuesX, FValuesY, FSource));
// if Assigned(Graph) and Assigned(Props) then
// begin
// with TPropSaver.CreateInMemory do
// try
// SetStrings(Props, True);
// ReadLineSeries('PROPERTIES', Graph.Series);
// finally
// Free;
// end;
// FreeAndNil(Props);
// end;
// FValueIndex := 0;
// FValueCount := 0;
// ValuesX := nil;
// ValuesY := nil;
//end;
end;
procedure TClipbrdDataReader.ProcessString(const Str: String);
begin
if Str[1] = '[' then
begin
if SameText(Copy(Str, 1, 12), '[PROPERTIES]') then
begin
// Построить график из предыдущей DATA-секции, если она была
ProcessData;
Props := TStringList.Create;
Props.Add('[PROPERTIES]');
ProcessingProps := True;
end
else if SameText(Copy(Str, 1, 6), '[DATA]') then
begin
// Построить график из предыдущей DATA-секции, если она была.
// (Случай, когда в буфере несколько графиков без свойств, только данные)
ProcessData;
// Заканчиваем собирать строки формата.
// (Если до этой DATA-секции была PROPERTIES-секция)
ProcessingProps := False;
end;
end
else if ProcessingProps then
begin
Props.Add(LeftTill(Str, #0));
end
else inherited;
end;
{%endregion}
{%region TClipbrdTableReader}
//constructor TClipbrdTableReader.Create(Params: TGraphAppendParams);
//begin
// inherited;
//
// FStream := TStringStream.Create(Clipboard.AsText);
// FOwnedStream := True;
//end;
{%endregion}
*)
{%region TFileReaders}
class function TFileReaders.GetReadersCount: Integer;
begin
Result := FReaders.Count;
end;
class function TFileReaders.GetReader(Index: Integer): TDataReaderClass;
begin
Result := TDataReaderClass(FReaders[Index]);
end;
class procedure TFileReaders.RegisterReader(AClass: TDataReaderClass);
begin
if FReaders = nil then FReaders := TList.Create;
FReaders.Add(Pointer(AClass));
end;
class function TFileReaders.ReaderByFilter(FilterIndex: Integer): TDataReaderClass;
begin
Result := TDataReaderClass(FFilters.Objects[FilterIndex-1]);
end;
class function TFileReaders.ReaderByExt(const FileName: String): TDataReaderClass;
var
I, J: Integer;
Ext: String;
Strs: TStringList;
begin
Ext := ExtractFileExtNoDot(FileName);
Strs := TStringList.Create;
try
for I := 0 to FReaders.Count-1 do
begin
Strs.Clear;
Readers[I].FileExts(Strs);
for J := 0 to Strs.Count-1 do
if SameText(Ext, Strs[J]) then
begin
Result := Readers[I];
Exit;
end;
end;
finally
Strs.Free;
end;
Result := TCSVFileReader; // default reader
end;
class function TFileReaders.FileFilters: String;
var
I, J: Integer;
R: TDataReaderClass;
begin
if FFilters = nil then
FFilters := TStringList.Create;
FFilters.Clear;
for I := 0 to FReaders.Count-1 do
begin
R := Readers[I];
J := FFilters.Count;
R.FileFilters(FFilters);
for J := J to FFilters.Count-1 do
FFilters.Objects[J] := TObject(R);
end;
FFilters.Add(Filter_All);
Result := '';
for I := 0 to FFilters.Count-1 do
Result := Result + FFilters[I];
end;
{%endregion}
initialization
TFileReaders.RegisterReader(TCSVFileReader);
TFileReaders.RegisterReader(TRSFileReader);
TFileReaders.RegisterReader(TOOFileReader);
TFileReaders.RegisterReader(TDagatronFileReaders);
finalization
TFileReaders.FReaders.Free;
TFileReaders.FFilters.Free;
end.
|
unit Vigilante.Configuracao.Observer.Impl;
interface
uses
System.Generics.Collections, Vigilante.Configuracao.Observer,
Vigilante.Configuracao;
type
TConfiguracaoSubject = class(TInterfacedObject, IConfiguracaoSubject)
private
FListaObserver: TList<IConfiguracaoObserver>;
public
constructor Create;
destructor Destroy; override;
procedure Adicionar(const AConfiguracaoObserver: IConfiguracaoObserver);
procedure Notificar(const AConfiguracao: IConfiguracao);
procedure Remover(const AConfiguracaoObserver: IConfiguracaoObserver);
end;
implementation
constructor TConfiguracaoSubject.Create;
begin
FListaObserver := TList<IConfiguracaoObserver>.Create;
end;
destructor TConfiguracaoSubject.Destroy;
begin
FListaObserver.Free;
inherited;
end;
procedure TConfiguracaoSubject.Adicionar(
const AConfiguracaoObserver: IConfiguracaoObserver);
begin
if FListaObserver.Contains(AConfiguracaoObserver) then
Exit;
FListaObserver.Add(AConfiguracaoObserver);
end;
procedure TConfiguracaoSubject.Notificar(const AConfiguracao: IConfiguracao);
var
_observer: IConfiguracaoObserver;
begin
for _observer in FListaObserver do
_observer.ConfiguracoesAlteradas(AConfiguracao);
end;
procedure TConfiguracaoSubject.Remover(
const AConfiguracaoObserver: IConfiguracaoObserver);
begin
if not FListaObserver.Contains(AConfiguracaoObserver) then
Exit;
FListaObserver.Remove(AConfiguracaoObserver);
end;
end.
|
unit IdSocketHandle;
interface
uses
Classes,
IdException,
IdGlobal,
IdStack, IdStackConsts;
type
TIdSocketHandle = class;
TIdSocketHandles = class(TOwnedCollection)
protected
FDefaultPort: integer;
function GetItem(Index: Integer): TIdSocketHandle;
procedure SetItem(Index: Integer; const Value: TIdSocketHandle);
public
constructor Create(AOwner: TComponent); reintroduce;
function Add: TIdSocketHandle; reintroduce;
function BindingByHandle(const AHandle: TIdStackSocketHandle):
TIdSocketHandle;
property Items[Index: Integer]: TIdSocketHandle read GetItem write SetItem;
default;
property DefaultPort: integer read FDefaultPort write FDefaultPort;
end;
TIdSocketHandle = class(TCollectionItem)
protected
FHandle: TIdStackSocketHandle;
FHandleAllocated: Boolean;
FIP, FPeerIP: string;
FPort, FPeerPort: integer;
public
procedure Accept(ASocket: TIdStackSocketHandle);
procedure AllocateSocket(const ASocketType: Integer = Id_SOCK_STREAM;
const AProtocol: Integer = Id_IPPROTO_IP);
procedure Assign(Source: TPersistent); override;
procedure Bind;
procedure CloseSocket(const AResetLocal: boolean = True); virtual;
function Connect(const AFamily: Integer = Id_PF_INET): Integer; virtual;
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Listen(const anQueueCount: integer = 5);
function Readable(AMSec: Integer = IdTimeoutDefault): boolean;
function Recv(var ABuf; ALen, AFlags: Integer): Integer;
function RecvFrom(var ABuffer; const ALength, AFlags: Integer; var VIP:
string;
var VPort: Integer): Integer; virtual;
procedure Reset(const AResetLocal: boolean = True);
function Send(var Buf; len, flags: Integer): Integer;
procedure SendTo(const AIP: string; const APort: Integer; var ABuffer;
const ABufferSize: Integer);
procedure SetPeer(const asIP: string; anPort: integer);
procedure SetSockOpt(level, optname: Integer; optval: PChar; optlen:
Integer);
procedure UpdateBindingLocal;
procedure UpdateBindingPeer;
property HandleAllocated: Boolean read FHandleAllocated;
property Handle: TIdStackSocketHandle read FHandle;
property PeerIP: string read FPeerIP;
property PeerPort: integer read FPeerPort;
published
property IP: string read FIP write FIP;
property Port: integer read FPort write FPort;
end;
EIdSocketHandleError = class(EIdException);
EIdPackageSizeTooBig = class(EIdSocketHandleError);
EIdNotAllBytesSent = class(EIdSocketHandleError);
EIdCouldNotBindSocket = class(EIdSocketHandleError);
implementation
uses
IdAntiFreezeBase,
IdComponent,
IdResourceStrings;
procedure TIdSocketHandle.AllocateSocket(const ASocketType: Integer =
Id_SOCK_STREAM;
const AProtocol: Integer = Id_IPPROTO_IP);
begin
CloseSocket;
FHandle := GStack.CreateSocketHandle(ASocketType, AProtocol);
FHandleAllocated := True;
end;
procedure TIdSocketHandle.CloseSocket(const AResetLocal: boolean = True);
begin
if HandleAllocated then
begin
FHandleAllocated := False;
GStack.WSShutdown(Handle, Id_SD_Send);
GStack.WSCloseSocket(Handle);
Reset(AResetLocal);
end;
end;
function TIdSocketHandle.Connect(const AFamily: Integer = Id_PF_INET): Integer;
begin
result := GStack.WSConnect(Handle, AFamily, PeerIP, PeerPort);
if result <> Id_Socket_Error then
begin
UpdateBindingLocal;
UpdateBindingPeer;
end;
end;
destructor TIdSocketHandle.Destroy;
begin
CloseSocket;
inherited;
end;
function TIdSocketHandle.Recv(var ABuf; ALen, AFlags: Integer): Integer;
begin
result := GStack.WSRecv(Handle, ABuf, ALen, AFlags);
end;
function TIdSocketHandle.Send(var Buf; len, flags: Integer): Integer;
begin
result := GStack.WSSend(Handle, Buf, len, flags);
end;
procedure TIdSocketHandle.SetSockOpt(level, optname: Integer; optval: PChar;
optlen: Integer);
begin
GStack.CheckForSocketError(GStack.WSSetSockOpt(Handle, level, optname, optval,
optlen));
end;
procedure TIdSocketHandle.SendTo(const AIP: string; const APort: Integer; var
ABuffer;
const ABufferSize: Integer);
var
BytesOut: Integer;
begin
BytesOut := GStack.WSSendTo(Handle, ABuffer, ABufferSize, 0, AIP, APort);
if BytesOut = Id_SOCKET_ERROR then
begin
if GStack.WSGetLastError() = Id_WSAEMSGSIZE then
begin
raise EIdPackageSizeTooBig.Create(RSPackageSizeTooBig);
end
else
begin
GStack.CheckForSocketError;
end;
end
else
if BytesOut <> ABufferSize then
begin
raise EIdNotAllBytesSent.Create(RSNotAllBytesSent);
end;
end;
function TIdSocketHandle.RecvFrom(var ABuffer; const ALength, AFlags: Integer;
var VIP: string;
var VPort: Integer): Integer;
begin
result := GStack.WSRecvFrom(Handle, ABuffer, ALength, AFlags, VIP, VPort);
end;
procedure TIdSocketHandle.Bind;
begin
if GStack.CheckForSocketError(GStack.WSBind(Handle, Id_PF_INET, IP, Port),
[Id_WSAEADDRINUSE]) then
begin
raise EIdCouldNotBindSocket.Create(RSCouldNotBindSocket);
end;
UpdateBindingLocal;
end;
procedure TIdSocketHandle.SetPeer(const asIP: string; anPort: integer);
begin
FPeerIP := asIP;
FPeerPort := anPort;
end;
procedure TIdSocketHandle.Listen(const anQueueCount: integer);
begin
GStack.CheckForSocketError(GStack.WSListen(Handle, anQueueCount));
end;
procedure TIdSocketHandle.Accept(ASocket: TIdStackSocketHandle);
var
LAcceptedSocket: TIdStackSocketHandle;
begin
LAcceptedSocket := GStack.WSAccept(ASocket, FIP, FPort);
GStack.CheckForSocketError(LAcceptedSocket);
FHandle := LAcceptedSocket;
FHandleAllocated := True;
UpdateBindingLocal;
UpdateBindingPeer;
end;
constructor TIdSocketHandle.Create(ACollection: TCollection);
begin
inherited;
Reset;
if assigned(ACollection) then
begin
Port := TIdSocketHandles(ACollection).DefaultPort;
end;
end;
function TIdSocketHandle.Readable(AMSec: Integer = IdTimeoutDefault): boolean;
var
ReadList: TList;
begin
if not FHandleAllocated then
begin
raise EIdConnClosedGracefully.Create(RSConnectionClosedGracefully);
end;
if GAntiFreeze <> nil then
begin
if GAntiFreeze.Active then
begin
if AMSec = IdTimeoutInfinite then
begin
repeat
result := Readable(GAntiFreeze.IdleTimeOut);
until result;
exit;
end
else
if AMSec > GAntiFreeze.IdleTimeOut then
begin
result := Readable(AMSec - GAntiFreeze.IdleTimeOut);
if result then
begin
exit;
end
else
begin
AMSec := GAntiFreeze.IdleTimeOut;
end;
end;
end;
end;
ReadList := TList.Create;
try
ReadList.Add(Pointer(Handle));
Result := GStack.WSSelect(ReadList, nil, nil, AMSec) = 1;
TIdAntiFreezeBase.DoProcess(result = false);
finally ReadList.free;
end;
end;
procedure TIdSocketHandle.Assign(Source: TPersistent);
var
LSource: TIdSocketHandle;
begin
if ClassType <> Source.ClassType then
begin
inherited
end
else
begin
LSource := TIdSocketHandle(Source);
IP := LSource.IP;
Port := LSource.Port;
FPeerIP := LSource.PeerIP;
FPeerPort := LSource.PeerPort;
end;
end;
procedure TIdSocketHandle.UpdateBindingLocal;
var
LFamily: integer;
begin
GStack.WSGetSockName(Handle, LFamily, FIP, FPort);
end;
procedure TIdSocketHandle.UpdateBindingPeer;
var
LFamily: integer;
begin
GStack.WSGetPeerName(Handle, LFamily, FPeerIP, FPeerPort);
end;
procedure TIdSocketHandle.Reset(const AResetLocal: boolean = True);
begin
FHandleAllocated := False;
FHandle := Id_INVALID_SOCKET;
if AResetLocal then
begin
FIP := '';
FPort := 0;
end;
FPeerIP := '';
FPeerPort := 0;
end;
function TIdSocketHandles.Add: TIdSocketHandle;
begin
result := inherited Add as TIdSocketHandle;
result.Port := DefaultPort;
end;
function TIdSocketHandles.BindingByHandle(const AHandle: TIdStackSocketHandle):
TIdSocketHandle;
var
i: integer;
begin
Result := nil;
i := Count - 1;
while (i >= 0) and (Items[i].Handle <> AHandle) do
begin
dec(i);
end;
if i >= 0 then
begin
Result := Items[i];
end;
end;
constructor TIdSocketHandles.Create(AOwner: TComponent);
begin
inherited Create(AOwner, TIdSocketHandle);
end;
function TIdSocketHandles.GetItem(Index: Integer): TIdSocketHandle;
begin
result := TIdSocketHandle(inherited Items[index]);
end;
procedure TIdSocketHandles.SetItem(Index: Integer; const Value:
TIdSocketHandle);
begin
inherited SetItem(Index, Value);
end;
end.
|
// testing AND and OR statements
PROGRAM test11;
VAR
a, b, c : integer;
BEGIN
a := 1;
b := 0;
c := 1;
if (a AND b)
then WRITE(a);
else WRITE(b);
if (a OR b)
then WRITE(a);
else WRITE(b);
if (a AND c)
then WRITE(a);
else WRITE(b);
if (a OR c)
then WRITE(a);
else WRITE(b);
END.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSAdd;
interface
{$IFDEF MSWINDOWS}
uses SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, StdCtrls, Buttons;
{$ENDIF}
{$IFDEF LINUX}
uses SysUtils, Windows, Messages, Classes, QGraphics, QControls,
QForms, QStdCtrls, QButtons;
{$ENDIF}
type
TAddFields = class(TForm)
OkBtn: TButton;
CancelBtn: TButton;
GroupBox1: TGroupBox;
FieldsList: TListBox;
HelpBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
public
procedure SelectAll;
end;
var
AddFields: TAddFields;
implementation
{$IFDEF MSWINDOWS}
{$R *.dfm}
{$ENDIF}
uses LibHelp;
procedure TAddFields.SelectAll;
var
I: Integer;
begin
with FieldsList do
for I := 0 to Items.Count - 1 do
Selected[I] := True;
end;
procedure TAddFields.FormCreate(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
HelpContext := hcDDataSetAdd;
{$ENDIF}
end;
procedure TAddFields.HelpBtnClick(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
Application.HelpContext(HelpContext);
{$ENDIF}
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC DataSnap driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.DSProxyCpp;
interface
uses
System.Classes, Datasnap.DSCommonProxy, Datasnap.DSProxyDelphi, Datasnap.DSProxyWriter;
type
TDSClientProxyWriterCpp = class(TDSProxyWriter)
public
function CreateProxyWriter: TDSCustomProxyWriter; override;
function Properties: TDSProxyWriterProperties; override;
function FileDescriptions: TDSProxyFileDescriptions; override;
end;
TDSCustomCppProxyWriter = class abstract(TDSCustomExtendedProxyWriter)
public
constructor Create;
procedure WriteProxy; override;
protected
FUnitName: string;
procedure StartCppHeader; virtual; abstract;
procedure EndCppHeader; virtual; abstract;
procedure WriteFileHeader; override;
function GetDelphiTypeName(const Param: TDSProxyParameter): String; override;
procedure WriteInterface; override;
procedure WriteImplementation; override;
function GetAssignmentString: String; override;
function GetCreateDataSetReader(const Param: TDSProxyParameter): String; override;
function GetCreateParamsReader(const Param: TDSProxyParameter): String; override;
private
procedure WriteHeaderUses;
procedure WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean);
procedure WriteClassInterface(const ProxyClass: TDSProxyClass);
procedure WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod);
procedure WriteOutgoingParameter(const Lhs: String; const InRhs: String; const Param: TDSProxyParameter; const CommandName: String; const ParamName: String);
procedure WriteClassImplementation(const ProxyClass: TDSProxyClass);
end;
TDSCppProxyWriter = class(TDSCustomCppProxyWriter)
private
FStreamWriter: TStreamWriter;
FHeaderStreamWriter: TStreamWriter;
FWritingHeader: Boolean;
protected
function IncludeMethod(const ProxyMethod: TDSProxyMethod): Boolean; override;
procedure DerivedWrite(const Line: String); override;
procedure DerivedWriteLine; override;
procedure StartCppHeader; override;
procedure EndCppHeader; override;
public
property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter;
property HeaderStreamWriter: TStreamWriter read FHeaderStreamWriter write FHeaderStreamWriter;
destructor Destroy; override;
end;
const
sCPlusPlusBuilderFireDACProxyWriter = 'C++Builder FireDAC';
implementation
uses
Data.DBXClientResStrs, Data.DBXCommon, System.StrUtils, System.SysUtils,
FireDAC.Stan.Util;
function CanMarshal: Boolean;
begin
Result := False;
end;
constructor TDSCustomCppProxyWriter.Create;
begin
inherited Create;
FIndentIncrement := 2;
FIndentString := '';
FUnitName := ChangeFileExt(ExtractFileName(FUnitFileName), '');
end;
procedure TDSCustomCppProxyWriter.WriteProxy;
begin
FUnitName := ChangeFileExt(ExtractFileName(FUnitFileName), '');
inherited;
end;
procedure TDSCustomCppProxyWriter.WriteFileHeader;
begin
inherited WriteFileHeader;
WriteLine('#include "' + FUnitName + '.h"');
WriteLine;
end;
function TDSCustomCppProxyWriter.GetDelphiTypeName(const Param: TDSProxyParameter): String;
var
Name: String;
begin
Name := Param.TypeName;
if SameText(Name, 'string') then
Result := 'System::string'
else if Name = 'WideString' then
Result := 'System::WideString'
else if Name = 'WideString' then
Result := 'System::WideString'
else if Name = 'AnsiString' then
Result := 'System::AnsiString'
else if Name = 'TDateTime' then
Result := 'System::TDateTime'
else if Name = 'Currency' then
Result := 'System::Currency'
else if Name = 'ShortInt' then
Result := 'System::ShortInt' // 'signed char'
else if Name = 'Byte' then
Result := 'System::Byte' // 'unsigned char'
else if Name = 'OleVariant' then
Result := 'System::OleVariant'
else if Name = 'TDBXTime' then
Result := 'Dbxcommon::TDBXTime'
else if Name = 'TDBXDate' then
Result := 'Dbxcommon::TDBXDate'
else if Name = 'SmallInt' then
Result := 'short'
else if Name = 'Boolean' then
Result := 'bool'
else if Name = 'Int64' then
Result := '__int64'
else if Name = 'Single' then
Result := 'float'
else if Name = 'Double' then
Result := 'double'
else if Name = 'Integer' then
Result := 'int'
else if Name = 'Word' then
Result := 'unsigned short'
else if Name = 'TDBXReader' then
Result := 'TDBXReader*'
else if Name = 'TDBXConnection' then
Result := 'TDBXConnection*'
else if (not CanMarshal) and (Param.DataType = TDBXDataTypes.JsonValueType) and (not IsKnownJSONTypeName(Name)) then
Result := 'TJSONObject*'
else
Result := inherited GetDelphiTypeName(Param) + '*';
end;
procedure TDSCustomCppProxyWriter.WriteHeaderUses;
begin
WriteLine('#include "DBXCommon.hpp"');
WriteLine('#include "Classes.hpp"');
WriteLine('#include "SysUtils.hpp"');
WriteLine('#include "DB.hpp"');
WriteLine('#include "SqlExpr.hpp"');
WriteLine('#include "DBXDBReaders.hpp"');
WriteLine('#include "DBXCDSReaders.hpp"');
WriteLine('#include "FireDAC.Stan.Util.hpp"');
WriteLine('#include "FireDAC.Comp.Client.hpp"');
end;
procedure TDSCustomCppProxyWriter.WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean);
var
Line: String;
ParamCount: Integer;
ProcessedCount: Integer;
Parameters: TDSProxyParameter;
Param: TDSProxyParameter;
LDelphiTypeName: string;
LIsPointer: Boolean;
begin
Parameters := Method.Parameters;
ParamCount := Method.ParameterCount;
if Method.HasReturnValue then
begin
ParamCount := ParamCount - 1;
Param := Method.ReturnParameter;
Line := GetDelphiTypeName(Param) + ' ';
end
else
Line := 'void ';
Line := Line + '__fastcall ';
if IsInterface then
Line := Line + Method.ProxyMethodName
else
Line := Line + ProxyClass.ProxyClassName + 'Client::' + Method.ProxyMethodName;
if ParamCount > 0 then
begin
Line := Line + '(';
Param := Parameters;
ProcessedCount := 0;
while (Param <> nil) and (ProcessedCount < ParamCount) do
begin
LDelphiTypeName := GetDelphiTypeName(Param);
LIsPointer := LDelphiTypeName[Length(LDelphiTypeName)] = '*';
Line := Line + LDelphiTypeName + ' ';
if not LIsPointer then
case Param.ParameterDirection of
TDBXParameterDirections.OutParameter,
TDBXParameterDirections.InOutParameter:
Line := Line + ' &';
end;
Line := Line + Param.ParameterName;
ProcessedCount := ProcessedCount + 1;
if (ProcessedCount) < ParamCount then
Line := Line + ', ';
Param := Param.Next;
end;
Line := Line + ')';
end
else
Line := Line + '()';
if IsInterface then
Line := Line + ';';
WriteLine(Line);
end;
procedure TDSCustomCppProxyWriter.WriteClassInterface(const ProxyClass: TDSProxyClass);
var
Methods: TDSProxyMethod;
ClassName: String;
begin
ClassName := ProxyClass.ProxyClassName + 'Client';
Indent;
WriteLine('class ' + ClassName + ' : public TObject');
WriteLine('{');
WriteLine('private:');
Indent;
WriteLine('TDBXConnection *FDBXConnection;');
WriteLine('bool FInstanceOwner;');
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteLine('TDBXCommand *F' + Methods.ProxyMethodName + 'Command;');
Methods := Methods.Next;
end;
Outdent;
WriteLine('public:');
Indent;
WriteLine('__fastcall ' + ClassName + '::' + ClassName + '(TFDConnection *AADConnection);');
WriteLine('__fastcall ' + ClassName + '::' + ClassName + '(TFDConnection *AADConnection, bool AInstanceOwner);');
WriteLine('__fastcall ' + ClassName + '::~' + ClassName + '();');
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteMethodSignature(ProxyClass, Methods, True);
Methods := Methods.Next;
end;
Outdent;
WriteLine('};');
Outdent;
WriteLine;
end;
procedure TDSCustomCppProxyWriter.WriteInterface;
var
Item: TDSProxyClass;
begin
StartCppHeader;
WriteLine('#ifndef ' + FUnitName + 'H');
WriteLine('#define ' + FUnitName + 'H');
WriteLine;
WriteHeaderUses;
WriteLine;
Item := Metadata.Classes;
while Item <> nil do
begin
if IncludeClass(Item) then
WriteClassInterface(Item);
Item := Item.Next;
end;
WriteLine('#endif');
EndCppHeader;
end;
procedure TDSCustomCppProxyWriter.WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod);
var
CommandName: String;
ParamCount: Integer;
Params: TDSProxyParameter;
Param: TDSProxyParameter;
InputCount: Integer;
OutputCount: Integer;
Ordinal: Integer;
Rhs: String;
Lhs: String;
begin
WriteMethodSignature(ProxyClass, ProxyMethod, False);
WriteLine('{');
Indent;
CommandName := 'F' + ProxyMethod.ProxyMethodName + 'Command';
WriteLine('if (' + CommandName + ' == NULL)');
WriteLine('{');
Indent;
WriteLine(CommandName + ' = FDBXConnection->CreateCommand();');
WriteLine(CommandName + '->CommandType = TDBXCommandTypes_DSServerMethod;');
WriteLine(CommandName + '->Text = "' + ProxyMethod.MethodAlias + '";');
WriteLine(CommandName + '->Prepare();');
Outdent;
WriteLine('}');
Params := ProxyMethod.Parameters;
ParamCount := ProxyMethod.ParameterCount;
if ProxyMethod.HasReturnValue then
ParamCount := ParamCount - 1;
InputCount := ProxyMethod.InputCount;
OutputCount := ProxyMethod.OutputCount;
if InputCount > 0 then
begin
Param := Params;
Ordinal := 0;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.InParameter) then
begin
if IsKnownDBXValueTypeName(Param.TypeName) then
begin
WriteLine('if (' + Param.ParameterName + ' == NULL) ');
Indent;
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->SetNull();');
Outdent;
WriteLine('else');
Indent;
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->SetValue(' + Param.ParameterName + ');');
Outdent;
end
else
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->' + GetSetter(Param) + ';');
end;
Ordinal := Ordinal + 1;
Param := Param.Next;
end;
end;
WriteLine(CommandName + '->ExecuteUpdate();');
if OutputCount > 0 then
begin
Param := Params;
Ordinal := 0;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.OutParameter) then
begin
if IsKnownDBXValueTypeName(Param.TypeName) then
begin
WriteLine('if (' + Param.ParameterName + ' != NULL)');
Indent;
WriteLine(Param.ParameterName + '->SetValue(' + CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value);');
Outdent;
end
else
begin
Lhs := Param.ParameterName + ' = ';
Rhs := CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->' + GetGetter(Param);
WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, Param.ParameterName);
end;
end;
Ordinal := Ordinal + 1;
Param := Param.Next;
end;
end;
if ProxyMethod.HasReturnValue then
begin
if ProxyMethod.ReturnParameter.DataType = TDBXDataTypes.DbxConnectionType then
WriteLine('return FDBXConnection;')
else if IsKnownDBXValueTypeName(ProxyMethod.ReturnParameter.TypeName) then
begin
WriteLine(GetDelphiTypeName(ProxyMethod.ReturnParameter) + ' result = new ' + ProxyMethod.ReturnParameter.TypeName + '();');
WriteLine('result->SetValue(' + CommandName + '->Parameters->Parameter[' + IntToStr(ParamCount) + ']->Value)');
WriteLine('return result;');
end
else
begin
Lhs := GetDelphiTypeName(ProxyMethod.ReturnParameter) + ' result = ';
Param := ProxyMethod.ReturnParameter;
Rhs := CommandName + '->Parameters->Parameter[' + IntToStr(ParamCount) + ']->Value->' + GetGetter(Param);
WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, 'result');
WriteLine('return result;');
end;
end;
Outdent;
WriteLine('}');
WriteLine;
end;
procedure TDSCustomCppProxyWriter.WriteOutgoingParameter(const Lhs: String; const InRhs: String; const Param: TDSProxyParameter; const CommandName: String; const ParamName: String);
var
Rhs: String;
LTypeName: string;
begin
Rhs := InRhs;
if (Param.DataType = TDBXDataTypes.TableType) and IsKnownTableTypeName(Param.TypeName) then
begin
if CompareText(Param.TypeName, 'TDataSet') = 0 then
begin
Rhs := 'new TCustomSQLDataSet(NULL, ' + Rhs + '(False), True)';
WriteLine(Lhs + Rhs + ';');
WriteLine(ParamName + '->Open();');
end
else if CompareText(Param.TypeName, 'TParams') = 0 then
begin
Rhs := 'TDBXParamsReader::ToParams(NULL, ' + Rhs + '(False), True)';
WriteLine(Lhs + Rhs + ';');
end
else
WriteLine(Lhs + Rhs + ';');
WriteLine('if (FInstanceOwner)');
Indent;
WriteLine(CommandName + '->FreeOnExecute(' + ParamName + ');');
Outdent;
end
else if (Param.DataType = TDBXDataTypes.TableType) or (Param.DataType = TDBXDataTypes.BinaryBlobType) then
WriteLine(Lhs + Rhs + '(FInstanceOwner);')
else if Param.DataType = TDBXDataTypes.JsonValueType then
begin
LTypeName := GetDelphiTypeName(Param);
if not SameText(LTypeName, 'TJSONValue*') then
WriteLine(Lhs + '(' + LTypeName + ')' + Rhs + '(FInstanceOwner);')
else
WriteLine(Lhs + Rhs + '(FInstanceOwner);')
end
else if ContainsText(Rhs,'->Get') then
WriteLine(Lhs + Rhs + '();')
else
WriteLine(Lhs + Rhs + ';');
end;
procedure TDSCustomCppProxyWriter.WriteClassImplementation(const ProxyClass: TDSProxyClass);
var
Methods: TDSProxyMethod;
ConErrorMessage: String;
LCommandName: string;
begin
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteMethodImplementation(ProxyClass, Methods);
Methods := Methods.Next;
end;
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::' + ProxyClass.ProxyClassName + 'Client(TFDConnection *AADConnection)');
WriteLine('{');
Indent;
ConErrorMessage := SConError;
WriteLine('if ((AADConnection == NULL) || (AADConnection->CliObj == NULL))');
Indent;
WriteLine('throw EInvalidOperation("' + ConErrorMessage + '");');
Outdent;
WriteLine('FDBXConnection = dynamic_cast<TDBXConnection *>(AADConnection->CliObj);');
WriteLine('FInstanceOwner = True;');
Outdent;
WriteLine('}');
WriteLine;
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::' + ProxyClass.ProxyClassName + 'Client(TFDConnection *AADConnection, bool AInstanceOwner)');
WriteLine('{');
Indent;
ConErrorMessage := SConError;
WriteLine('if ((AADConnection == NULL) || (AADConnection->CliObj == NULL))');
Indent;
WriteLine('throw EInvalidOperation("' + ConErrorMessage + '");');
Outdent;
WriteLine('FDBXConnection = dynamic_cast<TDBXConnection *>(AADConnection->CliObj);');
WriteLine('FInstanceOwner = AInstanceOwner;');
Outdent;
WriteLine('}');
Outdent;
WriteLine;
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::~' + ProxyClass.ProxyClassName + 'Client()');
WriteLine('{');
Indent;
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
begin
LCommandName := 'F' + Methods.ProxyMethodName + 'Command';
WriteLine('delete ' + LCommandName + ';');
end;
Methods := Methods.Next;
end;
Outdent;
WriteLine('}');
WriteLine;
end;
procedure TDSCustomCppProxyWriter.WriteImplementation;
var
Item: TDSProxyClass;
begin
Item := Metadata.Classes;
while Item <> nil do
begin
if IncludeClass(Item) then
WriteClassImplementation(Item);
Item := Item.Next;
end;
end;
function TDSCustomCppProxyWriter.GetAssignmentString: String;
begin
Result := '=';
end;
function TDSCustomCppProxyWriter.GetCreateDataSetReader(const Param: TDSProxyParameter): String;
begin
Result := '(new TDBXDataSetReader(' + Param.ParameterName + ', FInstanceOwner), True)';
end;
function TDSCustomCppProxyWriter.GetCreateParamsReader(const Param: TDSProxyParameter): String;
begin
Result := '(new TDBXParamsReader(' + Param.ParameterName + ', FInstanceOwner), True)';
end;
{ TDSCppProxyWriter }
procedure TDSCppProxyWriter.DerivedWrite(const Line: String);
begin
if FWritingHeader then
if FHeaderStreamWriter <> nil then
FHeaderStreamWriter.Write(Line)
else
ProxyWriters[sInterface].Write(Line)
else
if FStreamWriter <> nil then
FStreamWriter.Write(Line)
else
ProxyWriters[sImplementation].Write(Line);
end;
procedure TDSCppProxyWriter.DerivedWriteLine;
begin
if FWritingHeader then
if HeaderStreamWriter <> nil then
FHeaderStreamWriter.WriteLine
else
ProxyWriters[sInterface].WriteLine
else
if FStreamWriter <> nil then
FStreamWriter.WriteLine
else
ProxyWriters[sImplementation].WriteLine;
end;
destructor TDSCppProxyWriter.Destroy;
begin
FDFreeAndNil(FHeaderStreamWriter);
FDFreeAndNil(FStreamWriter);
inherited;
end;
procedure TDSCppProxyWriter.EndCppHeader;
begin
FWritingHeader := False;
end;
procedure TDSCppProxyWriter.StartCppHeader;
begin
FWritingHeader := True;
end;
function TDSCppProxyWriter.IncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean;
begin
// C++ does not support marshalling/unmarshalling
// But will support as JSONObject
Result := inherited; // and not ProxyMethod.HasParametersWithUserType;
end;
{ TDSClientProxyWriterCpp }
function TDSClientProxyWriterCpp.CreateProxyWriter: TDSCustomProxyWriter;
begin
Result := TDSCppProxyWriter.Create;
end;
function TDSClientProxyWriterCpp.FileDescriptions: TDSProxyFileDescriptions;
begin
SetLength(Result, 2);
Result[0].ID := sImplementation;
Result[0].DefaultFileExt := '.cpp';
Result[1].ID := sInterface;
Result[1].DefaultFileExt := '.h';
end;
function TDSClientProxyWriterCpp.Properties: TDSProxyWriterProperties;
begin
Result.UsesUnits := 'FireDAC.Phys.DSProxyCpp';
Result.DefaultExcludeClasses := sDSAdminClassName + ';' + sDSMetadataClassName; // 'DSMetadata;DSAdmin';
Result.DefaultExcludeMethods := sASMethodsPrefix;
Result.Author := 'Embarcadero'; // do not localize
Result.Comment := '';
Result.Language := sDSProxyCppLanguage;
Result.Features := [feConnectsWithDBXConnection, feDBXClient];
Result.DefaultEncoding := TEncoding.UTF8;
end;
initialization
TDSProxyWriterFactory.RegisterWriter(sCPlusPlusBuilderFireDACProxyWriter, TDSClientProxyWriterCpp);
finalization
TDSProxyWriterFactory.UnregisterWriter(sCPlusPlusBuilderFireDACProxyWriter);
end.
|
{
@html(<b>)
Component Registration
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
All RealThinClient VCL and Non-VCL components are being
registered to Delphi component palette using this unit.
}
unit rtcRegister;
{$INCLUDE rtcDefs.inc}
interface
// This procedure is being called by Delphi to register the components.
procedure Register;
implementation
uses
{$IFNDEF BCB5}
{$IFNDEF FPC}
{$IFDEF IDE_6up}
TypInfo, Consts,
DesignIntf, DesignEditors,
{$ELSE}
TypInfo, Consts,
DsgnIntf,
{$ENDIF}
{$ENDIF}
{$ENDIF}
rtcTcpCli, rtcTcpSrv,
rtcUdpCli, rtcUdpSrv,
rtcDataCli, rtcDataSrv,
rtcHttpSrv, rtcHttpCli,
rtcMsgSrv, rtcMsgCli,
{$IFNDEF FPC}
rtcISAPISrv,
{$ENDIF}
{$IFNDEF BCB5}
rtcEditors,
{$ENDIF}
rtcTransports,
rtcCliModule, rtcSrvModule,
rtcFunction,
rtcScript,
Classes;
{$IFNDEF BCB5}
{$IFNDEF FPC}
type
TRtcMessageReceiverInterfacedComponentProperty = class(TRtcInterfacedComponentProperty)
public
function GetIID: TGUID; override;
end;
function TRtcMessageReceiverInterfacedComponentProperty.GetIID: TGUID;
begin
Result := IRTCMessageReceiverGUID;
end;
{$ENDIF}
{$ENDIF}
procedure Register;
begin
RegisterComponents('RTC Server',[TRtcHttpServer,
{$IFNDEF FPC}TRtcISAPIServer,{$ENDIF}
TRtcMessageServer,
TRtcDataServerLink, TRtcDualDataServerLink,
TRtcDataProvider,
TRtcServerModule,
TRtcFunctionGroup, TRtcFunction,
TRtcScriptEngine]);
RegisterComponents('RTC Client',[TRtcHttpClient,
TRtcMessageClient,
TRtcDataClientLink, TRtcDualDataClientLink,
TRtcDataRequest,
TRtcClientModule,
TRtcResult]);
RegisterComponents('RTC LowLevel',[TRtcTcpClient, TRtcUdpClient,
TRtcTcpServer, TRtcUdpServer]);
{$IFNDEF BCB5}
{$IFNDEF FPC}
RegisterPropertyEditor(TComponent.ClassInfo,
TRtcMessageClient, 'Server',
TRtcMessageReceiverInterfacedComponentProperty);
{$ENDIF}
{$ENDIF}
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MySQL driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.MySQL;
interface
uses
System.Classes,
FireDAC.Stan.Intf,
FireDAC.Phys;
type
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysMySQLDriverLink = class(TFDPhysDriverLink)
private
FEmbeddedArgs: TStrings;
FEmbeddedGroups: TStrings;
procedure SetEmbeddedArgs(const AValue: TStrings);
procedure SetEmbeddedGroups(const AValue: TStrings);
protected
function GetBaseDriverID: String; override;
function IsConfigured: Boolean; override;
procedure ApplyTo(const AParams: IFDStanDefinition); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property EmbeddedArgs: TStrings read FEmbeddedArgs write SetEmbeddedArgs;
property EmbeddedGroups: TStrings read FEmbeddedGroups write SetEmbeddedGroups;
end;
{-------------------------------------------------------------------------------}
implementation
uses
{$IFDEF MSWINDOWS}
// Preventing from "Inline has not expanded"
Winapi.Windows,
{$ENDIF}
System.SysUtils, Data.DB, System.SyncObjs, System.Variants, Data.FmtBCD,
Data.SqlTimSt, System.DateUtils, System.Generics.Collections,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Stan.Util,
FireDAC.Stan.Consts, FireDAC.Stan.ResStrs,
FireDAC.UI.Intf,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.MySQLCli,
FireDAC.Phys.MySQLWrapper, FireDAC.Phys.MySQLMeta, FireDAC.Phys.MySQLDef;
type
TFDPhysMySQLDriver = class;
TFDPhysMySQLConnection = class;
TFDPhysMySQLTransaction = class;
TFDPhysMySQLCommand = class;
TFDPhysMySQLDriver = class(TFDPhysDriver)
private
FLib: TMySQLLib;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
procedure InternalUnload; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetCliObj: Pointer; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
end;
TFDPhysMySQLConnection = class(TFDPhysConnection)
private
FSession: TMySQLSession;
FServerVersion, FClientVersion: TFDVersion;
FLock: TCriticalSection;
FResultMode: TFDMySQLResultMode;
FNameModes: TFDPhysMySQLNameModes;
FTinyIntFormat: TFDDataType;
FLastInsertID: my_ulonglong;
procedure GetServerOutput;
procedure UpdateInsertId(AStmt: TMySQLStatement; AForce: Boolean);
protected
procedure InternalConnect; override;
procedure InternalDisconnect; override;
procedure InternalPing; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateTransaction: TFDPhysTransaction; override;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; override;
{$ENDIF}
function GetItemCount: Integer; override;
procedure GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override;
procedure InternalChangePassword(const AUserName, AOldPassword, ANewPassword: String); override;
function InternalCreateMetadata: TObject; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override;
procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override;
function GetMessages: EFDDBEngineException; override;
function GetCliObj: Pointer; override;
function InternalGetCliHandle: Pointer; override;
function GetLastAutoGenValue(const AName: String): Variant; override;
function QueryValue(const ACmd: String; AColIndex: Integer): String;
function InternalGetCurrentCatalog: String; override;
procedure InternalAnalyzeSession(AMessages: TStrings); override;
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
destructor Destroy; override;
end;
TFDPhysMySQLTransaction = class(TFDPhysTransaction)
private
function GetConection: TFDPhysMySQLConnection; inline;
protected
procedure InternalStartTransaction(ATxID: LongWord); override;
procedure InternalCommit(ATxID: LongWord); override;
procedure InternalRollback(ATxID: LongWord); override;
procedure InternalChanged; override;
procedure InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); override;
procedure InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); override;
property MyConnection: TFDPhysMySQLConnection read GetConection;
end;
PFDMySQLVarInfoRec = ^TFDMySQLVarInfoRec;
TFDMySQLVarInfoRec = record
FName,
FOriginDBName,
FOriginTabName,
FOriginColName: String;
FPos: Integer;
FSrcFieldType: TFieldType;
FSize: LongWord;
FPrec, FScale: Integer;
FAttrs: TFDDataAttributes;
FSrcDataType,
FDestDataType,
FOutDataType: TFDDataType;
FSrcTypeName: String;
FOutSQLDataType: enum_field_types;
FVar: TMySQLVariable;
FParamType: TParamType;
end;
TFDPhysMySQLCommand = class(TFDPhysCommand)
private
FMetaInfoSQLs: array of String;
FColumnIndex: Integer;
FCursor: TMySQLResult;
FStmt: TMySQLStatement;
FParInfos: array of TFDMySQLVarInfoRec;
FColInfos: array of TFDMySQLVarInfoRec;
FPreparedBatchSize: Integer;
FSPParsedName: TFDPhysParsedName;
FUseDirectExec: Boolean;
FHasIntStreams: Boolean;
FHasOutParams: Boolean;
FGetOutParams: Boolean;
function GetConection: TFDPhysMySQLConnection; inline;
function GetSession: TMySQLSession; inline;
procedure UpdateExecDirect;
procedure SetupReader(ARdr: TMySQLReader);
procedure FD2SQLDataType(AType: TFDDataType; ALen: LongWord;
APrec, AScale: Integer; out ASQLDataType: enum_field_types;
out ASQLUnsigned: Boolean; out ASQLLen: my_ulong; AInput: Boolean;
AFmtOpts: TFDFormatOptions);
procedure SQL2FDDataType(ASQLDataType: enum_field_types; ASQLUnsigned,
ASQLIsBinary, ASQLIsNum: Boolean; ASQLLen, ASQLDecimals: my_ulong;
out AType: TFDDataType; var AAttrs: TFDDataAttributes; out ALen: LongWord;
out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions);
procedure CreateParamInfos(ABatchSize: Integer);
procedure CreateColInfos;
procedure DestroyParamInfos;
procedure DestroyColInfos;
procedure PrepareBase;
procedure CheckSPPrepared(ASPUsage: TFDPhysCommandKind);
procedure SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
AVar: TMySQLVariable; ApInfo: PFDMySQLVarInfoRec; AParIndex: Integer);
procedure SetParamValues(ABatchSize, AOffset: Integer);
function GetBatchSQL(ABatchSize: Integer): String;
function DataValue2MySQL(AData: Pointer; ALen: LongWord; AType: TFDDataType;
out ATypeSupported: Boolean): TFDByteString;
function GetExpandedSQL(ATimes, AOffset: Integer): TFDByteString;
function GetResultMode: TFDMySQLResultMode;
function GetCursor(AClosing: Boolean; AParIndex: Integer): Boolean;
function CheckArray(ASize: Integer): Boolean;
procedure ExecuteBatchInsert(ATimes, AOffset: Integer; var ACount: TFDCounter);
procedure DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter;
AFlush: Boolean);
function AreOutParams: Boolean;
procedure GetParamValues(AIndex: Integer);
procedure CloseStatement(AForceClose: Boolean; AIndex: Integer);
procedure ProcessVarColumn(AFmtOpts: TFDFormatOptions; AColIndex: Integer;
ARow: TFDDatSRow; ApInfo: PFDMySQLVarInfoRec);
procedure ProcessResColumn(AFmtOpts: TFDFormatOptions; AColIndex: Integer;
ARow: TFDDatSRow; ApInfo: PFDMySQLVarInfoRec);
procedure FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
procedure MySQLType2FDType(var AStr: String; var AType: TFDDataType;
var AAttrs: TFDDataAttributes; var ALen: LongWord; var APrec, AScale: Integer);
function GetCrsData(ACrsCol: Integer; var AData: Pointer;
var ALen: LongWord; AType: TFDDataType): Boolean; overload;
function GetCrsData(ACrsCol: Integer; AData: Pointer): String; overload;
function GetMetaCatalog: String;
procedure FetchMetaRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowIndex: Integer);
function FetchFKRows(ATable: TFDDatSTable; AParentRow: TFDDatSRow): Integer;
function FetchSPParamRows(ATable: TFDDatSTable;
AParentRow: TFDDatSRow): Integer;
protected
procedure InternalClose; override;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
procedure InternalCloseStreams; override;
function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord; override;
procedure InternalAbort; override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
function InternalNextRecordSet: Boolean; override;
procedure InternalPrepare; override;
function InternalUseStandardMetadata: Boolean; override;
function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override;
function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override;
procedure InternalUnprepare; override;
function GetCliObj: Pointer; override;
property MyConnection: TFDPhysMySQLConnection read GetConection;
property Session: TMySQLSession read GetSession;
end;
const
S_FD_CharacterSets = 'big5;dec8;cp850;hp8;koi8r;latin1;latin2;swe7;ascii;ujis;' +
'sjis;cp1251;hebrew;tis620;euckr;koi8u;gb2312;greek;cp1250;gbk;latin5;armscii8;' +
'cp866;keybcs2;macce;macroman;cp852;latin7;cp1256;cp1257;binary;utf8;utf8mb4';
S_FD_StoreResult = 'Store';
S_FD_UseResult = 'Use';
S_FD_ChooseResult = 'Choose';
S_FD_Boolean = 'Boolean';
S_FD_Integer = 'Integer';
var
GLock: TCriticalSection;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLDriverLink }
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLDriverLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEmbeddedArgs := TFDStringList.Create(#0, ';');
FEmbeddedGroups := TFDStringList.Create(#0, ';');
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMySQLDriverLink.Destroy;
begin
FDFreeAndNil(FEmbeddedArgs);
FDFreeAndNil(FEmbeddedGroups);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_MySQLId;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLDriverLink.ApplyTo(const AParams: IFDStanDefinition);
begin
inherited ApplyTo(AParams);
if FEmbeddedArgs.Count > 0 then
AParams.AsString[S_FD_ConnParam_MySQL_EmbeddedArgs] := FEmbeddedArgs.DelimitedText;
if FEmbeddedGroups.Count > 0 then
AParams.AsString[S_FD_ConnParam_MySQL_EmbeddedGroups] := FEmbeddedGroups.DelimitedText;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLDriverLink.IsConfigured: Boolean;
begin
Result := inherited IsConfigured or (FEmbeddedArgs.Count > 0) or
(FEmbeddedGroups.Count > 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLDriverLink.SetEmbeddedArgs(const AValue: TStrings);
begin
FEmbeddedArgs.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLDriverLink.SetEmbeddedGroups(const AValue: TStrings);
begin
FEmbeddedGroups.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLDriver }
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLDriver.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
GLock := TCriticalSection.Create;
FLib := TMySQLLib.Create(FDPhysManagerObj);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMySQLDriver.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FLib);
FDFreeAndNil(GLock);
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMySQLDriver.GetBaseDriverID: String;
begin
Result := S_FD_MySQLId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMySQLDriver.GetBaseDriverDesc: String;
begin
Result := 'MySQL Server';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMySQLDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MySQL;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMySQLDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysMySQLConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLDriver.InternalLoad;
var
sHome, sLib, sEmbArgs, sEmbGrps: String;
begin
sHome := '';
sLib := '';
sEmbArgs := '';
sEmbGrps := '';
if Params <> nil then begin
GetVendorParams(sHome, sLib);
sEmbArgs := Params.AsString[S_FD_ConnParam_MySQL_EmbeddedArgs];
sEmbGrps := Params.AsString[S_FD_ConnParam_MySQL_EmbeddedGroups];
end;
FLib.Load(sHome, sLib, sEmbArgs, sEmbGrps);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLDriver.InternalUnload;
begin
FLib.Unload;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysMySQLConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLDriver.GetCliObj: Pointer;
begin
Result := FLib;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, S_FD_Local, S_FD_Local, S_FD_ConnParam_Common_Server, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', IntToStr(MYSQL_PORT), S_FD_ConnParam_Common_Port, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_Compress, '@L', S_FD_True, S_FD_ConnParam_MySQL_Compress, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_UseSSL, '@L', S_FD_False, S_FD_ConnParam_MySQL_UseSSL, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_LoginTimeout, '@I', '', S_FD_ConnParam_Common_LoginTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_ReadTimeout, '@I', '', S_FD_ConnParam_MySQL_ReadTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_WriteTimeout, '@I', '', S_FD_ConnParam_MySQL_WriteTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_ResultMode, S_FD_StoreResult + ';' + S_FD_UseResult + ';' + S_FD_ChooseResult, S_FD_StoreResult, S_FD_ConnParam_MySQL_ResultMode, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, S_FD_CharacterSets, '', S_FD_ConnParam_Common_CharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_TinyIntFormat, S_FD_Boolean + ';' + S_FD_Integer, S_FD_Boolean, S_FD_ConnParam_MySQL_TinyIntFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
if (AKeys <> nil) and
(CompareText(AKeys.Values[S_FD_ConnParam_MySQL_UseSSL], S_FD_True) = 0) then begin
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_SSL_key, '@S', '', S_FD_ConnParam_MySQL_SSL_key, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_SSL_cert, '@S', '', S_FD_ConnParam_MySQL_SSL_cert, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_SSL_ca, '@S', '', S_FD_ConnParam_MySQL_SSL_ca, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_SSL_capath, '@S', '', S_FD_ConnParam_MySQL_SSL_capath, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MySQL_SSL_cipher, '@S', '', S_FD_ConnParam_MySQL_SSL_cipher, -1]);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLConnection }
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLConnection.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
begin
FLock := TCriticalSection.Create;
inherited Create(ADriverObj, AConnHost);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMySQLConnection.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FLock);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysMySQLCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalCreateTransaction: TFDPhysTransaction;
begin
Result := TFDPhysMySQLTransaction.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalCreateMetadata: TObject;
begin
Result := TFDPhysMySQLMetadata.Create(Self, False, FServerVersion,
FClientVersion, FNameModes,
(FSession <> nil) and (FSession.Encoder.Encoding in [ecUTF8, ecUTF16]));
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysMySQLCommandGenerator.Create(ACommand)
else
Result := TFDPhysMySQLCommandGenerator.Create(Self);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalTracingChanged;
begin
if FSession <> nil then begin
FSession.Monitor := FMonitor;
FSession.Tracing := FTracing;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalConnect;
var
oParams: TFDPhysMySQLConnectionDefParams;
sDatabase: String;
uiClientFlag: LongWord;
procedure SetTimeout(const AParamName: String; AOption: mysql_option);
var
uiTimeout: LongWord;
begin
if ConnectionDef.HasValue(AParamName) then begin
uiTimeout := ConnectionDef.AsInteger[AParamName];
FSession.Options[AOption] := @uiTimeout;
end;
end;
begin
oParams := ConnectionDef.Params as TFDPhysMySQLConnectionDefParams;
if InternalGetSharedCliHandle() <> nil then
FSession := TMySQLSession.CreateUsingHandle(TFDPhysMySQLDriver(DriverObj).FLib,
PMYSQL(InternalGetSharedCliHandle()), Self)
else
FSession := TMySQLSession.Create(TFDPhysMySQLDriver(DriverObj).FLib, Self);
{$IFDEF FireDAC_MONITOR}
InternalTracingChanged;
{$ENDIF}
FClientVersion := FSession.ClientVersion;
if InternalGetSharedCliHandle() = nil then
FSession.Init;
FResultMode := oParams.ResultMode;
if oParams.TinyIntFormat = tifInteger then
FTinyIntFormat := dtSByte
else
FTinyIntFormat := dtBoolean;
if InternalGetSharedCliHandle() = nil then begin
if oParams.Compress then
FSession.Options[MYSQL_OPT_COMPRESS] := nil;
SetTimeout(S_FD_ConnParam_Common_LoginTimeout, MYSQL_OPT_CONNECT_TIMEOUT);
SetTimeout(S_FD_ConnParam_MySQL_ReadTimeout, MYSQL_OPT_READ_TIMEOUT);
SetTimeout(S_FD_ConnParam_MySQL_WriteTimeout, MYSQL_OPT_WRITE_TIMEOUT);
uiClientFlag := CLIENT_FOUND_ROWS or CLIENT_LONG_FLAG;
if not IsConsole then
uiClientFlag := uiClientFlag or CLIENT_INTERACTIVE;
sDatabase := oParams.ExpandedDatabase;
if sDatabase <> '' then
uiClientFlag := uiClientFlag or CLIENT_CONNECT_WITH_DB;
if oParams.UseSSL then begin
uiClientFlag := uiClientFlag or CLIENT_SSL;
FSession.SSLInit(oParams.SSL_key, oParams.SSL_cert, oParams.SSL_ca,
oParams.SSL_capath, oParams.SSL_cipher);
end;
if FClientVersion >= mvMySQL050000 then
uiClientFlag := uiClientFlag or FD_50_CLIENT_PROTOCOL_41 or CLIENT_MULTI_QUERIES or
CLIENT_MULTI_RESULTS
else if FClientVersion >= mvMySQL040100 then
uiClientFlag := uiClientFlag or CLIENT_PROTOCOL_41 or CLIENT_MULTI_STATEMENTS;
if (FClientVersion >= mvMySQL050600) and ConnectionDef.IsSpecified(S_FD_ConnParam_Common_NewPassword) then
uiClientFlag := uiClientFlag or CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS;
GLock.Enter;
try
FSession.Connect(oParams.Server, oParams.UserName, oParams.Password, sDatabase, oParams.Port, uiClientFlag);
if (FClientVersion >= mvMySQL050600) and ConnectionDef.IsSpecified(S_FD_ConnParam_Common_NewPassword) then
if FSession.ServerVersion >= mvMySQL080000 then
InternalExecuteDirect('ALTER USER USER() IDENTIFIED BY ''' + oParams.NewPassword + '''', nil)
else
InternalExecuteDirect('SET PASSWORD = PASSWORD("' + oParams.NewPassword + '")', nil);
finally
GLock.Leave;
end;
end;
FServerVersion := FSession.ServerVersion;
if FServerVersion < mvMySQL032000 then
FDException(Self, [S_FD_LPhys, S_FD_MySQLId], er_FD_MySQLBadVersion, [FServerVersion]);
if InternalGetSharedCliHandle() = nil then begin
if ConnectionDef.HasValue(S_FD_ConnParam_Common_CharacterSet) then
FSession.CharacterSetName := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet];
InternalExecuteDirect('SET SQL_AUTO_IS_NULL = 0', nil);
end;
FNameModes := [nmCaseSens, nmDBApply];
if FServerVersion >= mvMySQL032306 then begin
case StrToIntDef(QueryValue('SHOW VARIABLES LIKE ''lower_case_table_names''', 1), 0) of
0: FNameModes := [nmCaseSens];
1: FNameModes := [nmDefLowerCase];
2: FNameModes := [];
end;
if FServerVersion >= mvMySQL040002 then
Include(FNameModes, nmDBApply);
end;
FLastInsertID := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalDisconnect;
begin
if FSession <> nil then begin
GLock.Enter;
try
FSession.Disconnect;
finally
GLock.Leave;
FDFreeAndNil(FSession);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalPing;
begin
FLock.Enter;
try
FSession.Ping;
finally
FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalExecuteDirect(const ASQL: String;
ATransaction: TFDPhysTransaction);
begin
FLock.Enter;
try
FSession.Query(ASQL, Self);
UpdateInsertId(nil, False);
GetServerOutput;
finally
FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.QueryValue(const ACmd: String; AColIndex: Integer): String;
var
oRes: TMySQLResult;
pData: Pointer;
iLen: LongWord;
begin
FLock.Enter;
try
FSession.Query(ACmd, Self);
oRes := FSession.StoreResult;
try
oRes.Fetch(1);
pData := nil;
iLen := 0;
oRes.GetFieldData(AColIndex, pData, iLen);
Result := FSession.Encoder.Decode(pData, iLen);
finally
FDFree(oRes);
end;
GetServerOutput;
finally
FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String);
var
s: String;
begin
FLock.Enter;
try
if FSession.ServerVersion >= mvMySQL080000 then
InternalExecuteDirect('ALTER USER USER() IDENTIFIED BY ''' + ANewPassword + '''', nil)
else begin
s := QueryValue('SELECT CONCAT(SUBSTRING_INDEX(USER(), ''@'', 1), ''@"'', SUBSTRING_INDEX(USER(), ''@'', -1), ''"'')', 0);
InternalExecuteDirect('SET PASSWORD FOR ' + s + ' = PASSWORD("' + ANewPassword + '")', nil);
end;
finally
FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.UpdateInsertId(AStmt: TMySQLStatement; AForce: Boolean);
var
iID: my_ulonglong;
begin
if AStmt <> nil then
iID := AStmt.Insert_ID
else if FSession <> nil then
iID := FSession.Insert_ID
else
Exit;
if AForce or (iID <> 0) then
FLastInsertID := iID;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.GetLastAutoGenValue(const AName: String): Variant;
begin
if FLastInsertID <> 0 then
Result := FLastInsertID
else
Result := Null;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if DriverObj.State in [drsLoaded, drsActive] then begin
Inc(Result, 2);
if FSession <> nil then
Inc(Result, 6);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
var
s: String;
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else
case AIndex - inherited GetItemCount of
0:
begin
AName := 'DLL';
AValue := TFDPhysMySQLDriver(DriverObj).FLib.DLLName;
AKind := ikClientInfo;
end;
1:
begin
AName := 'Client version';
AValue := IntToStr(TFDPhysMySQLDriver(DriverObj).FLib.Version);
AKind := ikClientInfo;
end;
2:
begin
AName := 'Server info';
AValue := FSession.ServerInfo;
AKind := ikSessionInfo;
end;
3:
begin
AName := 'Client info';
AValue := FSession.ClientInfo;
AKind := ikSessionInfo;
end;
4:
begin
AName := 'Characterset name';
AValue := FSession.CharacterSetName;
AKind := ikSessionInfo;
end;
5:
begin
AName := 'Host info';
AValue := FSession.HostInfo;
AKind := ikSessionInfo;
end;
6:
begin
AName := 'Name modes';
s := '';
if nmCaseSens in FNameModes then
s := s + 'CS'
else
s := s + 'CI';
if nmDefLowerCase in FNameModes then
s := s + 'LC'
else
s := s + 'AI';
if nmDBApply in FNameModes then
s := s + 'TD'
else
s := s + 'T';
AValue := s;
AKind := ikSessionInfo;
end;
7:
begin
AName := 'SSL Cipher';
AValue := FSession.SSLCipher;
AKind := ikSessionInfo;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.GetMessages: EFDDBEngineException;
begin
if FSession <> nil then
Result := FSession.Info
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.GetCliObj: Pointer;
begin
Result := FSession;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalGetCliHandle: Pointer;
begin
if FSession <> nil then
Result := FSession.MySQL
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLConnection.InternalGetCurrentCatalog: String;
begin
if FSession <> nil then
Result := FSession.DB
else
Result := inherited InternalGetCurrentCatalog;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.InternalAnalyzeSession(AMessages: TStrings);
begin
inherited InternalAnalyzeSession(AMessages);
if (FServerVersion >= mvMySQL050000) and (FServerVersion < mvMySQL050100) then
AMessages.Add(Format(S_FD_MySQLWarnNoFK, [FDVerInt2Str(FServerVersion)]));
if FClientVersion < mvMySQL050503 then
AMessages.Add(Format(S_FD_MySQLWarnNoMR, [FDVerInt2Str(FClientVersion)]));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLConnection.GetServerOutput;
begin
if TFDTopResourceOptions(FOptions.ResourceOptions).ServerOutput and
(FSession.WarningCount > 0) then
FSession.GetServerOutput;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLTransaction }
{-------------------------------------------------------------------------------}
function TFDPhysMySQLTransaction.GetConection: TFDPhysMySQLConnection;
begin
Result := TFDPhysMySQLConnection(ConnectionObj);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalChanged;
var
s: String;
begin
if xoAutoCommit in GetOptions.Changed then
MyConnection.InternalExecuteDirect(
'SET AUTOCOMMIT = ' + IntToStr(Integer(GetOptions.AutoCommit)), nil);
if xoIsolation in GetOptions.Changed then begin
case GetOptions.Isolation of
xiUnspecified: Exit;
xiDirtyRead: s := 'READ UNCOMMITTED';
xiReadCommitted: s := 'READ COMMITTED';
xiRepeatableRead: s := 'REPEATABLE READ';
xiSnapshot: s := 'REPEATABLE READ';
xiSerializible: s := 'SERIALIZABLE';
end;
MyConnection.InternalExecuteDirect(
'SET SESSION TRANSACTION ISOLATION LEVEL ' + s, nil);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalStartTransaction(ATxID: LongWord);
begin
DisconnectCommands(nil, dmRelease);
MyConnection.InternalExecuteDirect('BEGIN', nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalCommit(ATxID: LongWord);
begin
DisconnectCommands(nil, dmRelease);
MyConnection.InternalExecuteDirect('COMMIT', nil);
if Retaining then
InternalStartTransaction(ATxID);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalRollback(ATxID: LongWord);
begin
DisconnectCommands(nil, dmRelease);
MyConnection.InternalExecuteDirect('ROLLBACK', nil);
if Retaining then
InternalStartTransaction(ATxID);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalCheckState(ACommandObj: TFDPhysCommand;
ASuccess: Boolean);
var
lInTx: Boolean;
begin
lInTx := (MyConnection.FSession <> nil) and
(MyConnection.FSession.ServerStatus and SERVER_STATUS_IN_TRANS <> 0);
if lInTx <> GetActive then
if lInTx then
TransactionStarted
else
TransactionFinished
else
inherited InternalCheckState(ACommandObj, ASuccess);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLTransaction.InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
begin
if (ANotification = cpBeforeCmdExecute) and (
// When server may have more results, eg in case of CALL <sp>, then
// next mysql_real_query will give "Commands out of sync" error. See
// http://dev.mysql.com/doc/refman/5.0/en/c-api-multiple-queries.html
MyConnection.FSession.HasMoreResults or
(TFDPhysMySQLCommand(ACommandObj).GetCommandKind in [skCommit, skRollback])
) then
DisconnectCommands(nil, dmRelease);
inherited InternalNotify(ANotification, ACommandObj);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLCommand }
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetCliObj: Pointer;
begin
if FStmt <> nil then
Result := FStmt
else
Result := FCursor;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetConection: TFDPhysMySQLConnection;
begin
Result := TFDPhysMySQLConnection(FConnectionObj);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetSession: TMySQLSession;
begin
Result := MyConnection.FSession;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.UpdateExecDirect;
var
i: Integer;
begin
FHasOutParams := False;
for i := 0 to GetParams.Count - 1 do
FHasOutParams := FHasOutParams or (GetParams()[i].ParamType in
[ptOutput, ptInputOutput, ptResult]);
if FHasOutParams and
// MySQL >= 5.5.3 supports output parameters in PS API
((Session.ServerVersion < mvMySQL050503) or (Session.ClientVersion < mvMySQL050503)) then
FUseDirectExec := True
else
FUseDirectExec :=
// MySQL >= 5.1.x has more or less stable PS API.
// Tested with 5.1.34. With 5.1.11 bugs reported.
(Session.ClientVersion < mvMySQL050134) or
GetOptions.ResourceOptions.DirectExecute or
(GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone) or
not (GetCommandKind in [skSelect, skSelectForLock, skSelectForUnLock,
skDelete, skInsert, skMerge, skUpdate,
skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs,
skExecute]) or
(Pos(';', FDbCommandText) <> 0) or
(StrLIComp(PChar(FDbCommandText), PChar('SHOW'), 4) = 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.SetupReader(ARdr: TMySQLReader);
var
oFmtOpts: TFDFormatOptions;
oStmt: TMySQLStatement;
begin
oFmtOpts := FOptions.FormatOptions;
if GetMetaInfoKind <> mkNone then begin
ARdr.StrsTrim := True;
ARdr.StrsEmpty2Null := True;
ARdr.StrsTrim2Len := False
end
else begin
ARdr.StrsTrim := oFmtOpts.StrsTrim;
ARdr.StrsEmpty2Null := oFmtOpts.StrsEmpty2Null;
ARdr.StrsTrim2Len := oFmtOpts.StrsTrim2Len;
end;
ARdr.MaxStringSize := oFmtOpts.MaxStringSize;
if ARdr is TMySQLStatement then begin
oStmt := TMySQLStatement(ARdr);
oStmt.UPDATE_MAX_LENGTH := 0;
oStmt.PREFETCH_ROWS := FOptions.FetchOptions.ActualRowsetSize;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.FD2SQLDataType(AType: TFDDataType; ALen: LongWord;
APrec, AScale: Integer; out ASQLDataType: enum_field_types; out ASQLUnsigned: Boolean;
out ASQLLen: my_ulong; AInput: Boolean; AFmtOpts: TFDFormatOptions);
begin
ASQLUnsigned := False;
ASQLLen := 0;
case AType of
dtSByte,
dtByte:
begin
ASQLDataType := MYSQL_TYPE_TINY;
ASQLUnsigned := AType = dtByte;
end;
dtInt16,
dtUInt16:
begin
ASQLDataType := MYSQL_TYPE_SHORT;
ASQLUnsigned := AType = dtUInt16;
end;
dtInt32,
dtUInt32:
begin
ASQLDataType := MYSQL_TYPE_LONG;
ASQLUnsigned := AType = dtUInt32;
end;
dtInt64,
dtUInt64:
begin
ASQLDataType := MYSQL_TYPE_LONGLONG;
ASQLUnsigned := AType = dtUInt64;
end;
dtSingle:
ASQLDataType := MYSQL_TYPE_FLOAT;
dtDouble,
dtExtended:
ASQLDataType := MYSQL_TYPE_DOUBLE;
dtCurrency:
begin
ASQLDataType := MYSQL_TYPE_DECIMAL;
ASQLLen := 18 + 2;
end;
dtBCD,
dtFmtBCD:
begin
ASQLDataType := MYSQL_TYPE_DECIMAL;
if APrec = 0 then
APrec := AFmtOpts.MaxBcdPrecision;
ASQLLen := APrec + 2;
end;
dtDateTime:
ASQLDataType := MYSQL_TYPE_DATETIME;
dtDateTimeStamp:
ASQLDataType := MYSQL_TYPE_TIMESTAMP;
dtTime:
ASQLDataType := MYSQL_TYPE_TIME;
dtDate:
ASQLDataType := MYSQL_TYPE_DATE;
dtAnsiString,
dtMemo,
dtHMemo:
begin
ASQLDataType := MYSQL_TYPE_VAR_STRING;
if (AType = dtAnsiString) and (ALen = 0) then
ASQLLen := AFmtOpts.MaxStringSize
else if (FStmt <> nil) and (Session.Encoder.Encoding = ecUTF8) then
ASQLLen := ALen * C_FD_MaxUTF8Len
else
ASQLLen := ALen;
end;
dtWideString,
dtWideMemo,
dtXML,
dtWideHMemo:
begin
ASQLDataType := MYSQL_TYPE_VAR_STRING;
if (AType = dtWideString) and (ALen = 0) then
ASQLLen := AFmtOpts.MaxStringSize
else if (FStmt = nil) or (Session.Encoder.Encoding = ecUTF8) then
ASQLLen := ALen * C_FD_MaxUTF8Len
else
ASQLLen := ALen;
end;
dtByteString,
dtBlob,
dtHBlob,
dtHBFile:
begin
ASQLDataType := MYSQL_TYPE_BLOB;
if (AType = dtByteString) and (ALen = 0) then
ASQLLen := AFmtOpts.MaxStringSize
else
ASQLLen := ALen;
end;
dtGUID:
begin
ASQLDataType := MYSQL_TYPE_VAR_STRING;
ASQLLen := 38;
end;
dtBoolean:
if not AInput and (MyConnection.FTinyIntFormat = dtBoolean) then begin
ASQLDataType := MYSQL_TYPE_BIT;
ASQLLen := 1;
end
else
ASQLDataType := MYSQL_TYPE_TINY;
else
ASQLDataType := 0;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.SQL2FDDataType(ASQLDataType: enum_field_types;
ASQLUnsigned, ASQLIsBinary, ASQLIsNum: Boolean; ASQLLen, ASQLDecimals: my_ulong;
out AType: TFDDataType; var AAttrs: TFDDataAttributes; out ALen: LongWord;
out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions);
begin
AType := dtUnknown;
ALen := 0;
APrec := 0;
AScale := 0;
Exclude(AAttrs, caFixedLen);
Exclude(AAttrs, caBlobData);
Include(AAttrs, caSearchable);
case ASQLDataType of
MYSQL_TYPE_BIT:
if ASQLLen = 1 then
AType := dtBoolean
else begin
AType := dtByteString;
ALen := (ASQLLen + 7) div 8;
Include(AAttrs, caFixedLen);
end;
MYSQL_TYPE_TINY:
begin
if (ASQLLen = 1) and (MyConnection.FTinyIntFormat = dtBoolean) then
AType := dtBoolean
else if ASQLUnsigned then
AType := dtByte
else
AType := dtSByte;
APrec := ASQLLen;
end;
MYSQL_TYPE_SHORT:
begin
if ASQLUnsigned then
AType := dtUInt16
else
AType := dtInt16;
APrec := ASQLLen;
end;
MYSQL_TYPE_LONG,
MYSQL_TYPE_INT24:
begin
if ASQLUnsigned then
AType := dtUInt32
else
AType := dtInt32;
APrec := ASQLLen;
end;
MYSQL_TYPE_LONGLONG:
begin
if ASQLUnsigned then
AType := dtUInt64
else
AType := dtInt64;
APrec := ASQLLen;
end;
MYSQL_TYPE_FLOAT,
MYSQL_TYPE_DOUBLE:
begin
if ASQLLen = 0 then begin
if ASQLDataType = MYSQL_TYPE_FLOAT then
AType := dtSingle
else
AType := dtDouble
end
else begin
if ASQLLen = 12 then
AType := dtSingle
else
AType := dtDouble;
end;
APrec := ASQLLen;
AScale := ASQLDecimals;
end;
MYSQL_TYPE_DECIMAL,
MYSQL_TYPE_NEWDECIMAL:
begin
if ASQLDecimals = 0 then
if ASQLUnsigned then begin
if ASQLLen <= 3 then
AType := dtByte
else if ASQLLen <= 5 then
AType := dtUInt16
else if ASQLLen <= 10 then
AType := dtUInt32
else if ASQLLen <= 21 then
AType := dtUInt64;
end
else begin
if ASQLLen <= 2 then
AType := dtSByte
else if ASQLLen <= 4 then
AType := dtInt16
else if ASQLLen <= 9 then
AType := dtInt32
else if ASQLLen <= 20 then
AType := dtInt64;
end;
APrec := ASQLLen;
if ASQLDecimals > 0 then
Dec(APrec);
if not ASQLUnsigned then
Dec(APrec);
AScale := ASQLDecimals;
if AType = dtUnknown then
if AFmtOpts.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
MYSQL_TYPE_DATE,
MYSQL_TYPE_NEWDATE:
AType := dtDate;
MYSQL_TYPE_TIME:
AType := dtTime;
MYSQL_TYPE_DATETIME:
AType := dtDateTime;
MYSQL_TYPE_YEAR:
AType := dtUInt16;
MYSQL_TYPE_TIMESTAMP:
begin
AType := dtDateTimeStamp;
Include(AAttrs, caRowVersion);
Include(AAttrs, caAllowNull);
end;
MYSQL_TYPE_ENUM,
MYSQL_TYPE_SET,
MYSQL_TYPE_VAR_STRING,
MYSQL_TYPE_STRING,
MYSQL_TYPE_VARCHAR:
if ASQLLen <= AFmtOpts.MaxStringSize then begin
ALen := ASQLLen;
if ASQLIsBinary then
AType := dtByteString
else if Session.Encoder.Encoding = ecUTF8 then begin
AType := dtWideString;
// MySQL multiplies ASQLLen (in characters) by 3 for UTF8 client character set.
// This is for normal result sets only, not for output parameters.
if not FGetOutParams then
ALen := ASQLLen div 3;
end
else
AType := dtAnsiString;
if ASQLDataType = MYSQL_TYPE_STRING then
Include(AAttrs, caFixedLen);
end
else begin
if ASQLIsBinary then
AType := dtBlob
else if Session.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo;
Include(AAttrs, caBlobData);
end;
MYSQL_TYPE_TINY_BLOB,
MYSQL_TYPE_MEDIUM_BLOB,
MYSQL_TYPE_LONG_BLOB,
MYSQL_TYPE_BLOB:
if ASQLLen <= AFmtOpts.MaxStringSize then begin
ALen := ASQLLen;
if ASQLIsBinary then
AType := dtByteString
else if Session.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
end
else begin
if ASQLIsBinary then
AType := dtBlob
else if Session.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
MYSQL_TYPE_JSON:
begin
AType := dtWideMemo;
Include(AAttrs, caBlobData);
end;
MYSQL_TYPE_NULL:
if ASQLIsNum then
AType := dtInt32
else if Session.Encoder.Encoding = ecUTF8 then
AType := dtWideString
else
AType := dtAnsiString;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.CreateParamInfos(ABatchSize: Integer);
var
n, i, j: Integer;
pInfo: PFDMySQLVarInfoRec;
oParams: TFDParams;
oParam: TFDParam;
oVar: TMySQLVariable;
oFmtOpts: TFDFormatOptions;
eDestFldType: TFieldType;
lUnsigned: Boolean;
iSize: my_ulong;
eAttrs: TFDDataAttributes;
iLen: LongWord;
iPrec, iScale: Integer;
begin
oParams := GetParams;
if (oParams.Count = 0) or (FStmt = nil) then
Exit;
oFmtOpts := FOptions.FormatOptions;
n := FStmt.Params.Count div ABatchSize;
SetLength(FParInfos, n);
for i := 0 to n - 1 do begin
pInfo := @FParInfos[i];
case GetParams.BindMode of
pbByName: oParam := oParams.FindParam(oParams.Markers[i]);
pbByNumber: oParam := oParams.FindParam(i + 1);
else oParam := nil;
end;
if oParam = nil then begin
pInfo^.FPos := -1;
Continue;
end;
oVar := FStmt.Params[i];
pInfo^.FVar := oVar;
pInfo^.FPos := oParam.Index + 1;
if (oVar.DumpLabel = '') or (oVar.DumpLabel[1] = '#') then
oVar.DumpLabel := oParam.DisplayName;
pInfo^.FParamType := oParam.ParamType;
pInfo^.FSrcFieldType := oParam.DataType;
if oParam.DataType = ftUnknown then
ParTypeUnknownError(oParam);
oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType,
oParam.FDDataType, oParam.Size, oParam.Precision, oParam.NumericScale,
eDestFldType, pInfo^.FSize, pInfo^.FPrec, pInfo^.FScale,
pInfo^.FSrcDataType, pInfo^.FDestDataType, False);
FD2SQLDataType(pInfo^.FDestDataType, pInfo^.FSize, pInfo^.FPrec, pInfo^.FScale,
pInfo^.FOutSQLDataType, lUnsigned, iSize, True, oFmtOpts);
SQL2FDDataType(pInfo^.FOutSQLDataType, lUnsigned,
pInfo^.FDestDataType in [dtByteString, dtBlob, dtHBlob, dtHBFile], False,
iSize, oFmtOpts.MaxBcdScale, pInfo^.FOutDataType, eAttrs, iLen, iPrec, iScale, oFmtOpts);
oVar.DataType := pInfo^.FOutSQLDataType;
oVar.FDDataType := pInfo^.FOutDataType;
oVar.Unsigned := lUnsigned;
oVar.FixedLen := eDestFldType in [ftFixedChar, ftFixedWideChar, ftBytes];
oVar.DataSize := iSize;
oVar.DumpLabel := oParam.SQLName;
for j := 1 to ABatchSize - 1 do
FStmt.Params[j * n + i].Assign(oVar);
end;
FStmt.BindParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.CreateColInfos;
var
pInfo: PFDMySQLVarInfoRec;
i: Integer;
oFld: TMySQLField;
name: PFDAnsiString;
srcname: PFDAnsiString;
db: PFDAnsiString;
table: PFDAnsiString;
type_: Byte;
length_: LongWord;
flags: LongWord;
decimals: LongWord;
charset: LongWord;
oFmtOpts: TFDFormatOptions;
oEnc: TFDEncoder;
oVar: TMySQLVariable;
lUnsigned: Boolean;
iSize: my_ulong;
eAttrs: TFDDataAttributes;
iLen: LongWord;
iPrec, iScale: Integer;
begin
oFmtOpts := FOptions.FormatOptions;
oEnc := Session.Encoder;
SetLength(FColInfos, FCursor.FieldCount);
for i := 0 to Length(FColInfos) - 1 do begin
oFld := FCursor.Fields[i];
pInfo := @FColInfos[i];
if FStmt <> nil then
oVar := FStmt.Fields[i]
else
oVar := nil;
name := nil;
srcname := nil;
db := nil;
table := nil;
type_ := 0;
length_ := 0;
flags := 0;
decimals := 0;
charset := 0;
oFld.GetInfo(name, srcname, table, db, type_, length_, flags, decimals,
charset, FStmt = nil);
// MySQL returns BINARY_FLAG for non-DBMS column based SELECT items,
// like a DAYNAME(SYSDATE()). So, just workaround this issue.
if ((srcname = nil) or (srcname^ = TFDAnsiChar(#0))) and
(type_ = MYSQL_TYPE_VAR_STRING) and (flags and BINARY_FLAG <> 0) then begin
flags := flags and not BINARY_FLAG;
if Session.Encoder.Encoding = ecUTF8 then
length_ := length_ * C_FD_MaxUTF8Len;
end;
pInfo^.FPos := i + 1;
pInfo^.FVar := oVar;
pInfo^.FName := oEnc.Decode(name, -1);
pInfo^.FOriginDBName := oEnc.Decode(db, -1);
pInfo^.FOriginTabName := oEnc.Decode(table, -1);
pInfo^.FOriginColName := oEnc.Decode(srcname, -1);
pInfo^.FAttrs := [];
if (flags and NOT_NULL_FLAG) = 0 then
Include(pInfo^.FAttrs, caAllowNull);
if (flags and AUTO_INCREMENT_FLAG) <> 0 then begin
Include(pInfo^.FAttrs, caAutoInc);
Include(pInfo^.FAttrs, caAllowNull);
end;
if (MyConnection.FServerVersion >= mvMySQL050200) and
not (caAutoInc in pInfo^.FAttrs) and
((flags and NO_DEFAULT_VALUE_FLAG) = 0) then
Include(pInfo^.FAttrs, caDefault);
SQL2FDDataType(type_, (flags and UNSIGNED_FLAG) <> 0,
((charset = 63) or (charset = 0)) and ((flags and BINARY_FLAG) <> 0),
(flags and NUM_FLAG) <> 0, length_, decimals, pInfo^.FSrcDataType,
pInfo^.FAttrs, pInfo^.FSize, pInfo^.FPrec, pInfo^.FScale, oFmtOpts);
if GetMetaInfoKind = mkNone then
oFmtOpts.ResolveDataType(pInfo^.FName, '',
pInfo^.FSrcDataType, pInfo^.FSize, pInfo^.FPrec, pInfo^.FScale,
pInfo^.FDestDataType, pInfo^.FSize, True)
else
pInfo^.FDestDataType := pInfo^.FSrcDataType;
FD2SQLDataType(pInfo^.FDestDataType, pInfo^.FSize, pInfo^.FPrec, pInfo^.FScale,
pInfo^.FOutSQLDataType, lUnsigned, iSize, False, oFmtOpts);
SQL2FDDataType(pInfo^.FOutSQLDataType, lUnsigned,
pInfo^.FDestDataType in [dtByteString, dtBlob, dtHBlob, dtHBFile], False,
iSize, pInfo^.FScale, pInfo^.FOutDataType, eAttrs, iLen, iPrec, iScale, oFmtOpts);
if oVar <> nil then begin
oVar.DataType := pInfo^.FOutSQLDataType;
oVar.FDDataType := pInfo^.FOutDataType;
oVar.Unsigned := lUnsigned;
oVar.FixedLen := caFixedLen in pInfo^.FAttrs;
oVar.DataSize := iSize;
oVar.DumpLabel := pInfo^.FName;
end;
if not CheckFetchColumn(pInfo^.FSrcDataType, pInfo^.FAttrs) then
pInfo^.FPos := -1;
end;
if FStmt <> nil then
FStmt.BindColumns;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.DestroyParamInfos;
begin
SetLength(FParInfos, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.DestroyColInfos;
begin
SetLength(FColInfos, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.PrepareBase;
begin
FStmt.Prepare(FDbCommandText);
SetupReader(FStmt);
if FStmt.Params.Count > 0 then
CreateParamInfos(1);
// Do not create here column infos or output param infos, we does not
// know how programmer will use command - Execute or Open. If Execute,
// then create param infos, else column infos.
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalPrepare;
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
i: Integer;
begin
UpdateExecDirect;
// generate metadata SQL command
if GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone then begin
GetSelectMetaInfoParams(rName);
GenerateSelectMetaInfo(rName);
i := 1;
while i <= Length(FDbCommandText) do begin
SetLength(FMetaInfoSQLs, Length(FMetaInfoSQLs) + 1);
FMetaInfoSQLs[Length(FMetaInfoSQLs) - 1] := FDExtractFieldName(FDbCommandText, i);
end;
end
// generate metadata SQL command
else if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
GetConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(Trim(GetCommandText()), FSPParsedName, Self, []);
FDbCommandText := '';
if fiMeta in FOptions.FetchOptions.Items then begin
GenerateStoredProcParams(FSPParsedName);
if (Session.ServerVersion < mvMySQL050503) or (Session.ClientVersion < mvMySQL050503) then
// output params are not supported in prepared statement mode before 5.5.3
UpdateExecDirect;
end;
if not FUseDirectExec then
FSPParsedName.FObject := '*' + FSPParsedName.FObject;
// If an exact stored proc kind is not specified, then do not build a stored
// proc call SQL, we does not know how a programmer will use a command - Execute
// or Open. If Execute, then - EXEC PROC, else - SELECT.
if (FDbCommandText = '') and (GetCommandKind <> skStoredProc) then
GenerateStoredProcCall(FSPParsedName, GetCommandKind);
end;
// adjust SQL command
GenerateLimitSelect();
GenerateParamMarkers();
if not FUseDirectExec then begin
FStmt := TMySQLStatement.Create(Session, Self);
if GetCommandKind <> skStoredProc then
PrepareBase;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.CheckSPPrepared(ASPUsage: TFDPhysCommandKind);
begin
if (FDbCommandText <> '') or (GetCommandKind <> skStoredProc) then
Exit;
GenerateStoredProcCall(FSPParsedName, ASPUsage);
if FStmt <> nil then
PrepareBase;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalUnprepare;
begin
SetLength(FMetaInfoSQLs, 0);
FPreparedBatchSize := 0;
DestroyColInfos;
DestroyParamInfos;
if FStmt <> nil then begin
FDFreeAndNil(FCursor);
FStmt.Unprepare;
FDFreeAndNil(FStmt);
end
else
CloseStatement(True, -1);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalUseStandardMetadata: Boolean;
begin
Result := not ((FGetOutParams or GetNextRecordSet) and
(GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]));
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean;
begin
Result := OpenBlocked;
if ATabInfo.FSourceID = -1 then begin
ATabInfo.FSourceName := GetCommandText;
ATabInfo.FSourceID := 1;
FColumnIndex := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean;
var
pColInfo: PFDMySQLVarInfoRec;
begin
if FColumnIndex < Length(FColInfos) then begin
pColInfo := @FColInfos[FColumnIndex];
AColInfo.FSourceName := pColInfo^.FName;
AColInfo.FSourceID := pColInfo^.FPos;
AColInfo.FSourceType := pColInfo^.FSrcDataType;
AColInfo.FSourceTypeName := pColInfo^.FSrcTypeName;
AColInfo.FOriginTabName.FCatalog := pColInfo^.FOriginDBName;
AColInfo.FOriginTabName.FObject := pColInfo^.FOriginTabName;
AColInfo.FOriginColName := pColInfo^.FOriginColName;
AColInfo.FType := pColInfo^.FDestDataType;
AColInfo.FLen := pColInfo^.FSize;
AColInfo.FPrec := pColInfo^.FPrec;
AColInfo.FScale := pColInfo^.FScale;
AColInfo.FAttrs := pColInfo^.FAttrs;
AColInfo.FForceAddOpts := [];
if caAutoInc in pColInfo^.FAttrs then
Include(AColInfo.FForceAddOpts, coAfterInsChanged);
Inc(FColumnIndex);
Result := True;
end
else
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.SetParamValue(AFmtOpts: TFDFormatOptions;
AParam: TFDParam; AVar: TMySQLVariable; ApInfo: PFDMySQLVarInfoRec;
AParIndex: Integer);
var
pData: PByte;
iSize, iSrcSize: LongWord;
oExtStr: TStream;
oIntStr: TMySQLBlobStream;
lExtStream: Boolean;
begin
pData := nil;
iSize := 0;
// null
if (AParam.DataType <> ftStream) and AParam.IsNulls[AParIndex] then
AVar.SetData(nil, 0)
// assign BLOB stream
else if AParam.IsStreams[AParIndex] then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TMySQLBlobStream) and (TMySQLBlobStream(oExtStr).OwningObj = Self));
if (AParam.DataType <> ftStream) and not lExtStream or
not AVar.LongData then
UnsupParamObjError(AParam);
oIntStr := TMySQLBlobStream.Create(AVar, smOpenWrite);
try
if lExtStream then
oIntStr.CopyFrom(oExtStr, -1)
else begin
FHasIntStreams := True;
AParam.AsStreams[AParIndex] := oIntStr;
end;
finally
if lExtStream then
FDFree(oIntStr);
end;
end
// conversion is not required
else if ApInfo^.FOutDataType = ApInfo^.FSrcDataType then begin
// byte string data, then optimizing - get data directly
if AVar.LongData then begin
oIntStr := TMySQLBlobStream.Create(AVar, smOpenWrite);
try
AParam.GetBlobRawData(iSize, pData, AParIndex);
oIntStr.WriteStr(pData, iSize, ApInfo^.FOutDataType);
finally
FDFree(oIntStr);
end;
end
else if ApInfo^.FOutDataType in (C_FD_VarLenTypes {$IFDEF NEXTGEN} - C_FD_AnsiTypes {$ENDIF}) then begin
AParam.GetBlobRawData(iSize, pData, AParIndex);
AVar.SetData(pData, iSize);
end
else begin
iSize := AParam.GetDataLength(AParIndex);
FBuffer.Check(iSize);
AParam.GetData(FBuffer.Ptr, AParIndex);
AVar.SetData(FBuffer.Ptr, iSize);
end;
end
// conversion is required
else begin
// calculate buffer size to move param values
iSrcSize := AParam.GetDataLength(AParIndex);
FBuffer.Extend(iSrcSize, iSize, ApInfo^.FSrcDataType, ApInfo^.FOutDataType);
// get, convert and set parameter value
AParam.GetData(FBuffer.Ptr, AParIndex);
AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FOutDataType,
FBuffer.Ptr, iSrcSize, FBuffer.FBuffer, FBuffer.Size, iSize, Session.Encoder);
if AVar.LongData then begin
oIntStr := TMySQLBlobStream.Create(AVar, smOpenWrite);
try
oIntStr.WriteStr(FBuffer.Ptr, iSize, ApInfo^.FOutDataType);
finally
FDFree(oIntStr);
end;
end
else
AVar.SetData(FBuffer.Ptr, iSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.SetParamValues(ABatchSize, AOffset: Integer);
var
oParams: TFDParams;
oFmtOpts: TFDFormatOptions;
oParam: TFDParam;
oVar: TMySQLVariable;
iParamsCount, i, j: Integer;
pParInfo: PFDMySQLVarInfoRec;
begin
FHasIntStreams := False;
oParams := GetParams;
if oParams.Count = 0 then
Exit;
oFmtOpts := GetOptions.FormatOptions;
iParamsCount := Length(FParInfos);
for i := 0 to iParamsCount - 1 do begin
pParInfo := @FParInfos[i];
if pParInfo^.FPos <> -1 then begin
oParam := oParams[pParInfo^.FPos - 1];
if (pParInfo^.FVar <> nil) and
(oParam.DataType <> ftCursor) and
(oParam.ParamType in [ptInput, ptInputOutput, ptUnknown]) then
CheckParamMatching(oParam, pParInfo^.FSrcFieldType, pParInfo^.FParamType, 0);
for j := 0 to ABatchSize - 1 do begin
if j = 0 then
oVar := pParInfo^.FVar
else
oVar := FStmt.Params[j * iParamsCount + pParInfo^.FPos - 1];
SetParamValue(oFmtOpts, oParam, oVar, pParInfo, j + AOffset);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.DataValue2MySQL(AData: Pointer; ALen: LongWord;
AType: TFDDataType; out ATypeSupported: Boolean): TFDByteString;
const
SDateFmt: String = '''%.4d-%.2d-%.2d''';
STimeFmt: String = '''%s%.2d:%.2d:%.2d.%.6d''';
SDateTimeFmt1: String = '''%.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.6d''';
SDateTimeFmt2: String = '''%.4d%.2d%.2d%.2d%.2d%.2d''';
SGUIDFmt: String = '''%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x''';
var
iSz: Integer;
aBuff: array [0..65] of Char;
pBuff: PChar;
s: String;
dt: TDateTime;
y, mo, d, h, mi, se, ms: Word;
sFmt: String;
rTS: TSQLTimeStamp;
procedure RetStr(const AStr: String);
begin
s := AStr;
pBuff := PChar(s);
iSz := Length(s);
end;
function EncodeUTF8(AData: Pointer; ALen: LongWord; AEncoding: TFDEncoding): TFDByteString;
const
C_UTF8: array [0 .. 4] of Byte = (Ord('_'), Ord('u'), Ord('t'), Ord('f'), Ord('8'));
C_UTF8MB4: array [0 .. 7] of Byte = (Ord('_'), Ord('u'), Ord('t'), Ord('f'), Ord('8'), Ord('m'), Ord('b'), Ord('4'));
var
pUTF8: Pointer;
iSz: Integer;
pEnc: PByte;
iEnc: Integer;
begin
pUTF8 := nil;
iSz := Session.Encoder.Encode(AData, ALen, pUTF8, AEncoding, ecUTF8);
if Session.UTf8mb4 then begin
pEnc := @C_UTF8MB4[0];
iEnc := SizeOf(C_UTF8MB4);
end
else begin
pEnc := @C_UTF8[0];
iEnc := SizeOf(C_UTF8);
end;
SetLength(Result, (iSz * 2 + iEnc + 4) * SizeOf(TFDAnsiChar));
iSz := Session.EscapeString(PFDAnsiString(Result) + (iEnc + 1) * SizeOf(TFDAnsiChar),
PFDAnsiString(pUTF8), iSz);
Move(pEnc^, PFDAnsiString(Result)^, iEnc);
(PFDAnsiString(Result) + iEnc)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + iSz + iEnc + 1)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + iSz + iEnc + 2)^ := TFDAnsiChar(#0);
SetLength(Result, iSz + iEnc + 3);
end;
begin
SetLength(Result, 0);
ATypeSupported := True;
pBuff := aBuff;
iSz := SizeOf(aBuff) div SizeOf(Char);
case AType of
dtBoolean:
if MyConnection.FServerVersion >= mvMySQL050000 then
if PWordBool(AData)^ then
RetStr('TRUE')
else
RetStr('FALSE')
else
if PWordBool(AData)^ then
RetStr('1')
else
RetStr('0');
dtSByte:
FDInt2Str(AData, SizeOf(ShortInt), pBuff, iSz, False, 0);
dtInt16:
FDInt2Str(AData, SizeOf(SmallInt), pBuff, iSz, False, 0);
dtInt32:
FDInt2Str(AData, SizeOf(Integer), pBuff, iSz, False, 0);
dtInt64:
FDInt2Str(AData, SizeOf(Int64), pBuff, iSz, False, 0);
dtByte:
FDInt2Str(AData, SizeOf(Byte), pBuff, iSz, True, 0);
dtUInt16:
FDInt2Str(AData, SizeOf(Word), pBuff, iSz, True, 0);
dtUInt32:
FDInt2Str(AData, SizeOf(Cardinal), pBuff, iSz, True, 0);
dtUInt64:
FDInt2Str(AData, SizeOf(UInt64), pBuff, iSz, True, 0);
dtCurrency:
FDCurr2Str(pBuff, iSz, PCurrency(AData)^, '.');
dtSingle:
RetStr(FDFloat2Str(PSingle(AData)^, '.', 8));
dtDouble:
RetStr(FDFloat2Str(PDouble(AData)^, '.', 16));
dtExtended:
RetStr(FDFloat2Str(PExtended(AData)^, '.', 20));
dtBCD,
dtFmtBCD:
FDBCD2Str(pBuff, iSz, PBcd(AData)^, '.');
dtDate:
begin
rTS := FDDate2SQLTimeStamp(PInteger(AData)^);
iSz := WideFormatBuf(aBuff[0], iSz, PChar(SDateFmt)^, Length(SDateFmt),
[rTS.Year, rTS.Month, rTS.Day]);
end;
dtTime:
begin
rTS := FDTime2SQLTimeStamp(PInteger(AData)^);
// Delphi does not support negative time value, but MySQL does
if PInteger(AData)^ < 0 then
s := '-'
else
s := '';
iSz := WideFormatBuf(aBuff[0], iSz, PChar(STimeFmt)^, Length(STimeFmt),
[s, rTS.Hour, rTS.Minute, rTS.Second, rTS.Fractions * 1000]);
end;
dtDateTime:
begin
dt := FDMSecs2DateTime(PDateTimeRec(AData)^.DateTime);
DecodeDate(dt, y, mo, d);
DecodeTime(dt, h, mi, se, ms);
iSz := WideFormatBuf(aBuff[0], iSz, PChar(SDateTimeFmt1)^, Length(SDateTimeFmt1),
[y, mo, d, h, mi, se, ms * 1000]);
end;
dtDateTimeStamp:
begin
rTS := PSQLTimeStamp(AData)^;
if MyConnection.FServerVersion >= mvMySQL040100 then
sFmt := SDateTimeFmt1
else
sFmt := SDateTimeFmt2;
iSz := WideFormatBuf(aBuff[0], iSz, PChar(sFmt)^, Length(sFmt),
[rTS.Year, rTS.Month, rTS.Day, rTS.Hour, rTS.Minute, rTS.Second, rTS.Fractions * 1000]);
end;
dtByteString,
dtBlob:
if (ALen = 0) and FOptions.FormatOptions.StrsEmpty2Null then
RetStr('NULL')
else begin
SetLength(Result, (ALen * 2 + 4) * SizeOf(TFDAnsiChar));
FDBin2HexBS(AData, ALen, PByte(Result) + 2 * SizeOf(TFDAnsiChar));
PFDAnsiString(Result)^ := TFDAnsiChar('x');
(PFDAnsiString(Result) + 1)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + ALen * 2 + 2)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + ALen * 2 + 3)^ := TFDAnsiChar(#0);
end;
dtAnsiString,
dtMemo:
if (ALen = 0) and FOptions.FormatOptions.StrsEmpty2Null then
RetStr('NULL')
else if Session.Encoder.Encoding = ecUTF8 then
Result := EncodeUTF8(AData, ALen, ecANSI)
else begin
SetLength(Result, (ALen * 2 + 4) * SizeOf(TFDAnsiChar));
iSz := Session.EscapeString(PFDAnsiString(Result) + 1 * SizeOf(TFDAnsiChar),
PFDAnsiString(AData), ALen);
PFDAnsiString(Result)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + iSz + 1)^ := TFDAnsiChar('''');
(PFDAnsiString(Result) + iSz + 2)^ := TFDAnsiChar(#0);
SetLength(Result, iSz + 3);
end;
dtWideString,
dtWideMemo,
dtXML:
if (ALen = 0) and FOptions.FormatOptions.StrsEmpty2Null then
RetStr('NULL')
else
Result := EncodeUTF8(AData, ALen, ecUTF16);
dtGUID:
iSz := WideFormatBuf(aBuff[0], iSz, PChar(SGUIDFmt)^, Length(SGUIDFmt),
[PGUID(AData)^.D1, PGUID(AData)^.D2, PGUID(AData)^.D3, PGUID(AData)^.D4[0],
PGUID(AData)^.D4[1], PGUID(AData)^.D4[2], PGUID(AData)^.D4[3],
PGUID(AData)^.D4[4], PGUID(AData)^.D4[5], PGUID(AData)^.D4[6],
PGUID(AData)^.D4[7]]);
else
ATypeSupported := False;
end;
if Length(Result) = 0 then
Result := Session.Encoder.Encode(pBuff, iSz);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetBatchSQL(ABatchSize: Integer): String;
var
sValues: String;
i, iOrigLen, iFullLen: Integer;
begin
Result := FDbCommandText;
if FSQLValuesPosEnd = 0 then
FSQLValuesPosEnd := Length(Result);
sValues := ',' + Copy(Result, FSQLValuesPos + 6, FSQLValuesPosEnd - (FSQLValuesPos + 6) + 1);
iOrigLen := Length(Result);
iFullLen := iOrigLen + (ABatchSize - 1) * Length(sValues);
SetLength(Result, iFullLen);
if FSQLValuesPosEnd < Length(FDbCommandText) then
Move(Result[FSQLValuesPosEnd + 1], Result[iFullLen - (iOrigLen - FSQLValuesPosEnd) + 1],
(iOrigLen - FSQLValuesPosEnd) * SizeOf(Char));
for i := 0 to ABatchSize - 2 do
Move(sValues[1], Result[FSQLValuesPosEnd + 1 + i * Length(sValues)],
Length(sValues) * SizeOf(Char));
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetExpandedSQL(ATimes, AOffset: Integer): TFDByteString;
var
pSrcCh, pDestCh, pDestEnd: PByte;
iFullLen, iPar, iRow: Integer;
sSQL: String;
sSubst, sEncSQL, sNULL, sQMark: TFDByteString;
oParam: TFDParam;
iSize, iSrcDataLen, iDestDataLen: LongWord;
iPrec, iScale: Integer;
iFieldType: TFieldType;
iSrcDataType, iDestDataType: TFDDataType;
oFmtOpts: TFDFormatOptions;
lTypeSupported: Boolean;
oParams: TFDParams;
oStr: TStream;
oEnc: TFDEncoder;
procedure ErrorParamType(const AReason: String);
begin
FDException(Self, [S_FD_LPhys, S_FD_MySQLId], er_FD_MySQLBadParams,
[oParam.Name, AReason]);
end;
procedure ExtendDest(AMinLen: Integer);
var
iPos: Integer;
begin
if AMinLen < 1024 then
AMinLen := 1024;
if pDestCh = nil then
iPos := 0
else
iPos := pDestCh - PByte(Result);
SetLength(Result, oEnc.EncodedLength(Result) + AMinLen);
pDestCh := PByte(Result) + iPos;
pDestEnd := PByte(Result) + oEnc.EncodedLength(Result);
end;
procedure WriteDest(const AStr: TFDByteString);
var
iLen: Integer;
begin
iLen := oEnc.EncodedLength(AStr);
if pDestCh + iLen >= pDestEnd then
ExtendDest(iLen);
Move(PByte(AStr)^, pDestCh^, iLen * SizeOf(TFDAnsiChar));
Inc(pDestCh, iLen);
end;
begin
oEnc := Session.Encoder;
if (ATimes - AOffset > 1) and
(GetCommandKind in [skInsert, skMerge]) and (FSQLValuesPos > 0) then
sSQL := GetBatchSQL(ATimes - AOffset)
else
sSQL := FDbCommandText;
sEncSQL := oEnc.Encode(sSQL);
oParams := GetParams();
if oParams.Count = 0 then
Result := sEncSQL
else begin
oFmtOpts := GetOptions.FormatOptions;
pSrcCh := PByte(sEncSQL);
pDestCh := nil;
ExtendDest(0);
iPar := 0;
iRow := AOffset;
SetLength(sNULL, 0);
SetLength(sQMark, 0);
while True do begin
while (PFDAnsiString(pSrcCh)^ <> TFDAnsiChar(#0)) and
(PFDAnsiString(pSrcCh)^ <> TFDAnsiChar('?')) do begin
if pDestCh = pDestEnd then
ExtendDest(0);
pDestCh^ := pSrcCh^;
Inc(pDestCh);
Inc(pSrcCh);
end;
if PFDAnsiString(pSrcCh)^ = TFDAnsiChar(#0) then
Break
else if PFDAnsiString(pSrcCh)^ = TFDAnsiChar('?') then begin
oParam := nil;
while True do begin
case GetParams.BindMode of
pbByName: oParam := oParams.FindParam(oParams.Markers[iPar]);
pbByNumber: oParam := oParams.FindParam(iPar + 1);
end;
if (oParam = nil) or (oParam.ParamType in [ptUnknown, ptInput, ptInputOutput]) then
Break;
if iPar = oParams.Markers.Count - 1 then begin
oParam := nil;
Break;
end;
Inc(iPar);
end;
if oParam <> nil then begin
// check parameter definition
if oParam.ParamType in [ptOutput, ptResult] then
ErrorParamType('Output parameters are not supported');
if oParam.DataType = ftUnknown then
ParTypeUnknownError(oParam);
lTypeSupported := True;
iFieldType := ftUnknown;
iSize := 0;
iPrec := 0;
iSrcDataType := dtUnknown;
iDestDataType := dtUnknown;
iDestDataLen := 0;
oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType, oParam.FDDataType,
oParam.Size, oParam.Precision, oParam.NumericScale, iFieldType, iSize, iPrec, iScale,
iSrcDataType, iDestDataType, False);
// null
if oParam.IsNulls[iRow] then begin
if Length(sNULL) = 0 then
sNULL := oEnc.Encode('NULL');
sSubst := sNULL;
end
// assign BLOB stream
else if oParam.IsStreams[iRow] then begin
oStr := oParam.AsStreams[iRow];
if (oStr = nil) or (oStr.Size < 0) then
UnsupParamObjError(oParam);
iSize := oStr.Size;
FBuffer.Check(iSize);
oStr.Position := 0;
oStr.Read(FBuffer.Ptr^, iSize);
sSubst := DataValue2MySQL(FBuffer.Ptr, iSize, iDestDataType,
lTypeSupported);
end
// scalar value
else begin
iSrcDataLen := oParam.GetDataLength(iRow);
// approximating destination data size and allocate buffer
FBuffer.Extend(iSrcDataLen, iDestDataLen, iSrcDataType, iDestDataType);
// fill buffer with value, converting it, if required
oParam.GetData(FBuffer.Ptr, iRow);
oFmtOpts.ConvertRawData(iSrcDataType, iDestDataType, FBuffer.Ptr,
iSrcDataLen, FBuffer.FBuffer, FBuffer.Size, iDestDataLen, oEnc);
sSubst := DataValue2MySQL(FBuffer.Ptr, iDestDataLen, iDestDataType,
lTypeSupported);
end;
if not lTypeSupported then
ParTypeMapError(oParam);
WriteDest(sSubst);
Inc(iPar);
if iPar >= oParams.Markers.Count then begin
iPar := 0;
Inc(iRow);
end;
end
else begin
if Length(sQMark) = 0 then
sQMark := oEnc.Encode('?');
WriteDest(sQMark);
end;
end;
Inc(pSrcCh);
end;
iFullLen := pDestCh - PByte(Result);
SetLength(Result, iFullLen + 1);
(PFDAnsiString(Result) + iFullLen)^ := TFDAnsiChar(#0);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetResultMode: TFDMySQLResultMode;
begin
case MyConnection.FResultMode of
rmStore:
Result := rmStore;
rmUse:
Result := rmUse;
rmChoose:
if FOptions.FetchOptions.Mode in [fmAll, fmExactRecsMax] then
Result := rmStore
else
Result := rmUse;
else
Result := rmStore;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetCursor(AClosing: Boolean; AParIndex: Integer): Boolean;
var
oCon: TFDPhysMySQLConnection;
begin
oCon := MyConnection;
oCon.UpdateInsertId(FStmt, False);
DestroyColInfos;
FDFreeAndNil(FCursor);
if FStmt <> nil then begin
repeat
if not AClosing and (GetResultMode = rmStore) and
(Session.ServerStatus and SERVER_PS_OUT_PARAMS = 0) then
FStmt.StoreResult;
FCursor := FStmt.Describe;
until (FCursor <> nil) or
not FStmt.MoreResults or
not FStmt.NextResult;
end
else begin
repeat
if GetResultMode = rmStore then
FCursor := oCon.FSession.StoreResult
else
FCursor := oCon.FSession.UseResult;
until (FCursor <> nil) or
not oCon.FSession.MoreResults or
not oCon.FSession.NextResult;
end;
if FCursor <> nil then begin
SetupReader(FCursor);
FGetOutParams := AreOutParams();
try
CreateColInfos;
Result := Length(FColInfos) > 0;
if Result and FGetOutParams then begin
GetParamValues(AParIndex);
Result := False;
if not AClosing then
CloseStatement(True, AParIndex);
end;
finally
FGetOutParams := False;
end;
end
else begin
Result := False;
oCon.GetServerOutput;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.CheckArray(ASize: Integer): Boolean;
begin
Result := (ASize = 1) and (FPreparedBatchSize <= 1) or
(ASize = FPreparedBatchSize);
if not Result then begin
FDFreeAndNil(FCursor);
DestroyParamInfos;
FStmt.Unprepare;
FPreparedBatchSize := ASize;
if ASize = 1 then begin
FStmt.Params.Count := Length(FParInfos);
FStmt.Prepare(FDBCommandText);
SetupReader(FStmt);
CreateParamInfos(ASize);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.ExecuteBatchInsert(ATimes, AOffset: Integer;
var ACount: TFDCounter);
var
iMaxSize, iBatchSize, iCurTimes, iCurOffset: Integer;
sSQL: String;
iRows: my_ulonglong;
begin
iBatchSize := ATimes - AOffset;
iMaxSize := 65535 div GetParams.Count;
if iBatchSize > iMaxSize then
iBatchSize := iMaxSize;
iMaxSize := GetOptions.ResourceOptions.ArrayDMLSize;
if (iMaxSize <> $7FFFFFFF) and (iBatchSize > iMaxSize) then
iBatchSize := iMaxSize;
iCurOffset := AOffset;
iCurTimes := AOffset + iBatchSize;
while iCurOffset < ATimes do begin
if iCurTimes > ATimes then begin
iCurTimes := ATimes;
iBatchSize := iCurTimes - iCurOffset;
end;
if not CheckArray(iBatchSize) then begin
sSQL := GetBatchSQL(iBatchSize);
FStmt.Prepare(sSQL);
CreateParamInfos(iBatchSize);
end;
FStmt.Reset;
SetParamValues(iBatchSize, iCurOffset);
try
FStmt.Execute;
finally
iRows := FStmt.AffectedRows;
if iRows <> MYSQL_COUNT_ERROR then
Inc(ACount, iRows);
end;
Inc(iCurOffset, iBatchSize);
Inc(iCurTimes, iBatchSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.DoExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter; AFlush: Boolean);
var
sSQL: TFDByteString;
oCon: TFDPhysMySQLConnection;
i: Integer;
iCount: TFDCounter;
iRows: my_ulonglong;
begin
if GetCommandKind = skStoredProc then
CheckSPPrepared(skStoredProcNoCrs);
ACount := 0;
oCon := MyConnection;
oCon.FLock.Enter;
try
if FStmt <> nil then begin
if (ATimes - AOffset > 1) and
(GetCommandKind in [skInsert, skMerge]) and (FSQLValuesPos > 0) then
ExecuteBatchInsert(ATimes, AOffset, ACount)
else begin
CheckArray(1);
for i := AOffset to ATimes - 1 do begin
if not AFlush then begin
FStmt.Reset;
SetParamValues(1, i);
CheckArrayDMLWithIntStr(FHasIntStreams, ATimes, AOffset);
end;
if FHasIntStreams xor AFlush then begin
ACount := -1;
Exit;
end;
try
try
FStmt.Execute;
finally
iRows := FStmt.AffectedRows;
if iRows <> MYSQL_COUNT_ERROR then
Inc(ACount, iRows)
else
iRows := 0;
end;
CheckExact(ATimes = 1, 1, 0, iRows, False);
except
on E: EMySQLNativeException do begin
E[0].RowIndex := i;
raise;
end;
end;
end;
end;
end
else begin
// For a while driver can create batch only for INSERT INTO statement.
// Probably, a technique similar to FB EXECUTE BLOCK may be used.
if (ATimes - AOffset > 1) and
(GetCommandKind in [skInsert, skMerge]) and (FSQLValuesPos > 0) then
sSQL := GetExpandedSQL(ATimes, AOffset)
// otherwise just emulate batch
else if ATimes - AOffset > 1 then begin
for i := AOffset to ATimes - 1 do begin
iCount := 0;
try
InternalExecute(i + 1, i, iCount);
finally
Inc(ACount, iCount);
end;
CheckExact(False, 1, 0, iCount, False);
end;
Exit;
end
else
sSQL := GetExpandedSQL(ATimes, AOffset);
try
try
oCon.FSession.QuerySB(sSQL, Self);
except
on E: EMySQLNativeException do begin
if ATimes - AOffset = 1 then
E.Errors[0].RowIndex := AOffset;
raise;
end;
end;
finally
if FCursor = nil then begin
iRows := oCon.FSession.AffectedRows;
if iRows <> MYSQL_COUNT_ERROR then
Inc(ACount, iRows);
end;
end;
end;
CloseStatement(True, AOffset);
oCon.GetServerOutput;
if not (GetCommandKind in [skSelect, skSelectForLock, skSelectForUnLock]) then
oCon.UpdateInsertId(FStmt, True);
finally
oCon.FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
DoExecute(ATimes, AOffset, ACount, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalCloseStreams;
var
iTmp: TFDCounter;
begin
if (FStmt <> nil) and FHasIntStreams then begin
GetParams.Close;
DoExecute(1, 0, iTmp, True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalAbort;
var
oCon: TFDPhysMySQLConnection;
begin
oCon := MyConnection;
if oCon.FServerVersion >= mvMySQL050000 then begin
oCon.FSession.KillQuery;
// Workaround for https://bugs.mysql.com/bug.php?id=70618
if oCon.FServerVersion <= mvMySQL050700 then
oCon.QueryValue('SELECT SLEEP(0)', 0);
end
else
inherited InternalAbort;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalOpen(var ACount: TFDCounter): Boolean;
var
sSQL: TFDByteString;
iSQL: Integer;
oCon: TFDPhysMySQLConnection;
oEnc: TFDEncoder;
lFailed: Boolean;
iRows: my_ulonglong;
begin
if GetCommandKind = skStoredProc then
CheckSPPrepared(skStoredProcWithCrs);
ACount := 0;
Result := False;
lFailed := False;
oCon := MyConnection;
oCon.FLock.Enter;
try
try
if FStmt <> nil then begin
if not (FStmt.State in [msInactive, msPrepared, msExecuted, msEOF]) then
Result := True
else begin
CheckArray(1);
FStmt.Reset;
SetParamValues(1, 0);
try
FStmt.Execute;
finally
iRows := FStmt.AffectedRows;
if iRows <> MYSQL_COUNT_ERROR then
ACount := iRows
else
ACount := -1;
end;
Result := GetCursor(False, -1);
end;
end
else if FCursor = nil then begin
oEnc := oCon.FSession.Encoder;
iSQL := 0;
if not (GetMetaInfoKind in [mkNone, mkForeignKeys, mkForeignKeyFields]) then
if Length(FMetaInfoSQLs) = 0 then
SetLength(sSQL, 0)
else
sSQL := oEnc.Encode(FMetaInfoSQLs[0])
else
sSQL := GetExpandedSQL(1, 0);
while oEnc.EncodedLength(sSQL) <> 0 do
try
try
oCon.FSession.QuerySB(sSQL, Self);
SetLength(sSQL, 0);
Result := GetCursor(False, -1);
finally
if FCursor = nil then begin
iRows := oCon.FSession.AffectedRows;
if iRows <> MYSQL_COUNT_ERROR then
ACount := iRows
else
ACount := -1;
end;
end;
except
on E: EMySQLNativeException do
if GetMetaInfoKind <> mkNone then begin
Inc(iSQL);
if iSQL = Length(FMetaInfoSQLs) then
if E.Kind = ekObjNotExists then
SetLength(sSQL, 0)
else
raise
else
sSQL := oEnc.Encode(FMetaInfoSQLs[iSQL]);
end
else
raise;
end;
end;
except
lFailed := True;
raise;
end;
finally
TFDPhysMySQLTransaction(FTransactionObj).InternalCheckState(Self, not lFailed);
oCon.FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalNextRecordSet: Boolean;
var
oCon: TFDPhysMySQLConnection;
begin
Result := False;
oCon := MyConnection;
oCon.FLock.Enter;
try
InternalClose;
if FStmt <> nil then begin
if FStmt.MoreResults and FStmt.NextResult then
Result := GetCursor(False, -1);
end
else begin
if oCon.FSession.MoreResults and oCon.FSession.NextResult then
Result := GetCursor(False, -1);
end;
finally
oCon.FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.AreOutParams: Boolean;
begin
Result := (FCursor <> nil) and
((Session.ServerStatus and SERVER_PS_OUT_PARAMS <> 0) or not Session.MoreResults) and
(GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.GetParamValues(AIndex: Integer);
var
oTab: TFDDatSTable;
i, j: Integer;
s: String;
v: Variant;
oParams: TFDParams;
oPar: TFDParam;
ePrevState: TFDPhysCommandState;
rState: TFDDatSLoadState;
begin
if AIndex < 0 then
AIndex := 0;
oParams := GetParams();
oTab := TFDDatSTable.Create;
oTab.Setup(FOptions);
ePrevState := GetState;
SetState(csOpen);
try
Define(oTab);
oTab.BeginLoadData(rState, lmHavyFetching);
try
if FStmt <> nil then
FStmt.Fetch
else
FCursor.Fetch(1);
FetchRow(oTab, nil);
for i := 0 to oTab.Columns.Count - 1 do begin
oPar := oParams.FindParam(oTab.Columns[i].Name);
if (oPar <> nil) and (oPar.ParamType in [ptOutput, ptInputOutput, ptResult]) then begin
v := oTab.Rows[0].GetData(i);
case oPar.DataType of
ftSingle,
ftFloat,
ftExtended,
ftCurrency,
ftBCD, ftFMTBcd:
if FormatSettings.DecimalSeparator <> '.' then begin
s := v;
j := Pos('.', s);
if j <> 0 then
s[j] := FormatSettings.DecimalSeparator;
oPar.Values[AIndex] := s;
end
else
oPar.Values[AIndex] := v;
ftBoolean:
begin
s := Trim(UpperCase(v));
oPar.Values[AIndex] := (s = '1') or (s = 'TRUE');
end;
else
oPar.Values[AIndex] := v;
end;
end;
end;
finally
oTab.EndLoadData(rState);
end;
finally
SetState(ePrevState);
FDFree(oTab);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.InternalClose;
begin
CloseStatement(False, -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.CloseStatement(AForceClose: Boolean; AIndex: Integer);
var
oCon: TFDPhysMySQLConnection;
begin
oCon := MyConnection;
if (FStmt <> nil) and not (AForceClose or not GetNextRecordSet) then
FStmt.Close;
if AForceClose or not GetNextRecordSet then
if FStmt <> nil then
while FStmt.MoreResults and FStmt.NextResult do begin
GetCursor(True, AIndex);
FStmt.Close;
end
else
while oCon.FSession.MoreResults and oCon.FSession.NextResult do
GetCursor(True, AIndex);
FDFreeAndNil(FCursor);
if not GetNextRecordSet then
oCon.GetServerOutput;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.ProcessResColumn(AFmtOpts: TFDFormatOptions;
AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDMySQLVarInfoRec);
var
pData: Pointer;
iSize, iDestSize: LongWord;
begin
pData := nil;
iSize := 0;
FCursor.GetFieldData(ApInfo^.FPos - 1, pData, iSize);
pData := FBuffer.Check((iSize + 1) * SizeOf(WideChar));
// null
if not FCursor.GetData(ApInfo^.FPos - 1, pData, iSize, ApInfo^.FOutDataType, ApInfo.FAttrs) then
ARow.SetData(AColIndex, nil, 0)
// conversion is not required
else if ApInfo^.FOutDataType = ApInfo^.FDestDataType then
ARow.SetData(AColIndex, pData, iSize)
// conversion is required
else begin
iDestSize := 0;
AFmtOpts.ConvertRawData(ApInfo^.FOutDataType, ApInfo^.FDestDataType,
pData, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize, Session.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.ProcessVarColumn(AFmtOpts: TFDFormatOptions;
AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDMySQLVarInfoRec);
var
pData: Pointer;
iSize, iByteSize, iDestSize: LongWord;
oStr: TMySQLBlobStream;
begin
pData := nil;
iSize := 0;
// null
if not ApInfo^.FVar.GetData(pData, iSize, True) then
ARow.SetData(AColIndex, nil, 0)
// conversion is not required
else if ApInfo^.FOutDataType = ApInfo^.FDestDataType then
if ApInfo^.FVar.LongData then begin
oStr := TMySQLBlobStream.Create(ApInfo^.FVar, smOpenRead);
try
iSize := oStr.Size;
if ApInfo^.FDestDataType in C_FD_WideTypes then
iSize := iSize div SizeOf(WideChar);
pData := ARow.BeginDirectWriteBlob(AColIndex, iSize);
try
if iSize > 0 then
iSize := oStr.ReadStr(pData, iSize, ApInfo^.FOutDataType);
finally
ARow.EndDirectWriteBlob(AColIndex, iSize);
end;
finally
FDFree(oStr);
end;
end
else if ApInfo^.FDestDataType in C_FD_VarLenTypes then
ARow.SetData(AColIndex, pData, iSize)
else begin
FBuffer.Check(iSize);
ApInfo^.FVar.GetData(FBuffer.FBuffer, iSize, False);
ARow.SetData(AColIndex, FBuffer.Ptr, iSize);
end
// conversion is required
else begin
if ApInfo^.FVar.LongData then begin
oStr := TMySQLBlobStream.Create(ApInfo^.FVar, smOpenRead);
try
iSize := oStr.Size;
iByteSize := iSize;
if ApInfo^.FOutDataType in C_FD_WideTypes then
iByteSize := iByteSize * SizeOf(WideChar);
pData := FBuffer.Check(iByteSize);
if iByteSize > 0 then
iSize := oStr.ReadStr(pData, iSize, ApInfo^.FOutDataType);
finally
FDFree(oStr);
end;
end
else begin
iByteSize := iSize;
if ApInfo^.FOutDataType in C_FD_WideTypes then
iByteSize := iByteSize * SizeOf(WideChar);
FBuffer.Check(iByteSize);
ApInfo^.FVar.GetData(FBuffer.FBuffer, iSize, False);
end;
iDestSize := 0;
AFmtOpts.ConvertRawData(ApInfo^.FOutDataType, ApInfo^.FDestDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize, Session.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
var
oRow: TFDDatSRow;
[unsafe] oCol: TFDDatSColumn;
pColInfo: PFDMySQLVarInfoRec;
j: Integer;
oFmtOpts: TFDFormatOptions;
begin
oFmtOpts := FOptions.FormatOptions;
oRow := ATable.NewRow(False);
try
for j := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[j];
if (oCol.SourceID > 0) and CheckFetchColumn(oCol.SourceDataType, oCol.Attributes) then begin
pColInfo := @FColInfos[oCol.SourceID - 1];
if pColInfo^.FPos <> -1 then
if FStmt <> nil then
ProcessVarColumn(oFmtOpts, j, oRow, pColInfo)
else
ProcessResColumn(oFmtOpts, j, oRow, pColInfo);
end;
end;
if AParentRow <> nil then begin
oRow.ParentRow := AParentRow;
AParentRow.Fetched[ATable.Columns.ParentCol] := True;
end;
ATable.Rows.Add(oRow);
except
FDFree(oRow);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.MySQLType2FDType(var AStr: String; var AType: TFDDataType;
var AAttrs: TFDDataAttributes; var ALen: LongWord; var APrec, AScale: Integer);
var
i1, i2: Integer;
iLen: LongWord;
sType, sArgs, sMod: String;
lUnsigned: Boolean;
oFmt: TFDFormatOptions;
procedure SetPrecScale(ADefPrec, ADefScale: Integer);
var
sPrec, sScale: String;
i: Integer;
begin
i := Pos(',', sArgs);
if i = 0 then
sPrec := sArgs
else begin
sPrec := Copy(sArgs, 1, i - 1);
sScale := Copy(sArgs, i + 1, Length(sArgs));
end;
APrec := StrToIntDef(sPrec, ADefPrec);
AScale := StrToIntDef(sScale, ADefScale);
end;
procedure SetLen(ADefLen: Integer);
begin
ALen := StrToIntDef(sArgs, ADefLen);
end;
begin
i1 := Pos('(', AStr);
i2 := Pos(')', AStr);
if i1 = 0 then begin
i1 := Pos(' ', AStr);
if i1 = 0 then begin
sType := UpperCase(AStr);
sArgs := '';
sMod := '';
end
else begin
sType := UpperCase(Copy(AStr, 1, i1 - 1));
sArgs := '';
sMod := UpperCase(Copy(AStr, i1 + 1, Length(AStr)));
end;
end
else begin
sType := UpperCase(Copy(AStr, 1, i1 - 1));
sArgs := Copy(AStr, i1 + 1, i2 - i1 - 1);
sMod := UpperCase(Copy(AStr, i2 + 1, Length(AStr)));
end;
lUnsigned := Pos(' UNSIGNED', sMod) <> 0;
AType := dtUnknown;
AAttrs := [caSearchable];
ALen := 0;
APrec := 0;
AScale := 0;
if sType = 'ENUM' then begin
AType := dtAnsiString;
i1 := 1;
while True do begin
i2 := Pos(',', sArgs, i1);
if i2 = 0 then
i2 := Length(sArgs) + 1;
iLen := i2 - i1;
if sArgs[i1] = '''' then
Dec(iLen, 2);
if ALen < iLen then
ALen := iLen;
i1 := i2 + 1;
if i1 > Length(sArgs) then
Break;
while sArgs[i1] = ' ' do
Inc(i1);
end;
end
else if sType = 'SET' then begin
AType := dtAnsiString;
i1 := 1;
while True do begin
i2 := Pos(',', sArgs, i1);
if i2 = 0 then
i2 := Length(sArgs);
iLen := i2 - i1;
if sArgs[i1] = '''' then
Dec(iLen, 2);
Inc(ALen, Longword(iLen + 1));
i1 := i2 + 1;
if i1 > Length(sArgs) then
Break;
while sArgs[i1] = ' ' do
Inc(i1);
end;
end
else if sType = 'TINYINT' then begin
SetPrecScale(0, 0);
if (APrec = 1) and (MyConnection.FTinyIntFormat = dtBoolean) then
AType := dtBoolean
else if lUnsigned then
AType := dtByte
else
AType := dtSByte;
end
else if sType = 'BIT' then begin
AType := dtByteString;
SetLen(1);
ALen := (ALen + 7) div 8;
Include(AAttrs, caFixedLen);
end
else if sType = 'BOOL' then
AType := dtBoolean
else if sType = 'SMALLINT' then begin
SetPrecScale(0, 0);
if lUnsigned then
AType := dtUInt16
else
AType := dtInt16;
end
else if (sType = 'MEDIUMINT') or (sType = 'INTEGER') or (sType = 'INT') then begin
SetPrecScale(0, 0);
if lUnsigned then
AType := dtUInt32
else
AType := dtInt32;
end
else if sType = 'BIGINT' then begin
SetPrecScale(0, 0);
if lUnsigned then
AType := dtUInt64
else
AType := dtInt64
end
else if (sType = 'FLOAT') or (sType = 'DOUBLE') or (sType = 'REAL') then begin
SetPrecScale(0, 0);
if APrec > 16 then begin
oFmt := FOptions.FormatOptions;
if oFmt.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end
else if sType = 'FLOAT' then begin
AType := dtSingle;
if APrec = 0 then
APrec := 7;
end
else begin
AType := dtDouble;
if APrec = 0 then
APrec := 15;
end;
end
else if (sType = 'DECIMAL') or (sType = 'DEC') or (sType = 'NUMERIC') then begin
SetPrecScale(10, 0);
if AScale = 0 then
if lUnsigned then begin
if APrec <= 3 then
AType := dtByte
else if APrec <= 5 then
AType := dtUInt16
else if APrec <= 10 then
AType := dtUInt32
else if APrec <= 21 then
AType := dtUInt64;
end
else begin
if APrec <= 2 then
AType := dtSByte
else if APrec <= 4 then
AType := dtInt16
else if APrec <= 9 then
AType := dtInt32
else if APrec <= 20 then
AType := dtInt64;
end;
if AType = dtUnknown then begin
oFmt := FOptions.FormatOptions;
if oFmt.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
end
else if sType = 'DATE' then
AType := dtDate
else if sType = 'DATETIME' then
AType := dtDateTime
else if sType = 'TIMESTAMP' then begin
AType := dtDateTimeStamp;
Include(AAttrs, caRowVersion);
end
else if sType = 'TIME' then
AType := dtTime
else if sType = 'YEAR' then
AType := dtUInt16
else if sType = 'CHAR' then begin
SetLen(1);
AType := dtAnsiString;
Include(AAttrs, caFixedLen);
end
else if sType = 'VARCHAR' then begin
SetLen(255);
AType := dtAnsiString;
end
else if sType = 'BINARY' then begin
SetLen(1);
AType := dtByteString;
Include(AAttrs, caFixedLen);
end
else if sType = 'VARBINARY' then begin
SetLen(255);
AType := dtByteString;
end
else if sType = 'TINYBLOB' then begin
AType := dtByteString;
ALen := 255;
end
else if sType = 'TINYTEXT' then begin
AType := dtAnsiString;
ALen := 255;
end
else if (sType = 'BLOB') or (sType = 'MEDIUMBLOB') or (sType = 'LONGBLOB') then begin
Exclude(AAttrs, caSearchable);
Include(AAttrs, caBlobData);
AType := dtBlob;
end
else if (sType = 'TEXT') or (sType = 'MEDIUMTEXT') or (sType = 'LONGTEXT') then begin
Exclude(AAttrs, caSearchable);
Include(AAttrs, caBlobData);
AType := dtMemo;
end;
AStr := sType;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetCrsData(ACrsCol: Integer; var AData: Pointer;
var ALen: LongWord; AType: TFDDataType): Boolean;
begin
AData := FBuffer.Ptr;
Result := FCursor.GetData(ACrsCol, AData, ALen, AType, []);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetCrsData(ACrsCol: Integer; AData: Pointer): String;
var
iLen: LongWord;
begin
GetCrsData(ACrsCol, AData, iLen, dtAnsiString);
Result := Session.Encoder.Decode(AData, iLen);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.GetMetaCatalog: String;
var
rName: TFDPhysParsedName;
begin
GetSelectMetaInfoParams(rName);
if rName.FCatalog = '' then
Result := MyConnection.InternalGetCurrentCatalog
else
Result := rName.FCatalog;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMySQLCommand.FetchMetaRow(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowIndex: Integer);
const
C_Primary: String = 'PRIMARY';
var
pData: Pointer;
uiLen: LongWord;
oRow: TFDDatSRow;
lDeleteRow: Boolean;
s: String;
eType: TFDDataType;
eAttrs: TFDDataAttributes;
iPrec, iScale: Integer;
iRecNo: Integer;
eIndKind: TFDPhysIndexKind;
i: Integer;
rName: TFDPhysParsedName;
oConnMeta: IFDPhysConnectionMetadata;
eTabKind: TFDPhysTableKind;
eScope: TFDPhysObjectScope;
begin
lDeleteRow := False;
iRecNo := FRecordsFetched + ARowIndex + 1;
oRow := ATable.NewRow(False);
pData := FBuffer.Check(1024);
case GetMetaInfoKind of
mkCatalogs:
begin
oRow.SetData(0, iRecNo);
uiLen := 0;
GetCrsData(0, pData, uiLen, dtWideString);
oRow.SetData(1, pData, uiLen);
end;
mkTables:
begin
s := GetMetaCatalog;
oRow.SetData(0, iRecNo);
oRow.SetData(1, s);
oRow.SetData(2, nil, 0);
uiLen := 0;
GetCrsData(0, pData, uiLen, dtWideString);
oRow.SetData(3, pData, uiLen);
eTabKind := tkTable;
if MyConnection.FServerVersion >= mvMySQL050002 then begin
GetCrsData(1, pData, uiLen, dtWideString);
if StrLComp('VIEW', PWideChar(pData), uiLen) = 0 then
eTabKind := tkView;
end;
oRow.SetData(4, SmallInt(eTabKind));
if (CompareText(s, 'MYSQL') = 0) or (CompareText(s, 'INFORMATION_SCHEMA') = 0) then
eScope := osSystem
else if CompareText(s, MyConnection.InternalGetCurrentCatalog) = 0 then
eScope := osMy
else
eScope := osOther;
oRow.SetData(5, SmallInt(eScope));
lDeleteRow := not (eTabKind in GetTableKinds) or not (eScope in GetObjectScopes);
end;
mkTableFields:
begin
oRow.SetData(0, iRecNo);
oRow.SetData(1, GetMetaCatalog);
oRow.SetData(2, nil, 0);
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(GetCommandText, rName, Self, [doUnquote, doNormalize]);
oRow.SetData(3, rName.FObject);
GetCrsData(0, pData, uiLen, dtWideString);
oRow.SetData(4, pData, uiLen);
oRow.SetData(5, iRecNo);
s := GetCrsData(1, pData);
eType := dtUnknown;
eAttrs := [];
uiLen := 0;
iPrec := 0;
iScale := 0;
MySQLType2FDType(s, eType, eAttrs, uiLen, iPrec, iScale);
oRow.SetData(6, LongWord(eType));
oRow.SetData(7, s);
oRow.SetData(9, iPrec);
oRow.SetData(10, iScale);
oRow.SetData(11, uiLen);
Include(eAttrs, caBase);
if CompareText(GetCrsData(2, pData), 'YES') = 0 then
Include(eAttrs, caAllowNull);
if GetCrsData(4, pData) <> '' then
Include(eAttrs, caDefault);
if CompareText(GetCrsData(5, pData), 'AUTO_INCREMENT') = 0 then begin
Include(eAttrs, caAutoInc);
Include(eAttrs, caAllowNull);
end;
oRow.SetData(8, PWord(@eAttrs)^);
end;
mkIndexes,
mkPrimaryKey:
begin
oRow.SetData(0, iRecNo);
oRow.SetData(1, GetMetaCatalog);
oRow.SetData(2, nil, 0);
GetCrsData(0, pData, uiLen, dtWideString);
oRow.SetData(3, pData, uiLen);
GetCrsData(1, pData, uiLen, dtUInt16);
if PWord(pData)^ = 0 then
eIndKind := ikUnique
else
eIndKind := ikNonUnique;
GetCrsData(2, pData, uiLen, dtWideString);
if (eIndKind = ikUnique) and (StrLIComp(PWideChar(pData), PWideChar(C_Primary), 7) = 0) then
eIndKind := ikPrimaryKey;
oRow.SetData(4, pData, uiLen);
if eIndKind in [ikUnique, ikPrimaryKey] then
oRow.SetData(5, pData, uiLen)
else
oRow.SetData(5, nil, 0);
oRow.SetData(6, Integer(eIndKind));
if (GetMetaInfoKind = mkPrimaryKey) and (iRecNo > 1) then
lDeleteRow := True;
if not lDeleteRow then
for i := 0 to ATable.Rows.Count - 1 do begin
if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(4, rvDefault)) = VarToStr(oRow.GetData(4, rvDefault))) then begin
lDeleteRow := True;
Break;
end;
end;
end;
mkIndexFields,
mkPrimaryKeyFields:
begin
oRow.SetData(0, iRecNo);
oRow.SetData(1, GetMetaCatalog);
oRow.SetData(2, nil, 0);
GetCrsData(0, pData, uiLen, dtWideString);
oRow.SetData(3, pData, uiLen);
GetCrsData(1, pData, uiLen, dtInt32);
if PSmallInt(pData)^ = 0 then
eIndKind := ikUnique
else
eIndKind := ikNonUnique;
GetCrsData(2, pData, uiLen, dtWideString);
if (eIndKind = ikUnique) and (StrLIComp(PWideChar(pData), PWideChar(C_Primary), 7) = 0) then
eIndKind := ikPrimaryKey;
oRow.SetData(4, pData, uiLen);
GetCrsData(4, pData, uiLen, dtWideString);
oRow.SetData(5, pData, uiLen);
GetCrsData(3, pData, uiLen, dtInt32);
oRow.SetData(6, pData, uiLen);
GetCrsData(5, pData, uiLen, dtWideString);
oRow.SetData(7, pData, uiLen);
oRow.SetData(8, nil, 0);
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(GetCommandText, rName, Self, [doUnquote, doNormalize]);
if not lDeleteRow then
if (GetMetaInfoKind = mkPrimaryKeyFields) and
((eIndKind <> ikPrimaryKey) or
(iRecNo > 1) and
(AnsiCompareText(VarToStr(ATable.Rows[0].GetData(4, rvDefault)), VarToStr(oRow.GetData(4, rvDefault))) <> 0)
) or
(GetMetaInfoKind = mkIndexFields) and
(AnsiCompareText(VarToStr(oRow.GetData(4, rvDefault)), rName.FObject) <> 0) then
lDeleteRow := True;
end;
mkForeignKeys:
begin
oRow.SetData(0, iRecNo);
GetCrsData(1, pData, uiLen, dtWideString);
oRow.SetData(1, pData, uiLen);
oRow.SetData(2, nil, 0);
GetCrsData(3, pData, uiLen, dtWideString);
oRow.SetData(3, pData, uiLen);
GetCrsData(4, pData, uiLen, dtWideString);
oRow.SetData(4, pData, uiLen);
GetCrsData(5, pData, uiLen, dtWideString);
oRow.SetData(5, pData, uiLen);
oRow.SetData(6, nil, 0);
GetCrsData(7, pData, uiLen, dtWideString);
oRow.SetData(7, pData, uiLen);
GetCrsData(8, pData, uiLen, dtInt32);
oRow.SetData(8, pData, uiLen);
GetCrsData(9, pData, uiLen, dtInt32);
oRow.SetData(9, pData, uiLen);
end;
mkForeignKeyFields:
begin
oRow.SetData(0, iRecNo);
GetCrsData(1, pData, uiLen, dtWideString);
oRow.SetData(1, pData, uiLen);
oRow.SetData(2, nil, 0);
GetCrsData(3, pData, uiLen, dtWideString);
oRow.SetData(3, pData, uiLen);
GetCrsData(4, pData, uiLen, dtWideString);
oRow.SetData(4, pData, uiLen);
GetCrsData(5, pData, uiLen, dtWideString);
oRow.SetData(5, pData, uiLen);
GetCrsData(6, pData, uiLen, dtWideString);
oRow.SetData(6, pData, uiLen);
GetCrsData(7, pData, uiLen, dtInt32);
oRow.SetData(7, pData, uiLen);
end;
mkProcs:
begin
oRow.SetData(0, iRecNo);
if GetCrsData(1, pData, uiLen, dtWideString) then
oRow.SetData(1, pData, uiLen);
if GetCrsData(2, pData, uiLen, dtWideString) then
oRow.SetData(2, pData, uiLen);
if GetCrsData(3, pData, uiLen, dtWideString) then
oRow.SetData(3, pData, uiLen);
if GetCrsData(4, pData, uiLen, dtWideString) then
oRow.SetData(4, pData, uiLen);
if GetCrsData(5, pData, uiLen, dtInt32) then
oRow.SetData(5, pData, uiLen);
if GetCrsData(6, pData, uiLen, dtInt32) then
oRow.SetData(6, pData, uiLen);
if GetCrsData(7, pData, uiLen, dtInt32) then
oRow.SetData(7, pData, uiLen);
if GetCrsData(8, pData, uiLen, dtInt32) then
oRow.SetData(8, pData, uiLen);
if GetCrsData(9, pData, uiLen, dtInt32) then
oRow.SetData(9, pData, uiLen);
end;
mkProcArgs:
ASSERT(False);
else
lDeleteRow := True;
end;
if lDeleteRow then
FDFree(oRow)
else
ATable.Rows.Add(oRow);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.FetchSPParamRows(ATable: TFDDatSTable;
AParentRow: TFDDatSRow): Integer;
var
sMode, sSQL: String;
lAnsiQuotes, {lNoBackslash,} lInQuote1, lInQuote2: Boolean;
i, iBraces, iPrev, iRecNo: Integer;
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
procedure SkipSpaces(const ASQL: String; var AFrom: Integer; ATo: Integer);
begin
while (AFrom <= ATo) and FDInSet(ASQL[AFrom], [' ', #9, #13, #10]) do
Inc(AFrom);
end;
procedure TrimSpaces(const ASQL: String; AFrom: Integer; var ATo: Integer);
begin
while (AFrom <= ATo) and FDInSet(ASQL[ATo], [' ', #9, #13, #10]) do
Dec(ATo);
end;
procedure AddParam(const ASQL: String; AFrom, ATo: Integer);
var
iPrev: Integer;
sType, sName: String;
eDir: TParamType;
eType: TFDDataType;
eAttrs: TFDDataAttributes;
iPrec, iScale: Integer;
uiLen: LongWord;
oRow: TFDDatSRow;
begin
TrimSpaces(ASQL, AFrom, ATo);
SkipSpaces(ASQL, AFrom, ATo);
if StrLIComp(PChar(ASQL) + AFrom - 1, PChar('RETURNS'), 7) = 0 then begin
eDir := ptResult;
Inc(AFrom, 7);
end
else if StrLIComp(PChar(ASQL) + AFrom - 1, PChar('INOUT'), 5) = 0 then begin
eDir := ptInputOutput;
Inc(AFrom, 5);
end
else if StrLIComp(PChar(ASQL) + AFrom - 1, PChar('IN'), 2) = 0 then begin
eDir := ptInput;
Inc(AFrom, 2);
end
else if StrLIComp(PChar(ASQL) + AFrom - 1, PChar('OUT'), 3) = 0 then begin
eDir := ptOutput;
Inc(AFrom, 3);
end
else
eDir := ptInput;
SkipSpaces(ASQL, AFrom, ATo);
if eDir = ptResult then begin
sName := 'result';
iPrev := AFrom;
repeat
Inc(AFrom);
until (AFrom > ATo) or FDInSet(ASQL[AFrom], [' ', #9, #13, #10]);
sType := Copy(ASQL, iPrev, AFrom - iPrev);
end
else begin
if ASQL[AFrom] = '`' then begin
iPrev := AFrom;
repeat
Inc(AFrom);
until (AFrom > ATo) or (ASQL[AFrom] = '`');
sName := Copy(ASQL, iPrev + 1, AFrom - iPrev - 1);
end
else begin
iPrev := AFrom;
repeat
Inc(AFrom);
until (AFrom > ATo) or FDInSet(ASQL[AFrom], [')', '(', ',', ' ', #9, #13, #10]);
sName := Copy(ASQL, iPrev, AFrom - iPrev);
end;
Inc(AFrom);
SkipSpaces(ASQL, AFrom, ATo);
sType := Copy(ASQL, AFrom, ATo - AFrom + 1);
end;
if (GetWildcard <> '') and not FDStrLike(sName, GetWildcard) then
Exit;
eType := dtUnknown;
eAttrs := [];
uiLen := 0;
iPrec := 0;
iScale := 0;
MySQLType2FDType(sType, eType, eAttrs, uiLen, iPrec, iScale);
Include(eAttrs, caAllowNull);
oRow := ATable.NewRow(False);
oRow.SetData(0, iRecNo);
oRow.SetData(1, rName.FCatalog);
oRow.SetData(2, rName.FSchema);
oRow.SetData(3, nil, 0);
oRow.SetData(4, rName.FObject);
oRow.SetData(5, 0);
oRow.SetData(6, sName);
oRow.SetData(7, Smallint(iRecNo));
oRow.SetData(8, Smallint(eDir));
oRow.SetData(9, Smallint(eType));
oRow.SetData(10, sType);
oRow.SetData(11, PWord(@eAttrs)^);
oRow.SetData(12, iPrec);
oRow.SetData(13, iScale);
oRow.SetData(14, uiLen);
ATable.Rows.Add(oRow);
Inc(iRecNo);
end;
begin
Result := 0;
iRecNo := 1;
sMode := GetCrsData(1, FBuffer.Ptr);
sSQL := GetCrsData(2, FBuffer.Ptr);
FConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self, [doNormalize, doUnquote]);
lAnsiQuotes := Pos('ANSI_QUOTES', sMode) <> 0;
// lNoBackslash := Pos('NO_BACKSLASH_ESCAPES', sMode) <> 0;
i := Pos('(', sSQL) + 1;
lInQuote1 := False;
lInQuote2 := False;
iBraces := 0;
iPrev := i;
while i < Length(sSQL) do begin
case sSQL[i] of
'`':
if not lInQuote2 then
lInQuote1 := not lInQuote1;
'"':
if lAnsiQuotes and not lInQuote1 then
lInQuote2 := not lInQuote2;
'(':
if not lInQuote2 and not lInQuote1 then
Inc(iBraces);
')':
if not lInQuote2 and not lInQuote1 then
if iBraces = 0 then begin
if iPrev <= i - 1 then begin
AddParam(sSQL, iPrev, i - 1);
Inc(Result);
end;
Inc(i);
Break;
end
else
Dec(iBraces);
',':
if not lInQuote2 and not lInQuote1 and (iBraces = 0) then begin
AddParam(sSQL, iPrev, i - 1);
Inc(Result);
iPrev := i + 1;
end;
end;
Inc(i);
end;
SkipSpaces(sSQL, i, Length(sSQL));
if StrLIComp(PChar(sSQL) + i - 1, PChar('RETURNS'), 7) = 0 then begin
AddParam(sSQL, i, Length(sSQL));
Inc(Result);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.FetchFKRows(ATable: TFDDatSTable;
AParentRow: TFDDatSRow): Integer;
function TrimQuotes(const AStr: String): String;
begin
Result := FDUnquote(Trim(AStr), '`');
end;
var
sFKCat, sFKTab, sFKName, sComment, sTabName, sFKey, sFKFields, sFields: String;
iCommentField, i, i1, i2, i3, i4, i5, j1, j2, iRecNo: Integer;
oRow: TFDDatSRow;
begin
Result := 0;
iRecNo := 1;
if MyConnection.FServerVersion < mvMySQL040100 then
iCommentField := 14
else
iCommentField := 15;
sComment := GetCrsData(iCommentField, FBuffer.Ptr);
sTabName := GetCrsData(0, FBuffer.Ptr);
if Pos('InnoDB', sComment) = 1 then begin
i := 1;
FDExtractFieldName(sComment, i, GSemicolonFmtSettings);
while i <= Length(sComment) do begin
sFKey := FDExtractFieldName(sComment, i, GSemicolonFmtSettings);
i1 := Pos('(', sFKey, 1);
i2 := Pos(')', sFKey, i1);
i3 := Pos('/', sFKey, i2);
i4 := Pos('(', sFKey, i3);
i5 := Pos(')', sFKey, i4);
if (i1 <> -1) and (i2 <> -1) and (i3 <> -1) and (i4 <> -1) and (i5 <> -1) then begin
sFKCat := TrimQuotes(Copy(sFKey, i2 + 8, i3 - i2 - 8));
sFKTab := TrimQuotes(Copy(sFKey, i3 + 1, i4 - i3 - 1));
sFKName := sTabName + '_to_' + sFKTab;
sFields := Copy(sFKey, i1 + 1, i2 - i1 - 1);
sFKFields := Copy(sFKey, i4 + 1, i5 - i4 - 1);
if GetMetaInfoKind = mkForeignKeys then begin
oRow := ATable.NewRow(False);
oRow.SetData(0, iRecNo);
oRow.SetData(1, GetMetaCatalog);
oRow.SetData(2, nil, 0);
oRow.SetData(3, sTabName);
oRow.SetData(4, sFKName);
oRow.SetData(5, sFKCat);
oRow.SetData(6, nil, 0);
oRow.SetData(7, sFKTab);
oRow.SetData(8, IntToStr(Integer(ckCascade)));
oRow.SetData(9, IntToStr(Integer(ckCascade)));
ATable.Rows.Add(oRow);
Inc(iRecNo);
Inc(Result);
end
else if AnsiCompareText(sFKName, TrimQuotes(GetCommandText)) = 0 then begin
j1 := 1;
j2 := 1;
while (j1 <= Length(sFields)) and (j2 <= Length(sFKFields)) do begin
oRow := ATable.NewRow(False);
oRow.SetData(0, iRecNo);
oRow.SetData(1, GetMetaCatalog);
oRow.SetData(2, nil, 0);
oRow.SetData(3, sTabName);
oRow.SetData(4, sFKName);
oRow.SetData(5, TrimQuotes(FDExtractFieldName(sFields, j1, GSpaceFmtSettings)));
oRow.SetData(6, TrimQuotes(FDExtractFieldName(sFKFields, j2, GSpaceFmtSettings)));
oRow.SetData(7, Result + 1);
ATable.Rows.Add(oRow);
Inc(iRecNo);
Inc(Result);
end;
Break;
end;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommand.InternalFetchRowSet(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord;
var
i: LongWord;
begin
Result := 0;
if GetMetaInfoKind = mkProcArgs then begin
if FCursor.Fetch(1) then
Result := FetchSPParamRows(ATable, AParentRow);
end
else if (GetMetaInfoKind in [mkForeignKeys, mkForeignKeyFields]) and
(MyConnection.FServerVersion < mvMySQL050100) then begin
if FCursor.Fetch(1) then
Result := FetchFKRows(ATable, AParentRow);
end
else
for i := 1 to ARowsetSize do begin
if FStmt <> nil then begin
if not FStmt.Fetch then
Break;
end
else begin
if not FCursor.Fetch(i) then
Break;
end;
if GetMetaInfoKind = mkNone then
FetchRow(ATable, AParentRow)
else
FetchMetaRow(ATable, AParentRow, i - 1);
Inc(Result);
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysMySQLDriver);
finalization
FDUnregisterDriverClass(TFDPhysMySQLDriver);
end.
|
unit UnCategoriaRegistroView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExStdCtrls, JvEdit, JvValidateEdit, StdCtrls, Grids, DBGrids,
JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, JvExControls, JvButton,
JvTransparentButton, ExtCtrls,
{ helsonsant }
Util, DataUtil, UnModelo, UnCategoriaRegistroModelo, UnAplicacao, Data.DB;
type
TCategoriaRegistroView = class(TForm)
Panel1: TPanel;
btnGravar: TJvTransparentButton;
btnMaisOpcoes: TJvTransparentButton;
pnlSpace: TPanel;
Panel2: TPanel;
btnRecebimentos: TPanel;
btnImpostos: TPanel;
Pages: TPageControl;
TabSheet1: TTabSheet;
gCategorias: TJvDBUltimGrid;
btnDespesasFixas: TPanel;
btnDespesasVariaveis: TPanel;
pnlCategoria: TPanel;
Label3: TLabel;
EdtCategoria: TEdit;
btnInclui: TPanel;
Panel12: TPanel;
procedure btnGravarClick(Sender: TObject);
procedure btnIncluiClick(Sender: TObject);
private
FControlador: IResposta;
FCategoriaRegistroModelo: TCategoriaRegistroModelo;
FGrupoSelecionado: Integer;
FGrupos: TStringList;
public
function Controlador(const Controlador: IResposta): TCategoriaRegistroView;
function Modelo(const Modelo: TModelo): TCategoriaRegistroView;
function Preparar: TCategoriaRegistroView;
published
procedure AlterarSelecaoDeCategoria(Sender: TObject);
procedure Desselecionar(const Botao: TPanel);
procedure Selecionar(const Botao: TPanel);
end;
var
CategoriaRegistroView: TCategoriaRegistroView;
implementation
{$R *.dfm}
function TCategoriaRegistroView.Modelo(
const Modelo: TModelo): TCategoriaRegistroView;
begin
Self.FCategoriaRegistroModelo := (Modelo as TCategoriaRegistroModelo);
Result := Self;
end;
function TCategoriaRegistroView.Preparar: TCategoriaRegistroView;
begin
Self.FGrupos := TStringList.Create;
Self.FGrupos.AddObject('Recebimentos', Self.btnRecebimentos);
Self.FGrupos.AddObject('Impostos', Self.btnImpostos);
Self.FGrupos.AddObject('Despesas Fixas', Self.btnDespesasFixas);
Self.FGrupos.AddObject('Despesas Variáveis', Self.btnDespesasVariaveis);
Self.FGrupoSelecionado := -1;
Self.AlterarSelecaoDeCategoria(Self.btnRecebimentos);
Self.gCategorias.DataSource := Self.FCategoriaRegistroModelo.DataSource;
Result := Self;
end;
procedure TCategoriaRegistroView.AlterarSelecaoDeCategoria(Sender: TObject);
var
_selecao: TPanel;
_chamada: TChamada;
begin
_selecao := TPanel(Sender);
if _selecao.Tag <> Self.FGrupoSelecionado then
begin
if Self.FGrupoSelecionado > -1 then
Self.Desselecionar(TPanel(Self.FGrupos.Objects[Self.FGrupoSelecionado]));
Self.Selecionar(_selecao);
Self.FCategoriaRegistroModelo.Parametros
.Gravar('acao', Ord(adrCarregar))
.Gravar('categoria', Self.FGrupoSelecionado);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(Self.FCategoriaRegistroModelo.Parametros);
Self.FControlador.Responder(_chamada);
end;
end;
procedure TCategoriaRegistroView.btnGravarClick(Sender: TObject);
begin
Self.ModalResult := mrOk;
end;
procedure TCategoriaRegistroView.Selecionar(const Botao: TPanel);
begin
Self.FGrupoSelecionado := Botao.Tag;
Botao.Color := $0082A901;
Botao.Font.Color := clWhite;
Botao.Font.Style := [fsBold];
end;
procedure TCategoriaRegistroView.Desselecionar(const Botao: TPanel);
begin
Botao.Color := clSilver;
Botao.Font.Color := clTeal;
Botao.Font.Style := [];
end;
function TCategoriaRegistroView.Controlador(
const Controlador: IResposta): TCategoriaRegistroView;
begin
Self.FControlador := Controlador;
Result := Self;
end;
procedure TCategoriaRegistroView.btnIncluiClick(Sender: TObject);
var
_chamada: TChamada;
begin
if Self.EdtCategoria.Text <> '' then
begin
Self.FCategoriaRegistroModelo.Parametros
.Gravar('acao', Ord(adrIncluir))
.Gravar('categoria', Self.FGrupoSelecionado)
.Gravar('descricaoCategoria', Self.EdtCategoria.Text);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(Self.FCategoriaRegistroModelo.Parametros);
try
Self.FControlador.Responder(_chamada);
Self.EdtCategoria.Clear;
finally
FreeAndNil(_chamada);
end;
end;
end;
end.
|
unit UUtils;
interface
uses
UHash, SysUtils,Classes;
{$define _log_}
type
Utils = class(TObject)
private
class function isNum(c: char): Boolean; static;
public
class procedure concat(A: string; B, Target: TStream); overload; static;
class procedure concat(A, B, Target: TStream); overload; static;
//1 Преобразует строку с разделителями glue в hash
class function explode(str, glue: string; toHash: THash = nil): THash;
static;
//1 Пребразует число в строку валидную к json
class function FloatToStr(f: Double): string; static;
//1 преобразует значения hash (value) в строку с разделителями
class function implode(fromHash: THash; glue: string = ';'): string;
static;
class function isFloat(const aStr: string): Boolean; static;
class function isInt(const aStr:string): Boolean; static;
class function isNumeric(const aStr: string): Boolean; static;
//1 Проверка строки на недопустимые символы. Возвращает 0 если все в порядке, либо позицию недопустимого символа (позиция первого символа 1)
class function prepare(str: string): Integer; static;
class function randomStr(aLen: integer=10): string; static;
class function readFromStream(Stream: TStream): string; static;
//1 Кодирует все кириличиские символы
class function rusCod(s: string): string; static;
//1 Декодирует все коды в их кириличиское представление
class function rusEnCod(s: string): string; static;
//1 Преобразует вещественное из строки ( с учетом что разделитель и точка и запятая)
class function StrToFloat(str: string): Double; static;
class function UrlDecode(Str: AnsiString): AnsiString; static;
class function UrlEncode(Str: AnsiString): AnsiString; static;
class function writeToStream(str: string; Stream: TStream): Integer;
static;
class function GetTimeSec: Double;static;
end;
implementation
uses {$ifdef _log_}ULogMsg,{$endif} IdURI;
{
************************************ Utils *************************************
}
class procedure Utils.concat(A: string; B, Target: TStream);
begin
Utils.writeToStream(A,Target);
Target.CopyFrom(B,B.Size-B.Position);
end;
class procedure Utils.concat(A, B, Target: TStream);
begin
Target.CopyFrom(A,A.Size-B.Position);
Target.CopyFrom(B,B.Size-B.Position);
end;
class function Utils.explode(str, glue: string; toHash: THash = nil): THash;
var
cPos: Integer;
cStr: string;
cStep: Integer;
begin
if (toHash = nil) then
toHash:=Hash();
result:=toHash;
cPos:=pos(glue,str);
cStep:=0;
while cPos>0 do begin
cStr:=copy(str,1,cPos-1);
str:=copy(str,cPos+1,length(str));
result[IntToStr(cStep)]:=cStr;
cPos:=pos(glue,str);
inc(cStep);
end;
if (length(str)>0) then
result[IntToStr(cStep)]:=str;
end;
class function Utils.FloatToStr(f: Double): string;
begin
result:=SysUtils.FloatToStr(f);
result:=StringReplace(result,',','.',[rfReplaceAll]);
end;
class function Utils.implode(fromHash: THash; glue: string = ';'): string;
var
i: Integer;
begin
result:='';
for i:=0 to fromHash.count-1 do begin
if (fromHash.Item[i].Hash.Count=0) then begin
if (result<>'') then
result:=result+glue;
result:=result+fromHash.value[i];
end;
end;
end;
class function Utils.isFloat(const aStr: string): Boolean;
var
i: Integer;
cChar: Char;
cStr: string;
cSep: Boolean;
begin
cStr:=aStr;
cStr:=trim(cStr);
if length(cStr)=0 then
begin
result:=false;
exit;
end;
result:=true;
cSep:=false;
if (cStr[1] = '-') or (cStr[1] = '+') then
cStr:=copy(cStr,2,length(cStr));
for i:=1 to Length(cStr) do
begin
cChar:=cStr[i];
if not isNum(cChar) then
begin
if (not cSep) and ((cChar = '.') or (cChar = ',')) then
cSep:=true
else
begin
result:=false;
exit;
end;
end;
end;//for
end;
class function Utils.isInt(const aStr:string): Boolean;
var
i: Integer;
cChar: Char;
cStr: string;
begin
cStr:=aStr;
cStr:=Trim(cStr);
if Length(cStr)=0 then
begin
result:=false;
exit;
end;
result:=true;
if (cStr[1] = '-') or (cStr[1] = '+') then
cStr:=copy(cStr,2,length(cStr));
for i:=1 to Length(cStr) do
begin
cChar:=cStr[i];
if not isNum(cChar) then
begin
result:=false;
exit;
end;
end;//for
end;
class function Utils.isNum(c: char): Boolean;
begin
result:=(ord(c)>=48) and (ord(c)<=57);
end;
class function Utils.isNumeric(const aStr: string): Boolean;
begin
result:= ( isInt(aStr) or isFloat(aStr) );
end;
class function Utils.prepare(str: string): Integer;
var
len,pos,i,c:integer;
stop:boolean;
const
lim : array[0..7,0..1] of integer = (
(9,10), //tab,coret
(13,13), //enter
(32,126), //space !"#$%&'()*+,-./0..9:;<=>?@A..Z[\]^_`a..z{|}
(8221,8221), // ”
(8470,8470), // №
(1040,1103), // А..Яа..я
(1105,1105), //ё
(1025,1025) //Ё
);
begin
//
// 0033| 0034| 0035| 0036| 0037| 0038| 0039| 0040| 0041| 0042| 0043| 0044| 0045| 0046| 0047| 0048|
// ! | " | # | $ | % | & | ' | ( | ) | * | + | , | - | . | / | 0 |
// 0049| 0050| 0051| 0052| 0053| 0054| 0055| 0056| 0057| 0058| 0059| 0060| 0061| 0062| 0063| 0064|
// 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | : | ; | < | = | > | ? | @ |
// 0065| 0066| 0067| 0068| 0069| 0070| 0071| 0072| 0073| 0074| 0075| 0076| 0077| 0078| 0079| 0080|
// A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P |
// 0081| 0082| 0083| 0084| 0085| 0086| 0087| 0088| 0089| 0090| 0091| 0092| 0093| 0094| 0095| 0096|
// Q | R | S | T | U | V | W | X | Y | Z | [ | \ | ] | ^ | _ | ` |
// 0097| 0098| 0099| 0100| 0101| 0102| 0103| 0104| 0105| 0106| 0107| 0108| 0109| 0110| 0111| 0112|
// a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p |
// 0113| 0114| 0115| 0116| 0117| 0118| 0119| 0120| 0121| 0122| 0123| 0124| 0125| 0126| 0127| 0128|
// q | r | s | t | u | v | w | x | y | z | { | | | } | ~ | | |
// 1025| 1026| 1027| 1028| 1029| 1030| 1031| 1032| 1033| 1034| 1035| 1036| 1037| 1038| 1039| 1040|
// Ё | Ђ | Ѓ | Є | Ѕ | І | Ї | Ј | Љ | Њ | Ћ | Ќ | Ѝ | Ў | Џ | А |
// 1041| 1042| 1043| 1044| 1045| 1046| 1047| 1048| 1049| 1050| 1051| 1052| 1053| 1054| 1055| 1056|
// Б | В | Г | Д | Е | Ж | З | И | Й | К | Л | М | Н | О | П | Р |
// 1057| 1058| 1059| 1060| 1061| 1062| 1063| 1064| 1065| 1066| 1067| 1068| 1069| 1070| 1071| 1072|
// С | Т | У | Ф | Х | Ц | Ч | Ш | Щ | Ъ | Ы | Ь | Э | Ю | Я | а |
// 1073| 1074| 1075| 1076| 1077| 1078| 1079| 1080| 1081| 1082| 1083| 1084| 1085| 1086| 1087| 1088|
// б | в | г | д | е | ж | з | и | й | к | л | м | н | о | п | р |
// 1089| 1090| 1091| 1092| 1093| 1094| 1095| 1096| 1097| 1098| 1099| 1100| 1101| 1102| 1103| 1104|
// с | т | у | ф | х | ц | ч | ш | щ | ъ | ы | ь | э | ю | я | ѐ |
// 1105| 1106| 1107| 1108| 1109| 1110| 1111| 1112| 1113| 1114| 1115| 1116| 1117| 1118| 1119| 1120|
// ё | ђ | ѓ | є | ѕ | і | ї | ј | љ | њ | ћ | ќ | ѝ | ў | џ | Ѡ |
len:=length(str);
result:=0;
for pos:=1 to len do begin
c:=Ord(Char(str[pos]));
stop:=true;
for i:=0 to 7 do begin
if (c>=lim[i][0]) and (c<=lim[i][1]) then begin
stop:=false;
break;
end;
end;
if (stop) then begin
result:=pos;
break;
end;
end;
end;
class function Utils.randomStr(aLen: integer=10): string;
var
i: Integer;
begin
randomize;
result:='';
if aLen>0 then
for i:=0 to aLen-1 do
result:=result+chr(65+random(25));
end;
class function Utils.readFromStream(Stream: TStream): string;
var
cLen: Integer;
begin
Stream.ReadBuffer(cLen,SizeOf(cLen));
SetLength(result, cLen div 2);
Stream.ReadBuffer(result[1], cLen);
end;
class function Utils.rusCod(s: string): string;
var
c: AnsiChar;
code: Integer;
i: Integer;
LMax, LMin, HMax, HMin: Integer;
ansi: AnsiString;
begin
LMin:=Ord(AnsiChar('а'));
LMax:=Ord(AnsiChar('я'));
HMin:=Ord(AnsiChar('А'));
HMax:=Ord(AnsiChar('Я')) ;
ansi:=AnsiString(s);
result:='';
for i:=1 to length(ansi) do begin
c:=ansi[i];
code:=ord(c);
if ((code>=HMin) and (code<=HMax)) or
((code>=LMin) and (code<=LMax)) then
result:=result+'#'+IntToStr(code)+';'
else if (code = Ord(AnsiChar('ё'))) then
result:=result+'#1027;'
else if (code = Ord(AnsiChar('Ё'))) then
result:=result+'#1028;'
else if (code = Ord(AnsiChar('”'))) then
result:=result+'"'
else if (code = Ord(AnsiChar('№'))) then
result:=result+'N'
else if (code = Ord(AnsiChar('&'))) then
result:=result+'+'
else
result:=result+c;
end;
end;
class function Utils.rusEnCod(s: string): string;
var
code: AnsiString;
cStr: AnsiString;
i: Integer;
LMax, LMin, HMax, HMin: Integer;
begin
LMin:=Ord(AnsiChar('а'));
LMax:=Ord(AnsiChar('я'));
HMin:=Ord(AnsiChar('А'));
HMax:=Ord(AnsiChar('Я'));
cStr:=AnsiString(s);
for i:=LMin to LMax do begin
code:='#'+IntToStr(i)+';';
cStr:=StringReplace(cStr,code,AnsiChar(chr(i)),[rfReplaceAll]);
end;
for i:=HMin to HMax do begin
code:='#'+IntToStr(i)+';';
cStr:=StringReplace(cStr,code,AnsiChar(chr(i)),[rfReplaceAll]);
end;
cStr:=StringReplace(cStr,'#1027;',AnsiChar('ё'),[rfReplaceAll]);
cStr:=StringReplace(cStr,'#1028;',AnsiChar('Ё'),[rfReplaceAll]);
result:=cStr;
end;
class function Utils.StrToFloat(str: string): Double;
begin
str:=StringReplace(str,'.',',',[rfReplaceAll]);
result:=SysUtils.StrToFloat(str);
end;
class function Utils.UrlDecode(Str: AnsiString): AnsiString;
function HexToChar(W: word): AnsiChar;
asm
cmp ah, 030h
jl @@error
cmp ah, 039h
jg @@10
sub ah, 30h
jmp @@30
@@10:
cmp ah, 041h
jl @@error
cmp ah, 046h
jg @@20
sub ah, 041h
add ah, 00Ah
jmp @@30
@@20:
cmp ah, 061h
jl @@error
cmp al, 066h
jg @@error
sub ah, 061h
add ah, 00Ah
@@30:
cmp al, 030h
jl @@error
cmp al, 039h
jg @@40
sub al, 030h
jmp @@60
@@40:
cmp al, 041h
jl @@error
cmp al, 046h
jg @@50
sub al, 041h
add al, 00Ah
jmp @@60
@@50:
cmp al, 061h
jl @@error
cmp al, 066h
jg @@error
sub al, 061h
add al, 00Ah
@@60:
shl al, 4
or al, ah
ret
@@error:
xor al, al
end;//asm func
function GetCh(P: PAnsiChar; var Ch: AnsiChar): AnsiChar;
begin
Ch := P^;
Result := Ch;
end;
var
P: PAnsiChar;
Ch: AnsiChar;
begin
Result := '';
if Str = '' then
exit;
P := @Str[1];
while GetCh(P, Ch) <> #0 do
begin
case Ch of
'+': Result := Result + ' ';
'%':begin
Inc(P);
Result := Result + HexToChar(PWord(P)^);
Inc(P);
end;
else
Result := Result + Ch;
end;//case
Inc(P);
end;
end;
class function Utils.UrlEncode(Str: AnsiString): AnsiString;
function CharToHex(Ch: AnsiChar): Integer;
asm
and eax, 0FFh
mov ah, al
shr al, 4
and ah, 00fh
cmp al, 00ah
jl @@10
sub al, 00ah
add al, 041h
jmp @@20
@@10:
add al, 030h
@@20:
cmp ah, 00ah
jl @@30
sub ah, 00ah
add ah, 041h
jmp @@40
@@30:
add ah, 030h
@@40:
shl eax, 8
mov al, '%'
end;
var
i, Len: Integer;
Ch: AnsiChar;
N: Integer;
P: PAnsiChar;
begin
Result := '';
Len := Length(Str);
P := PAnsiChar(@N);
for i := 1 to Len do
begin
Ch := Str[i];
if Ch in ['0'..'9', 'A'..'Z', 'a'..'z', '_'] then
Result := Result + Ch
else
begin
if Ch = ' ' then
Result := Result + '+'
else
begin
N := CharToHex(Ch);
Result := Result + P;
end;
end;
end;
end;
class function Utils.writeToStream(str: string; Stream: TStream): Integer;
const
cFuncName = 'writeToStream';
var
cLen: Integer;
cStr:ShortString;
begin
cStr:=ShortString(str);
cLen:=Length(cStr);
Stream.WriteBuffer(cLen,sizeof(Integer));
Stream.WriteBuffer(cStr[1],cLen);
end;
class function Utils.GetTimeSec: Double;
begin
result:=Now()*100000;
end;
end.
|
unit uFileBlockStream;
interface
uses classes, sysutils, forms;
type
TBufferEvent = procedure (Sender: TObject; var Buffer; Count: Longint; isLast:boolean) of Object;
TFileBlockStream = class (TFileStream)
private
RSobraAnterior: Integer;
WSobraAnterior: Integer;
RBuffer: PChar;
WBuffer: PChar;
FMaxSize : Longint;
FReadBlockSize : Longint;
FWriteBlockSize : Longint;
FInternalWBlockSize : Longint;
FInternalRBlockSize : Longint;
FOnWriteBuffer : TBufferEvent;
FOnReadBuffer : TBufferEvent;
procedure setReadBlockSize(value:Longint);
procedure setWriteBlockSize(value:Longint);
procedure SetInternalRBuffer(newBufferSize:Longint);
procedure SetInternalWBuffer(newBufferSize:Longint);
procedure InternalRead(const Buffer; Count: Longint);
procedure InternalWrite(const Buffer; Count: Longint);
public
property ReadBlockSize :Longint read FReadBlockSize write setReadBlockSize;
property WriteBlockSize :Longint read FWriteBlockSize write setWriteBlockSize;
property OnReadBuffer :TBufferEvent read FOnReadBuffer write FOnReadBuffer;
property OnWriteBuffer :TBufferEvent read FOnWriteBuffer write FOnWriteBuffer;
property MaxSize :Longint read FMaxSize write FMaxSize;
procedure ProcessarRestante;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
destructor Destroy; override;
end;
implementation
destructor TFileBlockStream.Destroy;
begin
ProcessarRestante;
FreeMem(RBuffer, FInternalRBlockSize);
FreeMem(WBuffer, FInternalWBlockSize);
inherited;
end;
procedure TFileBlockStream.SetInternalWBuffer(newBufferSize:Longint);
begin
if FInternalWBlockSize <> newBufferSize then begin
FInternalWBlockSize := newBufferSize;
ReallocMem(WBuffer, FInternalWBlockSize);
end;
end;
procedure TFileBlockStream.SetInternalRBuffer(newBufferSize:Longint);
begin
if FInternalRBlockSize <> newBufferSize then begin
FInternalRBlockSize := newBufferSize;
ReallocMem(RBuffer, FInternalRBlockSize);
end;
end;
procedure TFileBlockStream.setWriteBlockSize(value:Longint);
var
sobra : Longint;
tBuffer: PChar;
begin
if value<>FWriteBlockSize then begin
FWriteBlockSize := value;
if WSobraAnterior > value then begin
sobra := WSobraAnterior;
WSobraAnterior := 0;
getmem(tBuffer, sobra);
try
Move( WBuffer^, tBuffer^, Sobra);
InternalWrite (tBuffer^, sobra);
finally
freemem(tBuffer, sobra);
end;
end;
end;
end;
procedure TFileBlockStream.setReadBlockSize(value:Longint);
var
sobra : Longint;
tBuffer: PChar;
begin
if value<>FReadBlockSize then begin
FReadBlockSize := value;
if RSobraAnterior > value then begin
sobra := RSobraAnterior;
RSobraAnterior := 0;
getmem(tBuffer, sobra);
try
Move( RBuffer^, tBuffer^, Sobra);
InternalRead (tBuffer^, sobra);
finally
freemem(tBuffer, sobra);
end;
end;
end;
end;
function TFileBlockStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := inherited Read( Buffer, Count);
if FReadBlockSize=0 then setReadBlockSize(FWriteBlockSize);
InternalRead (Buffer, Count);
end;
function TFileBlockStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := inherited Write( Buffer, Count);
InternalWrite (Buffer, Count);
end;
procedure TFileBlockStream.InternalRead(const Buffer; Count: Longint);
var
TotalPraGravar : Longint;
Sobra : Longint;
gravados : Longint;
begin
gravados := 0;
if Count > 0 then begin
repeat
if RSobraAnterior + Count > FReadBlockSize then begin
if RSobraAnterior > FReadBlockSize then begin
TotalPraGravar := FReadBlockSize;
Sobra := RSobraAnterior - FReadBlockSize;
RSobraAnterior := FReadBlockSize;
end else begin
TotalPraGravar := FReadBlockSize - RSobraAnterior;
Sobra := RSobraAnterior + Count - FReadBlockSize;
end;
end else begin
TotalPraGravar := Count;
Sobra := RSobraAnterior + Count;
end;
if RSobraAnterior+TotalPraGravar > FInternalRBlockSize then SetInternalRBuffer(RSobraAnterior+TotalPraGravar);
Move(Buffer, (RBuffer + RSobraAnterior)^, TotalPraGravar);
gravados := gravados + TotalPraGravar;
if Count + RSobraAnterior = FReadBlockSize then begin
if Assigned(FOnReadBuffer) then begin
FOnReadBuffer (Self, RBuffer^, FReadBlockSize, false );
RSobraAnterior := 0;
Sobra := 0;
end;
end else
if TotalPraGravar + RSobraAnterior >= FReadBlockSize then begin
if Assigned(FOnReadBuffer) then begin
FOnReadBuffer (Self, RBuffer^, FReadBlockSize, false);
if (Sobra>0) then begin
if gravados+sobra > FInternalRBlockSize then SetInternalRBuffer(gravados+sobra);
Move( (Pchar(@Buffer) + gravados)^, RBuffer^, Sobra);
end;
RSobraAnterior := 0;
end;
end else
Sobra := TotalPraGravar;
RSobraAnterior := RSobraAnterior + Sobra;
Count := Count - FReadBlockSize;
application.ProcessMessages;
until sobra <= FReadBlockSize;
end;
end;
procedure TFileBlockStream.InternalWrite(const Buffer; Count: Longint);
var
TotalPraGravar : Longint;
Sobra : Longint;
gravados : Longint;
isLast : boolean;
begin
//glog.log(self, ldNone, lctrace, 'InternalWrite a ' + inttostr(FWriteBlockSize)+ ' s' + inttostr(Size)+ ' Count' + inttostr(Count) + ' p' + inttostr(position)+ ' ms' + inttostr(MaxSize));
gravados := 0;
if Count > 0 then begin
repeat
isLast := (Size=MaxSize) and (WSobraAnterior=0);
if WSobraAnterior + Count > FWriteBlockSize then begin
if WSobraAnterior > FWriteBlockSize then begin
TotalPraGravar := FWriteBlockSize;
Sobra := WSobraAnterior - FWriteBlockSize;
WSobraAnterior := FWriteBlockSize;
//glog.log(self, ldNone, lctrace, 'InternalWrite b '+inttostr(Sobra)+ ' ' + inttostr(WSobraAnterior));
end else begin
TotalPraGravar := FWriteBlockSize - WSobraAnterior;
Sobra := WSobraAnterior + Count - FWriteBlockSize;
//glog.log(self, ldNone, lctrace, 'InternalWrite c '+inttostr(Sobra)+ ' ' + inttostr(WSobraAnterior));
end;
end else begin
TotalPraGravar := Count;
Sobra := WSobraAnterior + Count;
//glog.log(self, ldNone, lctrace, 'InternalWrite d '+inttostr(Sobra)+ ' ' + inttostr(WSobraAnterior));
end;
if WSobraAnterior+TotalPraGravar > FInternalWBlockSize then SetInternalWBuffer(WSobraAnterior+TotalPraGravar);
Move(Buffer, (WBuffer + WSobraAnterior)^, TotalPraGravar);
gravados := gravados + TotalPraGravar;
if Count + WSobraAnterior = FWriteBlockSize then begin
if Assigned(FOnWriteBuffer) then begin
//glog.log(self, ldNone, lctrace, 'InternalWrite ba');
FOnWriteBuffer (Self, WBuffer^, FWriteBlockSize, isLast );
WSobraAnterior := 0;
Sobra := 0;
end;
end else
if TotalPraGravar + WSobraAnterior >= FWriteBlockSize then begin
if Assigned(FOnWriteBuffer) then begin
//glog.log(self, ldNone, lctrace, 'InternalWrite bb '+ inttostr(gravados)+ ' '+ inttostr(Sobra)+ ' ' +inttostr(TotalPraGravar)+ ' ' + inttostr(WSobraAnterior));
FOnWriteBuffer (Self, WBuffer^, FWriteBlockSize, isLast);
if (Sobra>0) then begin
if gravados + sobra > FInternalWBlockSize then SetInternalWBuffer(gravados+sobra);
Move( (Pchar(@Buffer) + gravados)^, WBuffer^, Sobra);
end;
WSobraAnterior := 0;
end;
end else
Sobra := TotalPraGravar;
WSobraAnterior := WSobraAnterior + Sobra;
Count := Count - FWriteBlockSize;
application.ProcessMessages;
//glog.log(self, ldNone, lctrace, 'InternalWrite bc '+ inttostr(sobra)+ ' '+ inttostr(FWriteBlockSize));
until (sobra <= FWriteBlockSize);
end;
end;
procedure TFileBlockStream.ProcessarRestante;
begin
if WSobraAnterior > 0 then begin
//glog.log(self, ldNone, lctrace, 'InternalWrite ca '+ inttostr(WSobraAnterior));
if Assigned(FOnWriteBuffer) then
FOnWriteBuffer (Self, WBuffer^, WSobraAnterior, true );
WSobraAnterior := 0;
end;
if RSobraAnterior > 0 then begin
//glog.log(self, ldNone, lctrace, 'InternalWrite cb '+ inttostr(RSobraAnterior));;
if Assigned(FOnReadBuffer) then
FOnReadBuffer (Self, RBuffer^, RSobraAnterior, true );
RSobraAnterior := 0;
end;
end;
end.
|
program Sample;
var c: Char;
begin
WriteLn('type a character and press enter:');
Read(c);
WriteLn('got chacter ''', c, '''');
end.
|
unit TMAbout;
{
Aestan Tray Menu
Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu
for more information.
This work is hereby released into the Public Domain. To view a copy of the
public domain dedication, visit:
http://creativecommons.org/licenses/publicdomain/
or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
California 94305, USA.
This is the about dialog for AeTrayMenu.
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvGradient, StdCtrls, ExtCtrls, JvExStdCtrls, JvRichEdit, ComCtrls,
JvStringHolder, JvExControls;
type
TAboutDiag = class(TForm)
VersionLabel: TLabel;
CloseBtn: TButton;
AboutText: TJvRichEdit;
AboutHeader: TLabel;
BottomLine: TBevel;
OtherAboutLabel: TLabel;
AboutAeTrayMenu: TJvStrHolder;
JvGradient2: TJvGradient;
procedure AboutTextsURLClick(Sender: TObject; const URLText: String;
Button: TMouseButton);
procedure OtherAboutLabelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FCustomAboutVersion: String;
FCustomAboutHeader: String;
FCustomAboutText: TStrings;
InternalVersionText: String;
FShowingCustom: Boolean;
procedure SetCustomAboutText(const Value: TStrings);
procedure SetShowingCustom(const Value: Boolean);
public
property CustomAboutHeader: String read FCustomAboutHeader write FCustomAboutHeader;
property CustomAboutVersion: String read FCustomAboutVersion write FCustomAboutVersion;
property CustomAboutText: TStrings read FCustomAboutText write SetCustomAboutText;
property ShowingCustom: Boolean read FShowingCustom write SetShowingCustom;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SwitchAboutBox(Custom: Boolean);
end;
var
AboutDiag: TAboutDiag;
implementation
uses ShellApi, JclFileUtils;
{$R *.dfm}
{$I AeTrayMenu.lc}
procedure TAboutDiag.AboutTextsURLClick(Sender: TObject;
const URLText: String; Button: TMouseButton);
begin
ShellExecute(0, nil, PChar(URLText), nil, nil, SW_SHOW);
end;
constructor TAboutDiag.Create(AOwner: TComponent);
var
VersionInfo: TJclFileVersionInfo;
begin
inherited;
FCustomAboutText := TStringList.Create;
try
VersionInfo := TJclFileVersionInfo.Create(ParamStr(0));
try
InternalVersionText := 'Version ' + VersionInfo.FileVersion + #13#10 +
'Built on ' + __COMPILE_DATETIME_AS_STRING__;
finally
FreeAndNil(VersionInfo);
end; //try..finally
except
//Ignore exceptions
end;
end;
destructor TAboutDiag.Destroy;
begin
FreeAndNil(FCustomAboutText);
inherited;
end;
procedure TAboutDiag.OtherAboutLabelClick(Sender: TObject);
begin
ShowingCustom := not ShowingCustom;
end;
procedure TAboutDiag.SetCustomAboutText(const Value: TStrings);
begin
FCustomAboutText.Assign(Value);
end;
procedure TAboutDiag.SwitchAboutBox(Custom: Boolean);
begin
if Custom then
begin
AboutHeader.Caption := ' ' + CustomAboutHeader;
VersionLabel.Caption := CustomAboutVersion;
AboutText.Lines.Assign(CustomAboutText);
OtherAboutLabel.Caption := 'About Aestan Tray Menu';
end
else //custom
begin
AboutHeader.Caption := ' Aestan Tray Menu';
VersionLabel.Caption := InternalVersionText;
AboutText.Lines.Assign(AboutAeTrayMenu.Strings);
OtherAboutLabel.Caption := 'About ' + CustomAboutHeader;
end; //else custom
end;
procedure TAboutDiag.FormShow(Sender: TObject);
begin
ShowingCustom := (CustomAboutHeader <> '');
SwitchAboutBox(ShowingCustom);
OtherAboutLabel.Visible := ShowingCustom;
end;
procedure TAboutDiag.SetShowingCustom(const Value: Boolean);
begin
FShowingCustom := Value;
SwitchAboutBox(Value);
end;
end.
|
unit ncVersionInfo;
{
ResourceString: Dario 13/03/13
}
interface
uses Windows, SysUtils, Classes;
{$I NEX.INC}
function GetVersionInfo(fn:String = ''):String;
var
SelfVersion: String = '';
SelfShortVer: String = '';
ProgShortVer: String = '';
WProgShortVer: Word = 0;
implementation
type
TEXEVersionData = record
CompanyName,
FileDescription,
FileVersion,
InternalName,
LegalCopyright,
LegalTrademarks,
OriginalFileName,
ProductName,
ProductVersion,
Comments,
PrivateBuild,
SpecialBuild: string;
end;
function GetEXEVersionData(const FileName: string): TEXEVersionData;
type
PLandCodepage = ^TLandCodepage;
TLandCodepage = record
wLanguage,
wCodePage: word;
end;
var
dummy,
len: cardinal;
buf, pntr: pointer;
lang: string;
begin
len := GetFileVersionInfoSize(PChar(FileName), dummy);
if len = 0 then
RaiseLastOSError;
GetMem(buf, len);
try
if not GetFileVersionInfo(PChar(FileName), 0, len, buf) then
RaiseLastOSError;
if not VerQueryValue(buf, '\VarFileInfo\Translation\', pntr, len) then
RaiseLastOSError;
lang := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage, PLandCodepage(pntr)^.wCodePage]);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\CompanyName'), pntr, len){ and (@len <> nil)} then
result.CompanyName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\FileDescription'), pntr, len){ and (@len <> nil)} then
result.FileDescription := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\FileVersion'), pntr, len){ and (@len <> nil)} then
result.FileVersion := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\InternalName'), pntr, len){ and (@len <> nil)} then
result.InternalName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\LegalCopyright'), pntr, len){ and (@len <> nil)} then
result.LegalCopyright := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\LegalTrademarks'), pntr, len){ and (@len <> nil)} then
result.LegalTrademarks := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\OriginalFileName'), pntr, len){ and (@len <> nil)} then
result.OriginalFileName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\ProductName'), pntr, len){ and (@len <> nil)} then
result.ProductName := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\ProductVersion'), pntr, len){ and (@len <> nil)} then
result.ProductVersion := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\Comments'), pntr, len){ and (@len <> nil)} then
result.Comments := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\PrivateBuild'), pntr, len){ and (@len <> nil)} then
result.PrivateBuild := PChar(pntr);
if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\SpecialBuild'), pntr, len){ and (@len <> nil)} then
result.SpecialBuild := PChar(pntr);
finally
FreeMem(buf);
end;
end;
function GetVersionInfo(fn:String = ''):String;
var
n, Len: DWORD;
Buf: PChar;
Value: PChar;
S: String;
begin
if fn='' then fn := ParamStr(0);
result := GetExeVersionData(fn).FileVersion;
Exit;
n := GetFileVersionInfoSize(PChar(fn), n);
if n > 0 then
begin
Buf := AllocMem(n);
GetFileVersionInfo(PChar(fn), 0, n, Buf);
if VerQueryValue(Buf, PChar('\StringFileInfo\041604E4\FileVersion'), Pointer(Value), Len) then // do not localize
if trim(value)<>'' then
result := Value;
FreeMem(Buf, n);
end
end;
initialization
try
SelfVersion := GetVersionInfo;
SelfShortVer := Copy(SelfVersion, 7, 20);
WProgShortVer := StrToIntDef(SelfShortVer, 0);
ProgShortVer := 'C'+SelfShortVer;
except
end;
end.
|
(*Pequeno exemplo do uso de um DBCtrlGrid para um sistema de controle de
comandas*)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DBCtrls, DB, DBClient, ExtCtrls, DBCGrids, Mask, Grids,
DBGrids;
type
TForm1 = class(TForm)
DBCtrlGrid1: TDBCtrlGrid;
DataSource1: TDataSource;
Memo1: TMemo;
Button1: TButton;
ClientDataSet1: TClientDataSet;
ClientDataSet1ID: TIntegerField;
ClientDataSet1Mesa: TStringField;
ClientDataSet1Valor: TIntegerField;
ClientDataSet1Ativa: TStringField;
DBText1: TDBText;
Label1: TLabel;
Image1: TImage;
procedure DBCtrlGrid1PaintPanel(DBCtrlGrid: TDBCtrlGrid; Index: Integer);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientDataSet1.CreateDataSet;
ClientDataSet1.DisableControls;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 10;
ClientDataSet1Ativa.AsString := 'S';
ClientDataSet1ID.AsInteger := 1;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 0;
ClientDataSet1Ativa.AsString := 'N';
ClientDataSet1ID.AsInteger := 2;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 15;
ClientDataSet1Ativa.AsString := 'S';
ClientDataSet1ID.AsInteger := 3;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 14;
ClientDataSet1Ativa.AsString := 'S';
ClientDataSet1ID.AsInteger := 4;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 0;
ClientDataSet1Ativa.AsString := 'N';
ClientDataSet1ID.AsInteger := 5;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 0;
ClientDataSet1Ativa.AsString := 'N';
ClientDataSet1ID.AsInteger := 6;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 0;
ClientDataSet1Ativa.AsString := 'N';
ClientDataSet1ID.AsInteger := 7;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 100;
ClientDataSet1Ativa.AsString := 'S';
ClientDataSet1ID.AsInteger := 8;
ClientDataSet1.Post;
ClientDataSet1.Append;
ClientDataSet1Valor.AsCurrency := 60;
ClientDataSet1Ativa.AsString := 'S';
ClientDataSet1ID.AsInteger := 9;
ClientDataSet1.Post;
ClientDataSet1.EnableControls;
ClientDataSet1.Last;
end;
procedure TForm1.DBCtrlGrid1PaintPanel(DBCtrlGrid: TDBCtrlGrid; Index: Integer);
var i:integer;
begin
if not ClientDataSet1.IsEmpty then
begin
memo1.Lines.Add(
' index1 = '+intToStr(Index)+
' ID = '+ClientDataSet1.FieldByName('id').AsString+' '+
' Index2 ='+intToStr(DBCtrlGrid.PanelIndex)+' '+
ClientDataSet1.FieldByName('Ativa').AsString
);
if ClientDataSet1.FieldByName('Ativa').AsString = 'S' then
begin
DBText1.Font.Color := clGreen;
Image1.Picture.LoadFromFile('green.bmp');
end
else
begin
DBText1.Font.Color := clRed;
Image1.Picture.LoadFromFile('red.bmp');
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
DBCtrlGrid1.Color := clWhite;
end;
end.
|
unit uDownloads.Service.HTTPDownload;
interface
uses
System.Classes, System.Net.HttpClientComponent, System.IOUtils,
System.SysUtils, System.Net.HttpClient;
type
EErorHTTPDownload = class(Exception)
public
constructor Create(AcMensagem: String); overload;
end;
TThreadHTTPDownload = class(TThread)
private
FoHttpRequest: TNetHTTPRequest;
FoHttpClient: TNetHTTPClient;
FOnReceiveData: TReceiveDataEvent;
FOnRequestCompleted: TRequestCompletedEvent;
FcUrl: String;
FbEmpProcesso: Boolean;
function GetOnReceiveData: TReceiveDataEvent;
function GetOnRequestCompleted: TRequestCompletedEvent;
procedure SetOnReceiveData(AValue: TReceiveDataEvent);
procedure SetOnRequestCompleted(AValue: TRequestCompletedEvent);
procedure DoRequestCompletedExecute(const Sender: TObject;
const AResponse: IHTTPResponse);
procedure DoReciveDataExecute(const Sender: TObject;
AContentLength: Int64; AReadCount: Int64; var AAbort: Boolean);
procedure SetUrl(const Value: String);
protected
procedure Execute; override;
public
procedure AfterConstruction; override;
property Url: String read FcUrl write SetUrl;
property OnReceiveData: TReceiveDataEvent read GetOnReceiveData write SetOnReceiveData;
property OnRequestCompleted: TRequestCompletedEvent read GetOnRequestCompleted write SetOnRequestCompleted;
end;
implementation
{ TThreadHTTPDownload }
procedure TThreadHTTPDownload.Execute;
begin
try
inherited;
if FbEmpProcesso then
Exit;
FoHttpRequest.Get(FcUrl, nil, nil);
FbEmpProcesso := True;
except
on E: Exception do
raise EErorHTTPDownload.Create(E.Message);
end;
end;
procedure TThreadHTTPDownload.AfterConstruction;
begin
FoHttpClient := TNetHTTPClient.Create(nil);
FoHttpRequest := TNetHTTPRequest.Create(nil);
FoHttpRequest.Client := FoHttpClient;
FoHttpRequest.OnReceiveData := DoReciveDataExecute;
FoHttpRequest.OnRequestCompleted := DoRequestCompletedExecute;
FbEmpProcesso := False;
end;
procedure TThreadHTTPDownload.DoRequestCompletedExecute(const Sender: TObject; const AResponse: IHTTPResponse);
begin
try
FbEmpProcesso := False;
if Assigned(OnRequestCompleted) then
OnRequestCompleted(Self, AResponse);
finally
if Assigned(FoHttpRequest) then
FreeAndNil(FoHttpRequest);
if Assigned(FoHttpClient) then
FreeAndNil(FoHttpClient);
end;
end;
procedure TThreadHTTPDownload.DoReciveDataExecute(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var AAbort: Boolean);
begin
if Assigned(OnReceiveData) then
OnReceiveData(Self, AContentLength, AReadCount, AAbort);
end;
function TThreadHTTPDownload.GetOnReceiveData: TReceiveDataEvent;
begin
Result := FOnReceiveData;
end;
function TThreadHTTPDownload.GetOnRequestCompleted: TRequestCompletedEvent;
begin
Result := FOnRequestCompleted;
end;
procedure TThreadHTTPDownload.SetOnReceiveData(AValue: TReceiveDataEvent);
begin
FOnReceiveData := AValue;
end;
procedure TThreadHTTPDownload.SetOnRequestCompleted(AValue: TRequestCompletedEvent);
begin
FOnRequestCompleted := AValue;
end;
procedure TThreadHTTPDownload.SetUrl(const Value: String);
begin
if (Value <> FcUrl) then
FcUrl := Value;
end;
constructor EErorHTTPDownload.Create(AcMensagem: String);
begin
Self.Message := 'Ocorreu o seguinte erro ao realizar o Download: '
+ AcMensagem;
end;
end.
|
{$I RLReport.inc}
unit RLAbout;
interface
uses
SysUtils, Classes,
{$ifdef MSWINDOWS}
ShellAPI,
{$endif}
{$ifdef VCL}
Windows, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons,
{$endif}
{$ifdef CLX}
Types,
Qt, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QButtons,
{$endif}
RLConsts, RLUtils, RLComponentFactory;
type
TFormRLAbout = class(TForm)
ImageLogo: TImage;
LabelTitle: TLabel;
LabelVersion: TLabel;
LabelHome: TLabel;
LabelCopyright: TLabel;
BitBtnOk: TBitBtn;
procedure LabelHomeClick(Sender: TObject);
private
TypedAuthorKey: string;
procedure Init;
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{ TFormRLAbout }
constructor TFormRLAbout.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
TypedAuthorKey := '';
Init;
end;
procedure TFormRLAbout.KeyDown(var Key: Word; Shift: TShiftState);
const
TheAuthorKey = 'TEAM';
begin
inherited;
if (ssCtrl in Shift) and (Key >= 65) and (Key <= 90) then
begin
TypedAuthorKey := TypedAuthorKey + Char(Key);
if Length(TypedAuthorKey) > Length(TheAuthorKey) then
Delete(TypedAuthorKey, 1, 1);
if SameText(TypedAuthorKey, TheAuthorKey) then
Caption := 'Autor: ' + CS_AuthorNameStr;
end;
{$ifdef CLX}
if Key = key_escape then
BitBtnOk.Click;
{$endif}
{$ifdef VCL}
if Key = vk_escape then
BitBtnOk.Click;
{$endif}
end;
procedure TFormRLAbout.LabelHomeClick(Sender: TObject);
begin
{$ifdef MSWINDOWS}
ShellExecute(0, nil, PChar(TLabel(Sender).Hint), nil, nil, SW_SHOWNORMAL);
{$endif}
end;
procedure TFormRLAbout.Init;
begin
Left := 250;
Top := 223;
ActiveControl := BitBtnOk;
{$ifdef VCL}
BorderStyle := bsDialog;
{$else}
BorderStyle := fbsDialog;
{$endif};
Caption := LocaleStrings.LS_AboutTheStr + ' ' + CS_ProductTitleStr;
ClientHeight := 155;
ClientWidth := 373;
Color := clWhite;
Position := poScreenCenter;
Scaled := False;
PixelsPerInch := 96;
KeyPreview := True;
Scaled := False;
AutoScroll := False;
ImageLogo := TImage.Create(Self);
with ImageLogo do
begin
Name := 'ImageLogo';
Parent := Self;
Left := 12;
Top := 12;
Width := 32;
Height := 32;
AutoSize := True;
Picture.Graphic := HexToGraphic(
'07544269746D617076020000424D760200000000000076000000280000002000' +
'000020000000010004000000000000020000120B0000120B0000100000001000' +
'000000000000000080000080000000808000800000008000800080800000C0C0' +
'C000808080000000FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFF' +
'FF00FFFFFFFFFFFFFFFFFFFF9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9FFFFFFFF' +
'FFFFFFFFFFFFFFFFFFFFFF9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF99FFFFFFFFF' +
'FFFFFFFFFFFFFFFFFFFF99FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF99FFFFFFFFFF' +
'FFFFFFFFFFFFFFFFFFF99FFFFFFFFFFFFFFFFFFFFFFFFFFFFF999FFFFFFFFFFF' +
'FFFFFFFFFFFFFFFFFF99FFFFFFFFFFFFFFFFFFFFFFFFFFFFF999FFFFFFFFFFFF' +
'FFFFFFFFFFFF99FFF999FFFFFFFFFFFFFFFFFFFFFF99FFFF999FFFFFFFFFFFFF' +
'FFFFFFFF999FFFFF999FFFFFFFFFFFFFFFFFFFF9999FFFF9999FFFFFFFFFFFFF' +
'FFFFFF9999FFFFF9999FFFFFFFFFFFFFFFFFF99999FFFFF9999FFFFFFFFFFFFF' +
'FFFFF99999FFFF99999FFFFFFFFFFFFFFFFFF99999FFFF99999FFFFFFFFFFFFF' +
'FFFFF999999FFF99999FFFFFFFFFFFFFFFFFFF999999FF99999FFFFFFFFFFFFF' +
'FFFFFFF999999F99999FFFFFFFFFFFFFFFFFFFFFF9999999999FFFFFFFFFFFFF' +
'FFFFFFFFFFF999999999FFFFFFFFFFFFFFFFFFFFFFFFF9999999FFFFFFFFFFFF' +
'FFFFFFFFFFFFFF9999999FFFFFFFFF999FFFFF9999FFFFF999999999999999FF' +
'FFFFF999999FFFFF99999999999FFFFFFFFFF999999FFFFFF999999FFFFFFFFF' +
'FFFFF999999FFFFFFF9999999FFFFFFFFFFFF999999FFFFFFFFF99999999FFFF' +
'999FFF9999FFFFFFFFFFFF99999999999FFFFFFFFFFFFFFFFFFFFFFFF9999FFF' +
'FFFF');
end;
TRLComponentFactory.CreateComponent(TLabel, Self, LabelTitle);
with LabelTitle do
begin
Name := 'LabelTitle';
Parent := Self;
Left := 52;
Top := 12;
Width := 101;
Height := 19;
Caption := CS_ProductTitleStr;
Font.Name := 'helvetica';
Font.Color := clBlack;
Font.Height := 19;
Font.Pitch := fpVariable;
Font.Style := [fsBold];
ParentFont := False;
end;
TRLComponentFactory.CreateComponent(TLabel, Self, LabelVersion);
with LabelVersion do
begin
Name := 'LabelVersion';
Parent := Self;
Left := 52;
Top := 32;
Width := 65;
Height := 13;
{$ifdef VCL}
Caption := CS_Version + ' VCL';
{$endif}
{$ifdef CLX}
Caption := CS_Version + ' CLX';
{$endif}
Font.Name := 'helvetica';
Font.Color := clBlack;
Font.Height := 13;
Font.Pitch := fpVariable;
Font.Style := [];
ParentFont := False;
end;
TRLComponentFactory.CreateComponent(TLabel, Self, LabelCopyright);
with LabelCopyright do
begin
Name := 'LabelCopyright';
Parent := Self;
Left := 52;
Top := 56;
Width := 211;
Height := 14;
Caption := CS_CopyrightStr + #13 + CS_AuthorNameStr;
Font.Name := 'helvetica';
Font.Color := clBlack;
Font.Height := -11;
Font.Pitch := fpVariable;
Font.Style := [];
ParentFont := False;
end;
TRLComponentFactory.CreateComponent(TLabel, Self, LabelHome);
with LabelHome do
begin
Name := 'LabelHome';
Parent := Self;
Left := 52;
Top := 92;
Hint := CS_URLStr;
Caption := CS_URLStr;
Font.Name := 'helvetica';
Font.Color := clBlue;
Font.Height := -11;
Font.Pitch := fpVariable;
Font.Style := [fsUnderline];
ParentFont := False;
Cursor := crHandPoint;
OnClick := LabelHomeClick;
end;
TRLComponentFactory.CreateComponent(TBitBtn, Self, BitBtnOk);
with BitBtnOk do
begin
Name := 'BitBtnOk';
Parent := Self;
Left := 286;
Top := 112;
Width := 69;
Height := 26;
Caption := '&Ok';
TabOrder := 0;
Kind := bkOK;
end;
end;
end.
|
unit UCtrlTransportadora;
interface
uses uController, DB, UDaoTransportadora;
type CtrlTransportadora = class(Controller)
private
protected
umaDaoTransportadora : DaoTransportadora;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
end;
implementation
{ CtrlTransportadora }
function CtrlTransportadora.Buscar(obj: TObject): Boolean;
begin
result := umaDaoTransportadora.Buscar(obj);
end;
function CtrlTransportadora.Carrega(obj: TObject): TObject;
begin
result := umaDaoTransportadora.Carrega(obj);
end;
constructor CtrlTransportadora.CrieObjeto;
begin
umaDaoTransportadora := DaoTransportadora.CrieObjeto;
end;
destructor CtrlTransportadora.Destrua_se;
begin
umaDaoTransportadora.Destrua_se;
end;
function CtrlTransportadora.Excluir(obj: TObject): string;
begin
result := umaDaoTransportadora.Excluir(obj);
end;
function CtrlTransportadora.GetDS: TDataSource;
begin
result := umaDaoTransportadora.GetDS;
end;
function CtrlTransportadora.Salvar(obj: TObject): string;
begin
result := umaDaoTransportadora.Salvar(obj);
end;
end.
|
unit u_CommonDef;
interface
uses
Classes;
type
TExamineMode = (emSingle, emBatch);
TExamineStatus = (esReady, esWait, esExecute, esComplete);
IExamineItem = Interface;
//===================================
IExamineItemUI = Interface
['{E0847D71-7731-48A8-BF5E-A59E37626696}']
function get_ExamineItem: IExamineItem;
Procedure set_ExamineItem(const Value: IExamineItem);
Procedure set_Percent(const Value: Single);
function get_Enabled(): Boolean;
Procedure set_Enabled(const Value: Boolean);
function get_ButtonCaption: String;
Procedure set_ButtonCaption(const Value: String);
function get_ButtonEnabled: Boolean;
Procedure set_ButtonEnabled(const Value: Boolean);
Procedure SetEnableRecursion(const Value: Boolean);
Procedure SyncUI(Ptr: Pointer);
Property ExamineItem: IExamineItem Read get_ExamineItem Write set_ExamineItem;
Property Enabled: Boolean Read get_Enabled Write set_Enabled;
Property ButtonCaption: String Read get_ButtonCaption Write set_ButtonCaption;
Property ButtonEnabled: Boolean Read get_ButtonEnabled Write set_ButtonEnabled;
End;
IChannelUI = interface
['{9BE12CDA-126B-4CB9-8DF2-C0A24FD918AE}']
function get_EnvIndex: Integer;
Property EnvIndex: Integer Read get_EnvIndex;
end;
IExamineItem = Interface
//实现时需要负责销毁掉UI界面
['{9D4D91F5-2D94-46EA-8266-A9268F090FD2}']
Procedure Start();
Procedure Stop();
function get_Status: TExamineStatus;
Procedure Set_Status(const Value: TExamineStatus);
function get_UI: IExamineItemUI;
Procedure set_UI(const Value: IExamineItemUI);
function get_InlineInsertLost: Double;
Procedure set_InlineInsertLost(const Value: double);
function get_ExamineCaption: String;
Procedure set_ExamineCaption(const Value: String);
function get_ManageList: TInterfaceList;
Procedure set_ManageList(const Value: TInterfaceList);
Procedure RecallStatus; //恢复状态,仅在等待状态中可以调用
Procedure SetAll_Status(Value: TExamineStatus; const ExceptItem: IExamineItem);
Procedure RecallAll_FromWaiting(const ExceptItem: IExamineItem);
Procedure SetAll_Enable(Value: Boolean; const ExceptItem: IExamineItem; Recursion: Boolean);
Procedure CheckWishStop(Delay: Integer = 2);
//============================
Property Status: TExamineStatus Read get_Status Write Set_Status;
Property UI: IExamineItemUI Read get_UI Write set_UI;
Property InlineInsertLost: Double read get_InlineInsertLost write set_InlineInsertLost;
Property ExamineCaption: String read get_ExamineCaption write set_ExamineCaption;
Property ManageList: TInterfaceList Read get_ManageList Write set_ManageList;
End;
implementation
end.
|
unit uEngine2DExtend;
{$ZEROBASEDSTRINGS OFF}
interface
uses
System.Classes,System.SysUtils,System.Types,System.UITypes,System.UIConsts,
FMX.Graphics, FMX.Objects, FMX.Types, uEngine2DObject,
uEngineConfig, System.JSON, uGeometryClasses, FMX.Dialogs;
Type
TObjectStatus = (osStatic,osDynamic,osNone);
{TEngine2DImage 类顾名思义,集成了图片元素的基本属性和方法}
TEngine2DImage = class(TEngine2DObject)
private
FImageStatus : TObjectStatus; // 标记对象状态(静态,动态)
FConfig : TImageConfig; // 记录除位置、大小等之外的其他属性 ..
//FBitmap : TBitmap;
FCurTick : Integer; //记录当前帧,单位:毫秒(步长取决于引擎重绘时间)
FWaitTick : Integer; //记录等待时间
FImageIndex : Integer; //当前播放第几张图片
FIsDelayPlay : boolean; // 当前是否处于延迟播放状态
procedure MsgFromImageConfig(const S : String);
protected
public
Constructor Create(AImage: TBitmap);
Destructor Destroy;override;
procedure Repaint;override;
procedure ClearOldStatus;override; // 清除旧状态
procedure LoadConfig(AConfig : String);override;
procedure Resize(TheParentPosition : T2DPosition);override;
Procedure ReadFromJSONObject(Var inJObj : TJSONObject); override;
procedure ModifyNormalBitmap; // 正常情况下图片切换
procedure ModifyMouseMoveBitmap; // 响应MouseMove事件 图片切换
property ImageStatus : TObjectStatus read FImageStatus write FImageStatus;
property ImageConfig : TImageConfig read FConfig write FConfig;
property InitPosition : TPointF read FInitPosition write FInitPosition;
property MouseDownPoint : TPointF read FMouseDownPoint write FMouseDownPoint;
end;
{TEngine2DImageEX类中的ImageConfig无须创建,为引用对象}
TEngine2DImageEX = class(TEngine2DImage)
private
FConfigRef : TImageConfig;
public
procedure Repaint;override;
property ImageConfig : TImageConfig read FConfigRef write FConfigRef;
end;
{TEngine2DText 类集成了在动画场景中显示文本信息的基本属性和方法}
TEngine2DText = class(TEngine2DObject)
private
FFontFamily : String;
FInitSize : Integer; // 字体初始大小
FFontSize : Integer;
FText : String;
FWordWrap : boolean;
FFontColor : TAlphaColor;
FStyle : TFontStyles;
FTrimming : TTextTrimming;
FHorzAlign: TTextAlign;
FVertAlign : TTextAlign;
procedure SetFontSize(value : Integer);
procedure SetFontColor(value : TAlphaColor);
procedure SetStyle(value : TFontStyles);
public
Constructor Create(AImage : TBitmap);
Destructor Destroy;override;
procedure Resize(TheParentPosition : T2DPosition);override;
Procedure ReadFromJSONObject(Var inJObj : TJSONObject);override;
procedure Repaint;override;
property FontFamily : String read FFontFamily write FFontFamily;
property FontSize : Integer read FFontSize write SetFontSize;
property Text : String read FText write FText;
property Style: TFontStyles read FStyle write SetStyle;
property WordWrap : boolean read FWordWrap write FWordWrap default false;
property FontColor : TAlphaColor read FFontColor write SetFontColor;
property Trimming : TTextTrimming read FTrimming write FTrimming;
end;
implementation
uses
uEngineUtils,uPublic,uEngineAnimation;
{ TEngine2DImage }
procedure TEngine2DImage.ClearOldStatus;
begin
// FIsMouseMove := false;
end;
constructor TEngine2DImage.Create(AImage: TBitmap);
begin
Inherited Create(AImage);
//FBitmap := TBitmap.Create;
FCurTick := 0;
FWaitTick := 0;
FImageIndex := 0;
FIsDelayPlay := false;
end;
destructor TEngine2DImage.Destroy;
begin
//FBitmap.DisposeOf;
if Assigned(FConfig) then
FConfig.DisposeOf;
inherited;
end;
procedure TEngine2DImage.LoadConfig(AConfig: String);
begin
end;
procedure TEngine2DImage.ModifyMouseMoveBitmap;
var
LBmp : TBitmap;
begin
LBmp := FConfig.MouseMovePlayControler.Item;
if LBmp <> nil then
begin
// FCurTick := 0;
// FBitmap.Clear($FF000000);
FBitmap.Assign(LBmp);
end;
// Repaint;
end;
procedure TEngine2DImage.ModifyNormalBitmap;
var
LBmp : TBitmap;
begin
// if (FIsMouseMove) and (FConfig.MouseMovePlayControler.AnimationCount>0) then
// exit;
if FConfig.NormalPlayControler = nil then
exit;
if FConfig.NormalPlayControler.AnimationCount <=1 then
exit;
// 延迟播放
if FIsDelayPlay and (FConfig.NormalPlayControler.DelayInterval > 0) then
begin
FWaitTick := FWaitTick + DRAW_INTERVAL;
if FWaitTick < FConfig.NormalPlayControler.DelayInterval then
begin
exit;
end else
begin
FIsDelayPlay := false;
end;
end;
FCurTick := FCurTick + DRAW_INTERVAL;
if FCurTick >= FConfig.NormalPlayControler.AnimationInterval then
begin
FCurTick := 0;
Inc(FImageIndex);
if FImageIndex >= FConfig.NormalPlayControler.AnimationCount then
begin
if FConfig.NormalPlayControler.Loop then
begin
FImageIndex := 0;
FWaitTick := 0;
FIsDelayPlay := true;
end else
begin
FImageIndex := FConfig.NormalPlayControler.AnimationCount-1;
if Assigned(FConfig.FinishProc) then
begin
FImageIndex := 0;
FConfig.FinishProc();
FConfig.FinishProc := nil;
end;
end;
end;
end;
FConfig.SetNormalImg(FImageIndex);
end;
procedure TEngine2DImage.MsgFromImageConfig(const S : String);
begin
FImageIndex := 0;
end;
procedure TEngine2DImage.Repaint;
var
I : Integer;
begin
try
With FBitmap do
begin
Canvas.DrawBitmap( FConfig.NormalBitmap,
RectF(0,0,FConfig.NormalBitmap.Width,FConfig.NormalBitmap.Height),
RectF(FPosition.X, FPosition.Y, FPosition.X+FPosition.Width, FPosition.Y+FPosition.Height),
FOpacity,
true);
end;
finally
end;
inherited;
end;
procedure TEngine2DImage.Resize(TheParentPosition : T2DPosition);
begin
//TResizeHelper.ResizeObject(Round(FBitmap.Width),Round(FBitmap.Height),Self);
TResizeHelper.DoResize(self.Align, TheParentPosition, FPosition);
Self.FParentPosition := TheParentPosition;
UpdateInvadePoints;
end;
Procedure TEngine2DImage.ReadFromJSONObject(var inJObj: TJSONObject);
var
tmpValue : TJSONValue;
tmpArray : TJSONArray;
tmpObject : TJSONObject;
I : Integer;
tmpRAnimation : T2DRotationAnimation;
tmpPAnimation : T2DPathAnimation;
begin
// 首先读取一些基本的参数...
tmpValue := inJObj.Values['Name'];
if tmpValue <> nil then
begin
Self.FSpriteName := tmpValue.Value;
end;
tmpValue := inJObj.Values['AniType'];
if tmpValue <> nil then
begin
if tmpValue.Value = '0' then
begin
Self.FImageStatus := osStatic;
end else
if tmpValue.Value = '1' then
begin
Self.FImageStatus := osDynamic;
end else
begin
Self.FImageStatus := osNone;
end;
end;
tmpValue := inJObj.Values['Align'];
if tmpValue <> nil then
begin
Self.FAlign := GetAlignNew(tmpValue.Value);
end;
tmpValue := inJObj.Values['Visible'];
if tmpValue <> nil then
begin
Self.FVisible := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['Width'];
if tmpValue <> nil then
begin
try
FPosition.InitWidth := StrToInt(tmpValue.Value);
except
end;
end;
tmpValue := inJObj.Values['Height'];
if tmpValue <> nil then
begin
try
FPosition.InitHeight := StrToInt(tmpValue.Value);
except
end;
end;
tmpValue := inJObj.Values['PositionX'];
if tmpValue <> nil then
begin
try
FPosition.InitX := StrToInt(tmpValue.Value);
except
end;
end;
tmpValue := inJObj.Values['PositionY'];
if tmpValue <> nil then
begin
try
FPosition.InitY := StrToInt(tmpValue.Value);
except
end;
end;
tmpValue := inJObj.Values['Opacity'];
if tmpValue <> nil then
begin
FOpacity := StrToFloatDef(tmpValue.Value,1);
end;
tmpValue := inJObj.Values['HitTest'];
if tmpValue <> nil then
begin
FHitTest := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['Drag'];
if tmpValue <> nil then
begin
FDrag := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['OnMouseDown'];
if tmpValue <> nil then
begin
FOnMouseDown := G_CurrentLogic.MouseDownHandler;
end;
tmpValue := inJObj.Values['OnMouseMove'];
if tmpValue <> nil then
begin
FOnMouseMove := G_CurrentLogic.MouseMoveHandler;
end;
tmpValue := inJObj.Values['OnMouseUp'];
if tmpValue <> nil then
begin
FOnMouseUp := G_CurrentLogic.MouseUpHandler;
end;
tmpValue := inJObj.Values['OnMouseEnter'];
if tmpValue <> nil then
begin
FOnMouseEnter := G_CurrentLogic.MouseEnterHandler;
end;
tmpValue := inJObj.Values['OnMouseLeave'];
if tmpValue <> nil then
begin
FOnMouseLeave := G_CurrentLogic.MouseLeaveHandler;
end;
if not Assigned(Self.FConfig) then
begin
Self.FConfig := TImageConfig.Create(nil,FResManager);
FConfig.OnSwitchStatus := MsgFromImageConfig;
end;
Self.FConfig.SourceName := Self.SpriteName;
// FConfig.Resmanager := Self.FResManager;
tmpValue := inJObj.Values['ImgSource'];
if tmpValue <> nil then
begin
FConfig.SetNormalImg(tmpValue.Value);
end;
// 读取下当前的入侵区域...
tmpValue := inJObj.Values['InvadeArea'];
if tmpValue <> nil then
begin
tmpArray := TJSONArray(tmpValue);
if tmpArray <> nil then
begin
for I := 0 to tmpArray.Size - 1 do
begin
tmpObject := TJSONObject(tmpArray.Get(i));
Self.AcceptAInvade(tmpObject.Values['Name'].Value,
tmpObject.Values['Points'].Value,
tmpObject.Values['InfluenceName'].Value,
tmpObject.Values['DstPoint'].Value
);
end;
end;
end;
//读取正常动画播放
tmpValue := inJObj.Values['NormalPlay'];
if tmpValue <> nil then
begin
tmpArray := TJSONArray(tmpValue);
FConfig.LoadNormalControler(tmpArray) ;
end;
// 读取下Animaton ...
tmpArray := TJSONArray(inJObj.Values['Animation']);
if tmpArray <> nil then
begin
for i := 0 to tmpArray.Size-1 do
begin
tmpObject := TJSONObject(tmpArray.Get(i));
if tmpObject <> nil then
begin
tmpValue := tmpObject.Values['Type'];
if tmpValue <> nil then
begin
if tmpValue.Value = 'Rotation' then
begin
tmpRAnimation := T2DRotationAnimation.Create;
tmpRAnimation.ReadFromJSON(tmpObject);
tmpRAnimation.TimeDur := DRAW_INTERVAL;
tmpRAnimation.Owner := Self;
FAnimation.Add(tmpRAnimation.Name, tmpRAnimation);
end else
if tmpValue.Value = 'Path' then
begin
tmpPAnimation := T2DPathAnimation.Create;
tmpPAnimation.ReadFromJSON(tmpObject);
tmpPAnimation.TimeDur := Draw_INTERVAL;
tmpPAnimation.Owner := Self;
FAnimation.Add(tmpPAnimation.Name, tmpPAnimation);
end;
end;
end;
end;
end;
end;
{ TEngine2DImageEX }
procedure TEngine2DImageEX.Repaint;
begin
try
With FBitmap do
begin
Canvas.DrawBitmap( FConfigRef.NormalBitmap,
RectF(0,0,FConfigRef.NormalBitmap.Width,FConfigRef.NormalBitmap.Height),
RectF(FPosition.X, FPosition.Y, FPosition.X+FPosition.Width, FPosition.Y+FPosition.Height),
FOpacity,
true);
end;
finally
end;
end;
{ TEngine2DText }
constructor TEngine2DText.Create(AImage: TBitmap);
begin
inherited Create(AImage);
FBitmap.Canvas.Font.Family := 'Arial';
FBitmap.Canvas.Fill.Color := TAlphaColors.White;
FBitmap.Canvas.Font.Size := 12;
FBitmap.Canvas.Font.Style := [];
end;
destructor TEngine2DText.Destroy;
begin
inherited;
end;
procedure TEngine2DText.ReadFromJSONObject(var inJObj: TJSONObject);
var
LValue : TJSONValue;
LS,LSubs : String;
begin
LValue := inJObj.Values['Name'];
if LValue <> nil then
begin
Self.SpriteName := LValue.Value;
end;
LValue := inJObj.Values['Align'];
if LValue <> nil then
begin
Self.Align := GetAlignNew(LValue.Value);
end;
LValue := inJObj.Values['Visible'];
if LValue <> nil then
begin
Self.FVisible := UpperCase(LValue.Value) = 'TRUE';
end;
LValue := inJObj.Values['Width'];
if LValue <> nil then
begin
FPosition.InitWidth := StrToIntDef(LValue.Value,50);
end;
LValue := inJObj.Values['Height'];
if LValue <> nil then
begin
FPosition.InitHeight := StrToIntDef(LValue.Value,50);
end;
LValue := inJObj.Values['PositionX'];
if LValue <> nil then
begin
FPosition.InitX := StrToIntDef(LValue.Value,0);
end;
LValue := inJObj.Values['PositionY'];
if LValue <> nil then
begin
FPosition.InitY := StrToIntDef(LValue.Value,0);
end;
LValue := inJObj.Values['FontColor'];
if LValue <> nil then
begin
FontColor := StringToAlphaColor(LValue.Value);
end;
LValue := inJObj.Values['Content'];
if LValue <> nil then
begin
FText := LValue.Value;
end;
LValue := inJObj.Values['WordWrap'];
if LValue <> nil then
begin
FWordWrap := UpperCase(LValue.Value) = 'TRUE';
end;
LValue := inJObj.Values['HorzAlign'];
if LValue <> nil then
begin
FHorzAlign := TTextAlign(StrToIntDef(LValue.Value,0));
end;
LValue := inJObj.Values['VerzAlign'];
if LValue <> nil then
begin
FVertAlign := TTextAlign(StrToIntDef(LValue.Value,0));
end;
LValue := inJObj.Values['FontStyle'];
if LValue <> nil then
begin
LS := LValue.Value;
while LS <> '' do
begin
LSubs := GetHeadString(LS,',');
try
Style := Style + [TFontStyle(StrToInt(LSubs))];
except
end;
end;
end;
LValue := inJObj.Values['FontFamily'];
if LValue <> nil then
begin
FontFamily := LValue.Value;
end;
LValue := inJObj.Values['FontSize'];
if LValue <> nil then
begin
FInitSize := StrToIntDef(LValue.Value,12) ;
end;
end;
procedure TEngine2DText.Repaint;
begin
try
With FBitmap do
begin
Canvas.FillText(RectF(FPosition.X, FPosition.Y, FPosition.X+FPosition.Width, FPosition.Y+FPosition.Height),
FText,
FWordWrap,
FOpacity,
[TFillTextFlag.RightToLeft],
FHorzAlign,
FVertAlign);
end;
finally
end;
end;
procedure TEngine2DText.Resize(TheParentPosition: T2DPosition);
var
LSize : Integer;
begin
LSize := FInitSize;
TResizeHelper.DoTextResize(self.Align, TheParentPosition, FPosition, LSize);
FontSize := LSize;
end;
procedure TEngine2DText.SetFontColor(value: TAlphaColor);
begin
if Not Assigned(FBitmap) then exit;
FFontColor := value;
FBitmap.Canvas.Fill.Color := value;
end;
procedure TEngine2DText.SetFontSize(value: Integer);
begin
if Not Assigned(FBitmap) then exit;
FFontSize := value;
FBitmap.Canvas.Font.Size := FFontSize;
end;
procedure TEngine2DText.SetStyle(value: TFontStyles);
begin
if Not Assigned(FBitmap) then exit;
FStyle := value;
FBitmap.Canvas.Font.Style := FStyle;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLCgRegister<p>
Registration unit for CG shader.<p>
<b>History :</b><font size=-1><ul>
<li>11/11/09 - DaStr - Improved FPC compatibility
(thanks Predator) (BugtrackerID = 2893580)
<li>23/02/07 - DaStr - Initial version
}
unit GLCgRegister;
interface
{$I GLScene.inc}
uses
Classes,
DesignIntf,
DesignEditors,
VCLEditors,
// GLScene
GLMaterial,
GLSceneRegister,
// CG
Cg, CgGL, GLCgShader, GLCgBombShader;
procedure Register;
implementation
procedure Register;
begin
// Register components.
RegisterComponents('GLScene Shaders', [TCgShader, TGLCgBombShader]);
// Register property editors.
RegisterPropertyEditor(TypeInfo(TGLLibMaterialName), TGLCgBombShader, '', TGLLibMaterialNameProperty);
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Bindings.Consts;
interface
resourcestring
sMaxArgsExceeded = 'Maximum number of arguments allowed exceeded (%d)';
sFormatArgError = 'Expected at least one variable for Format() call';
sFormatExpectedStr = 'First argument to Format() must be a string';
sFormatUnexpectedType = 'Unsupported Format() type found: %s';
sUnexpectedArgCount = 'Expected %d arguments, but received %d';
sToStrArgCount = 'Expected 1 argument to ToStr';
sManagerNotFound = 'Manager cannot be Nil.';
sOwnerNotFound = 'Owner cannot be Nil.';
sScopeObjNull = 'Scope obj cannot be Nil.';
sUncompiledExpression = 'The expression has not been compiled yet.';
sUnsupportedManager = 'Manager does not support IBindingNotification.';
sClassTypeNotFound = 'ClassType must be specified.';
sOutputIsReadOnly = 'Output expression evaluates a read only value';
sUnavailNotifier = 'Unable to create notifier';
sConversionUnavailable = 'No conversion is available from type %s to %s';
sConverterNotFound = 'Unable to cast or find converters between types %s and %s.';
sConverterIDNotFound = 'Converter ID must be specified';
sConverterIDNotRegistered = 'No converter with the name %s has been registered';
sDuplicatedConverterType = 'The converter named "%s" with an identical input type (%s) and output type (%s) has already been added';
sMismatchedSignature = 'Method signature does not match expected';
sDuplicatedMethodName = 'A method with name %s already exists';
sMethodNotFound = 'No method with the name %s has been registered';
sDoSetUpRequired = 'Class %s must provide an override for DoSetUp';
sInvalidObject = 'Object must be valid';
sHandlerNotFound = 'No handler to link types %s and %s.';
sIsStillInactive = '%s needs to be activated first.';
sCannotChangeWhileActive = '%s needs to be disabled before changed.';
sMismatchAttach = 'Cannot attach the specified object because it is not of the same type as the metaclass.';
sMetaClassNotFound = 'MetaClass cannot be nil.';
sOverloadGroupArgCount = 'Overload group %s must all have same number of arguments (%d)';
sNamedMismatchArgCount = 'Invalid number of arguments to %s: expected %d, received %d';
sMismatchArgCount = 'Wrong number of args: expected %d, got %d';
sOverloadNotFound = 'No matching overload for %s found';
sAmbiguousOverloadCall = 'Ambiguous overloaded call to %s';
sAddOpFail = 'Don''t know how to add "%s" and "%s"';
sSubtractOpFail = 'Don''t know how to subtract "%s" and "%s"';
sMultiplyOpFail = 'Don''t know how to multiply "%s" and "%s"';
sDivideOpFail = 'Don''t know how to divide "%s" and "%s"';
sNegateOpFail = 'Don''t know how to negate "%s"';
sCompareOpFail = 'Don''t know how to compare "%s" and "%s"';
sParserUnexpected = 'Expected %s but got %s';
sInvalidFloatingPt = 'Invalid floating-point constant - expected one or more digits after "."';
sInvalidFloatingPtExpt = 'Invalid floating-point constant - expected one or more digits as part of exponent';
sUnterminatedString = 'Unterminated string found';
sInvalidOperator = 'Invalid operator in source (%s)';
sInvalidOperatorNum = 'Invalid character in source (#%d)';
sExpectedEOF = 'Expected EOF - trailing text in expression';
sTooManyArgs = 'Too many arguments';
sExpectedIdentifier = 'Expected an identifier, number or string';
sExpressionTooComplex = 'Expression too complex (too many constants)';
sEvalStackOverflow = 'Stack underflow';
sLookupError = 'Couldn''t find %s';
sInvokeError = 'Tried to invoke non-function / non-indexed-property';
sUnsupportedWrapper = 'Cannot determine value because the wrapper does not support IValue';
sUnsupportedGroup = 'Cannot find result wrapper because the member wrapper does not support IGroup';
sWrapError = 'Unable to wrap: %s';
sEmptyOutValue = 'Expression evaluated an empty (nil) value and cannot be assigned';
sClassConflict = 'Unexpected class conflict';
sObjectTypeNotRegistered = 'Object type %s not registered';
sScopeClassNotRegistered = 'Scope class %s not registered';
sScopeClassAlreadyRegistered = 'Scope class %s is already registered';
sInvalidCustomWrapper = 'The given custom wrapper does not support %s';
sPropertyNotFound = 'Property %s not found';
sNoGetterOrSetter = 'Need at least a getter or a setter.';
sUpdateOutputLocFailed = 'Unable to recompile output expression for %s (%s)';
sNoOutputScopes = 'An output scope is required';
sVirtualMemberReadOnly = 'Virtual members are read-only.';
sConvertWrapperFail = 'Cannot convert wrapper. It does not support %s';
// Converters
sNilToTDateTime = 'NilToDateTime';
sNilToTDateTimeDesc = '';
sNilToTStrings = 'NilToTStrings';
sNilToTStringsDesc = '';
sPersistentToPersistent = 'PersistentToPersistent';
sPersistentToPersistentDesc = '';
sPersistentToString = 'PersistentToString';
sPersistentToStringDesc = '';
sBoolToString = 'BoolToString';
sBoolToStringDesc = '';
sStringToBool = 'StringToBool';
sStringToBoolDesc = '';
sNilToNumber = 'NilToNumber';
sNilToNumberDesc = '';
sIntegerToString = 'IntegerToString';
sIntegerToStringDesc = '';
sStringToInteger = 'StringToInteger';
sStringToIntegerDesc = '';
sFloatToString = 'FloatToString';
sFloatToStringDesc = '';
sStrToTDateTime = 'StrToTDateTime';
sStrToTDateTimeDesc = '';
sTDateTimeToStr = 'TDateTimeToStr';
sTDateTimeToStrDesc = '';
sStrToTDate = 'TStrTDate';
sStrToTDateDesc = '';
sStrToTTime = 'TStrTTime';
sStrToTTimeDesc = '';
sNilToString = 'NilToString';
sNilToStringDesc = '';
sNilToBoolean = 'NilToBoolean';
sNilToBooleanDesc = '';
sNilToVariant = 'NilToVariant';
sNilToVariantDesc = '';
sStringToVariant = 'StringToVariant';
sStringToVariantDesc = '';
sFloatToVariant = 'FloatToVariant';
sFloatToVariantDesc = '';
sIntToVariant = 'IntToVariant';
sIntToVariantDesc = '';
sBoolToVariant = 'BoolToVariant';
sBoolToVariantDesc = '';
sVariantToBool = 'VariantToBool';
sVariantToBoolDesc = '';
sStrToFloat = 'StrToFloat';
sStrToFloatDesc = '';
sFloatToInteger = 'FloatToInteger';
sFloatToIntegerDesc = 'Convert float to integer using Round()';
sTStringsToString = 'TStringsToString';
sTStringToStringDesc = '';
sStringToTStrings = 'StringToTStrings';
sStringToTStringsDesc = '';
sStringToChar = 'StringToChar';
sStringToCharDesc = '';
// Methods
sToStrDesc = '';
sToVariantDesc = '';
sToNotifyEventDesc = '';
sFormatDesc = '';
sUpperCaseDesc = '';
sLowerCaseDesc = '';
implementation
end.
|
unit cadastro.modelo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.Mask, Vcl.Grids,
Vcl.DBGrids, Datasnap.Provider, Datasnap.DBClient, Data.DB, UnFuncoesAuxiliares, UnTipos, JvExComCtrls, JvComCtrls, Vcl.ImgList, 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
TfrmCadModelo = class(TForm)
Image2: TImage;
pnCentralCadastro: TPanel;
StatusBar1: TStatusBar;
dsPesquisa: TDataSource;
BalloonHint1: TBalloonHint;
pgCadastro: TPageControl;
tsPesquisa: TTabSheet;
gridPesquisa: TDBGrid;
pnResultado: TPanel;
tsDadosCad: TTabSheet;
pnBotoes: TPanel;
Image3: TImage;
btIncluir: TSpeedButton;
btAlterar: TSpeedButton;
btCancelar: TSpeedButton;
btExcluir: TSpeedButton;
btGravar: TSpeedButton;
btPesquisar: TSpeedButton;
lbTitulo: TLabel;
btSair: TSpeedButton;
procedure btSairClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btIncluirClick(Sender: TObject);
procedure btAlterarClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
procedure btGravarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btPesquisaInicialClick(Sender: TObject);
function TudoNove(S:String):Boolean;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btExcluirClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure gridPesquisaDblClick(Sender: TObject);
private
{ Private declarations }
FNomeTabela: String;
FCondicaoSQL: String;
FSQLCompleto: String;
FValorCampoControle: String;
FCampoControle: String;
public
{ Public declarations }
FComponenteControle : TCustomEdit;
FModoPesquisaAtivo, FExibeResultadoPesquisaNoPanel : boolean;
FPesquisaInicial : string;
procedure MudarEstadoBotoes(opcao: TStatusBotoes);
procedure ColocarEmEstadoInclusao; Virtual;
procedure ColocarEmEstadoEdicao; Virtual;
procedure CancelarEdicao; virtual;
procedure Excluir; Virtual;
procedure Persistir; virtual;
procedure ExecutarPesquisa; virtual;
procedure CarregarRegistroPesquisa(AValor: String); virtual;
property NomeTabela: String read FNomeTabela write FNomeTabela;
property CampoControle: String read FCampoControle write FCampoControle;
end;
var
frmCadModelo: TfrmCadModelo;
FInclusao, FEdicao : boolean;
FUpperCaseAtivo : boolean;
implementation
{$R *.dfm}
uses unConstantes, Dados.Firebird, UnMensagem;
{ TfrmModelo }
procedure TfrmCadModelo.btAlterarClick(Sender: TObject);
begin
ColocarEmEstadoEdicao;
end;
procedure TfrmCadModelo.btCancelarClick(Sender: TObject);
begin
CancelarEdicao;
end;
procedure TfrmCadModelo.btExcluirClick(Sender: TObject);
begin
Excluir;
end;
procedure TfrmCadModelo.btGravarClick(Sender: TObject);
begin
Persistir;
end;
procedure TfrmCadModelo.btIncluirClick(Sender: TObject);
begin
ColocarEmEstadoInclusao;
end;
procedure TfrmCadModelo.btPesquisaInicialClick(Sender: TObject);
begin
ExecutarPesquisa;
end;
procedure TfrmCadModelo.btSairClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadModelo.CancelarEdicao;
begin
tsPesquisa.Enabled := True;
tsDadosCad.Enabled := False;
MudarEstadoBotoes(sbInicialSemDados);
FInclusao := False;
FEdicao := false;
end;
procedure TfrmCadModelo.CarregarRegistroPesquisa(AValor: String);
begin
end;
procedure TfrmCadModelo.ColocarEmEstadoEdicao;
begin
tsPesquisa.Enabled := False;
tsDadosCad.Enabled := True;
MudarEstadoBotoes(sbInsercaoEdicao);
FEdicao := True;
end;
procedure TfrmCadModelo.ColocarEmEstadoInclusao;
begin
tsPesquisa.Enabled := False;
tsDadosCad.Enabled := True;
MudarEstadoBotoes(sbInsercaoEdicao);
FInclusao := True;
end;
procedure TfrmCadModelo.Excluir;
begin
end;
procedure TfrmCadModelo.ExecutarPesquisa;
begin
end;
procedure TfrmCadModelo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FInclusao or FEdicao then
begin
TFrmMensagem.ExibirMensagem(mCanceleOuGrave,tmAlerta);
Action := caNone;
end
else
begin
FreeAndNil(FComponenteControle);
Action := caFree;
end;
end;
procedure TfrmCadModelo.FormCreate(Sender: TObject);
begin
FExibeResultadoPesquisaNoPanel := False;
FModoPesquisaAtivo := False;
FComponenteControle := TCustomEdit.Create(self);
FUpperCaseAtivo := True;
FPesquisaInicial := '';
end;
procedure TfrmCadModelo.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
if (Sender is TMaskEdit) then
begin
Key := #0;
SelectNext(ActiveControl, true, true);
end;
if (Sender is TEdit) then
begin
Key := #0;
SelectNext(ActiveControl, true, true);
end;
end;
if FUpperCaseAtivo then
key := AnsiUpperCase(key)[1];
end;
procedure TfrmCadModelo.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ActiveControl is TComboBox) or
(ActiveControl is TCheckBox) or
(ActiveControl is TRadioGroup) then
begin
StatusBar1.Panels[0].Text := ActiveControl.Hint;
end;
end;
procedure TfrmCadModelo.FormShow(Sender: TObject);
var TextoSQL : String;
Campo : String;
begin
inherited;
MudarEstadoBotoes(sbInicialSemDados);
pgCadastro.ActivePageIndex := 0;
FInclusao := False;
FEdicao := false;
end;
procedure TfrmCadModelo.gridPesquisaDblClick(Sender: TObject);
begin
CarregarRegistroPesquisa('');
end;
procedure TfrmCadModelo.MudarEstadoBotoes(opcao: TStatusBotoes);
begin
if opcao = sbInicialSemDados then
begin
{* Estado inicial da tela *}
btIncluir.Visible := True;
btAlterar.Visible := True;
btCancelar.Visible := False;
btGravar.Visible := False;
btExcluir.Visible := True;
// btPesquisar.Visible := False;
btSair.Visible := True;
end;
if opcao = sbInsercaoEdicao then
begin
{* Estado de edição *}
btIncluir.Visible := False;
btAlterar.Visible := False;
btCancelar.Visible := True;
btGravar.Visible := True;
btExcluir.Visible := False;
// btPesquisar.Visible := False;
btSair.Visible := False;
end;
end;
procedure TfrmCadModelo.Persistir;
begin
tsPesquisa.Enabled := True;
tsDadosCad.Enabled := False;
pgCadastro.ActivePageIndex := 0;
MudarEstadoBotoes(sbInicialSemDados);
FInclusao := False;
FEdicao := false;
end;
function TfrmCadModelo.TudoNove(S: String): Boolean;
var i:Integer;
begin
Result:=True;
For i:=1 to Length(S) do
if S[i]<>'9' then
begin
Result:=False;
Break;
end;
end;
end.
|
// **************************************************************************************************
// Delphi Aio Library.
// Unit MonkeyPatch
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
//
// The Original Code is MoneyPatch.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit MonkeyPatch;
interface
uses DDetours;
procedure PatchWinMsg(Patch: Boolean);
procedure PatchEvent(Patch: Boolean);
implementation
uses Hub, SysUtils, Gevent, SyncObjs,
{$IFDEF MSWINDOWS}
Windows
{$ENDIF}
;
const
INSTR_SIZE = 6;
{$IFDEF MSWINDOWS}
type
TGetMessageWProc = function(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): BOOL; stdcall;
TWaitMessageProc = function: BOOL; stdcall;
TWaitForSingleObjectProc = function (hHandle: THandle; dwMilliseconds: DWORD): DWORD; stdcall;
var
WinMsgPatched: Boolean = False;
EventPatched: Boolean = False;
WaitMessageHook: TWaitMessageProc;
GetMessageWHook: TGetMessageWProc;
WaitForSingleObjectHook: TWaitForSingleObjectProc;
{$ENDIF}
{$IFDEF MSWINDOWS}
function PatchedWaitMessage: BOOL; stdcall;
var
Ev: TSingleThreadHub.TMultiplexorEvent;
lpMsg: TMsg;
begin
Result := PeekMessageW(lpMsg, 0, 0, 0, PM_NOREMOVE);
while not Result do begin
Ev := DefHub.Wait(INFINITE, [], False);
case Ev of
meWinMsg:
Exit(True)
else
DefHub.Serve(0)
end;
end;
end;
function PatchedGetMessageW(var lpMsg: TMsg; hWnd: HWND;
wMsgFilterMin, wMsgFilterMax: UINT): BOOL; stdcall;
var
Ev: TSingleThreadHub.TMultiplexorEvent;
begin
Result := PeekMessageW(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, PM_REMOVE);
while not Result do begin
Ev := DefHub.Wait(INFINITE, [], False);
Result := (Ev = meWinMsg) and PeekMessageW(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, PM_REMOVE);
end;
end;
function PatchedWaitForSingleObject(hHandle: THandle; dwMilliseconds: DWORD): DWORD; stdcall;
var
E: TGevent;
begin
E := TGevent.Create(hHandle);
try
case E.WaitFor(dwMilliseconds) of
wrSignaled:
Exit(WAIT_OBJECT_0);
wrTimeout:
Exit(WAIT_TIMEOUT);
else
Exit(WAIT_ABANDONED)
end;
finally
E.Free
end;
end;
procedure ApiRedirect(OrigFunction, NewFunction: Pointer; var Old);
const
TEMP_JMP: array[0..INSTR_SIZE-1] of Byte = ($E9,$90,$90,$90,$90,$C3);
var
JmpSize: DWORD;
JMP: array [0..INSTR_SIZE-1] of Byte;
OldProtect: DWORD;
begin
Move(TEMP_JMP, JMP, INSTR_SIZE);
JmpSize := DWORD(NewFunction) - DWORD(OrigFunction) - 5;
if not VirtualProtect(LPVOID(OrigFunction), INSTR_SIZE, PAGE_EXECUTE_READWRITE, OldProtect) then
raise Exception.CreateFmt('%s', [SysErrorMessage(GetLastError)]);
Move(OrigFunction^, Old, INSTR_SIZE);
Move(JmpSize, JMP[1], 4);
Move(JMP, OrigFunction^, INSTR_SIZE);
VirtualProtect(LPVOID(OrigFunction), INSTR_SIZE, OldProtect, nil);
end;
procedure PatchWinMsg(Patch: Boolean);
var
OrigGetMessageW: Pointer;
OrigWaitMessage: Pointer;
begin
if Patch <> WinMsgPatched then begin
if Patch then begin
GetMessageWHook := InterceptCreate(@GetMessageW, @PatchedGetMessageW);
WaitMessageHook := InterceptCreate(@WaitMessage, @PatchedWaitMessage);
end
else begin
InterceptRemove(@GetMessageWHook);
InterceptRemove(@WaitMessageHook);
end;
WinMsgPatched := Patch;
end;
end;
procedure PatchEvent(Patch: Boolean);
var
OrigWaitEvent: Pointer;
begin
if Patch <> EventPatched then begin
if Patch then begin
WaitForSingleObjectHook := InterceptCreate(@WaitForSingleObject, @PatchedWaitForSingleObject)
end
else begin
InterceptRemove(@WaitForSingleObjectHook);
end;
WinMsgPatched := Patch;
end;
end;
{$ENDIF}
end.
|
unit AppConfiguration;
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
System.IOUtils,
System.Generics.Collections;
type
TAppConfiguration = class
private const
KeySourceUnits = 'sourceUnits';
KeyReadmeSection = 'bumpReadme';
KeyReadmeFilePath = 'fileName';
KeyReadmeSearchPattern = 'versionPrefix';
private
FSourceUnits: TList<string>;
FDoReadmeBump: boolean;
FReadmeFilePath: string;
FReadmeSearchPattern: string;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile;
property SourceUnits: TList<string> read FSourceUnits write FSourceUnits;
property DoReadmeBump: boolean read FDoReadmeBump write FDoReadmeBump;
property ReadmeFilePath: string read FReadmeFilePath write FReadmeFilePath;
property ReadmeSearchPattern: string read FReadmeSearchPattern
write FReadmeSearchPattern;
end;
implementation
constructor TAppConfiguration.Create;
begin
FSourceUnits := TList<string>.Create;
end;
destructor TAppConfiguration.Destroy;
begin
FSourceUnits.Free;
inherited;
end;
procedure TAppConfiguration.LoadFromFile;
var
aJsonData: string;
jsObject: TJSONObject;
jsTrue: TJSONTrue;
jsValueSourceUnits: TJSONValue;
jsSourceUnitsArray: TJSONArray;
aSourcePath: string;
i: integer;
jsReadmeBump: TJSONObject;
begin
aJsonData := TFile.ReadAllText('app-config.json');
jsObject := TJSONObject.ParseJSONValue(aJsonData) as TJSONObject;
jsTrue := TJSONTrue.Create;
try
// --- PAS Source ----
jsValueSourceUnits := jsObject.GetValue(KeySourceUnits);
if jsValueSourceUnits=nil then
begin
writeln(Format('Error! Mandatory configuration item: "%s" does not exist.',
[KeySourceUnits]));
Halt(2);
end;
if not(jsValueSourceUnits is TJSONArray) then
begin
writeln(Format('Error! Configuration item: "%s" is not array of strings',
[KeySourceUnits]));
Halt(2);
end;
jsSourceUnitsArray := jsValueSourceUnits as TJSONArray;
FSourceUnits.Clear;
for i := 0 to jsSourceUnitsArray.Count - 1 do
begin
aSourcePath := jsSourceUnitsArray.Items[i].Value;
FSourceUnits.Add(aSourcePath);
end;
// --- README ----
DoReadmeBump := (jsObject.GetValue(KeyReadmeSection) <> nil);
if DoReadmeBump then
begin
jsReadmeBump := jsObject.GetValue(KeyReadmeSection) as TJSONObject;
ReadmeFilePath := jsReadmeBump.GetValue(KeyReadmeFilePath).Value;
ReadmeSearchPattern := jsReadmeBump.GetValue(KeyReadmeSearchPattern).Value;
end;
finally
jsObject.Free;
jsTrue.Free;
end;
end;
end.
|
unit FC.Trade.Trainer.ModifyOrderDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Menus, ActnPopup,
Buttons, Spin, Mask, StockChart.Definitions, FC.Definitions, ufmDialogClose_B,FC.Trade.TrainerDialog,
FC.Trade.Trainer.NewOrderDialog, PlatformDefaultStyleActnCtrls;
type
TfmTrainerModifyOrderDialog = class(TfmTrainerNewOrderDialog)
procedure acOKExecute(Sender: TObject);
procedure acOKUpdate(Sender: TObject);
public
constructor Create(const aTrader: TStockTraderTrainer; aOrder: IStockorder);
destructor Destroy; override;
end;
implementation
uses SystemService, BaseUtils, FC.Datautils, FC.Trade.Trader.Base;
{$R *.dfm}
{ TfmTrainerModifyOrderDialog }
procedure TfmTrainerModifyOrderDialog.acOKExecute(Sender: TObject);
begin
try
if (OpenedOrder.GetState=osPending) and (GetOpenPrice<>OpenedOrder.GetPendingOpenPrice) then
OpenedOrder.OpenAt(OpenedOrder.GetSymbol,OpenedOrder.GetKind,GetOpenPrice,GetRate,GetStopLoss,GetTakeProfit,GetTrailingStop,GetComment)
else begin
OpenedOrder.SetStopLoss(GetStopLoss);
OpenedOrder.SetTakeProfit(GetTakeProfit);
OpenedOrder.SetTrailingStop(GetTrailingStop);
end;
except
on E:Exception do
begin
ModalResult:=mrNone;
MsgBox.MessageFailure(0,E.Message);
end;
end;
end;
procedure TfmTrainerModifyOrderDialog.acOKUpdate(Sender: TObject);
begin
inherited;
edOpenPrice.Enabled:=OpenedOrder.GetState=osPending;
laOpenPriceTitle.Enabled:=edOpenPrice.Enabled;
edLots.Enabled:=OpenedOrder.GetState=osPending;
laLotsTitle.Enabled:=edLots.Enabled;
edComment.Enabled:=(OpenedOrder.GetState=osPending) and (GetOpenPrice<>OpenedOrder.GetPendingOpenPrice) ;
laCommentTitle.Enabled:=edComment.Enabled;
if (OpenedOrder.GetState=osPending) and (GetOpenPrice<>OpenedOrder.GetPendingOpenPrice) then
laOrderType.Caption:='Reopen Pending Order'
else if OpenedOrder.GetState=osPending then
laOrderType.Caption:='Modify Pending Order'
else
laOrderType.Caption:='Modify Opened Order';
end;
constructor TfmTrainerModifyOrderDialog.Create(const aTrader: TStockTraderTrainer; aOrder: IStockorder);
begin
if aOrder=nil then
raise EAlgoError.Create;
if not (aOrder.GetState in [osOpened,osPending]) then
raise EAlgoError.Create;
inherited Create(aTrader,aOrder.GetKind);
OpenedOrder:=aOrder;
Caption:='Modify '+OrderKindNames[aOrder.GetKind]+' Order';
if OpenedOrder.GetState=osPending then
edOpenPrice.ValueFloat:=OpenedOrder.GetPendingOpenPrice
else begin
edOpenPrice.ValueFloat:=OpenedOrder.GetOpenPrice;
if OpenedOrder.GetKind=okBuy then
begin
laAsk.Font.Style:=[];
laBid.Font.Style:=[fsBold];
end
else begin
laAsk.Font.Style:=[fsBold];
laBid.Font.Style:=[];
end;
end;
edLots.ValueFloat:=OpenedOrder.GetLots;
edStopLoss.ValueFloat:=OpenedOrder.GetStopLoss;
edTakeProfit.ValueFloat:=OpenedOrder.GetTakeProfit;
edTrailingStop.ValueFloat:=OpenedOrder.GetTrailingStop;
if edStopLoss.ValueFloat=0 then
edStopLoss.Text:='';
if edTakeProfit.ValueFloat=0 then
edTakeProfit.Text:='';
if edTrailingStop.ValueFloat=0 then
edTrailingStop.Text:='';
end;
destructor TfmTrainerModifyOrderDialog.Destroy;
begin
inherited;
end;
end.
|
unit Artista;
interface
type
TArtista = class
procedure Nome;
procedure Biografia;
procedure Discos;
procedure Shows;
end;
implementation
{ TArtista }
procedure TArtista.Biografia;
begin
Writeln('Biografia: Quando os jovens Ryan Ross e Spencer Smith pediram guitarra e bateria, respectivamente, como presentes de natal,' +
'eles nunca iriam imaginar que seu interesse por música poderia levá-los tão longe.');
end;
procedure TArtista.Discos;
begin
Writeln('Discos: ');
Writeln ('2005: A Fever You Can''t Sweat Out');
Writeln('2008: Pretty. Odd');
Writeln('2011: Vices & Virtues');
Writeln('2013: Too Weird To Live, Too Rare To Die!');
Writeln('2016: Death Of A Bachelor');
end;
procedure TArtista.Nome;
begin
Writeln('Panic! at the Disco');
end;
procedure TArtista.Shows;
begin
Writeln('Shows: JUL 11 WED Target Center A R I Z O N A Hayley Kiyoko Minneapolis, MN, United States TICKETS RSVP' +
'JUL 13 FRI Bankers Life Fieldhouse Hayley Kiyoko A R I Z O N A Indianapolis, IN, United States');
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QButtons;
{$S-,W-,R-,H+,X+}
interface
uses Qt, Classes, QTypes, QControls, QForms, QGraphics, QStdCtrls, Types,
QExtCtrls;
const
CM_BUTTONPRESSED = CM_BASE + 100;
type
TCMButtonPressed = packed record
Msg: Cardinal;
Control: TControl;
Index: Integer;
end;
TButtonLayout = (blGlyphLeft, blGlyphRight, blGlyphTop, blGlyphBottom);
TButtonState = (bsUp, bsDisabled, bsDown, bsExclusive);
TNumGlyphs = 1..4;
TSpeedButton = class(TGraphicControl)
private
FDown: Boolean;
FDragging: Boolean;
FAllowAllUp: Boolean;
FTransparent: Boolean;
FFlat: Boolean;
FMouseInControl: Boolean;
FLayout: TButtonLayout;
FGroupIndex: Integer;
FGlyph: Pointer;
FSpacing: Integer;
FMargin: Integer;
FCaption: TCaption;
procedure GlyphChanged(Sender: TObject);
procedure UpdateExclusive;
function GetGlyph: TBitmap;
procedure SetGlyph(Value: TBitmap);
function GetNumGlyphs: TNumGlyphs;
procedure SetNumGlyphs(Value: TNumGlyphs);
procedure SetDown(Value: Boolean);
procedure SetFlat(Value: Boolean);
procedure SetAllowAllUp(Value: Boolean);
procedure SetGroupIndex(Value: Integer);
procedure SetLayout(Value: TButtonLayout);
procedure SetSpacing(Value: Integer);
procedure SetTransparent(Value: Boolean);
procedure SetMargin(Value: Integer);
function IsGlyphStored: Boolean;
protected
FState: TButtonState;
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override;
procedure ButtonPressed(Sender: TSpeedButton; GroupIndex: Integer);
procedure DblClick; override;
procedure EnabledChanged; override;
function GetText: TCaption; override;
procedure FontChanged; override;
procedure Loaded; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseEnter(AControl: TControl); override;
procedure MouseLeave(AControl: TControl); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure SetText(const Value: TCaption); override;
procedure TextChanged; override;
function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Click; override;
published
property Action;
property Anchors;
property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False;
property Constraints;
property GroupIndex: Integer read FGroupIndex write SetGroupIndex default 0;
property Down: Boolean read FDown write SetDown default False;
property DragMode;
property Caption;
property Enabled;
property Flat: Boolean read FFlat write SetFlat default False;
property Font;
property Glyph: TBitmap read GetGlyph write SetGlyph stored IsGlyphStored;
property Layout: TButtonLayout read FLayout write SetLayout default blGlyphLeft;
property Margin: Integer read FMargin write SetMargin default -1;
property NumGlyphs: TNumGlyphs read GetNumGlyphs write SetNumGlyphs default 1;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Spacing: Integer read FSpacing write SetSpacing default 4;
property Transparent: Boolean read FTransparent write SetTransparent default True;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TBitBtnKind = (bkCustom, bkOK, bkCancel, bkHelp, bkYes, bkNo, bkClose,
bkAbort, bkRetry, bkIgnore, bkAll);
TBitBtn = class(TButton)
private
FKind: TBitBtnKind;
FLayout: TButtonLayout;
FModifiedGlyph: Boolean;
FCanvas: TCanvas;
FGlyph: Pointer;
FSpacing: Integer;
FMargin: Integer;
procedure SetGlyph(Value: TBitmap);
function GetGlyph: TBitmap;
function GetNumGlyphs: TNumGlyphs;
procedure SetNumGlyphs(Value: TNumGlyphs);
procedure GlyphChanged(Sender: TObject);
function IsCustom: Boolean;
function IsCustomCaption: Boolean;
procedure SetKind(Value: TBitBtnKind);
function GetKind: TBitBtnKind;
procedure PaintHook(p: QPainterH; R: PRect) cdecl;
procedure SetLayout(Value: TButtonLayout);
procedure SetSpacing(Value: Integer);
procedure SetMargin(Value: Integer);
protected
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override;
procedure CreateWidget; override;
procedure InitWidget; override;
procedure EnabledChanged; override;
procedure FontChanged; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Click; override;
published
property Action;
property Anchors;
property Cancel stored IsCustom;
property Caption stored IsCustomCaption;
property Constraints;
property Default stored IsCustom;
property Enabled;
property Glyph: TBitmap read GetGlyph write SetGlyph stored IsCustom;
property Kind: TBitBtnKind read GetKind write SetKind default bkCustom;
property Layout: TButtonLayout read FLayout write SetLayout default blGlyphLeft;
property Margin: Integer read FMargin write SetMargin default -1;
property ModalResult stored IsCustom;
property NumGlyphs: TNumGlyphs read GetNumGlyphs write SetNumGlyphs stored IsCustom default 1;
property ParentShowHint;
property ShowHint;
property Spacing: Integer read FSpacing write SetSpacing default 4;
property TabOrder;
property TabStop;
property Visible;
property OnEnter;
property OnExit;
end;
function DrawButtonFace(Canvas: TCanvas; const Client: TRect;
BevelWidth: Integer; IsDown, IsFocused: Boolean; Flat: Boolean = False;
FillColor: TColor = clButton; FillStyle: TBrushStyle = bsSolid): TRect;
implementation
uses QConsts, SysUtils, QActnList, QImgList;
{$R QButtons.res}
{ TBitBtn data }
var
BitBtnResNames: array[TBitBtnKind] of PChar = (
nil, 'QBOK', 'QBCANCEL', 'QBHELP', 'QBYES', 'QBNO', 'QBCLOSE',
'QBABORT', 'QBRETRY', 'QBIGNORE', 'QBALL');
BitBtnCaptions: array[TBitBtnKind] of Pointer = (
nil, @SOKButton, @SCancelButton, @SHelpButton, @SYesButton, @SNoButton,
@SCloseButton, @SAbortButton, @SRetryButton, @SIgnoreButton,
@SAllButton);
BitBtnModalResults: array[TBitBtnKind] of TModalResult = (
0, mrOk, mrCancel, 0, mrYes, mrNo, 0, mrAbort, mrRetry, mrIgnore,
mrAll);
var
BitBtnGlyphs: array[TBitBtnKind] of TBitmap;
{ DrawButtonFace - returns the remaining usable area inside the Client rect.}
function DrawButtonFace(Canvas: TCanvas; const Client: TRect;
BevelWidth: Integer; IsDown, IsFocused: Boolean; Flat: Boolean = False;
FillColor: TColor = clButton; FillStyle: TBrushStyle = bsSolid): TRect;
var
R: TRect;
SaveColor: TColor;
SaveStyle: TBrushStyle;
begin
R := Client;
with Canvas do
begin
SaveColor := Brush.Color;
Brush.Color := FillColor;
try
SaveStyle := Brush.Style;
if Brush.Color <> clNone then
Brush.Style := FillStyle
else
Brush.Style := bsClear;
try
Canvas.FillRect(R);
if IsDown then
begin
if not Flat then
DrawEdge(Canvas, R, esLowered, esNone, [ebTop, ebLeft]);
DrawEdge(Canvas, R, esNone, esLowered, [ebBottom, ebRight]);
DrawEdge(Canvas, R, esNone, esLowered, [ebTop, ebLeft]);
end
else
begin
DrawEdge(Canvas, R, esNone, esRaised, [ebBottom, ebRight]);
if not Flat then
DrawEdge(Canvas, R, esRaised, esNone, [ebBottom, ebRight]);
Dec(R.Bottom); Dec(R.Right);
DrawEdge(Canvas, R, esNone, esRaised, [ebLeft, ebTop]);
end;
finally
Brush.Style := SaveStyle;
end;
finally
Brush.Color := SaveColor;
end;
end;
Result := Rect(Client.Left + 1, Client.Top + 1, Client.Right - 2,
Client.Bottom - 2);
if IsDown then OffsetRect(Result, 1, 1);
end;
function GetBitBtnGlyph(Kind: TBitBtnKind): TBitmap;
begin
if BitBtnGlyphs[Kind] = nil then
begin
BitBtnGlyphs[Kind] := TBitmap.Create;
BitBtnGlyphs[Kind].LoadFromResourceName(HInstance, BitBtnResNames[Kind]);
end;
Result := BitBtnGlyphs[Kind];
end;
type
TGlyphList = class(TImageList)
private
Used: TBits;
FCount: Integer;
function AllocateIndex(Bitmap: TBitmap): Integer;
public
constructor CreateSize(AWidth, AHeight: Integer);
destructor Destroy; override;
function AddMasked(Image: TBitmap; MaskColor: TColor): Integer; reintroduce;
procedure Delete(Index: Integer);
property Count: Integer read FCount;
end;
TButtonGlyph = class
private
FOriginal: TBitmap;
FGlyphList: TGlyphList;
FIndexs: array[TButtonState] of Integer;
FTransparentColor: TColor;
FNumGlyphs: TNumGlyphs;
FOnChange: TNotifyEvent;
procedure GlyphChanged(Sender: TObject);
procedure SetGlyph(Value: TBitmap);
procedure SetNumGlyphs(Value: TNumGlyphs);
procedure Invalidate;
function CreateButtonGlyph(State: TButtonState): Integer;
procedure DrawButtonGlyph(Canvas: TCanvas; const GlyphPos: TPoint;
State: TButtonState; Transparent: Boolean);
procedure DrawButtonText(Canvas: TCanvas; const Caption: TCaption;
TextBounds: TRect; State: TButtonState);
procedure CalcButtonLayout(Canvas: TCanvas; const Client: TRect;
const Offset: TPoint; const Caption: TCaption; Layout: TButtonLayout;
Margin, Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect);
public
constructor Create;
destructor Destroy; override;
{ return the text rectangle }
function Draw(Canvas: TCanvas; const Client: TRect; const Offset: TPoint;
const Caption: TCaption; Layout: TButtonLayout; Margin, Spacing: Integer;
State: TButtonState; Transparent: Boolean): TRect;
property Glyph: TBitmap read FOriginal write SetGlyph;
property NumGlyphs: TNumGlyphs read FNumGlyphs write SetNumGlyphs;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
{ TGlyphList }
constructor TGlyphList.CreateSize(AWidth, AHeight: Integer);
begin
inherited CreateSize(AWidth, AHeight);
Used := TBits.Create;
end;
destructor TGlyphList.Destroy;
begin
Used.Free;
inherited Destroy;
end;
function TGlyphList.AllocateIndex(Bitmap: TBitmap): Integer;
begin
Result := Used.OpenBit;
if Result >= Used.Size then
begin
Result := inherited Add(Bitmap, nil);
Used.Size := Result + 1;
end;
Used[Result] := True;
end;
function TGlyphList.AddMasked(Image: TBitmap; MaskColor: TColor): Integer;
begin
Result := AllocateIndex(Image);
ReplaceMasked(Result, Image, MaskColor);
Inc(FCount);
end;
procedure TGlyphList.Delete(Index: Integer);
begin
if Used[Index] then
begin
Dec(FCount);
Used[Index] := False;
end;
end;
{ TButtonGlyph }
constructor TButtonGlyph.Create;
var
I: TButtonState;
begin
inherited Create;
FOriginal := TBitmap.Create;
FOriginal.OnChange := GlyphChanged;
FTransparentColor := clOlive;
FNumGlyphs := 1;
for I := Low(I) to High(I) do
FIndexs[I] := -1;
end;
destructor TButtonGlyph.Destroy;
begin
FOriginal.Free;
Invalidate;
inherited Destroy;
end;
procedure TButtonGlyph.Invalidate;
var
I: TButtonState;
begin
for I := Low(I) to High(I) do
begin
if FIndexs[I] <> -1 then FGlyphList.Delete(FIndexs[I]);
FIndexs[I] := -1;
end;
FreeAndNil(FGlyphList);
end;
procedure TButtonGlyph.GlyphChanged(Sender: TObject);
begin
if Sender = FOriginal then
begin
Invalidate;
if Assigned(FOnChange) then FOnChange(Self);
end;
end;
procedure TButtonGlyph.SetGlyph(Value: TBitmap);
var
Glyphs: Integer;
begin
Invalidate;
FOriginal.Assign(Value);
if Value = nil then
begin
FOriginal.Width := 0;
FOriginal.Height := 0;
end else
if (Value <> nil) and (Value.Height > 0) then
begin
if Value.Width mod Value.Height = 0 then
begin
Glyphs := Value.Width div Value.Height;
if Glyphs > 4 then Glyphs := 1;
SetNumGlyphs(Glyphs);
end;
end;
end;
procedure TButtonGlyph.SetNumGlyphs(Value: TNumGlyphs);
begin
if (Value <> FNumGlyphs) and (Value > 0) then
begin
Invalidate;
FNumGlyphs := Value;
GlyphChanged(Glyph);
end;
end;
function TButtonGlyph.CreateButtonGlyph(State: TButtonState): Integer;
var
TmpImage: TBitmap;
IWidth, IHeight: Integer;
IRect, ORect: TRect;
I: TButtonState;
begin
if (State = bsDown) and (NumGlyphs < 3) then State := bsUp;
Result := FIndexs[State];
if Result <> -1 then Exit;
if (FOriginal.Width or FOriginal.Height) = 0 then Exit;
IWidth := FOriginal.Width div FNumGlyphs;
IHeight := FOriginal.Height;
if FGlyphList = nil then
FGlyphList := TGlyphList.CreateSize(IWidth, IHeight);
TmpImage := TBitmap.Create;
try
TmpImage.Width := IWidth;
TmpImage.Height := IHeight;
IRect := Rect(0, 0, IWidth, IHeight);
TmpImage.Canvas.Brush.Color := clBtnFace;
I := State;
if Ord(I) >= NumGlyphs then I := bsUp;
ORect := Rect(Ord(I) * IWidth, 0, (Ord(I) + 1) * IWidth, IHeight);
case State of
bsUp, bsDown,
bsExclusive:
begin
TmpImage.Canvas.CopyRect(IRect, FOriginal.Canvas, ORect);
if FOriginal.TransparentMode = tmFixed then
FIndexs[State] := FGlyphList.AddMasked(TmpImage, FTransparentColor)
else
FIndexs[State] := FGlyphList.AddMasked(TmpImage, clDefault);
end;
bsDisabled:
begin
if NumGlyphs > 1 then
TmpImage.Canvas.CopyRect(IRect, FOriginal.Canvas, ORect)
else
FGlyphList.Draw(TmpImage.Canvas, 0, 0, FIndexs[bsUp], itImage, False);
if FOriginal.TransparentMode = tmFixed then
FIndexs[State] := FGlyphList.AddMasked(TmpImage, FTransparentColor)
else
FIndexs[State] := FGlyphList.AddMasked(TmpImage, clDefault);
end;
end;
finally
TmpImage.Free;
end;
Result := FIndexs[State];
FOriginal.Dormant;
end;
procedure TButtonGlyph.DrawButtonGlyph(Canvas: TCanvas; const GlyphPos: TPoint;
State: TButtonState; Transparent: Boolean);
var
Index: Integer;
begin
if FOriginal = nil then Exit;
if (FOriginal.Width = 0) or (FOriginal.Height = 0) then Exit;
Index := CreateButtonGlyph(State);
FGlyphList.Draw(Canvas, GlyphPos.X, GlyphPos.Y, Index, itImage, True);
end;
procedure TButtonGlyph.DrawButtonText(Canvas: TCanvas; const Caption: TCaption;
TextBounds: TRect; State: TButtonState);
var
AlignFlags: Integer;
BrushStyle: TBrushStyle;
begin
AlignFlags := Integer(AlignmentFlags_ShowPrefix);
with Canvas do
begin
BrushStyle := Brush.Style;
try
Brush.Style := bsClear;
if State = bsDisabled then
begin
OffsetRect(TextBounds, 1, 1);
Font.Color := clBtnHighlight;
Canvas.TextRect(TextBounds, TextBounds.Left, TextBounds.Top, Caption, AlignFlags);
OffsetRect(TextBounds, -1, -1);
Font.Color := clBtnShadow;
Canvas.TextRect(TextBounds, TextBounds.Left, TextBounds.Top, Caption, AlignFlags);
end else
Canvas.TextRect(TextBounds, TextBounds.Left, TextBounds.Top, Caption, AlignFlags);
finally
Brush.Style := BrushStyle;
end;
end;
end;
procedure TButtonGlyph.CalcButtonLayout(Canvas: TCanvas; const Client: TRect;
const Offset: TPoint; const Caption: TCaption; Layout: TButtonLayout; Margin,
Spacing: Integer; var GlyphPos: TPoint; var TextBounds: TRect);
var
TextPos: TPoint;
ClientSize, GlyphSize, TextSize: TPoint;
TotalSize: TPoint;
AlignFlags: Integer;
begin
AlignFlags := Integer(AlignmentFlags_ShowPrefix);
{ calculate the item sizes }
ClientSize := Point(Client.Right - Client.Left, Client.Bottom -
Client.Top);
if Length(Caption) > 0 then
begin
TextBounds := Client;
Canvas.TextExtent(Caption, TextBounds, AlignFlags);
TextSize := Point(TextBounds.Right - TextBounds.Left, TextBounds.Bottom -
TextBounds.Top);
end
else
begin
TextBounds := Rect(0, 0, 0, 0);
TextSize := Point(0,0);
end;
if FOriginal <> nil then
begin
GlyphSize := Point(FOriginal.Width div FNumGlyphs, FOriginal.Height);
if Layout in [blGlyphLeft, blGlyphRight] then
begin
GlyphPos.Y := (ClientSize.Y - GlyphSize.Y + 1) div 2;
TextPos.Y := (ClientSize.Y - TextSize.Y + 1) div 2;
end
else
begin
GlyphPos.X := (ClientSize.X - GlyphSize.X + 1) div 2;
TextPos.X := (ClientSize.X - TextSize.X + 1) div 2;
end;
end else
GlyphSize := Point(0, 0);
{ If the layout has the glyph on the right or the left, then both the
text and the glyph are centered vertically. If the glyph is on the top
or the bottom, then both the text and the glyph are centered horizontally.}
{ if there is no text or no bitmap, then Spacing is irrelevant }
if (TextSize.X = 0) or (GlyphSize.X = 0) then
Spacing := 0;
{ adjust Margin and Spacing }
if Margin = -1 then
begin
if Spacing = -1 then
begin
TotalSize := Point(GlyphSize.X + TextSize.X, GlyphSize.Y + TextSize.Y);
if Layout in [blGlyphLeft, blGlyphRight] then
Margin := (ClientSize.X - TotalSize.X) div 3
else
Margin := (ClientSize.Y - TotalSize.Y) div 3;
Spacing := Margin;
end
else
begin
TotalSize := Point(GlyphSize.X + Spacing + TextSize.X, GlyphSize.Y +
Spacing + TextSize.Y);
if Layout in [blGlyphLeft, blGlyphRight] then
Margin := (ClientSize.X - TotalSize.X + 1) div 2
else
Margin := (ClientSize.Y - TotalSize.Y + 1) div 2;
end;
end
else
begin
if Spacing = -1 then
begin
TotalSize := Point(ClientSize.X - (Margin + GlyphSize.X), ClientSize.Y -
(Margin + GlyphSize.Y));
if Layout in [blGlyphLeft, blGlyphRight] then
Spacing := (TotalSize.X - TextSize.X) div 2
else
Spacing := (TotalSize.Y - TextSize.Y) div 2;
end;
end;
case Layout of
blGlyphLeft:
begin
GlyphPos.X := Margin;
TextPos.X := GlyphPos.X + GlyphSize.X + Spacing;
end;
blGlyphRight:
begin
GlyphPos.X := ClientSize.X - Margin - GlyphSize.X;
TextPos.X := GlyphPos.X - Spacing - TextSize.X;
end;
blGlyphTop:
begin
GlyphPos.Y := Margin;
TextPos.Y := GlyphPos.Y + GlyphSize.Y + Spacing;
end;
blGlyphBottom:
begin
GlyphPos.Y := ClientSize.Y - Margin - GlyphSize.Y;
TextPos.Y := GlyphPos.Y - Spacing - TextSize.Y;
end;
end;
{ fixup the result variables }
with GlyphPos do
begin
Inc(X, Client.Left + Offset.X);
Inc(Y, Client.Top + Offset.Y);
end;
OffsetRect(TextBounds, TextPos.X + Offset.X,
TextPos.Y+ Offset.X);
end;
function TButtonGlyph.Draw(Canvas: TCanvas; const Client: TRect;
const Offset: TPoint; const Caption: TCaption; Layout: TButtonLayout;
Margin, Spacing: Integer; State: TButtonState; Transparent: Boolean): TRect;
var
GlyphPos: TPoint;
begin
CalcButtonLayout(Canvas, Client, Offset, Caption, Layout, Margin, Spacing,
GlyphPos, Result);
DrawButtonGlyph(Canvas, GlyphPos, State, Transparent);
DrawButtonText(Canvas, Caption, Result, State);
end;
{ TSpeedButton }
constructor TSpeedButton.Create(AOwner: TComponent);
begin
FGlyph := TButtonGlyph.Create;
TButtonGlyph(FGlyph).OnChange := GlyphChanged;
inherited Create(AOwner);
SetBounds(0, 0, 23, 22);
ControlStyle := [csCaptureMouse, csDoubleClicks, csClickEvents];
ParentFont := True;
Color := clBtnFace;
FSpacing := 4;
FMargin := -1;
FLayout := blGlyphLeft;
Transparent := True;
end;
destructor TSpeedButton.Destroy;
begin
TButtonGlyph(FGlyph).Free;
inherited Destroy;
end;
procedure TSpeedButton.Paint;
var
BrushStyle: TBrushStyle;
PaintRect: TRect;
Offset: TPoint;
begin
if (Height <= 0) or (Width <= 0) then Exit;
if not Enabled and not (csDesigning in ComponentState) then
begin
FState := bsDisabled;
FDragging := False;
end
else if FState = bsDisabled then
if FDown and (GroupIndex <> 0) then
FState := bsExclusive
else
FState := bsUp;
Canvas.Font := Self.Font;
PaintRect := Rect(0, 0, Width, Height);
if Transparent then
BrushStyle := bsClear
else
BrushStyle := bsSolid;
if not FFlat then
DrawButtonFace(Canvas, PaintRect, 1, FState in [bsDown, bsExclusive], False,
False, Color, BrushStyle)
else
begin
if not Transparent then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(PaintRect);
end;
if FState in [bsDown, bsExclusive] then
DrawEdge(Canvas, PaintRect, esNone, esLowered, ebRect)
else if (FMouseInControl and (FState = bsUp))
or (csDesigning in ComponentState) then
DrawEdge(Canvas, PaintRect, esNone, esRaised, ebRect);
end;
if FState in [bsDown, bsExclusive] then
begin
if (FState = bsExclusive) and (not FFlat or not FMouseInControl) then
begin
Inc(PaintRect.Top);
Inc(PaintRect.Left);
Canvas.Brush.Bitmap := AllocPatternBitmap(clBtnFace, clBtnHighlight);
Canvas.FillRect(PaintRect);
end;
Offset.X := 1;
Offset.Y := 1;
end
else
begin
Offset.X := 0;
Offset.Y := 0;
end;
TButtonGlyph(FGlyph).Draw(Canvas, PaintRect, Offset, Caption, FLayout, FMargin,
FSpacing, FState, Transparent);
end;
procedure TSpeedButton.Loaded;
var
State: TButtonState;
begin
inherited Loaded;
if Enabled then
State := bsUp
else
State := bsDisabled;
TButtonGlyph(FGlyph).CreateButtonGlyph(State);
end;
procedure TSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if (Button = mbLeft) and Enabled then
begin
if not FDown then
begin
FState := bsDown;
Invalidate;
end;
FDragging := True;
end;
end;
procedure TSpeedButton.MouseMove(Shift: TShiftState; X, Y: Integer);
var
NewState: TButtonState;
begin
inherited MouseMove(Shift, X, Y);
if FDragging then
begin
if not FDown then NewState := bsUp
else NewState := bsExclusive;
if (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight) then
if FDown then NewState := bsExclusive else NewState := bsDown;
if NewState <> FState then
begin
FState := NewState;
Invalidate;
end;
end;
end;
procedure TSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
DoClick: Boolean;
begin
inherited MouseUp(Button, Shift, X, Y);
if FDragging then
begin
FDragging := False;
DoClick := (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight);
if FGroupIndex = 0 then
begin
{ Redraw face in-case mouse is captured }
FState := bsUp;
if DoClick and not (FState in [bsExclusive, bsDown]) then
Invalidate;
end
else
if DoClick then
begin
SetDown(not FDown);
if FDown then Repaint;
end
else
begin
if FDown then FState := bsExclusive;
Repaint;
end;
end;
end;
procedure TSpeedButton.Click;
begin
inherited Click;
end;
function TSpeedButton.GetGlyph: TBitmap;
begin
Result := TButtonGlyph(FGlyph).Glyph;
end;
procedure TSpeedButton.SetGlyph(Value: TBitmap);
begin
TButtonGlyph(FGlyph).Glyph := Value;
Invalidate;
end;
function TSpeedButton.GetNumGlyphs: TNumGlyphs;
begin
Result := TButtonGlyph(FGlyph).NumGlyphs;
end;
procedure TSpeedButton.SetNumGlyphs(Value: TNumGlyphs);
begin
if Value < 0 then Value := 1
else if Value > 4 then Value := 4;
if Value <> TButtonGlyph(FGlyph).NumGlyphs then
begin
TButtonGlyph(FGlyph).NumGlyphs := Value;
Invalidate;
end;
end;
procedure TSpeedButton.GlyphChanged(Sender: TObject);
begin
Invalidate;
end;
procedure TSpeedButton.UpdateExclusive;
var
Msg: TCMButtonPressed;
I: Integer;
begin
if (FGroupIndex <> 0) and (Parent <> nil) then
begin
Msg.Msg := CM_BUTTONPRESSED;
Msg.Control := Self;
Msg.Index := FGroupIndex;
Parent.Broadcast(Msg);
for I := 0 to Parent.ControlCount-1 do
if Parent.Controls[I] is TSpeedButton then
TSpeedButton(Parent.Controls[I]).ButtonPressed(Self, FGroupIndex);
end;
end;
procedure TSpeedButton.SetDown(Value: Boolean);
begin
if FGroupIndex = 0 then Value := False;
if Value <> FDown then
begin
if FDown and (not FAllowAllUp) and (GroupIndex <> 0) then Exit;
FDown := Value;
if Value then
begin
if FState = bsUp then Invalidate;
FState := bsExclusive;
end
else
begin
FState := bsUp;
Repaint;
end;
if Value then UpdateExclusive;
end;
end;
procedure TSpeedButton.SetFlat(Value: Boolean);
begin
if Value <> FFlat then
begin
FFlat := Value;
Invalidate;
end;
end;
procedure TSpeedButton.SetGroupIndex(Value: Integer);
begin
if FGroupIndex <> Value then
begin
FGroupIndex := Value;
UpdateExclusive;
if FGroupIndex = 0 then
Down := False;
end;
end;
procedure TSpeedButton.SetLayout(Value: TButtonLayout);
begin
if FLayout <> Value then
begin
FLayout := Value;
Invalidate;
end;
end;
procedure TSpeedButton.SetMargin(Value: Integer);
begin
if (Value <> FMargin) and (Value >= -1) then
begin
FMargin := Value;
Invalidate;
end;
end;
procedure TSpeedButton.SetSpacing(Value: Integer);
begin
if Value <> FSpacing then
begin
FSpacing := Value;
Invalidate;
end;
end;
procedure TSpeedButton.SetTransparent(Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
if Value then
ControlStyle := ControlStyle - [csOpaque] else
ControlStyle := ControlStyle + [csOpaque];
Invalidate;
end;
end;
procedure TSpeedButton.SetAllowAllUp(Value: Boolean);
begin
if FAllowAllUp <> Value then
begin
FAllowAllUp := Value;
UpdateExclusive;
end;
end;
procedure TSpeedButton.EnabledChanged;
const
NewState: array[Boolean] of TButtonState = (bsDisabled, bsUp);
begin
TButtonGlyph(FGlyph).CreateButtonGlyph(NewState[Enabled]);
Repaint;
end;
procedure TSpeedButton.ButtonPressed(Sender: TSpeedButton; GroupIndex: Integer);
begin
if GroupIndex = FGroupIndex then
begin
if Sender <> Self then
begin
if Sender.Down and FDown then
begin
FDown := False;
FState := bsUp;
Invalidate;
end;
FAllowAllUp := Sender.AllowAllUp;
end;
end;
end;
procedure TSpeedButton.DblClick;
begin
if FDown and(GroupIndex <> 0) then
inherited DblClick;
end;
procedure TSpeedButton.FontChanged;
begin
Invalidate;
end;
procedure TSpeedButton.TextChanged;
begin
Invalidate;
end;
procedure TSpeedButton.MouseEnter(AControl: TControl);
begin
inherited MouseEnter(AControl);
if FFlat and not FMouseInControl and Enabled
and (GetCaptureControl = nil) then
begin
FMouseInControl := True;
Repaint;
end;
end;
procedure TSpeedButton.MouseLeave(AControl: TControl);
begin
inherited MouseLeave(AControl);
if FFlat and FMouseInControl and Enabled and not FDragging then
begin
FMouseInControl := False;
Invalidate;
end;
end;
procedure TSpeedButton.ActionChange(Sender: TObject; CheckDefaults: Boolean);
procedure CopyImage(ImageList: TCustomImageList; Index: Integer);
begin
with Glyph do
begin
Width := ImageList.Width;
Height := ImageList.Height;
Canvas.Brush.Color := clFuchsia; {! for lack of a better color }
Canvas.FillRect(Rect(0,0, Width, Height));
ImageList.Draw(Canvas, 0, 0, Index);
end;
end;
begin
inherited ActionChange(Sender, CheckDefaults);
if Sender is TCustomAction then
with TCustomAction(Sender) do
begin
{ Copy image from action's imagelist }
if (Glyph.Empty) and (ActionList <> nil) and (ActionList.Images <> nil) and
(ImageIndex >= 0) and (ImageIndex < ActionList.Images.Count) then
CopyImage(ActionList.Images, ImageIndex);
end;
end;
function TSpeedButton.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TSpeedButton.SetText(const Value: TCaption);
begin
if FCaption <> Value then
begin
FCaption := Value;
TextChanged;
Invalidate;
end;
end;
function TSpeedButton.WantKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean;
begin
Result := IsAccel(Key, Caption);
if Result then Click else
Result := inherited WantKey(Key, Shift, KeyText);
end;
{ TBitBtn }
type
TBitBtnPaintEvent = procedure(p: QPainterH; R: PRect) of object cdecl;
constructor TBitBtn.Create(AOwner: TComponent);
begin
FGlyph := TButtonGlyph.Create;
TButtonGlyph(FGlyph).OnChange := GlyphChanged;
inherited Create(AOwner);
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FKind := bkCustom;
FLayout := blGlyphLeft;
FSpacing := 4;
FMargin := -1;
end;
destructor TBitBtn.Destroy;
begin
inherited Destroy;
TButtonGlyph(FGlyph).Free;
FCanvas.Free;
end;
procedure TBitBtn.Click;
var
Form: TCustomForm;
Control: TWinControl;
function UsesDefaultHelp(Querant: TWinControl) : Boolean;
begin
Result := false;
if (Querant.HelpType = htKeyword) and (Querant.HelpKeyword = '') then
Result := true;
if (Querant.HelpType = htContext) and (Querant.HelpContext = 0) then
Result := true;
end;
begin
case FKind of
bkClose:
begin
Form := GetParentForm(Self);
if Form <> nil then Form.Close
else inherited Click;
end;
bkHelp:
begin
Control := Self;
while (Control <> nil) and UsesDefaultHelp(Control) do
Control := Control.Parent;
if Control <> nil then
begin
if Control.HelpType = htKeyword then
Application.KeywordHelp(Control.HelpKeyword);
if Control.HelpType = htContext then
Application.ContextHelp(Control.HelpContext);
end;
inherited Click;
end;
else
inherited Click;
end;
end;
procedure TBitBtn.FontChanged;
begin
inherited FontChanged;
Invalidate;
end;
procedure TBitBtn.EnabledChanged;
begin
inherited EnabledChanged;
Invalidate;
end;
procedure TBitBtn.SetGlyph(Value: TBitmap);
begin
TButtonGlyph(FGlyph).Glyph := Value as TBitmap;
FModifiedGlyph := True;
Invalidate;
end;
function TBitBtn.GetGlyph: TBitmap;
begin
Result := TButtonGlyph(FGlyph).Glyph;
end;
procedure TBitBtn.GlyphChanged(Sender: TObject);
begin
Invalidate;
end;
function TBitBtn.IsCustom: Boolean;
begin
Result := Kind = bkCustom;
end;
procedure TBitBtn.SetKind(Value: TBitBtnKind);
begin
if Value <> FKind then
begin
if Value <> bkCustom then
begin
Default := Value in [bkOK, bkYes];
Cancel := Value in [bkCancel, bkNo];
if ((csLoading in ComponentState) and (Caption = '')) or
(not (csLoading in ComponentState)) then
begin
if BitBtnCaptions[Value] <> nil then
Caption := LoadResString(BitBtnCaptions[Value]);
end;
ModalResult := BitBtnModalResults[Value];
TButtonGlyph(FGlyph).Glyph := GetBitBtnGlyph(Value);
NumGlyphs := 2;
FModifiedGlyph := False;
end;
FKind := Value;
Invalidate;
end;
end;
function TBitBtn.IsCustomCaption: Boolean;
begin
Result := AnsiCompareStr(Caption, LoadResString(BitBtnCaptions[FKind])) <> 0;
end;
function TBitBtn.GetKind: TBitBtnKind;
begin
if FKind <> bkCustom then
if ((FKind in [bkOK, bkYes]) xor Default) or
((FKind in [bkCancel, bkNo]) xor Cancel) or
(ModalResult <> BitBtnModalResults[FKind]) or
FModifiedGlyph then
FKind := bkCustom;
Result := FKind;
end;
procedure TBitBtn.SetLayout(Value: TButtonLayout);
begin
if FLayout <> Value then
begin
FLayout := Value;
Invalidate;
end;
end;
function TBitBtn.GetNumGlyphs: TNumGlyphs;
begin
Result := TButtonGlyph(FGlyph).NumGlyphs;
end;
procedure TBitBtn.SetNumGlyphs(Value: TNumGlyphs);
begin
if Value < 0 then Value := 1
else if Value > 4 then Value := 4;
if Value <> TButtonGlyph(FGlyph).NumGlyphs then
begin
TButtonGlyph(FGlyph).NumGlyphs := Value;
Invalidate;
end;
end;
procedure TBitBtn.SetSpacing(Value: Integer);
begin
if FSpacing <> Value then
begin
FSpacing := Value;
Invalidate;
end;
end;
procedure TBitBtn.SetMargin(Value: Integer);
begin
if (Value <> FMargin) and (Value >= - 1) then
begin
FMargin := Value;
Invalidate;
end;
end;
procedure TBitBtn.ActionChange(Sender: TObject; CheckDefaults: Boolean);
procedure CopyImage(ImageList: TCustomImageList; Index: Integer);
begin
with Glyph do
begin
Width := ImageList.Width;
Height := ImageList.Height;
Canvas.Brush.Color := clFuchsia; {! for lack of a better color }
Canvas.FillRect(Rect(0,0, Width, Height));
ImageList.Draw(Canvas, 0, 0, Index);
end;
end;
begin
inherited ActionChange(Sender, CheckDefaults);
if Sender is TCustomAction then
with TCustomAction(Sender) do
begin
{ Copy image from action's imagelist }
if (Glyph.Empty) and (ActionList <> nil) and (ActionList.Images <> nil) and
(ImageIndex >= 0) and (ImageIndex < ActionList.Images.Count) then
CopyImage(ActionList.Images, ImageIndex);
end;
end;
procedure DestroyLocals; far;
var
I: TBitBtnKind;
begin
for I := Low(TBitBtnKind) to High(TBitBtnKind) do
BitBtnGlyphs[I].Free;
end;
procedure TBitBtn.InitWidget;
var
State: TButtonState;
begin
if Enabled then
State := bsUp
else
State := bsDisabled;
inherited InitWidget;
TButtonGlyph(FGlyph).CreateButtonGlyph(State);
end;
procedure TBitBtn.CreateWidget;
var
Method: TMethod;
begin
TBitBtnPaintEvent(Method) := PaintHook;
FHandle := QClxBitBtn_create(ParentWidget, nil, Method);
Hooks := QButton_hook_create(Handle);
end;
procedure TBitBtn.PaintHook(p: QPainterH; r: PRect);
var
Offset: TPoint;
State: TButtonState;
begin
try
FCanvas.Handle := p;
FCanvas.Start(False);
FCanvas.Font := Font;
try
if not Enabled then State := bsDisabled
else if Down then State := bsDown
else State := bsUp;
if State = bsDown then
Offset := Point(1, 1)
else
Offset := Point(0, 0);
TButtonGlyph(FGlyph).Draw(FCanvas, r^, Offset, Caption, FLayout, FMargin,
FSpacing, State, False);
finally
FCanvas.Stop;
FCanvas.Handle := nil;
end;
except
Application.HandleException(Self);
end;
end;
function TSpeedButton.IsGlyphStored: Boolean;
begin
Result := not Glyph.Empty;
end;
initialization
FillChar(BitBtnGlyphs, SizeOf(BitBtnGlyphs), 0);
finalization
DestroyLocals;
end.
|
Program VelkeCislo;
{ umluva 1: pole[1] ma nejmene dulezitou cislici a pole[MAX] nejvice dulezitou cislici }
{ umluva 2: kazdy prvek pole obsahuje cislo v rozmezi od 0 po 99 }
const
MAX = 50;
var
pole, pole2: array[1..MAX] of integer;
i, n : integer;
procedure VypisCislo();
var
i : integer;
begin
for i := MAX downto 1 do begin
if pole[i] < 10 then
write('0');
write(pole[i]);
end;
writeln();
end;
{ pricte k poli cislo }
procedure PrictiCislo(cislo, offset : integer);
var
i, mezicislo, zbytek : integer;
begin
i := offset;
zbytek := cislo;
while zbytek <> 0 do begin
mezicislo := pole[i] + zbytek;
{ pokud je mezicislo vice jak 10, z cislice se stane 0 }
if mezicislo >= 100 then begin
pole[i] := (mezicislo mod 100);
zbytek := mezicislo div 100;
end
else begin
pole[i] := mezicislo;
zbytek := 0;
end;
inc(i);
end;
end;
{ k poli pricte pole2 }
procedure PrictiPole2();
var
i : integer;
begin
for i := 1 to MAX do begin
if pole2[i] <> 0 then
PrictiCislo(pole2[i], i);
end;
end;
{ duplikuje pole do pole2 }
procedure DuplikujDoPole2();
var
i : integer;
begin
for i := 1 to MAX do
pole2[i] := pole[i];
end;
{ vynasobi pole cislem}
procedure VynasobCislem(cislo : integer);
var
i: integer;
begin
DuplikujDoPole2();
{ provede se cislo-krat }
for i := cislo downto 2 do
PrictiPole2();
end;
begin
{ vyplni vsechny pozice pole na nulu }
for i := 0 to MAX do
pole[i] := 0;
write('zadejte n pro n!: ');
readln(n);
PrictiCislo(1, 1); { zacatek nasobku musi byt 1 }
{ iteraktivni provedeni faktorialu, viz komentar dole }
for i := 2 to n do
VynasobCislem(i);
VypisCislo();
end.
{ iteraktivni provedeni faktorialu je dano predpisem:
int product = 1;
for ( int j=1; j<=N; j++ )
product *= j;
}
|
program SystemSlotsInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
function ByteToBinStr(AValue:Byte):string;
const
Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1);
var i: integer;
begin
Result:='00000000';
if (AValue<>0) then
for i:=1 to 8 do
if (AValue and Bits[i])<>0 then Result[i]:='1';
end;
procedure GetSystemSlotInfo;
Var
SMBios: TSMBios;
LSlot: TSystemSlotInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('System Slot Information');
WriteLn('--------------------------');
if SMBios.HasSystemSlotInfo then
for LSlot in SMBios.SystemSlotInfo do
begin
WriteLn('Slot Designation '+LSlot.SlotDesignationStr);
WriteLn('Slot Type '+LSlot.GetSlotType);
WriteLn('Slot Data Bus Width '+LSlot.GetSlotDataBusWidth);
WriteLn('Current Usage '+LSlot.GetCurrentUsage);
WriteLn('Slot Length '+LSlot.GetSlotLength);
WriteLn(Format('Slot ID %.4x',[LSlot.RAWSystemSlotInformation^.SlotID]));
WriteLn('Characteristics 1 '+ByteToBinStr(LSlot.RAWSystemSlotInformation^.SlotCharacteristics1));
WriteLn('Characteristics 2 '+ByteToBinStr(LSlot.RAWSystemSlotInformation^.SlotCharacteristics2));
if SMBios.SmbiosVersion>='2.6' then
begin
WriteLn(Format('Segment Group Number %.4x',[LSlot.RAWSystemSlotInformation^.SegmentGroupNumber]));
WriteLn(Format('Bus Number %d',[LSlot.RAWSystemSlotInformation^.BusNumber]));
end;
WriteLn;
end
else
Writeln('No System Slot Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetSystemSlotInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995,99 Inprise Corporation }
{ }
{*******************************************************}
{ This unit defines the TTabbedNotebook Component. }
unit Tabnotbk;
{$H+,X+}
interface
uses Windows, Classes, Stdctrls, Forms, Messages, Graphics, Controls,
ComCtrls;
const
CM_TABFONTCHANGED = CM_BASE + 100;
type
TPageChangeEvent = procedure(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean) of object;
{ Class : TTabPage
Description : This class implements the individual tab page behavior.
Each instance of this class will hold controls to be
displayed when it is the active page of a TTabbedNotebook
component. }
TTabPage = class(TWinControl)
protected
procedure ReadState(Reader: TReader); override;
public
constructor Create(AOwner: TComponent); override;
published
property Caption;
property Height stored False;
property TabOrder stored False;
property Visible stored False;
property Width stored False;
property Enabled stored False;
end;
{ Class : TTabbedNotebook
Description : This class implements Tabbed notebook component.
It holds a collection of TTabPages onto which
users can drop controls. It uses MS-Word style
tab buttons to allow the user to control which
page is currently active. }
TTabbedNotebook = class(TCustomTabControl)
private
FPageList: TList;
FAccess: TStrings;
FPageIndex: Integer;
FTabFont: TFont;
FTabsPerRow: Integer;
FOnClick: TNotifyEvent;
FOnChange: TPageChangeEvent;
function GetActivePage: string;
procedure SetPages(Value: TStrings);
procedure SetActivePage(const Value: string);
procedure SetTabFont(Value: TFont);
procedure SetTabsPerRow(NewTabCount: Integer);
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure WMPaint(var Message: TWMPaint); message wm_Paint;
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure Change; override;
procedure Click; override;
procedure CreateHandle; override;
procedure CreateParams(var Params: TCreateParams); override;
function GetChildOwner: TComponent; override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure Loaded; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure ReadState(Reader: TReader); override;
procedure SetPageIndex(Value: Integer);
procedure ShowControl(AControl: TControl); override;
procedure CMTabFontChanged(var Message: TMessage); message CM_TABFONTCHANGED;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetIndexForPage(const PageName: string): Integer;
property TopFont: TFont read FTabFont;
procedure TabFontChanged(Sender: TObject);
published
property ActivePage: string read GetActivePage write SetActivePage
stored False;
property Align;
property Anchors;
property Constraints;
property Enabled;
property PageIndex: Integer read FPageIndex write SetPageIndex default 0;
property Pages: TStrings read FAccess write SetPages stored False;
property Font;
property TabsPerRow: Integer read FTabsPerRow write SetTabsPerRow default 3;
property TabFont: TFont read FTabFont write SetTabFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnChange: TPageChangeEvent read FOnChange write FOnChange;
property OnContextPopup;
property OnEnter;
property OnExit;
end;
implementation
uses SysUtils, Consts;
const
TabTopBorder = 4;
PageLeftBorder = 2;
PageBevelWidth = 3;
BorderWidth = 8;
type
{ Class : TTabPageAccess
Description : Maintains the list of TTabPages for a
TTabbedNotebook component. }
TTabPageAccess = class(TStrings)
private
PageList: TList;
Notebook: TTabbedNotebook;
protected
function GetCount: Integer; override;
function Get(Index: Integer): string; override;
procedure Put(Index: Integer; const S: string); override;
function GetObject(Index: Integer): TObject; override;
procedure SetUpdateState(Updating: Boolean); override;
public
constructor Create(APageList: TList; ANotebook: TTabbedNotebook);
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; const S: string); override;
procedure Move(CurIndex, NewIndex: Integer); override;
end;
{ TTabPageAccess }
{ Method : Create
Description : Keeps track of the pages for the notebook. }
constructor TTabPageAccess.Create(APageList: TList; ANotebook: TTabbedNotebook);
begin
inherited Create;
PageList := APageList;
Notebook := ANotebook;
end;
{ Method : GetCount
Description : Return the number of pages in the notebook. }
function TTabPageAccess.GetCount: Integer;
begin
Result := PageList.Count;
end;
{ Method : Get
Description : Return the name of the indexed page, which should match
the name of the corresponding button. }
function TTabPageAccess.Get(Index: Integer): string;
begin
Result := TTabPage(PageList[Index]).Caption;
end;
{ Method : Put
Description : Put a name into a page. The button for the page must have
the same name. }
procedure TTabPageAccess.Put(Index: Integer; const S: string);
begin
TTabPage(PageList[Index]).Caption := S;
if Notebook.HandleAllocated then
Notebook.Tabs[Index] := S;
end;
{ Method : GetObject
Description : Return the page indexed. }
function TTabPageAccess.GetObject(Index: Integer): TObject;
begin
Result := PageList[Index];
end;
{ Method : SetUpdateState
Description : We don't want to do this. }
procedure TTabPageAccess.SetUpdateState(Updating: Boolean);
begin
{ do nothing }
end;
{ Method : Clear
Description : Remove the pages and buttons from the list. }
procedure TTabPageAccess.Clear;
var
Index: Integer;
begin
for Index := 0 to PageList.Count - 1 do
(TObject(PageList[Index]) as TTabPage).Free;
PageList.Clear;
if Notebook.HandleAllocated then
Notebook.Tabs.Clear;
Notebook.Realign;
end;
{ Method : Delete
Description : Delete a page from the pagelist. Take its button away too. }
procedure TTabPageAccess.Delete(Index: Integer);
begin
(TObject(PageList[Index]) as TTabPage).Free;
PageList.Delete(Index);
if Notebook.HandleAllocated then
Notebook.Tabs.Delete(Index);
{ We need to make sure the active page index moves along with the pages. }
if index = Notebook.FPageIndex then
begin
Notebook.FpageIndex := -1;
Notebook.SetPageIndex(0);
end
else if index < Notebook.FPageIndex then
Dec(Notebook.FPageIndex);
{ Clean up the apperance. }
Notebook.Realign;
Notebook.Invalidate;
end;
{ Method : Insert
Description : Add a page, along with its button, to the list. }
procedure TTabPageAccess.Insert(Index: Integer; const S: string);
var
Page: TTabPage;
begin
Page := TTabPage.Create(Notebook);
with Page do
begin
Parent := Notebook;
Caption := S;
end;
PageList.Insert(Index, Page);
if Notebook.HandleAllocated then
Notebook.Tabs.Insert(Index, S);
Notebook.SetPageIndex(Index);
{ Clean up the apperance. }
Notebook.Realign;
Notebook.Invalidate;
end;
{ Method : Move
Description : Move a page, and its button, to a new index. the object
currently at the new location gets swapped to the old
position. }
procedure TTabPageAccess.Move(CurIndex, NewIndex: Integer);
begin
if CurIndex <> NewIndex then
begin
PageList.Exchange(CurIndex, NewIndex);
with Notebook do
begin
if HandleAllocated then
Tabs.Exchange(CurIndex, NewIndex);
if PageIndex = CurIndex then
PageIndex := NewIndex
else if PageIndex = NewIndex then
PageIndex := CurIndex;
Realign;
end;
end;
end;
{ TTabPage }
{ Method : Create
Description : Since the border is drawn by the notebook, this should be
invisible. Don't waste time drawing pages you can't see. }
constructor TTabPage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csAcceptsControls];
Align := alClient;
TabStop := False;
Enabled := False;
Visible := False;
end;
{ Method : ReadState
Description : Another procedure that shouldn't be messed with. }
procedure TTabPage.ReadState(Reader: TReader);
begin
if Reader.Parent is TTabbedNotebook then
TTabbedNotebook(Reader.Parent).FPageList.Add(Self);
inherited ReadState(Reader);
TabStop := False;
end;
{ TTabbedNotebook }
{ Method : Create
Description : Set all the notebook defaults and create the mandatory
one page. }
var
Registered: Boolean = False; { static class data }
constructor TTabbedNotebook.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Exclude(FComponentStyle, csInheritable);
ControlStyle := ControlStyle + [csClickEvents] - [csAcceptsControls];
Width := 300;
Height := 250;
TabStop := True;
FPageList := TList.Create;
FTabFont := TFont.Create;
FTabFont.Color := clBtnText;
FTabFont.OnChange := TabFontChanged;
FTabsPerRow := 3;
FAccess := TTabPageAccess.Create(FPageList, Self);
FPageIndex := -1;
FAccess.Add(SDefault);
PageIndex := 0;
if not Registered then
begin
RegisterClasses([TTabPage]);
Registered := True;
end;
end;
{ Method : Destroy
Description : Remove all the lists before removing self. }
destructor TTabbedNotebook.Destroy;
begin
FAccess.Free;
FPageList.Free;
FTabFont.Free;
inherited Destroy;
end;
procedure TTabbedNotebook.CreateHandle;
var
X: Integer;
begin
inherited CreateHandle;
if not (csReading in ComponentState) and (Tabs.Count = 0) then
begin
{ don't copy the objects into the Tabs list }
for X := 0 to FAccess.Count-1 do
Tabs.Add(FAccess[X]);
TabIndex := FPageIndex;
end;
end;
{ Method : CreateParams
Description : Make sure ClipChildren is set. }
procedure TTabbedNotebook.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or WS_CLIPCHILDREN;
end;
function TTabbedNotebook.GetChildOwner: TComponent;
begin
Result := Self;
end;
procedure TTabbedNotebook.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
I: Integer;
begin
for I := 0 to FPageList.Count - 1 do Proc(TControl(FPageList[I]));
end;
{ Method : Loaded
Description : Make sure only one page is visible, the one set as the
default page. }
procedure TTabbedNotebook.Loaded;
var
Index: Integer;
begin
inherited Loaded;
for Index := 0 to FPageList.Count - 1 do
if Index <> FPageIndex then
begin
(TObject(FPageList[Index]) as TTabPage).Enabled := False;
(TObject(FPageList[Index]) as TTabPage).Visible := False;
end
else
begin
(TObject(FPageList[Index]) as TTabPage).Enabled := True;
(TObject(FPageList[Index]) as TTabPage).Visible := True;
end;
if HandleAllocated then
begin
Tabs.Clear;
for Index := 0 to FAccess.Count-1 do
Tabs.Add(FAccess[Index]);
TabIndex := FPageIndex;
end;
Realign;
end;
{ Method : ReadState
Description : Don't send the button information out since it is all the
same anyway.}
procedure TTabbedNotebook.ReadState(Reader: TReader);
begin
FAccess.Clear;
inherited ReadState(Reader);
if (FPageIndex >= 0) and (FPageIndex < FPageList.Count) then
begin
with (TObject(FPageList[FPageIndex]) as TTabPage) do
begin
Enabled := True;
BringToFront;
Align := alClient;
end;
end
else
FPageIndex := -1;
end;
{ Method : SetPages
Description : }
procedure TTabbedNotebook.SetPages(Value: TStrings);
begin
FAccess.Assign(Value);
if FAccess.Count > 0 then
FPageIndex := 0
else
FPageIndex := -1;
end;
procedure TTabbedNotebook.ShowControl(AControl: TControl);
var
I: Integer;
begin
for I := 0 to FPageList.Count - 1 do
if FPageList[I] = AControl then
begin
SetPageIndex(I);
Exit;
end;
inherited ShowControl(AControl);
end;
{ Method : SetPageIndex
Description : Set the active page to the one specified in Value. }
procedure TTabbedNotebook.SetPageIndex(Value: Integer);
var
AllowChange: Boolean;
ParentForm: TCustomForm;
begin
if csLoading in ComponentState then
begin
FPageIndex := Value;
Exit;
end;
if (Value <> FPageIndex) and (Value >= 0) and (Value < FPageList.Count) then
begin
if Assigned(FOnChange) then
begin
AllowChange := True;
FOnChange(Self, Value, AllowChange);
if not AllowChange then Exit;
end;
ParentForm := GetParentForm(Self);
if ParentForm <> nil then
if ContainsControl(ParentForm.ActiveControl) then
ParentForm.ActiveControl := Self;
if HandleAllocated then
TabIndex := Value;
with TTabPage(FPageList[Value]) do
begin
BringToFront;
Visible := True;
Enabled := True;
end;
if (FPageIndex >= 0) and (FPageIndex < FPageList.Count) then
with TTabPage(FPageList[FPageIndex]) do
begin
Visible := False;
Enabled := False;
end;
if (FPageIndex div FTabsPerRow) <> (Value div FTabsPerRow) then
begin
FPageIndex := Value;
Realign;
end
else
FPageIndex := Value;
end;
end;
{ Method : SetActivePage
Description : Set the active page to the named page. }
procedure TTabbedNotebook.SetActivePage(const Value: string);
begin
SetPageIndex(FAccess.IndexOf(Value));
end;
{ Method : GetActivePage
Description : Return the name of the currently active page. }
function TTabbedNotebook.GetActivePage: string;
begin
if (FAccess.Count > 0) and (FPageIndex >= 0) then
Result := FAccess[FPageIndex]
else
Result := '';
end;
{ Method : WMGetDlgCode
Description : Get arrow keys to manage the tab focus rect }
procedure TTabbedNotebook.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTARROWS;
end;
{ Method : CMDialogChar
Description : Check for dialog keys in the tabs }
procedure TTabbedNotebook.CMDialogChar(var Message: TCMDialogChar);
var
Index: Integer;
begin
with Message do
if FPageList <> nil then
begin
for Index := 0 to FPageList.Count - 1 do
begin
if IsAccel(CharCode, TTabPage(FPageList[Index]).Caption) then
begin
SetFocus;
if Focused then
begin
SetPageIndex(Index);
Click;
end;
Result := 1;
Exit;
end;
end;
end;
inherited;
end;
{ Method : KeyDown
Description : Grab arrow keys to manage the active page. }
procedure TTabbedNotebook.KeyDown(var Key: Word; Shift: TShiftState);
begin
case Key of
VK_RIGHT, VK_DOWN:
begin
if FPageIndex >= (FPageList.Count-1) then SetPageIndex(0)
else SetPageIndex(FPageIndex + 1);
Click;
end;
VK_LEFT, VK_UP:
begin
if FPageIndex > 0 then SetPageIndex(FPageIndex - 1)
else SetPageIndex(FPageList.Count - 1);
Click;
end;
end;
end;
{ Method : SetTabsPerRow
Description : Set the number of tabs in each row. Don't allow less than
three. }
procedure TTabbedNotebook.SetTabsPerRow(NewTabCount: Integer);
begin
if (NewTabCount >= 3) then
begin
FTabsPerRow := NewTabCount;
Realign;
Invalidate;
end;
end;
{ Mathod: GetIndexForPage
Description : Given a page name, return its index number. }
function TTabbedNotebook.GetIndexForPage(const PageName: String): Integer;
var
Index: Integer;
begin
Result := -1;
if FPageList <> nil then
begin
For Index := 0 to FPageList.Count-1 do
begin
if ((TObject(FPageList[Index]) as TTabPage).Caption = PageName) then
begin
Result := Index;
Exit;
end;
end;
end;
end;
{ Method : SetTabFont
Description : Set the font for the tabs. }
procedure TTabbedNotebook.SetTabFont(Value: TFont);
begin
FTabFont.Assign(Value);
end;
{ Method : CMTabFontChanged
Description : Fix the TopFont and redraw the buttons with the new font. }
procedure TTabbedNotebook.CMTabFontChanged(var Message: TMessage);
begin
Invalidate;
end;
procedure TTabbedNotebook.AlignControls(AControl: TControl; var Rect: TRect);
begin
If (FPageIndex >= 0) and (FPageIndex < FPageList.Count) then
inherited AlignControls(FPageList[FPageIndex], Rect);
end;
{ Method : TabFontChanged
Description : Send out the proper message. }
procedure TTabbedNotebook.TabFontChanged(Sender: TObject);
begin
Perform(CM_TABFONTCHANGED, 0, 0);
end;
{ Method : Click
Description : Call event procedure. }
procedure TTabbedNotebook.Click;
begin
if Assigned(FOnClick) then FOnClick(Self);
end;
procedure TTabbedNotebook.Change;
begin
if TabIndex >= 0 then
SetPageIndex(TabIndex);
if FPageIndex = TabIndex then
inherited Change
else
TabIndex := FPageIndex;
end;
procedure TTabbedNotebook.WMPaint(var Message: TWMPaint);
begin
SendMessage(Handle, wm_SetFont, TabFont.Handle, 0);
inherited;
end;
end.
|
unit classe.Spend;
interface
uses System.SysUtils;
type
TSpend = class
private
FName : String;
FSpend : Currency;
FDate: TDateTime;
procedure SetName(const Value: String);
procedure SetSpend(const Value: Currency);
procedure SetDate(const Value: TDateTime);
public
property Name : String read FName write SetName;
property Spend : Currency read FSpend write SetSpend;
property Date : TDateTime read FDate write SetDate;
procedure SaveInDatabase;
end;
implementation
{ TSpend }
//*************************************
// METHODS
//*************************************
procedure TSpend.SaveInDatabase;
var
MyFile : TextFile;
FileName : String;
begin
FileName := 'Gasto.txt';
AssignFile(myFile, FileName);
if not FileExists(FileName) then
begin
ReWrite(myFile);
WriteLn(myFile, 'Nome,Valor,Data');
end;
Append(myFile);
WriteLn(myFile, Name + ',"' + CurrToStr(Spend) + '","' + DateTimeToStr(Date)+'"');
CloseFile(myFile);
end;
//*************************************
// GETTERS AND SETTERS
//*************************************
procedure TSpend.SetDate(const Value: TDateTime);
begin
FDate := Value;
end;
procedure TSpend.SetName(const Value: String);
begin
FName := Value;
end;
procedure TSpend.SetSpend(const Value: Currency);
begin
FSpend := Value;
end;
end.
|
unit UCondicaoPagamento;
interface
uses UGenerico, UFormaPagamento, UParcelas;
type CondicaoPagamento = class(Generico)
protected
umaFormaPagamento: FormaPagamento;
ListaParcela: array of Parcelas;
public
p : Integer;
Constructor CrieObjeto;
Destructor Destrua_Se;
procedure setUmaFormaPagamento (vUmaFormaPagamento : FormaPagamento);
function getUmaFormaPagamento : FormaPagamento;
procedure addParcela;
procedure removeParcela;
function getParcela: Parcelas; overload;
function getParcela(parc:Integer):Parcelas; overload;
end;
implementation
{ CondicaoPagamento }
procedure CondicaoPagamento.addParcela;
begin
inc(p);
setLength(ListaParcela,p);
ListaParcela[p-1] := Parcelas.CrieObjeto;
end;
constructor CondicaoPagamento.CrieObjeto;
begin
inherited;
umaFormaPagamento := FormaPagamento.CrieObjeto;
end;
destructor CondicaoPagamento.Destrua_Se;
begin
end;
function CondicaoPagamento.getParcela: Parcelas;
begin
result := ListaParcela[p-1];
end;
function CondicaoPagamento.getParcela(parc: Integer): Parcelas;
begin
result := ListaParcela[parc];
end;
function CondicaoPagamento.getUmaFormaPagamento: FormaPagamento;
begin
Result := umaFormaPagamento;
end;
procedure CondicaoPagamento.removeParcela;
begin
dec(p);
setLength(ListaParcela,p);
end;
procedure CondicaoPagamento.setUmaFormaPagamento(
vUmaFormaPagamento: FormaPagamento);
begin
umaFormaPagamento := vUmaFormaPagamento;
end;
end.
|
unit ComponentsExQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.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, ApplyQueryFrame, NotifyEvents,
ComponentsQuery, System.Generics.Collections, DSWrap;
type
TComponentsExW = class(TComponentsW)
private
FAnalog: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure RefreshQuery; override;
property Analog: TFieldWrap read FAnalog;
end;
TQueryComponentsEx = class(TQueryComponents)
private
FOnLocate: TNotifyEventsEx;
FOn_ApplyUpdate: TNotifyEventsEx;
function GetWEx: TComponentsExW;
{ 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 ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LocateInStorehouse;
property WEx: TComponentsExW read GetWEx;
property OnLocate: TNotifyEventsEx read FOnLocate;
property On_ApplyUpdate: TNotifyEventsEx read FOn_ApplyUpdate;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses DBRecordHolder;
constructor TQueryComponentsEx.Create(AOwner: TComponent);
begin
inherited;
FOn_ApplyUpdate := TNotifyEventsEx.Create(Self);
FOnLocate := TNotifyEventsEx.Create(Self);
FRecordHolder := TRecordHolder.Create();
end;
destructor TQueryComponentsEx.Destroy;
begin
inherited;
FreeAndNil(FOn_ApplyUpdate);
FreeAndNil(FOnLocate);
FreeAndNil(FRecordHolder);
end;
procedure TQueryComponentsEx.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
// ничего не делаем при удаении
end;
procedure TQueryComponentsEx.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
// Ничего не делаем при добавлении
end;
procedure TQueryComponentsEx.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
// Оповещаем что надо обработать обновление
On_ApplyUpdate.CallEventHandlers(Self);
end;
function TQueryComponentsEx.CreateDSWrap: TDSWrap;
begin
Result := TComponentsExW.Create(FDQuery);
end;
function TQueryComponentsEx.GetWEx: TComponentsExW;
begin
Result := W as TComponentsExW;
end;
procedure TQueryComponentsEx.LocateInStorehouse;
Var
l: TList<String>;
begin
Assert(FOnLocate <> nil);
Assert(FDQuery.RecordCount > 0);
l := TList<String>.Create();
try
l.Add(W.Value.F.AsString);
// Извещаем всех что нужно осуществить поиск этого компонента на складах
FOnLocate.CallEventHandlers(l);
finally
FreeAndNil(l);
end;
end;
constructor TComponentsExW.Create(AOwner: TComponent);
begin
inherited;
FAnalog := TFieldWrap.Create(Self, 'Analog');
end;
procedure TComponentsExW.RefreshQuery;
begin
// При каждом обновлении в запрос добавляются разные дополнительные поля.
// Поэтому обычный Refresh не подходит
DataSet.DisableControls;
try
if DataSet.Active then
DataSet.Close;
DataSet.Open;
NeedRefresh := False;
finally
DataSet.EnableControls;
end;
end;
end.
|
{9. .Scrieti subprograme care rezolva urmatoarele cerinte:
a. Determina cel mai mare divizor comun a 2 numere naturale
b. Determina cel mai mare divizor al unui numar natural, divizor mai mic decat numarul parametru
c. Determina suma divizorilor proprii unui numar dat.
Folosind subprogramele de mai sus si altele daca sunt necesare, rezolvati urmatoarele probleme:
1. Pentru numerele unui vector afisati cel mai mare divizor comun al tuturor perechilor de valori.
2. Calculati si afisati cel mai mare divizor comun al tuturor numerelor din vector.
3. Afisati numerele prime din vector.
4. Afisati perechile de numere vecine din vector care sunt prime intre ele.
5. Afisati numerele din vector care sunt formate din produsul a doua numere prime.
6. Afisati perechile de numere din vector care au aceeasi suma a divizorilor.
7. Afisati numerele perfecte din vector (un numar este perfect daca este egal cu suma divizorilor sai mai mici decat el).}
program problema9;
type sir=array[1..200] of longint;
function cmmdc(a,b:longint):longint;
var r:longint;
begin
while b<>0 do begin
r:=a mod b;
a:=b;
b:=r;
end;
cmmdc:=a;
end;
function maxDivNr(a:longint):longint;
var max,d:longint;
begin
max:=1;
for d:=2 to a div 2 do
if a mod d=0 then max:=d;
end;
function sumaDivProprii(a:longint):longint;
var sum,d:longint
begin
sum:=0;
for d:=2 to a div 2 do
if a mod d=0 then sum:=sum+d;
end;
function cmmdSir(a:sir;n:byte):longint;
var d,divSir,min:longint;
i,n:byte;
ok:boolean;
begin
min:=10000;
for i:=1 to n do
if a[i]<min then min:=a[i];
for d:=1 to min do begin
i:=1;
ok:=true;
while (i<=n) and (ok=true) do begin
if a[i] mod d<>o then ok:=false
else divSir:=d;
i:=i+1;
end;
if ok=true then cmmdSir:=divSir;
end;
end;
procedure citire(var a:sir;var n:byte);
var i:byte;
begin
read(n);
for i:=1 to n do
read(a[i]);
end;
procedure afisare(a:sir; n:byte);
var i,j:byte;
begin
for i:=1 to n do
write(a[i],',',' ');
end;
var a:array[1..200] of longint;
n,i:byte;
begin{programul principal}
citire(a,n);
afisare(a,n);
writeln('cel mai mare divizor al tuturor elementelor din sir este',' ',cmmdSir(a,n));
writeln('numerele prime din sir sunt:',' ');
for i:=1 to n do
if sumaDivProprii(a[i])=0 then write(a[i],' ',',');
writeln('perechile de numere prime intre ele din sir sunt:',' ');
for i:= 1 to n-1 do
if cmmdc(a[i],a[i+1])=1 then write('(',a[i],',',' ',a[i+1],')');
writeln('numerele care sunt formate din produsul a 2 nr prime sunt:',' ');
for i:=1 to n do
if (sumaDivProprii(a[i])=maxDivNr(a[i])+a[i] div maxDivNr(a[i])) and (maxDivNr(a[i])=1) and (maxDivNr(a[i] div maxDivNr(a[i]))=1) then
write(a[i],',',' ');
writeln('perechile de numere care au acelasi nr de divizori sunt',' ');
for i:=1 to n do
for j:=i to n do
if sumaDivProprii(a[i])=sumaDivProprii(a[j]) then write('(',a[i],',',' ',a[j],')');
writeln('numerele perfecte din sir sunt:',' ');
for i:=1 to n do
if sumaDivProprii(a[i])+1=a[i] then write(a[i],',',' ');
end.
|
unit AnovoClientePerdidoVendedor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Localizacao, StdCtrls, Buttons,
Mask, numericos, UnDados, Constantes, DBKeyViolation;
type
TFNovoClientePerdidoVendedor = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BOK: TBitBtn;
BCancelar: TBitBtn;
Localiza: TConsultaPadrao;
Label11: TLabel;
SpeedButton4: TSpeedButton;
LNomVendedor: TLabel;
EVendedor: TEditLocaliza;
EQtdDias: Tnumerico;
Label1: TLabel;
ValidaGravacao1: TValidaGravacao;
Label2: TLabel;
EQtdDiasComPedido: Tnumerico;
ERegiaoVendas: TRBEditLocaliza;
SpeedButton1: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
CCliente: TCheckBox;
CProspect: TCheckBox;
Label5: TLabel;
EQtdDiasSemTelemarketing: Tnumerico;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure EQtdDiasChange(Sender: TObject);
procedure BOKClick(Sender: TObject);
private
{ Private declarations }
VprDClientesPerdidos : TRBDClientePerdidoVendedor;
VprAcao : Boolean;
VprOperacaoCadastro : TRBDOperacaoCadastro;
procedure InicializaTela;
procedure CarDClasse;
public
{ Public declarations }
Function NovoClientePerdidoVendedor : Boolean;
end;
var
FNovoClientePerdidoVendedor: TFNovoClientePerdidoVendedor;
implementation
uses APrincipal, funObjeto, ConstMsg, UnClientes;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovoClientePerdidoVendedor.FormCreate(Sender: TObject);
begin
VprAcao := false;
VprDClientesPerdidos := TRBDClientePerdidoVendedor.cria;
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovoClientePerdidoVendedor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
VprDClientesPerdidos.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFNovoClientePerdidoVendedor.InicializaTela;
begin
VprDClientesPerdidos.free;
VprDClientesPerdidos := TRBDClientePerdidoVendedor.cria;
VprDClientesPerdidos.CodUsuario := varia.CodigoUsuario;
VprDClientesPerdidos.DatPerdido := now;
LimpaComponentes(PanelColor1,0);
EQtdDias.AsInteger := 90;
CCliente.Checked := true;
CProspect.Checked := true;
end;
{******************************************************************************}
procedure TFNovoClientePerdidoVendedor.CarDClasse;
begin
VprDClientesPerdidos.CodVendedorDestino := EVendedor.AInteiro;
VprDClientesPerdidos.QtdDiasSemPedido := EQtdDias.AsInteger;
VprDClientesPerdidos.QtdDiasComPedido := EQtdDiasComPedido.AsInteger;
VprDClientesPerdidos.QtdDiasSemTelemarketing := EQtdDiasSemTelemarketing.AsInteger;
VprDClientesPerdidos.CodRegiaoVendas := ERegiaoVendas.AInteiro;
VprDClientesPerdidos.QtdDiasSemTelemarketing := EQtdDiasSemTelemarketing.AsInteger;
VprDClientesPerdidos.IndCliente := CCliente.Checked;
VprDClientesPerdidos.IndProspect := CProspect.Checked;
end;
{******************************************************************************}
Function TFNovoClientePerdidoVendedor.NovoClientePerdidoVendedor : Boolean;
begin
InicializaTela;
VprOperacaoCadastro := ocInsercao;
showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFNovoClientePerdidoVendedor.BCancelarClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFNovoClientePerdidoVendedor.EQtdDiasChange(Sender: TObject);
begin
if (VprOperacaoCadastro in [ocInsercao,ocEdicao]) then
ValidaGravacao1.execute;
end;
procedure TFNovoClientePerdidoVendedor.BOKClick(Sender: TObject);
var
VpfResultado : String;
begin
CarDClasse;
VpfResultado := FunClientes.GravaDClientePerdido(VprDClientesPerdidos);
if VpfResultado = '' then
begin
VprAcao := true;
close;
end
else
aviso(VpfREsultado);
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovoClientePerdidoVendedor]);
end.
|
unit Ths.Erp.PersistentObject;
interface
uses
Rtti, StrUtils, Variants, Classes, FireDAC.Comp.Client,
FireDAC.VCLUI.Wait, FireDAC.DApt, SysUtils,
Ths.Erp.Database;
type
TPersintentObject = class
private
FSQL: WideString;
function GetValue(const ARTP: TRttiProperty; const AFK: Boolean): String;
procedure SetValue(P: TRttiProperty; S: Variant);
public
property CustomSQL: WideString read FSQL write FSQL;
function Insert: Boolean;
function Update: Boolean;
function Delete: Boolean;
procedure Load(const AValue: Integer); overload; virtual; abstract;
function Load: Boolean; overload;
end;
implementation
uses
Ths.Erp.Database.Table.Attribute;
{ TPersintentObject }
function TPersintentObject.Delete: Boolean;
begin
Result := False;
end;
function TPersintentObject.GetValue(const ARTP: TRttiProperty;
const AFK: Boolean): String;
begin
case ARTP.PropertyType.TypeKind of
tkUnknown, tkInteger,
tkInt64: Result := ARTP.GetValue(Self).ToString;
tkEnumeration: Result := IntToStr(Integer(ARTP.GetValue(Self).AsBoolean));
tkChar, tkString,
tkWChar, tkLString,
tkWString, tkUString: Result := QuotedStr(ARTP.GetValue(Self).ToString);
tkFloat: Result := StringReplace(FormatFloat('0.00',ARTP.GetValue(Self).AsCurrency)
,FormatSettings.DecimalSeparator,'.',[rfReplaceAll,rfIgnoreCase]);
end;
if (AFK) and (Result = '0') then
Result := 'null';
end;
function TPersintentObject.Insert: Boolean;
var
Ctx: TRttiContext;
RTT: TRttiType;
RTP: TRttiProperty;
Att: TCustomAttribute;
SQL,
Field,
Value,
FieldID,
NomeTabela,Error: String;
Qry: TFDQuery;
begin
Field := '';
Value := '';
// TDatabase.GetInstance.BeginTrans;
Ctx := TRttiContext.Create;
try
try
RTT := CTX.GetType(ClassType);
for Att in RTT.GetAttributes do
begin
if Att is AttTableName then
begin
SQL := 'INSERT INTO ' + AttTableName(ATT).Name;
NomeTabela := AttTableName(ATT).Name;
end;
end;
for RTP in RTT.GetProperties do
begin
for Att in RTP.GetAttributes do
begin
if Att is AttFieldName then
begin
if not (AttFieldName(ATT).AutoInc) then {Auto incremento não pode entrar no insert}
begin
Field := Field + AttFieldName(ATT).Name + ',';
Value := Value + GetValue(RTP, AttFieldName(ATT).FK) + ',';
end
else
FieldID := AttFieldName(ATT).Name;
end;
end;
end;
Field := Copy(Field,1,Length(Field)-1);
Value := Copy(Value,1,Length(Value)-1);
SQL := SQL + ' (' + Field + ') VALUES (' + Value + ')';
if Trim(CustomSQL) <> '' then
SQL := CustomSQL;
// Result := TConnection.GetInstance.Execute(SQL,Error);
SQL := 'SELECT ' + FieldID + ' FROM ' + NomeTabela + ' ORDER BY ' + FieldID + ' DESC';
// Qry := TConnection.GetInstance.ExecuteQuery(SQL);
for RTP in RTT.GetProperties do
begin
for Att in RTP.GetAttributes do
begin
if (Att is AttFieldName) and (AttFieldName(ATT).AutoInc) then
begin
RTP.SetValue(Self,TValue.FromVariant(qry.Fields[0].AsInteger));
end;
end;
end;
finally
CustomSQL := '';
// TConnection.GetInstance.Commit;
CTX.Free;
end;
except
// TConnection.GetInstance.Rollback;
raise;
end;
end;
function TPersintentObject.Load: Boolean;
var
Ctx: TRttiContext;
RTT: TRttiType;
RTP: TRttiProperty;
Att: TCustomAttribute;
SQL,
Where: String;
Reader: TFDQuery;
begin
Result := True;
Ctx := TRttiContext.Create;
try
RTT := CTX.GetType(ClassType);
for Att in RTT.GetAttributes do
begin
if Att is AttTableName then
SQL := 'SELECT * FROM ' + AttTableName(ATT).Name;
end;
for RTP in RTT.GetProperties do
begin
for Att in RTP.GetAttributes do
begin
if Att is AttFieldName then
begin
if (AttFieldName(ATT).PK) then
Where := Where + Ifthen(Trim(where)='','',' AND ') + AttFieldName(ATT).Name + ' = ' + GetValue(RTP, AttFieldName(ATT).FK);
end;
end;
end;
SQL := SQL + ' WHERE ' + Where;
if Trim(CustomSQL) <> '' then
SQL := CustomSQL;
// Reader := TConnection.GetInstance.ExecuteQuery(SQL);
if (Assigned(Reader)) and (Reader.RecordCount > 0) then
begin
with Reader do
begin
First;
while not EOF do
begin
for RTP in RTT.GetProperties do
begin
for Att in RTP.GetAttributes do
begin
if Att is AttFieldName then
begin
if Assigned(FindField(AttFieldName(ATT).Name)) then
SetValue(RTP, FieldByName(AttFieldName(ATT).Name).Value);
end;
end;
end;
Next;
end;
end;
end
else
Result := False;
finally
CustomSQL := '';
CTX.Free;
end;
end;
procedure TPersintentObject.SetValue(P: TRttiProperty; S: Variant);
var
V: TValue;
w: Word;
begin
w := VarType(S);
case w of
271: v := StrToFloat(S); {smallmoney}
272: v := StrToDateTime(S); {smalldatetime}
3: v := StrToInt(S);
else
begin
P.SetValue(Self,TValue.FromVariant(S));
exit;
end;
end;
p.SetValue(Self,v);
end;
function TPersintentObject.Update: Boolean;
var
Ctx: TRttiContext;
RTT: TRttiType;
RTP: TRttiProperty;
Att: TCustomAttribute;
SQL,
Field,
Where,
Error: String;
begin
Field := '';
Ctx := TRttiContext.Create;
try
RTT := CTX.GetType(ClassType);
for Att in RTT.GetAttributes do
begin
if Att is AttTableName then
SQL := 'UPDATE ' + AttTableName(ATT).Name + ' SET';
end;
for RTP in RTT.GetProperties do
begin
for Att in RTP.GetAttributes do
begin
if Att is AttFieldName then
begin
if (not (AttFieldName(ATT).AutoInc)) and (not (AttFieldName(ATT).PK)) then {Auto incremento não pode entrar no update}
begin
Field := Field + AttFieldName(ATT).Name + ' = ' + GetValue(RTP, AttFieldName(ATT).FK) + ',';
end
else if (AttFieldName(ATT).PK) then
Where := Where + Ifthen(Trim(where)='','',' AND ') + AttFieldName(ATT).Name + ' = ' + GetValue(RTP, AttFieldName(ATT).FK);
end;
end;
end;
Field := Copy(Field,1,Length(Field)-1);
SQL := SQL + ' ' + Field + ' WHERE ' + Where;
if Trim(CustomSQL) <> '' then
SQL := CustomSQL;
// Result := TConnection.GetInstance.Execute(SQL,Error);
if not Result then
raise Exception.Create(Error);
finally
CustomSQL := '';
CTX.Free;
end;
end;
end.
|
unit SourceCode;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, ComCtrls, ExtCtrls, Grids, RichEdit, ShellAPI,
Buttons, ToolWin, ImgList, ActnMan, ActnCtrls, ActnMenus, Gauges, ActnList,
SyntacticAnalysis, SemanticAnalysis, GenerateObjectCode;
type
TformMain = class(TForm)
mainMenu: TMainMenu;
File1: TMenuItem;
Edit1: TMenuItem;
Help1: TMenuItem;
New1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
Copy1: TMenuItem;
Cut1: TMenuItem;
Paste1: TMenuItem;
N2: TMenuItem;
Delete1: TMenuItem;
About1: TMenuItem;
Execute1: TMenuItem;
Compile1: TMenuItem;
warningPanel: TRichEdit;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
lineNumber: TRichEdit;
Highlight1: TMenuItem;
N3: TMenuItem;
sourceEdit: TRichEdit;
dlgColor: TColorDialog;
ToolBar: TToolBar;
popupMenu: TPopupMenu;
Cut2: TMenuItem;
Copy2: TMenuItem;
Paste2: TMenuItem;
N4: TMenuItem;
Delete2: TMenuItem;
imageListToolBar: TImageList;
btnNew: TToolButton;
btnOpen: TToolButton;
btnSave: TToolButton;
btnSep1: TToolButton;
btnCut: TToolButton;
btnCopy: TToolButton;
btnPaste: TToolButton;
btnSep2: TToolButton;
btnTools: TToolButton;
btnLock: TToolButton;
btnRun: TToolButton;
btnSep3: TToolButton;
imageListMainMenu: TImageList;
pageCtrl: TPageControl;
tabErrorPage: TTabSheet;
sgCodeList: TStringGrid;
tblTetrads: TStringGrid;
SplitterOfPages: TSplitter;
SplitterOfTetrTable: TSplitter;
btnDebug: TSpeedButton;
btnSep4: TToolButton;
btnSep5: TToolButton;
btnGenASM: TSpeedButton;
dlgFont: TFontDialog;
Font1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure Compile1Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure SaveAs1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
procedure Delete1Click(Sender: TObject);
procedure New1Click(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnCutClick(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
procedure btnPasteClick(Sender: TObject);
procedure btnRunClick(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure btnLockClick(Sender: TObject);
procedure Highlight1Click(Sender: TObject);
procedure btnNewClick(Sender: TObject);
procedure Cut2Click(Sender: TObject);
procedure Copy2Click(Sender: TObject);
procedure Paste2Click(Sender: TObject);
procedure Delete2Click(Sender: TObject);
procedure btnDebugClick(Sender: TObject);
procedure btnGenASMClick(Sender: TObject);
procedure Font1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
highlightcolor: TColor;
HighLightList: TStringlist;
OldRichEditWndProc: {integer} pointer;
PRichEditWndProc: pointer;
end;
var
formMain: TformMain;
fname: string = '';
LN: set of char = ['A'..'Z', 'a'..'z', 'А'..'п', 'р'..'я', #95];
srcFile: TextFile;
ReservedWordsArr: array[1..100] of string;
isSuc: boolean;
procedure PrintTetrads;
procedure PrintPointListArr;
procedure LexAnal;
function HighLight: boolean;
implementation
uses SourceCodeAbout;
{$R *.dfm}
procedure PrintTetrads;
var
i: integer;
begin
with formMain do begin
tblTetrads.RowCount := TetN;
for i := 1 to TetN-1 do begin
tblTetrads.Cells[1, i] := Tetr[i].KO;
if (Tetr[i].Op1 <> -1) then begin
if (Tetr[i].flag) then
tblTetrads.Cells[2, i] := SymbolsArr[Tetr[i].Op1].Symb
else
tblTetrads.Cells[2, i] := '#' + IntToStr(Tetr[i].Op1);
end;
tblTetrads.Cells[3, i] := SymbolsArr[Tetr[i].Op2].Symb;
tblTetrads.Cells[4, i] := SymbolsArr[Tetr[i].Result].Symb;
tblTetrads.Cells[5, i] := Tetr[i].Etiket;
tblTetrads.Cells[0, i] := IntToStr(i);
end;
end
end;
procedure PrintPointListArr;
var
i, j: integer;
begin
with formMain.sgCodeList do begin
for j := 0 to indexList-1 do begin
i := PointListArr[j];
Cells[0, j+1] := SymbolsArr[i].Symb;
Cells[1, j+1] := IntToStr(SymbolsArr[i].Code);
if (SymbolsArr[i].Code = 222) or (SymbolsArr[i].Code = 111) then
Cells[2, j+1] := FloatToStr(SymbolsArr[i].Value);
RowCount := RowCount + 1;
end;
RowCount := indexList + 1;
end;
end;
function HighLight:boolean;
var
UText, WordName: string;
FoundAt, WordLength: integer;
i, Line: integer;
hdc: integer;
CharPosion: integer;
FirstVisibleLine, LastVisibleLine: integer;
FirstCharPosofLine: integer;
h: hwnd;
visrect: Trect;
vispoint: TPoint;
index: integer;
begin
{Get the handle of the device context}
h := formMain.sourceEdit.Handle;
hdc := getdc(h);
result := SendMessage (h, EM_GETRECT, 0, integer(@visrect)) = 0;
if (result) then begin
VisPoint.x := VisRect.right;
VisPoint.y := VisRect.bottom;
CharPosion := SendMessage (h, EM_CHARFROMPOS, 0, integer(@VisPoint));
LASTVISIBLELINE := SendMessage (h, EM_LINEFROMCHAR, CharPosion, 0);
FIRSTVISIBLELINE := SendMessage (h, EM_GETFIRSTVISIBLELINE, 0, 0);
SetBkMode (hDC, TRANSPARENT);
SelectObject(hdc, formMain.sourceEdit.font.Handle);
for Line := FIRSTVISIBLELINE to LASTVISIBLELINE do begin
UText := ' ' + formMain.sourceEdit.Lines[Line];
FirstCharPosofLine := SendMessage(formMain.sourceEdit.Handle, EM_LINEINDEX, Line, 0);
i := 0;
while (i <= LENgth(UText)) do begin
FoundAt := i - 1;
{Any character except these will count as a word delimiter}
while (utext[i] in ['#','$','A'..'Z','a'..'z','0'..'9','{', '}','|',#60..#62,#42,#43,'!']) do
Inc(i);
WordLength := i - FoundAt - 1;
WordName := copy(UText, i - WordLength, WordLength);
if (formMain.HighLightList.find(uppercase(WordName), index)) then begin
SendMessage (formMain.sourceEdit.Handle, EM_POSFROMCHAR, integer(@VisPoint), FirstCharPosofLine + FoundAt-1);
SetTextColor(hdc, formMain.highlightcolor);
TextOut(hdc, VisPoint.x, VisPoint.y, pchar(WordName), WordLength);
end;
Inc(i);
end;
end;
end;
ReleaseDC(formMain.sourceEdit.Handle, hDC);
end;
Function RichEditWndProc(handla: HWnd; uMsg, wParam, lParam: longint): longint stdcall;
begin
Result := CallWindowProc(formMain.OldRichEditWndProc, handla, uMsg, wParam, lParam);
if (uMsg = WM_PAINT) then
HighLight;
End;
procedure TformMain.FormCreate(Sender: TObject);
var
ch: char;
buffer, codeInt: string;
numbLine, i: integer;
begin
pageCtrl.ActivePage := tabErrorPage;
HighLightlist := tStringlist.Create;
highlightcolor := RGB(255, 0, 95);
PRichEditWndProc := @RichEditWndProc;
formMain.sourceEdit.Perform(EM_EXLIMITTEXT, 0, 65535*32);
formMain.sourceEdit.Enabled := false;
formMain.sourceEdit.Color := cl3DLight;
OldRichEditWndProc := Pointer(SetWindowLong(sourceEdit.Handle, GWL_WNDPROC, longint(@RichEditWndProc)));
fname := '';
sgCodeList.Cells[0, 0] := 'SYMBOL';
sgCodeList.Cells[1, 0] := 'CODE';
sgCodeList.Cells[2, 0] := 'VALUE';
tblTetrads.Cells[0, 0] := '№';
tblTetrads.Cells[1, 0] := 'Command';
tblTetrads.Cells[2, 0] := 'Op1';
tblTetrads.Cells[3, 0] := 'Op2';
tblTetrads.Cells[4, 0] := 'Result';
tblTetrads.Cells[5, 0] := 'Label';
for numbLine := 1 to 70 do
lineNumber.Lines.Text := lineNumber.Lines.Text + IntToStr(numbLine);
codeInt := '';
indexList := 0;
AssignFile(srcFile, 'reserved.rcpas');
{$I-} Reset(srcFile); {$I+}
if (ioresult <> 0) then begin
ShowMessage('Грешка при отваряне на файла с ключовите думи!');
exit;
end
else begin
buffer := '';
Read(srcFile, ch);
while not eof (srcFile) do begin
if (ch in [#0..#32] = true) then begin
Read(srcFile, ch);
end
else if not(ch in ['0'..'9']) then begin
buffer := '';
while not(ch in ['0'..'9', #0..#32]) do begin
buffer := buffer + ch;
Read(srcFile, ch);
end;
end
else if (ch in ['0'..'9'] = true) then begin
codeInt := '';
while (ch in ['0'..'9'] = true) do begin
codeInt := codeInt + ch;
Read(srcFile, ch);
end;
HighLightList.Text := HighLightList.Text + buffer;
with HighLightList do
for i := 0 to count-1 do
strings[i] := trim(strings[i]);
HighLightList.sort;
FindTab(buffer, StrToInt(codeInt), 0);
end
else warningPanel.Text := 'Лексична грешка: ' +
ch + ' - [Виж Файла с ключовите думи]';
end;
CloseFile(srcFile);
end;
end;
procedure TformMain.Open1Click(Sender: TObject);
var
buffer: string;
begin
if (dlgOpen.Execute) then begin
fname := dlgOpen.FileName;
formMain.Caption := fname;
AssignFile(srcFile, fname);
{ Зареждане съдържанието на файла в редактора }
{$I-} Reset(srcFile); {$I+}
if ioresult <> 0 then begin
ShowMessage('Грешка при отваряне сорс файла!');
exit;
end
else begin
sourceEdit.Enabled := true;
sourceEdit.Color := RGB(28, 28, 28);
buffer := '';
sourceEdit.Text := '';
while not eof (srcFile) do begin
Readln(srcFile, buffer);
sourceEdit.Lines.Text := sourceEdit.Lines.Text + buffer;
end;
end;
CloseFile(srcFile);
end;
end;
procedure LexAnal;
var
indChar, P, symbCode: integer;
ch: char;
strBuffer: string;
flagDot: boolean;
begin
indChar := 0;
if (formMain.sourceEdit.Text <> '') then begin
while indChar <= Length(formMain.sourceEdit.Text) do begin
Inc(indChar);
ch := formMain.sourceEdit.Text[indChar];
if (ch in [#0..#32]) then
continue
else if (ch in LN) then begin
strBuffer := '';
while ((ch in LN) or (ch in ['0'..'9', '_'])) do begin
strBuffer := strBuffer + ch;
Inc(indChar);
ch := formMain.sourceEdit.Text[indChar];
end;
Dec(indChar);
symbCode := 111;
P := FindTab(strBuffer, symbCode, 0);
AddToList(P);
end
else if (ch in ['0'..'9']) then begin
flagDot := false;
strBuffer := '';
Inc(indChar);
if (formMain.sourceEdit.Text[indChar] in LN = true) then begin
formMain.warningPanel.Text := 'Имената на променливите не могат ' +
'да започват с число.';
isSuc := false;
exit;
end;
Dec(indChar);
while (ch in ['0'..'9', ',']) do begin
strBuffer := strBuffer + ch;
if (ch = '.') and (flagDot = true) then begin
formMain.warningPanel.Text := 'Лексична грешка: " ' +
strBuffer + ' "';
isSuc := false;
exit;
end;
if (ch = ',') then
flagDot := true;
Inc(indChar);
ch := formMain.sourceEdit.Text[indChar];
end;
Dec(indChar);
symbCode := 222;
P := FindTab(strBuffer, symbCode, StrToFloat(strBuffer));
AddToList(P);
end
else if (ch in [#33, #34, #36, #40..#47, #59..#62, #91, #93..#95, #123..#126]) then begin
strBuffer := ch;
if (ch in ['=', '!', '|', '$']) then begin
Inc(indChar);
ch := formMain.sourceEdit.Text[indChar];
if (strBuffer = '=') then begin
if (ch in ['=', '<', '>']) then
strBuffer := strBuffer + ch
else Dec(indChar);
end
else if (strBuffer = '!') then begin
if (ch = '=') then
strBuffer := strBuffer + ch
else Dec(indChar);
end
else if (strBuffer = '|') then begin
if (ch = '|') then
strBuffer := strBuffer + ch
else Dec(indChar);
end
else if (strBuffer = '$') then begin
if (ch = '$') then
strBuffer := strBuffer + ch
else Dec(indChar);
end
end;
P := FindTab(strBuffer, 0, 0);
AddToList(P);
end
else begin
formMain.warningPanel.Text := 'Лексична грешка: " ' + ch +' "';
isSuc := false;
end;
end;
end;
end;
procedure TformMain.Compile1Click(Sender: TObject);
var
firstElem: integer;
begin
if (sourceEdit.Text <> '') then
Save1Click(Sender);
warningPanel.Text := '';
if (fname <> '') then begin
isSuc := true;
firstElem := 0;
indexList := 0;
LexAnal();
if (isSuc) then begin
if (sourceEdit.Text <> '') then begin
if (SymbolsArr[PointListArr[firstElem]].Code = 33) then begin
warningPanel.Text := SyntAnal(SymbolsArr, PointListArr, indexList);
if (warningPanel.Text = '') then begin
SemAnal(SymbolsArr, PointListArr, indexList);
NovaTetrada('STOP', -1, -1, -1, true);
step := 1;
PrintPointListArr;
PrintTetrads;
tblTetrads.Row := 1;
btnGenASM.Enabled := true;
btnDebug.Enabled := true;
end;
end
else warningPanel.Text := 'Очаква се "void", но е намерен: ' +
SymbolsArr[PointListArr[firstElem]].Symb;
pageCtrl.ActivePage := tabErrorPage;
end
else begin
warningPanel.Text := '';
end;
end;
end;
end;
procedure TformMain.Save1Click(Sender: TObject);
begin
if (fname = '') then begin
SaveAs1Click(Sender);
end
else begin
Rewrite(srcFile);
write(srcFile, sourceEdit.Text);
CloseFile(srcFile);
end;
end;
procedure TformMain.SaveAs1Click(Sender: TObject);
begin
if (dlgSave.Execute) then begin
fname := dlgSave.FileName;
if (Pos('.cpas', fname) = 0) then
fname := fname + '.cpas';
formMain.Caption := fname;
AssignFile(srcFile, fname);
Rewrite(srcFile);
write(srcFile, sourceEdit.Text);
CloseFile(srcFile);
end;
end;
procedure TformMain.Copy1Click(Sender: TObject);
begin
if (sourceEdit.Focused) then
sourceEdit.CopyToClipboard
else if (warningPanel.Focused) then
warningPanel.CopyToClipboard;
end;
procedure TformMain.Cut1Click(Sender: TObject);
begin
sourceEdit.CutToClipboard;
end;
procedure TformMain.Paste1Click(Sender: TObject);
begin
sourceEdit.PasteFromClipboard;
end;
procedure TformMain.Delete1Click(Sender: TObject);
begin
sourceEdit.ClearSelection;
end;
procedure TformMain.New1Click(Sender: TObject);
begin
fname := '';
sourceEdit.Text := '';
warningPanel.Text := '';
sgCodeList.RowCount := 2;
sgCodeList.Cells[0, 1] := '';
sgCodeList.Cells[1, 1] := '';
sourceEdit.Enabled := true;
sourceEdit.Color := RGB(28, 28, 28);
end;
procedure TformMain.btnOpenClick(Sender: TObject);
begin
Open1Click(Sender);
end;
procedure TformMain.btnSaveClick(Sender: TObject);
begin
Save1Click(Sender);
end;
procedure TformMain.btnCutClick(Sender: TObject);
begin
Cut1Click(Sender);
end;
procedure TformMain.btnCopyClick(Sender: TObject);
begin
Copy1Click(Sender);
end;
procedure TformMain.btnPasteClick(Sender: TObject);
begin
Paste1Click(Sender);
end;
procedure TformMain.btnRunClick(Sender: TObject);
begin
Compile1Click(Sender);
Beep;
end;
procedure TformMain.Exit1Click(Sender: TObject);
begin
formMain.Close;
end;
procedure TformMain.btnLockClick(Sender: TObject);
begin
if (sourceEdit.ReadOnly) then begin
sourceEdit.ReadOnly := false;
btnLock.ImageIndex := 9;
btnLock.Hint := 'Lock...';
end
else begin
sourceEdit.ReadOnly := true;
btnLock.ImageIndex := 8;
btnLock.Hint := 'Unlock...';
end;
end;
procedure TformMain.Highlight1Click(Sender: TObject);
begin
if (dlgColor.Execute = true) then
highlightcolor := dlgColor.Color;
sourceEdit.Invalidate;
end;
procedure TformMain.btnNewClick(Sender: TObject);
begin
New1Click(Sender);
end;
procedure TformMain.Cut2Click(Sender: TObject);
begin
Cut1Click(Sender);
end;
procedure TformMain.Copy2Click(Sender: TObject);
begin
Copy1Click(Sender);
end;
procedure TformMain.Paste2Click(Sender: TObject);
begin
Paste1Click(Sender);
end;
procedure TformMain.Delete2Click(Sender: TObject);
begin
Delete1Click(Sender);
end;
procedure TformMain.btnDebugClick(Sender: TObject);
begin
if (step < tetN-1) then begin
tblTetrads.Row := GenObjCode;
PrintPointListArr;
end
else begin
Compile1Click(Sender);
ShowMessage('Край на изпълнението!');
end;
end;
procedure TformMain.btnGenASMClick(Sender: TObject);
begin
GenASMCode;
isCreatedASM := false;
ShowMessage('Асемблерският код е генериран!' + #10#13 +
'Файлът се намира в директорията на програмата с име: ' +
'GeneratedASM.asm');
end;
procedure TformMain.Font1Click(Sender: TObject);
begin
if (dlgFont.Execute) then
sourceEdit.Font := dlgFont.Font;
end;
procedure TformMain.About1Click(Sender: TObject);
begin
formAbout.Show;
end;
end.
|
unit TestCharLiterals;
{ AFS 30 Jan 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
This unit tests chars and strings }
interface
implementation
uses Dialogs;
procedure Chars;
const
Fred = #80;
LineBreak = #13#10;
SomeChars = #78#79#80;
HEXCHARS = #$12#$2E#60;
DQS_0 = '';
DQS_1 = '''';
DQS_2 = '''''';
DQS_3 = '''''''';
DQS_4 = '''''''''';
var
ls:string;
ls2: string;
begin
ls:=#90+LineBreak+#90#91+SomeChars+#90;
ls2:= #$F#$A;
ls2 := ls + #$1F + HEXCHARS;
end;
procedure Stringchars;
const
Boo = 'Boo';
HELLO = 'Hello'#13;
OLLA = #10'Olla!';
var
ls: string;
begin
ls := 'Fred';
ls := #13;
ls := #12'Fred'#32'Fred'#22;
end;
{ hat char literals.
Undocumented, but works.
Described as "Old-style" - perhaps a Turbo-pascal holdover
Pointed out by Dimentiy }
const
str1 = ^M;
HAT_FOO = ^A;
HAT_BAR = ^b;
HAT_FISH = ^F;
HAT_WIBBLE = ^q;
HAT_SPON = ^Z;
HAT_AT = ^@;
HAT_FROWN = ^[;
HAT_HMM = ^\;
HAT_SMILE = ^];
HAT_HAT = ^^;
HAT_UNDER = ^_;
HAT_EQ_NOSPACE=^=;
HAT_EQ_SPACEAFT=^= ;
HAT_EQ_LONG=^=^=#0^='foo'^=;
var
hat1: char = ^h;
hat2: char = ^j;
hat3: char = ^m;
procedure HatBaby;
var
str: string;
ch: char;
begin
str := HAT_FOO + ^M;
ch := ^N;
str := HAT_FOO + ^@ + ^] + ^^ + ^- + ^\ + ^[;
end;
procedure TestHatCharliteralsInStrings;
var
Str1: string;
begin
Str1 := 'prefix'^M + 'substr2';
Str1 := 'prefix'^M'foo' + 'substr2';
Str1 := 'prefix'^M'foo'#23 + 'substr2'#56;
Str1 := 'prefix'^M'foo'^M'bar'^N + 'substr2'^O;
Str1 := 'prefix'#13^M#12^@'foo'#10^M'bar';
{ these are harder, as the '^' char has other uses }
Str1 := ^M;
Str1 := ^M + 'substr2';
Str1 := ^M'foo' + 'substr2';
Str1 := ^M^N^@'foo' + 'substr2';
Str1 := ^M'foo'#23 + 'substr2'#56;
Str1 := ^M'foo'^M'bar'^N + 'substr2'^O;
Str1 := #13^M#12^@'foo'#10^M'bar';
end;
procedure HatEquals(const Value: pchar);
const
{ ambiguous.
same chars lexed differently in if-statement
Impossble to lex cleanly }
HAT_EQ = ^=;
HAT_EQ_C = ^='C';
HAT_EQ_NIL = ^=#0;
HAT_EQ_C_NIL = ^='C'^=#0^='C'^=#0;
var
st: string;
begin
if value^='C' then
ShowMessage('See')
else if (Value^=#0) then
ShowMessage('nil')
else if (Value^=^=) then
ShowMessage('terrence, this is stupid stuff');
{ space }
if value ^='C' then
{ brackets }
else if ((Value^)=#0) then
ShowMessage('nil')
{ new line }
else if (Value
^=^=) then
ShowMessage('terrence, this is stupid stuff');
st := value^+value^;
if (Value^=^=^=) then
ShowMessage('meep');
if (Value^=^+^-^^^_) then
ShowMessage('meep');
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit AzureUI;
interface
uses System.Classes, Vcl.ComCtrls, Vcl.Controls, DSAzure, Vcl.Graphics, Vcl.ValEdit, Xml.XMLIntf;
type
///<summary>
/// Base class for Azure management components which provides common functionality.
///</summary>
TAzureManagement = class abstract(TCustomTreeView)
protected
FConnectionInfo: TAzureConnectionString;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
/// <summary> Azure connection information </summary>
property ConnectionInfo: TAzureConnectionString read FConnectionInfo write FConnectionInfo;
end;
///<summary>
/// Tree node which Frees the data held by it when it is destroyed.
///</summary>
TAzureTreeNode = class(TTreeNode)
public
destructor Destroy; override;
end;
///<summary> Returns the bitmap for the given image key </summary>
function GetAzureImage(Key: String): TBitmap;
///<summary> Returns the first child node of the given parent with the specified node name. </summary>
function GetFirstMatchingChildNode(Parent: IXMLNode; ChildName: String): IXMLNode;
///<summary> Helper function for confirming the deletion of one or more items. </summary>
function ConfirmDeleteItem(Plural: Boolean = False): Boolean;
///<summary> Selects either the bottom left or bottom right cell of the given table </summary>
procedure SelectBottomCell(Table: TValueListEditor; LeftCell: Boolean);
///<summary> Selects either the top left or top right cell of the given table </summary>
procedure SelectTopCell(Table: TValueListEditor; LeftCell: Boolean);
///<summary> Show an error message dialog with the given message. </summary>
procedure ShowErrorMessage(const Msg: String);
///<summary> Show an information message dialog with the given message. </summary>
procedure ShowInformationMessage(const Msg: String);
implementation
uses Data.DBXClientResStrs, Vcl.Dialogs, System.SysUtils, System.UITypes;
{$R dsazurereg.res}
function ConfirmDeleteItem(Plural: Boolean): Boolean;
var
MessageStr: String;
begin
if Plural then
MessageStr := SDeleteConfirmPlural
else
MessageStr := SDeleteConfirm;
Result := MessageDlg(MessageStr, mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
function GetAzureImage(Key: String): TBitmap;
begin
Result := TBitmap.Create;
Result.LoadFromResourceName(HInstance, Key);
end;
function GetFirstMatchingChildNode(Parent: IXMLNode; ChildName: String): IXMLNode;
var
Child: IXMLNode;
begin
Result := nil;
if (Parent <> nil) and Parent.HasChildNodes and (ChildName <> EmptyStr) then
begin
Child := Parent.ChildNodes.First;
while Child <> nil do
begin
if Child.NodeName = ChildName then
Exit(Child);
Child := Child.NextSibling;
end;
end;
end;
procedure SelectBottomCell(Table: TValueListEditor; LeftCell: Boolean);
var
RowIndex: Integer;
ColumnIndex: Integer;
begin
if (Table <> nil) and (Table.RowCount > 1) and (Table.ColCount > 0) and (Table.Strings.Count > 0) then
begin
if LeftCell then
ColumnIndex := 0
else
ColumnIndex := 1;
RowIndex := Table.RowCount - 1;
Table.Row := RowIndex;
Table.Col := ColumnIndex;
end;
end;
procedure SelectTopCell(Table: TValueListEditor; LeftCell: Boolean);
begin
if (Table <> nil) and (Table.RowCount > 1) and (Table.ColCount > 0) and (Table.Strings.Count > 0) then
begin
Table.Row := 1;
if LeftCell then
Table.Col := 0
else
Table.Col := 1;
end;
end;
procedure ShowErrorMessage(const Msg: String);
begin
TThread.Synchronize(nil, procedure
begin
MessageDlg(Msg, mtError, [mbOK], 0);
end );
end;
procedure ShowInformationMessage(const Msg: String);
begin
TThread.Synchronize(nil, procedure
begin
MessageDlg(Msg, mtInformation, [mbOK], 0);
end );
end;
{ TAzureTreeNode }
destructor TAzureTreeNode.Destroy;
begin
if Data <> nil then
begin
TObject(Pointer((IntPtr(Data) shr 1) shl 1)).Free;
Data := nil;
end;
inherited;
end;
{ TAzureManagement }
procedure TAzureManagement.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
if (AComponent = ConnectionInfo) then
ConnectionInfo := nil;
end;
end.
|
{
ID:asiapea1
PROG:sprime
LANG:PASCAL
}
var
n:byte;
function flag(i:longint):boolean;
var
j:longint;
begin
flag:=true;
if i=1 then begin
flag:=false;
exit;
end;
for j:=2 to trunc(sqrt(i)) do
if i mod j=0 then begin
flag:=false;
exit;
end;
end;
procedure sub(a,b:longint);
begin
if a=n then writeln(b)
else begin
if flag(b*10+1) then sub(a+1,b*10+1);
if flag(b*10+3) then sub(a+1,b*10+3);
if flag(b*10+7) then sub(a+1,b*10+7);
if flag(b*10+9) then sub(a+1,b*10+9);
end;
end;
begin
assign(input,'sprime.in'); reset(input);
assign(output,'sprime.out'); rewrite(output);
readln(n);
sub(1,2);
sub(1,3);
sub(1,5);
sub(1,7);
close(input); close(output);
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Mac.Sensors;
interface
uses
System.Sensors;
type
TPlatformSensorManager = class(TSensorManager)
protected
class function GetSensorManager: TSensorManager; override;
end;
TPlatformGeocoder = class(TGeocoder)
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
end;
TPlatformGpsStatus = class(TGpsStatus)
protected
class function GetGpsStatusImplementer: TGpsStatusClass; override;
end;
implementation
uses
Macapi.ObjectiveC,
Macapi.CocoaTypes,
Macapi.CoreLocation,
System.RTLConsts,
System.SysUtils,
System.Math,
Macapi.Foundation,
Macapi.Helpers;
function ConvCLLocationCoord(const Value: CLLocationCoordinate2D): TLocationCoord2D;
begin
Result := TLocationCoord2D.Create(Value.latitude, Value.longitude);
end;
function ConvCLLocation(const Value: CLLocation): TLocationCoord2D;
begin
if Assigned(Value) then
Result := ConvCLLocationCoord(Value.coordinate)
else
Result := TLocationCoord2D.Create(0, 0);
end;
function ConvLocationRegion(const Region: TLocationRegion): CLRegion;
var
Center: CLLocationCoordinate2D;
UniqueID: NSString;
begin
Center := CLLocationCoordinate2DMake(Region.Center.Latitude, Region.Center.Longitude);
{$IFDEF NEXTGEN}
{$ELSE NEXTGEN}
UniqueID := TNSString.Wrap(TNSString.OCClass.stringWithUTF8String(PAnsiChar(UTF8String(Region.ID))));
{$ENDIF NEXTGEN}
// create the region object and add it for monitorization
Result := TCLRegion.Wrap(TCLRegion.Create.initCircularRegionWithCenter(Center, Region.Radius , UniqueID));
end;
function ConvCLRegion(const Region: CLRegion): TLocationRegion;
begin
Result := TLocationRegion.Create(
ConvCLLocationCoord(Region.center),
Region.radius,
NSStrToStr(Region.identifier));
end;
type
TMacLocationSensor = class;
TMacLocationSensorNotifHandler = class(TOCLocal, CLLocationManagerDelegate)
private
FSensor: TMacLocationSensor;
public
{ CLLocationManagerDelegate }
procedure locationManager(manager: CLLocationManager; didChangeAuthorizationStatus: CLAuthorizationStatus); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didEnterRegion: CLRegion); overload; cdecl;
// procedure locationManager(manager: CLLocationManager; didExitRegion: CLRegion); cdecl; overload;
procedure locationManager(manager: CLLocationManager; didFailWithError: NSError); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateHeading: CLHeading); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateToLocation: CLLocation; fromLocation: CLLocation); overload; cdecl;
procedure locationManager(manager: CLLocationManager; monitoringDidFailForRegion: CLRegion; withError: NSError); overload; cdecl;
constructor Create(Sensor: TMacLocationSensor);
end;
TMacLocationSensor = class(TCustomLocationSensor)
private var
FLocater: CLLocationManager;
FDelegate: CLLocationManagerDelegate;
FLocation: CLLocation;
FSensorState: TSensorState;
protected
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetLocationSensorType: TLocationSensorType; override;
// the sensor doesn't support properties such as address, city, street name etc
// because they can be easily obtain using the Geocoder class
function GetAvailableProperties: TCustomLocationSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double; override;
function GetAuthorized: TAuthorizationType; override;
function GetAccuracy: TLocationAccuracy; override;
function GetDistance: TLocationDistance; override;
function GetPowerConsumption: TPowerConsumption; override;
procedure SetAccuracy(const Value: TLocationAccuracy); override;
procedure SetDistance(const Value: TLocationDistance); override;
procedure DoLocationChangeType; override;
procedure DoOptimize; override;
function DoStart: Boolean; override;
procedure DoStop; override;
procedure RegionAdded(const Item: TLocationRegion); override;
procedure RegionRemoved(const Item: TLocationRegion); override;
constructor Create(AManager: TSensorManager); override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
destructor Destroy; override;
end;
TMacSensorManager = class(TPlatformSensorManager)
private
FActive: Boolean;
protected
function GetCanActivate: Boolean; override;
function GetActive: Boolean; override;
public
procedure Activate; override;
procedure Deactivate; override;
end;
TMacGeocoder = class(TGeocoder)
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
class procedure GeocodeRequest(const Address: TCivicAddress); override;
class procedure GeocodeReverseRequest(const Coords: TLocationCoord2D); override;
public
class function Supported: Boolean; override;
class function Authorized: TAuthorizationType; override;
class procedure Cancel; override;
end;
TMacGpsStatus = class(TGpsStatus)
public
class function Supported: Boolean; override;
class function Authorized: TAuthorizationType; override;
class function Satellites(Index: Integer): TGpsSatellite; override;
class function SatelliteCount: Integer; override;
class function SatelliteFirstFixTime: Integer; override;
end;
{ TPlatformSensorManager }
class function TPlatformSensorManager.GetSensorManager: TSensorManager;
begin
Result := TMacSensorManager.Create;
end;
{ TMacSensorManager }
procedure TMacSensorManager.Activate;
begin
// For now add only the location sensor
if not Active then
begin
FActive := True;
// automatically adds itself to the internal list of the manager
TMacLocationSensor.Create(Self);
end;
end;
procedure TMacSensorManager.Deactivate;
var
i: Integer;
begin
FActive := False;
for i := Count - 1 downto 0 do
RemoveSensor(Sensors[i]);
end;
function TMacSensorManager.GetActive: Boolean;
begin
Result := FActive;
end;
function TMacSensorManager.GetCanActivate: Boolean;
begin
Result := True;
end;
{ TMacLocationSensor }
constructor TMacLocationSensor.Create(AManager: TSensorManager);
var
Handler: TMacLocationSensorNotifHandler;
begin
inherited;
// create and retain the delegate
Handler := TMacLocationSensorNotifHandler.Create(Self);
FDelegate := Handler;
// create the location manager and attach the delegate
FLocater := TCLLocationManager.Create;
FLocater.retain;
FLocater.setDelegate(Handler.GetObjectID);
FLocation := TCLLocation.Create;
end;
destructor TMacLocationSensor.Destroy;
begin
FLocater.setDelegate(nil);
FLocation.release;
FLocater.release;
FDelegate := nil;
inherited;
end;
function TMacLocationSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FLocater <> nil then
Result := FLocater.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FDelegate <> nil) then
Result := FDelegate.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FLocation <> nil) then
Result := FLocation.QueryInterface(IID, Obj);
end;
procedure TMacLocationSensor.DoLocationChangeType;
begin
// do nothing; location change type values influence the way notifications
// will be done the next time the sensor is started
end;
procedure TMacLocationSensor.DoOptimize;
begin
// do nothing; the location services on iOS are already optimized
// by selecting the appropriate sensor (GPS, Wifi, cell towers) to determine
// the best location
end;
function TMacLocationSensor.DoStart: Boolean;
begin
try
// check authorization
if Authorized = TAuthorizationType.atUnauthorized then
SensorError(SLocationServiceUnauthorized);
// check if location sensor is enabled
if not FLocater.locationServicesEnabled then
SensorError(SLocationServiceDisabled);
// start location updates
FLocater.startUpdatingLocation;
Result := FLocater.locationServicesEnabled;
except on Exception do
raise;
end;
end;
procedure TMacLocationSensor.DoStop;
begin
// stop the location update
FLocater.stopUpdatingLocation;
end;
function TMacLocationSensor.GetAccuracy: TLocationAccuracy;
begin
Result := FLocater.desiredAccuracy
end;
function TMacLocationSensor.GetAuthorized: TAuthorizationType;
begin
case TCLLocationManager.OCClass.authorizationStatus of
kCLAuthorizationStatusNotDetermined:
Result := TAuthorizationType.atNotSpecified;
kCLAuthorizationStatusDenied,
kCLAuthorizationStatusRestricted:
Result := TAuthorizationType.atUnauthorized;
kCLAuthorizationStatusAuthorized:
Result := TAuthorizationType.atAuthorized;
else // avoids compiler warnings
Result := TAuthorizationType.atNotSpecified;
end;
end;
function TMacLocationSensor.GetAvailableProperties: TCustomLocationSensor.TProperties;
begin
Result := [];
if (Authorized <> TAuthorizationType.atUnauthorized) and
FLocater.locationServicesEnabled then
Result := [TProperty.Latitude, TProperty.Longitude, TProperty.Altitude, TProperty.Speed];
end;
function TMacLocationSensor.GetDistance: TLocationDistance;
begin
Result := FLocater.distanceFilter;
end;
function TMacLocationSensor.GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double;
begin
Result := NaN;
case Prop of
TProperty.Latitude:
Result := FLocation.coordinate.latitude;
TProperty.Longitude:
Result := FLocation.coordinate.longitude;
TProperty.Speed:
Result := FLocation.speed;
TProperty.Altitude:
Result := FLocation.altitude;
TProperty.ErrorRadius:
Result := 0;
end;
end;
function TMacLocationSensor.GetLocationSensorType: TLocationSensorType;
begin
// based on internal mechanisms of selection between GPS, Wifi, cell towers;
// there is no way to query from which of these the location information comes
Result := TLocationSensorType.Other;
end;
function TMacLocationSensor.GetPowerConsumption: TPowerConsumption;
begin
Result := TPowerConsumption.pcNotSpecified;
end;
function TMacLocationSensor.GetState: TSensorState;
begin
Result := FSensorState;
end;
function TMacLocationSensor.GetTimeStamp: TDateTime;
begin
Result := 0;
end;
procedure TMacLocationSensor.RegionAdded(const Item: TLocationRegion);
begin
// no region support
end;
procedure TMacLocationSensor.RegionRemoved(const Item: TLocationRegion);
begin
// no region support
end;
procedure TMacLocationSensor.SetAccuracy(const Value: TLocationAccuracy);
begin
FLocater.setDesiredAccuracy(Value);
end;
procedure TMacLocationSensor.SetDistance(const Value: TLocationDistance);
begin
FLocater.setDistanceFilter(Value);
end;
{ TMacGpsStatus }
class function TMacGpsStatus.Authorized: TAuthorizationType;
begin
Result := TAuthorizationType.atUnauthorized;
end;
class function TMacGpsStatus.SatelliteCount: Integer;
begin
Result := 0;
end;
class function TMacGpsStatus.SatelliteFirstFixTime: Integer;
begin
Result := 0;
end;
class function TMacGpsStatus.Satellites(Index: Integer): TGpsSatellite;
begin
Result := TGpsSatellite.Create(0, 0, 0, 0, False, False, False);
end;
class function TMacGpsStatus.Supported: Boolean;
begin
Result := False;
end;
{ TMacGeocoder }
class function TMacGeocoder.Authorized: TAuthorizationType;
begin
Result := TAuthorizationType.atNotSpecified;
end;
class procedure TMacGeocoder.Cancel;
begin
// do nothing
end;
class function TMacGeocoder.Supported: Boolean;
begin
// MacOS cannot obtain geocode information
Result := False;
end;
class procedure TMacGeocoder.GeocodeRequest(const Address: TCivicAddress);
begin
// do nothing
end;
class procedure TMacGeocoder.GeocodeReverseRequest(const Coords: TLocationCoord2D);
begin
// do nothing
end;
class function TMacGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := Self;
end;
{ TMacLocationSensor.TNotifHandler }
constructor TMacLocationSensorNotifHandler.Create(Sensor: TMacLocationSensor);
begin
inherited Create;
FSensor := Sensor;
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager; didEnterRegion: CLRegion);
begin
// no region support
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager;
didChangeAuthorizationStatus: CLAuthorizationStatus);
begin
if (didChangeAuthorizationStatus <> kCLAuthorizationStatusAuthorized) and FSensor.Started then
begin
FSensor.FSensorState := TSensorState.AccessDenied;
FSensor.Stop;
end
else if didChangeAuthorizationStatus = kCLAuthorizationStatusAuthorized then
FSensor.Start; // Start the sensor if it has now become authorized.
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager; didFailWithError: NSError);
begin
case didFailWithError.code of
kCLErrorLocationUnknown: // can't get a location right now; wait for a new event
FSensor.FSensorState := TSensorState.Error;
kCLErrorDenied: // user denied usage of location services
begin
FSensor.FSensorState := TSensorState.AccessDenied;
FSensor.Stop;
end;
kCLErrorHeadingFailure: // strong interference from nearby magnetic fields
FSensor.FSensorState := TSensorState.Error;
end;
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager; monitoringDidFailForRegion: CLRegion;
withError: NSError);
begin
// no region support
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager; didUpdateHeading: CLHeading);
var
LHeading : THeading;
begin
if Assigned(FSensor) then
begin
LHeading.Azimuth := didUpdateHeading.trueHeading;
FSensor.DoHeadingChanged(LHeading);
end;
end;
procedure TMacLocationSensorNotifHandler.locationManager(
manager: CLLocationManager; didUpdateToLocation, fromLocation: CLLocation);
begin
FSensor.FSensorState := TSensorState.Ready;
// store the new location internally and trigger the event
FSensor.FLocation := didUpdateToLocation;
FSensor.FLocation.retain;
FSensor.DoLocationChanged(
ConvCLLocation(fromLocation),
ConvCLLocation(FSensor.FLocation));
FSensor.FSensorState := TSensorState.NoData;
end;
{ TPlatformGeocoder }
class function TPlatformGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := TMacGeocoder;
end;
{ TPlatformGpsStatus }
class function TPlatformGpsStatus.GetGpsStatusImplementer: TGpsStatusClass;
begin
Result := TMacGpsStatus;
end;
end.
|
////////////////////////////////////////////
// Кодировка и расчет CRC для приборов типа УБЗ-302 и ТР-101
////////////////////////////////////////////
unit Devices.UBZ;
interface
uses GMGlobals, Windows, Classes, StrUtils, Devices.ReqCreatorBase, GMConst, Devices.Modbus.ReqCreatorBase, Devices.ModbusBase;
type TTransformatorType = (ttUnknown, ttInternalOrSmall, ttExternalAndBig);
procedure UBZ_CRC(var buf: array of Byte; Len: int);
function UBZ_CheckCRC(buf: array of Byte; Len: int): bool;
function IntFromTR101Word(w: word): int;
type
TUBZReqCreator = class(TModbusRTUDevReqCreator)
protected
function PrepareCommand(var prmIds: TChannelIds; var Val: double): bool; override;
public
procedure AddRequests(); override;
end;
const
COUNT_UBZ_ALARMS = 3;
COUNT_UBZ_TRANSFORMATOR = 2;
COUNT_UBZ_I = 4;
COUNT_UBZ_U = 3;
COUNT_UBZ_A = 1;
COUNT_UBZ_P = 1;
COUNT_ALARM_LOG1 = 12;
COUNT_ALARM_LOG2 = 8;
implementation
uses
System.Math;
procedure UBZ_CRC(var buf: array of Byte; Len: int);
begin
Modbus_CRC(buf, Len);
end;
function UBZ_CheckCRC(buf: array of Byte; Len: int): bool;
begin
Result := Modbus_CheckCRC(buf, Len);
end;
function IntFromTR101Word(w: word): int;
begin
if w and $8000 > 0 then
Result := -($FFFF - w + 1)
else
Result := w;
end;
{ TUBZReqCreator }
procedure TUBZReqCreator.AddRequests();
begin
// тип трансформатора
AddModbusRequestToSendBuf(150, COUNT_UBZ_TRANSFORMATOR, rqtUBZ_TRANSFORMATOR);
// токи
AddModbusRequestToSendBuf(100, COUNT_UBZ_I, rqtUBZ_I);
// напряжения
AddModbusRequestToSendBuf(114, COUNT_UBZ_U, rqtUBZ_U);
// время наработки двигателя
AddModbusRequestToSendBuf(208, COUNT_UBZ_A, rqtUBZ_A);
// время наработки двигателя
AddModbusRequestToSendBuf(135, COUNT_UBZ_P, rqtUBZ_P);
// события
AddModbusRequestToSendBuf(240, COUNT_UBZ_ALARMS, rqtUBZ_ALARMS);
// архив событий
AddModbusRequestToSendBuf(243, COUNT_ALARM_LOG1, rqtUBZ_ALARM_LOG1);
AddModbusRequestToSendBuf(255, COUNT_ALARM_LOG2, rqtUBZ_ALARM_LOG2);
end;
function TUBZReqCreator.PrepareCommand(var prmIds: TChannelIds; var Val: double): bool;
begin
Result := inherited;
if not Result then Exit;
prmIds.ID_Src := SRC_AO;
prmIds.N_Src := $00ED;
Val := IfThen(CompareValue(Val, 0) <> 0, 2, 0);
Result := true;
end;
end.
|
unit Form.ConnectionDialog;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseEditForm, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore,
dxSkinMetropolis, System.ImageList, Vcl.ImgList, cxClasses, dxSkinsForm,
Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxPropertiesStore;
type
TfrmDlgConnection = class(TfrmBaseEditor)
cbbConnections: TcxComboBox;
psDefaultParams: TcxPropertiesStore;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
function GetDBFile: string;
public
property DBFile: string read GetDBFile;
end;
var
frmDlgConnection: TfrmDlgConnection;
implementation
uses
System.IniFiles, synautil, Common.Utils, Common.GoogleAuth;
{$R *.dfm}
procedure TfrmDlgConnection.FormCreate(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'conn.ini');
try
ini.ReadSectionValues('Database', cbbConnections.Properties.Items);
finally
ini.Free;
end;
psDefaultParams.RestoreFrom;
end;
procedure TfrmDlgConnection.FormDestroy(Sender: TObject);
begin
inherited;
psDefaultParams.StoreTo();
end;
function TfrmDlgConnection.GetDBFile: string;
var
DBFile, DBFileType, LocalDBFile: string;
I: Integer;
begin
DBFileType := SeparateLeft(cbbConnections.Text, '=');
DBFile := SeparateRight(cbbConnections.Text, '=');
if CompareText('GDrive', DBFileType) = 0 then begin
// 1. Соединяемся с Google Drive
// 2. Скачиваем файл БД
Screen.Cursor := crHourGlass;
try
LocalDBFile := ExtractFilePath(ParamStr(0)) + DBFile;
if FileExists(LocalDBFile) then begin
if DeleteFile(LocalDBFile) then
RenameFile(LocalDBFile, ChangeFileExt(LocalDBFile, '.bak'));
end;
TGoogleAuth.DownloadFile(LocalDBFile);
finally
Screen.Cursor := crDefault;
end;
end;
Result := DBFile;
end;
end.
|
unit IdTelnet;
interface
uses
Classes,
IdException, IdTCPClient, IdThread, IdStack;
const
{ These are the telnet command constansts from RFC 854 }
TNC_EOR = #239; // End of Record RFC 885
TNC_SE = #240; // End of subnegotiation parameters.
TNC_NOP = #241; // No operation.
TNC_DATA_MARK = #242; // The data stream portion of a Synch.
// This should always be accompanied
// by a TCP Urgent notification.
TNC_BREAK = #243; // NVT character BRK.
TNC_IP = #244; // The function IP.
TNC_AO = #245; // The function ABORT OUTPUT.
TNC_AYT = #246; // The function ARE YOU THERE.
TNC_EC = #247; // The function ERASE CHARACTER.
TNC_EL = #248; // The function ERASE LINE.
TNC_GA = #249; // The GO AHEAD signal.
TNC_SB = #250; // Indicates that what follows is
// subnegotiation of the indicated
// option.
TNC_WILL = #251; // Indicates the desire to begin
// performing, or confirmation that
// you are now performing, the
// indicated option.
TNC_WONT = #252; // Indicates the refusal to perform,
// or continue performing, the
// indicated option.
TNC_DO = #253; // Indicates the request that the
// other party perform, or
// confirmation that you are expecting
// the other party to perform, the
// indicated option.
TNC_DONT = #254; // Indicates the demand that the
// other party stop performing,
// or confirmation that you are no
// longer expecting the other party
// to perform, the indicated option.
TNC_IAC = #255; // Data Byte 255.
{ Telnet options from RFC 1010 }
TNO_BINARY = #0; // Binary Transmission
TNO_ECHO = #1; // Echo
TNO_RECONNECT = #2; // Reconnection
TNO_SGA = #3; // Suppress Go Ahead
TNO_AMSN = #4; // Approx Message Size Negotiation
TNO_STATUS = #5; // Status
TNO_TIMING_MARK = #6; // Timing Mark
TNO_RCTE = #7; // Remote Controlled Trans and Echo
TNO_OLW = #8; // Output Line Width
TNO_OPS = #9; // Output Page Size
TNO_OCRD = #10; // Output Carriage-Return Disposition
TNO_OHTS = #11; // Output Horizontal Tab Stops
TNO_OHTD = #12; // Output Horizontal Tab Disposition
TNO_OFD = #13; // Output Formfeed Disposition
TNO_OVT = #14; // Output Vertical Tabstops
TNO_OVTD = #15; // Output Vertical Tab Disposition
TNO_OLD = #16; // Output Linefeed Disposition
TNO_EA = #17; // Extended ASCII
TNO_LOGOUT = #18; // Logout
TNO_BYTE_MACRO = #19; // Byte Macro
TNO_DET = #20; // Data Entry Terminal
TNO_SUPDUP = #21; // SUPDUP
TNO_SUPDUP_OUTPUT = #22; // SUPDUP Output
TNO_SL = #23; // Send Location
TNO_TERMTYPE = #24; // Terminal Type
TNO_EOR = #25; // End of Record
TNO_TACACS_ID = #26; // TACACS User Identification
TNO_OM = #27; // Output Marking
TNO_TLN = #28; // Terminal Location Number
TNO_3270REGIME = #29; // 3270 regime
TNO_X3PAD = #30; // X.3 PAD
TNO_NAWS = #31; // Window size
TNO_TERM_SPEED = #32; // Terminal speed
TNO_RFLOW = #33; // Remote flow control
TNO_LINEMODE = #34; // Linemode option
TNO_XDISPLOC = #35; // X Display Location
TNO_AUTH = #37; // Authenticate
TNO_ENCRYPT = #38; // Encryption option
TNO_EOL = #255; // Extended-Options-List
// Sub options
TNOS_TERM_IS = #0;
TNOS_TERMTYPE_SEND = #1; // Sub option
TNOS_REPLY = #2;
TNOS_NAME = #3;
type
TIdTelnet = class;
TTnDataAvail = procedure(Buffer: string) of object;
TTnState = (tnsDATA, tnsIAC, tnsIAC_SB, tnsIAC_WILL, tnsIAC_DO, tnsIAC_WONT,
tnsIAC_DONT, tnsIAC_SBIAC, tnsIAC_SBDATA, tnsSBDATA_IAC);
TTelnetCommand = (tncNoLocalEcho, tncLocalEcho, tncEcho);
TClientEvent = procedure of object;
TOnTelnetCommand = procedure(Sender: TComponent; Status: TTelnetCommand) of
object;
TIdTelnetReadThread = class(TIdThread)
protected
FClient: TIdTelnet;
FRecvData: string;
procedure Run; override;
public
constructor Create(AClient: TIdTelnet); reintroduce;
end;
TIdTelnet = class(TIdTCPClient)
protected
fState: TTnState;
fReply: Char;
fSentDoDont: string;
fSentWillWont: string;
fReceivedDoDont: string;
fReceivedWillWont: string;
fTerminal: string;
FOnDataAvailable: TTnDataAvail;
fIamTelnet: Boolean;
FOnDisconnect: TClientEvent;
FOnConnect: TClientEvent;
FOnTelnetCommand: TOnTelnetCommand;
procedure DoOnDataAvailable;
procedure SetOnTelnetCommand(const Value: TOnTelnetCommand);
property State: TTnState read fState write fState;
property Reply: Char read fReply write fReply;
property SentDoDont: string read fSentDoDont write fSentDoDont;
property SentWillWont: string read fSentWillWont write fSentWillWont;
property ReceivedDoDont: string read fReceivedDoDont write fReceivedDoDont;
property ReceivedWillWont: string read fReceivedWillWont write
fReceivedWillWont;
property IamTelnet: Boolean read fIamTelnet write fIamTelnet;
function Negotiate(const Buf: string): string;
procedure Handle_SB(CurrentSb: Byte; sbData: string; sbCount: Integer);
procedure SendNegotiationResp(var Resp: string);
procedure DoTelnetCommand(Status: TTelnetCommand);
public
TelnetThread: TIdTelnetReadThread;
constructor Create(AOwner: TComponent); override;
procedure Connect; override;
procedure Disconnect; override;
procedure SendCh(Ch: Char);
published
property OnTelnetCommand: TOnTelnetCommand read FOnTelnetCommand write
SetOnTelnetCommand;
property OnDataAvailable: TTnDataAvail read FOnDataAvailable write
FOnDataAvailable;
property Terminal: string read fTerminal write fTerminal;
property OnConnect: TClientEvent read FOnConnect write FOnConnect;
property OnDisconnect: TClientEvent read FOnDisconnect write FOnDisconnect;
end;
EIdTelnetError = class(EIdException);
EIdTelnetClientConnectError = class(EIdTelnetError);
EIdTelnetServerOnDataAvailableIsNil = class(EIdTelnetError);
implementation
uses
IdGlobal, IdResourceStrings;
constructor TIdTelnetReadThread.Create(AClient: TIdTelnet);
begin
inherited Create(False);
FClient := AClient;
FreeOnTerminate := True;
end;
procedure TIdTelnet.SendCh(Ch: Char);
begin
if Ch <> #13 then
Write(Ch)
else
if (Ch = #13) and (IamTelnet = true) then
Write(Ch)
else
Writeln('');
end;
procedure TIdTelnetReadThread.Run;
begin
FRecvData := FClient.Negotiate(FClient.CurrentReadBuffer);
Synchronize(FClient.DoOnDataAvailable);
FClient.CheckForDisconnect;
end;
constructor TIdTelnet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Port := 23;
State := tnsData;
SentDoDont := #0;
SentWillWont := #0;
ReceivedDoDont := #0;
ReceivedWillWont := #0;
Terminal := 'dumb';
IamTelnet := False;
end;
procedure TIdTelnet.Disconnect;
begin
if TelnetThread <> nil then
begin
TelnetThread.Terminate;
end;
IAmTelnet := False;
inherited;
if Assigned(FOnDisconnect) then
begin
OnDisconnect;
end;
end;
procedure TIdTelnet.DoOnDataAvailable;
begin
if assigned(FOnDataAvailable) then
begin
OnDataAvailable(TelnetThread.FRecvData);
end
else
begin
raise
EIdTelnetServerOnDataAvailableIsNil.Create(RSTELNETSRVOnDataAvailableIsNil);
end;
end;
procedure TIdTelnet.Connect;
begin
try
if Assigned(FOnConnect) then
OnConnect;
inherited Connect;
if Connected then
TelnetThread := TIdTelnetReadThread.Create(Self);
except on E: EIdSocketError do
raise EIdTelnetClientConnectError.Create(RSTELNETCLIConnectError);
// translate
end;
end;
procedure TIdTelnet.SendNegotiationResp(var Resp: string);
begin
Write(Resp);
Resp := '';
end;
procedure TIdTelnet.Handle_SB(CurrentSB: Byte; sbData: string; sbCount:
Integer);
var
Resp: string;
begin
if (sbcount > 0) and (sbdata = TNOS_TERMTYPE_SEND) then
begin
if Terminal = '' then
Terminal := 'dumb';
Resp := TNC_IAC + TNC_SB + TNO_TERMTYPE + TNOS_TERM_IS + Terminal + TNC_IAC
+ TNC_SE;
SendNegotiationResp(Resp);
end;
end;
function TIdTelnet.Negotiate(const Buf: string): string;
var
LCount: Integer;
bOffset: Integer;
nOffset: Integer;
B: Char;
nBuf: string;
sbBuf: string;
sbCount: Integer;
CurrentSb: Integer;
SendBuf: string;
begin
bOffset := 1;
nOffset := 0;
sbCount := 1;
CurrentSB := 1;
nbuf := '';
LCount := Length(Buf);
while bOffset < LCount + 1 do
begin
b := Buf[bOffset];
case State of
tnsData:
if b = TNC_IAC then
begin
IamTelnet := True;
State := tnsIAC;
end
else
nbuf := nbuf + b;
tnsIAC:
case b of
TNC_IAC:
begin
State := tnsData;
inc(nOffset);
nbuf[nOffset] := TNC_IAC;
end;
TNC_WILL:
State := tnsIAC_WILL;
TNC_WONT:
State := tnsIAC_WONT;
TNC_DONT:
State := tnsIAC_DONT;
TNC_DO:
State := tnsIAC_DO;
TNC_EOR:
State := tnsDATA;
TNC_SB:
begin
State := tnsIAC_SB;
sbCount := 0;
end;
else
State := tnsData;
end;
tnsIAC_WILL:
begin
case b of
TNO_ECHO:
begin
Reply := TNC_DO;
DoTelnetCommand(tncNoLocalEcho);
end;
TNO_EOR:
Reply := TNC_DO;
else
Reply := TNC_DONT;
end;
begin
SendBuf := TNC_IAC + Reply + b;
SendNegotiationResp(SendBuf);
SentDoDont := Reply;
ReceivedWillWont := TNC_WILL;
end;
State := tnsData;
end;
tnsIAC_WONT:
begin
case b of
TNO_ECHO:
begin
DoTelnetCommand(tncLocalEcho);
Reply := TNC_DONT;
end;
TNO_EOR:
Reply := TNC_DONT;
else
Reply := TNC_DONT;
end;
begin
SendBuf := TNC_IAC + Reply + b;
SendNegotiationResp(SendBuf);
SentDoDont := Reply;
ReceivedWillWont := TNC_WILL;
end;
State := tnsData;
end;
tnsIAC_DO:
begin
case b of
TNO_ECHO:
begin
DoTelnetCommand(tncLocalEcho);
Reply := TNC_WILL;
end;
TNO_TERMTYPE:
Reply := TNC_WILL;
TNO_AUTH:
begin
Reply := TNC_WONT;
end;
else
Reply := TNC_WONT;
end;
begin
SendBuf := TNC_IAC + Reply + b;
SendNegotiationResp(SendBuf);
SentWillWont := Reply;
ReceivedDoDont := TNC_DO;
end;
State := tnsData;
end;
tnsIAC_DONT:
begin
case b of
TNO_ECHO:
begin
DoTelnetCommand(tncEcho);
Reply := TNC_WONT;
end;
TNO_NAWS:
Reply := TNC_WONT;
TNO_AUTH:
Reply := TNC_WONT
else
Reply := TNC_WONT;
end;
begin
SendBuf := TNC_IAC + reply + b;
SendNegotiationResp(SendBuf);
end;
State := tnsData;
end;
tnsIAC_SB:
begin
if b = TNC_IAC then
State := tnsIAC_SBIAC
else
begin
CurrentSb := Ord(b);
sbCount := 0;
State := tnsIAC_SBDATA;
end;
end;
tnsIAC_SBDATA:
begin
if b = TNC_IAC then
State := tnsSBDATA_IAC
else
begin
inc(sbCount);
sbBuf := b;
end;
end;
tnsSBDATA_IAC:
case b of
TNC_IAC:
begin
State := tnsIAC_SBDATA;
inc(sbCount);
sbBuf[sbCount] := TNC_IAC;
end;
TNC_SE:
begin
handle_sb(CurrentSB, sbBuf, sbCount);
CurrentSB := 0;
State := tnsData;
end;
TNC_SB:
begin
handle_sb(CurrentSB, sbBuf, sbCount);
CurrentSB := 0;
State := tnsIAC_SB;
end
else
State := tnsDATA;
end;
else
State := tnsData;
end;
inc(boffset);
end;
Result := nBuf;
end;
procedure TIdTelnet.SetOnTelnetCommand(const Value: TOnTelnetCommand);
begin
FOnTelnetCommand := Value;
end;
procedure TIdTelnet.DoTelnetCommand(Status: TTelnetCommand);
begin
if assigned(FOnTelnetCommand) then
FOnTelnetCommand(Self, Status);
end;
end.
|
unit NLDQuadrisEdit;
interface
uses
Classes, DesignEditors, DesignIntf;
type
TThemeProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure Register;
implementation
uses
NLDQuadris;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TThemeName), TNLDQuadris, 'Theme',
TThemeProperty);
end;
{ TThemeProperty }
function TThemeProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect, paRevertable];
end;
procedure TThemeProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
ThemeNames: TStrings;
begin
inherited;
ThemeNames := TNLDQuadris.GetThemeNames;
for i := 0 to ThemeNames.Count - 1 do
Proc(ThemeNames[i]);
end;
end.
|
unit UDaoContasPagar;
interface
uses uDao, DB, SysUtils, Messages, UContasPagar, UDaoFornecedor,
UDaoFormaPagamento, UDaoUsuario;
type DaoContasPagar = class(Dao)
private
protected
umaContasPagar : ContasPagar;
umaDaoFornecedor : DaoFornecedor;
umaDaoUsuario : DaoUsuario;
umaDaoFormaPagamento : DaoFormaPagamento;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function VerificarNota (obj : TObject) : Boolean;
function VerificarContas (obj : TObject) : Boolean;
function VerificarParcelas (obj : TObject) : Boolean;
procedure VerificarCompra (obj : TObject);
function ContarContasPagar(obj : TObject) : Integer;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
uses UCtrlCompra, UCompra;
{ DaoContasPagar }
function DaoContasPagar.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umaContasPagar: ContasPagar;
begin
e := ' and ';
onde := ' where';
prim := true;
umaContasPagar := ContasPagar(obj);
sql := 'select * from contapagar conta';
if umaContasPagar.getUmFornecedor.getNome_RazaoSoCial <> '' then
begin
//Buscar a descricao do fornecedor na tabela fornecedor
sql := sql+' INNER JOIN fornecedor c ON conta.idfornecedor = c.idfornecedor and c.nome_razaosocial like '+quotedstr('%'+umaContasPagar.getUmFornecedor.getNome_RazaoSoCial+'%');
if (prim) and (umaContasPagar.getStatus <> '')then
begin
prim := false;
sql := sql+onde;
end
end;
if umaContasPagar.getStatus <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end;
sql := sql+' conta.status like '+quotedstr('%'+umaContasPagar.getStatus+'%'); //COLOCA CONDIÇAO NO SQL
end;
if (DateToStr(umaContasPagar.getDataEmissao) <> '30/12/1899') and (datetostr(umaContasPagar.getDataPagamento) <> '30/12/1899') then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' dataemissao between '+QuotedStr(DateToStr(umaContasPagar.getDataEmissao))+' and '+QuotedStr(DateToStr(umaContasPagar.getDataPagamento));
end;
with umDM do
begin
QContasPagar.Close;
QContasPagar.sql.Text := sql+' order by numnota, serienota, numparcela';
QContasPagar.Open;
if QContasPagar.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoContasPagar.VerificarNota(obj: TObject): Boolean;
var sql : string;
umaContaPagar : ContasPagar;
i : Integer;
begin
umaContaPagar := ContasPagar(obj);
for i := 1 to 2 do
begin
if i = 1 then
umaContaPagar.setStatus('PAGA')
else
umaContaPagar.setStatus('PENDENTE');
sql := 'select * from contapagar where numnota = '+IntToStr(umaContaPagar.getNumNota)+' and serienota = '''+umaContaPagar.getSerieNota+ ''' and idfornecedor = '+IntToStr(umaContaPagar.getUmFornecedor.getId)+' and status = '''+umaContaPagar.getStatus+'''';
with umDM do
begin
QContasPagar.Close;
QContasPagar.sql.Text := sql+' order by numnota, serienota, numparcela';
QContasPagar.Open;
if QContasPagar.RecordCount > 0 then
begin
result := True;
Self.AtualizaGrid;
Exit;
end
else
result := false;
end;
end;
Self.AtualizaGrid;
end;
function DaoContasPagar.VerificarContas (obj : TObject) : Boolean;
var sql : string;
umaContaPagar : ContasPagar;
begin
umaContaPagar := ContasPagar(obj);
sql := 'select * from contapagar where numnota = '+IntToStr(umaContaPagar.getNumNota)+' and serienota = '''+umaContaPagar.getSerieNota+ ''' and idfornecedor = '+IntToStr(umaContaPagar.getUmFornecedor.getId)+'';
if(umaContaPagar.getStatus <> '')then
sql := sql +' and status = '''+umaContaPagar.getStatus+'''';
with umDM do
begin
QContasPagar.Close;
QContasPagar.sql.Text := sql;
QContasPagar.Open;
if QContasPagar.RecordCount > 0 then
result := True
else
result := false;
end;
Self.AtualizaGrid;
end;
function DaoContasPagar.VerificarParcelas (obj : TObject) : Boolean;
var umaContaPagar : ContasPagar;
begin
umaContaPagar := ContasPagar(obj);
with umDM do
begin
QContasPagar.Close;
QContasPagar.sql.Text := 'select * from contapagar where numnota = '+IntToStr(umaContaPagar.getNumNota)+' and serienota = '''+umaContaPagar.getSerieNota+ ''' and idfornecedor = '+IntToStr(umaContaPagar.getUmFornecedor.getId)+' order by numparcela';;
QContasPagar.Open;
while not QContasPagar.Eof do
begin
if (QContasPagarstatus.AsString = 'PENDENTE') then
if(umaContaPagar.getNumParcela = QContasPagarnumparcela.AsInteger) then
begin
Result := True;
Break;
end
else
begin
Result := False;
Break;
end;
QContasPagar.Next;
end;
Self.AtualizaGrid;
end;
end;
procedure DaoContasPagar.VerificarCompra (obj : TObject);
var umaCtrlCompra : CtrlCompra;
umaCompra : Compra;
begin
umaContasPagar := ContasPagar(obj);
umaCtrlCompra := CtrlCompra.CrieObjeto;
umaCompra := Compra.CrieObjeto;
umaCompra.setNumNota(umaContasPagar.getNumNota);
umaCompra.setSerieNota(umaContasPagar.getSerieNota);
umaCompra.getUmFornecedor.setId(umaContasPagar.getUmFornecedor.getId);
if (umaCtrlCompra.VerificarNota(umaCompra)) then
begin
umaCtrlCompra.Carrega(umaCompra);
umaCompra.setStatus('CANCELADA');
umaCompra.setTipo(False);
umaCtrlCompra.Salvar(umaCompra)
end;
end;
function DaoContasPagar.ContarContasPagar(obj : TObject) : Integer;
var count : Integer;
begin
count := 0;
umaContasPagar := ContasPagar(obj);
with umDM do
begin
QContasPagar.Close;
QContasPagar.SQL.Text := 'select * from contapagar where numnota = '+IntToStr(umaContasPagar.getNumNota)+ ' and serienota = '''+umaContasPagar.getSerieNota+'''';
QContasPagar.Open;
QContasPagar.First;
if umaContasPagar.CountParcelas <> 0 then
umaContasPagar.LimparListaParcelas;
while not QContasPagar.Eof do
begin
count := count + 1;
umaContasPagar.CrieObjetoParcela;
umaContasPagar.addParcelas(umaContasPagar.getUmaParcelas);
umaContasPagar.getParcelas(count-1).setNumParcela(QContasPagarnumparcela.AsInteger);
QContasPagar.Next;
end;
end;
Result := count;
end;
procedure DaoContasPagar.AtualizaGrid;
begin
with umDM do
begin
QContasPagar.Close;
QContasPagar.sql.Text := 'select * from contapagar INNER JOIN fornecedor on (fornecedor.idfornecedor = contapagar.idfornecedor) order by numnota, serienota, numparcela';
QContasPagar.Open;
end;
end;
function DaoContasPagar.Carrega(obj: TObject): TObject;
var umaContasPagar: ContasPagar;
count : Integer;
begin
umaContasPagar := ContasPagar(obj);
count := 0;
with umDM do
begin
if not QContasPagar.Active then
QContasPagar.Open;
//
// if umaContasPagar.getId <> 0 then
// begin
// QContasPagar.Close;
// QContasPagar.SQL.Text := 'select * from estado where idestado = '+IntToStr(umaContasPagar.getId);
// QContasPagar.Open;
// end;
//
umaContasPagar.setIdCompra(QContasPagaridcompra.AsInteger);
umaContasPagar.setNumNota(QContasPagarnumnota.AsInteger);
umaContasPagar.setSerieNota(QContasPagarserienota.AsString);
umaContasPagar.setNumParcela(QContasPagarnumparcela.AsInteger);
umaContasPagar.setDataEmissao(QContasPagardataemissao.AsDateTime);
umaContasPagar.setDataVencimento(QContasPagardatavencimento.AsDateTime);
umaContasPagar.setDataPagamento(QContasPagardatapagamento.AsDateTime);
umaContasPagar.setValor(QContasPagarvalor.AsFloat);
umaContasPagar.setMulta(QContasPagarmulta.AsFloat);
umaContasPagar.setJuros(QContasPagarjuros.AsFloat);
umaContasPagar.setDesconto(QContasPagardesconto.AsFloat);
umaContasPagar.setStatus(QContasPagarstatus.AsString);
umaContasPagar.setObservacao(QContasPagarobservacao.AsString);
// Busca o Fornecedor referente ao ContasPagar
umaContasPagar.getUmFornecedor.setId(QContasPagaridfornecedor.AsInteger);
umaDaoFornecedor.Carrega(umaContasPagar.getUmFornecedor);
// Busca o Usuario referente ao ContasPagar
umaContasPagar.getUmUsuario.setIdUsuario(QContasPagaridusuario.AsInteger);
umaDaoUsuario.Carrega(umaContasPagar.getUmUsuario);
// Busca a Forma de Pagamento referente ao ContasPagar
umaContasPagar.getUmaFormaPagamento.setId(QContasPagaridformapagamento.AsInteger);
umaDaoFormaPagamento.Carrega(umaContasPagar.getUmaFormaPagamento);
//Cria uma Parcela referente a que foi selecionada na grid apenas para percorrer o FOR na hora de salvar
umaContasPagar.getUmaCondicaoPagamento.addParcela;
umaContasPagar.addParcelas(umaContasPagar.getUmaCondicaoPagamento.getParcela);
end;
// Self.AtualizaGrid;
result := umaContasPagar;
end;
constructor DaoContasPagar.CrieObjeto;
begin
inherited;
umaDaoFornecedor := DaoFornecedor.CrieObjeto;
umaDaoUsuario := DaoUsuario.CrieObjeto;
umaDaoFormaPagamento := DaoFormaPagamento.CrieObjeto;
end;
destructor DaoContasPagar.Destrua_se;
begin
inherited;
end;
function DaoContasPagar.Excluir(obj: TObject): string;
var
umaContasPagar: ContasPagar;
begin
// umaContasPagar := ContasPagar(obj);
// with umDM do
// begin
// try
// beginTrans;
// QContasPagar.SQL := UpdateContasPagar.DeleteSQL;
// QContasPagar.Params.ParamByName('OLD_idestado').Value := umaContasPagar.getId;
// QContasPagar.ExecSQL;
// Commit;
// result := 'ContasPagar excluído com sucesso!';
// except
// on e:Exception do
// begin
// rollback;
// if pos('chave estrangeira',e.Message)>0 then
// result := 'Ocorreu um erro! O ContasPagar não pode ser excluído pois ja está sendo usado pelo sistema.'
// else
// result := 'Ocorreu um erro! ContasPagar não foi excluído. Erro: '+e.Message;
// end;
// end;
// end;
// Self.AtualizaGrid;
end;
function DaoContasPagar.GetDS: TDataSource;
begin
//------Formatar Grid--------//
(umDM.QContasPagar.FieldByName('valor') as TFloatField).DisplayFormat := '0.00'; //Formatar o campo valor do tipo Float
(umDM.QContasPagar.FieldByName('multa') as TFloatField).DisplayFormat := '0.00';
(umDM.QContasPagar.FieldByName('juros') as TFloatField).DisplayFormat := '0.00';
(umDM.QContasPagar.FieldByName('desconto') as TFloatField).DisplayFormat := '0.00';
umDM.QContasPagar.FieldByName('numnota').DisplayLabel := 'NN';
umDM.QContasPagar.FieldByName('serienota').DisplayLabel := 'SN';
umDM.QContasPagar.FieldByName('numparcela').DisplayLabel := 'P';
umDM.QContasPagar.FieldByName('numnota').DisplayWidth := 5;
umDM.QContasPagar.FieldByName('serienota').DisplayWidth := 5;
umDM.QContasPagar.FieldByName('numparcela').DisplayWidth := 5;
umDM.QContasPagar.FieldByName('valor').DisplayWidth := 10;
umDM.QContasPagar.FieldByName('multa').DisplayWidth := 5;
umDM.QContasPagar.FieldByName('juros').DisplayWidth := 5;
umDM.QContasPagar.FieldByName('desconto').DisplayWidth := 5;
//-----------------------------//
Self.AtualizaGrid;
result := umDM.DSContasPagar;
end;
procedure DaoContasPagar.Ordena(campo: string);
begin
umDM.QContasPagar.IndexFieldNames := campo;
end;
function DaoContasPagar.Salvar(obj: TObject): string;
var umaContasPagar : ContasPagar;
umaCtrlCompra : CtrlCompra;
i, numParcela : Integer;
valor : Real;
status : string;
countParcelas : Integer;
cancelar : Boolean;
begin
umaContasPagar := ContasPagar(obj);
with umDM do
begin
try
beginTrans;
QContasPagar.Close;
if (umaContasPagar.getStatus = 'CANCELADA' ) then
begin
countParcelas := ContarContasPagar(umaContasPagar);
status := umaContasPagar.getStatus;
cancelar := True;
end
else
begin
countParcelas := umaContasPagar.CountParcelas;
status := umaContasPagar.getStatus;
cancelar := False;
end;
for i := 1 to countParcelas do
begin
if (cancelar) then
numParcela := umaContasPagar.getParcelas(i-1).getNumParcela
else
numParcela := umaContasPagar.getNumParcela;
if umaContasPagar.getStatus = 'PENDENTE' then
QContasPagar.SQL := UpdateContasPagar.InsertSQL
else
begin
QContasPagar.SQL := UpdateContasPagar.ModifySQL;
QContasPagar.Params.ParamByName('OLD_numnota').Value := umaContasPagar.getNumNota;
QContasPagar.Params.ParamByName('OLD_serienota').Value := umaContasPagar.getSerieNota;
QContasPagar.Params.ParamByName('OLD_numparcela').Value := numParcela;
QContasPagar.Params.ParamByName('OLD_idfornecedor').Value := umaContasPagar.getUmFornecedor.getId;
end;
QContasPagar.Params.ParamByName('numnota').Value := umaContasPagar.getNumNota;
QContasPagar.Params.ParamByName('serienota').Value := umaContasPagar.getSerieNota;
QContasPagar.Params.ParamByName('idfornecedor').Value := umaContasPagar.getUmFornecedor.getId;
QContasPagar.Params.ParamByName('idusuario').Value := umaContasPagar.getUmUsuario.getIdUsuario;
QContasPagar.Params.ParamByName('idformapagamento').Value := umaContasPagar.getUmaFormaPagamento.getId;
QContasPagar.Params.ParamByName('multa').Value := umaContasPagar.getMulta;
QContasPagar.Params.ParamByName('juros').Value := umaContasPagar.getJuros;
QContasPagar.Params.ParamByName('desconto').Value := umaContasPagar.getDesconto;
QContasPagar.Params.ParamByName('status').Value := status;
QContasPagar.Params.ParamByName('observacao').Value := umaContasPagar.getObservacao;
QContasPagar.Params.ParamByName('dataemissao').Value := umaContasPagar.getDataEmissao;
if (umaContasPagar.getDataPagamento <> StrToDateTime('30/12/1899')) then
QContasPagar.Params.ParamByName('datapagamento').Value := umaContasPagar.getDataPagamento;
if umaContasPagar.getStatus = 'PENDENTE' then
begin
QContasPagar.Params.ParamByName('numparcela').Value := umaContasPagar.getParcelas(i-1).getNumParcela;
valor := StrToFloat(FormatFloat('#0.00',(umaContasPagar.getParcelas(i-1).getPorcentagem/100) * umaContasPagar.getTotalAux));
QContasPagar.Params.ParamByName('valor').Value := valor;
QContasPagar.Params.ParamByName('datavencimento').Value := DateToStr(Date + umaContasPagar.getParcelas(i-1).getDias);
end
else
begin
QContasPagar.Params.ParamByName('numparcela').Value := numParcela;
QContasPagar.Params.ParamByName('valor').Value := umaContasPagar.getValor;
QContasPagar.Params.ParamByName('datavencimento').Value := umaContasPagar.getDataVencimento;
end;
QContasPagar.ExecSQL;
end;
//Chamada para o cancelamento da compra quando uma contas a pagar for cancelada pela propria tela
if (status = 'CANCELADA') then
Self.VerificarCompra(umaContasPagar);
Commit;
if umaContasPagar.getStatus = 'CANCELADA' then
result := 'Conta Cancelada com sucesso!'
else
result := 'Conta Paga com sucesso!';
except
on e: Exception do
begin
rollback;
if umaContasPagar.getStatus = 'CANCELADA' then
Result := 'Ocorreu um erro! Essa Conta não foi cancelada. Erro: '+e.Message
else
Result := 'Ocorreu um erro! Essa Conta não foi salva. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
UNIT mySys;
INTERFACE
USES dos,myGenerics,sysutils,Process,
{$ifdef Windows}
windows,
ActiveX,
ComObj,
Variants,
{$endif}
FileUtil,Classes,LazUTF8;
TYPE
T_fileAttrib=(aExistent ,
aReadOnly ,
aHidden ,
aSysFile ,
aDirectory,
aArchive ,
aSymLink );
CONST
C_fileAttribName:array[T_fileAttrib] of string=(
'existent',
'readOnly',
'hidden',
'sysFile',
'directory',
'archive',
'symLink');
TYPE
T_fileAttribs=set of T_fileAttrib;
T_fileInfo=record
filePath:string;
time:double;
size:int64;
attributes:T_fileAttribs;
end;
T_fileInfoArray=array of T_fileInfo;
TYPE
T_basicThread=class(TThread)
protected
PROCEDURE threadSleepMillis(CONST millisecondsToSleep:longint);
public
CONSTRUCTOR create(CONST prio:TThreadPriority=tpNormal; CONST createSuspended:boolean=false);
DESTRUCTOR destroy; override;
end;
T_xosPrng = object
private
criticalSection:TRTLCriticalSection;
w,x,y,z:dword;
FUNCTION XOS:dword;inline;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE resetSeed(CONST newSeed:dword);
PROCEDURE resetSeed(CONST s:array of byte);
PROCEDURE randomize;inline;
FUNCTION intRandom(CONST imax:int64):int64;
FUNCTION realRandom:double;
FUNCTION dwordRandom:dword;
end;
T_taskInfo=object
pid,parentPID: UInt32;
workingSetSize,userModeTime: UInt64;
caption,commandLine:shortstring; //using ansi-strings instead seems to provoke memory leaks
end;
T_taskInfoArray = array of T_taskInfo;
F_cleanupCallback=PROCEDURE;
F_objectCleanupCallback=PROCEDURE of object;
T_cleanupLevel=0..5;
T_memoryCleaner=class(T_basicThread)
private
MemoryUsed:ptrint;
cleanerCs:TRTLCriticalSection;
methods :array[T_cleanupLevel] of array of F_cleanupCallback;
methods2:array[T_cleanupLevel] of array of F_objectCleanupCallback;
protected
PROCEDURE execute; override;
public
memoryComfortThreshold:int64;
CONSTRUCTOR create;
DESTRUCTOR destroy; override;
PROCEDURE registerCleanupMethod (CONST level: T_cleanupLevel; CONST m:F_cleanupCallback);
PROCEDURE registerObjectForCleanup (CONST level: T_cleanupLevel; CONST m:F_objectCleanupCallback);
PROCEDURE unregisterObjectForCleanup(CONST m:F_objectCleanupCallback);
PROCEDURE callCleanupMethods (CONST upToIncludingLevel:T_cleanupLevel);
FUNCTION isMemoryInComfortZone:boolean;
FUNCTION getMemoryUsedInBytes:int64;
FUNCTION getMemoryUsedAsString(OUT fractionOfThreshold:double):string;
end;
FUNCTION getEnvironment:T_arrayOfString;
FUNCTION findDeeply(CONST rootPath,searchPattern:ansistring):ansistring;
FUNCTION findOne(CONST searchPattern:ansistring):ansistring;
FUNCTION runCommand(CONST executable: ansistring; CONST parameters: T_arrayOfString; OUT output: TStringList): boolean;
PROCEDURE runDetachedCommand(CONST executable: ansistring; CONST parameters: T_arrayOfString);
FUNCTION myCommandLineParameters:T_arrayOfString;
PROCEDURE clearConsole;
FUNCTION containsPlaceholder(CONST S:string):boolean;
FUNCTION findFileInfo(CONST pathOrPattern:string):T_fileInfoArray;
FUNCTION getNumberOfCPUs:longint;
{$ifdef Windows}
PROCEDURE deleteMyselfOnExit;
{$ifndef debugMode}
FUNCTION GetConsoleWindow: HWND; stdcall; external kernel32;
{$endif}
FUNCTION getTaskInfo:T_taskInfoArray;
FUNCTION getCPULoadPercentage:longint;
{$endif}
FUNCTION showConsole:boolean;
FUNCTION hideConsole:boolean;
FUNCTION isConsoleShowing:boolean;
PROCEDURE writeFile(CONST fileName:string; CONST lines:T_arrayOfString);
FUNCTION readFile(CONST fileName:string):T_arrayOfString;
FUNCTION getGlobalRunningThreads:longint;
FUNCTION getGlobalThreads:longint;
PROCEDURE threadStartsSleeping;
PROCEDURE threadStopsSleeping;
PROCEDURE threadSleepMillis(CONST millisecondsToSleep:longint);
CONST GLOBAL_THREAD_LIMIT={$ifdef CPU64}500{$else}100{$endif};
VAR memoryCleaner:T_memoryCleaner;
IMPLEMENTATION
VAR numberOfCPUs:longint=0;
globalRunningThreads:longint=1; //The main thread is already running
globalThreads:longint=1;
FUNCTION getGlobalRunningThreads:longint;
begin result:=globalRunningThreads; end;
FUNCTION getGlobalThreads:longint;
begin result:=globalThreads; end;
PROCEDURE threadStartsSleeping;
begin
interlockedDecrement(globalRunningThreads);
end;
PROCEDURE threadStopsSleeping;
begin
interLockedIncrement(globalRunningThreads);
end;
CONSTRUCTOR T_basicThread.create(CONST prio:TThreadPriority; CONST createSuspended:boolean);
begin
inherited create(createSuspended);
FreeOnTerminate := not(createSuspended);
Priority:=prio;
interLockedIncrement(globalRunningThreads);
interLockedIncrement(globalThreads);
end;
DESTRUCTOR T_basicThread.destroy;
begin
inherited destroy;
interlockedDecrement(globalRunningThreads);
interlockedDecrement(globalThreads);
end;
PROCEDURE threadSleepMillis(CONST millisecondsToSleep:longint);
begin
threadStartsSleeping;
sleep(millisecondsToSleep);
threadStopsSleeping;
end;
PROCEDURE T_basicThread.threadSleepMillis(CONST millisecondsToSleep:longint);
begin
if Terminated then exit;
threadStartsSleeping;
sleep(millisecondsToSleep);
threadStopsSleeping;
end;
CONSTRUCTOR T_memoryCleaner.create;
VAR l:longint;
begin
inherited create(tpLower);
FreeOnTerminate:=false;
MemoryUsed:=0;
for l in T_cleanupLevel do setLength(methods [l],0);
for l in T_cleanupLevel do setLength(methods2[l],0);
initCriticalSection(cleanerCs);
memoryComfortThreshold:={$ifdef UNIX}1 shl 30{$else}{$ifdef CPU32}1 shl 30{$else}4 shl 30{$endif}{$endif};
end;
DESTRUCTOR T_memoryCleaner.destroy;
VAR l:longint;
begin
enterCriticalSection(cleanerCs);
for l in T_cleanupLevel do setLength(methods [l],0);
for l in T_cleanupLevel do setLength(methods2[l],0);
leaveCriticalSection(cleanerCs);
doneCriticalSection(cleanerCs);
end;
PROCEDURE T_memoryCleaner.registerCleanupMethod(CONST level: T_cleanupLevel; CONST m:F_cleanupCallback);
begin
enterCriticalSection(cleanerCs);
try
setLength(methods[level],length(methods[level])+1);
methods[level,length(methods[level])-1]:=m;
finally
leaveCriticalSection(cleanerCs);
end;
end;
PROCEDURE T_memoryCleaner.registerObjectForCleanup(CONST level: T_cleanupLevel; CONST m:F_objectCleanupCallback);
begin
enterCriticalSection(cleanerCs);
try
setLength(methods2[level],length(methods2[level])+1);
methods2[level,length(methods2[level])-1]:=m;
finally
leaveCriticalSection(cleanerCs);
end;
end;
PROCEDURE T_memoryCleaner.unregisterObjectForCleanup(CONST m:F_objectCleanupCallback);
VAR l:longint;
i:longint=0;
begin
enterCriticalSection(cleanerCs);
try
for l in T_cleanupLevel do begin
i:=0;
while i<length(methods2[l]) do begin
if methods2[l,i]=m then begin
methods2[l,i]:=methods2[l ,length(methods2[l])-1];
setLength (methods2[l],length(methods2[l])-1);
end else inc(i);
end;
end;
finally
leaveCriticalSection(cleanerCs);
end;
end;
PROCEDURE T_memoryCleaner.callCleanupMethods(CONST upToIncludingLevel:T_cleanupLevel);
VAR l :T_cleanupLevel;
VAR m :F_cleanupCallback;
m2:F_objectCleanupCallback;
begin
enterCriticalSection(cleanerCs);
try
for l:=0 to upToIncludingLevel do begin
for m in methods [l] do m();
for m2 in methods2[l] do m2();
end;
finally
leaveCriticalSection(cleanerCs);
end;
end;
FUNCTION getNumberOfCPUs: longint;
{$ifdef Windows}
{$WARN 5057 OFF}
VAR SystemInfo:SYSTEM_INFO;
begin
if numberOfCPUs>0 then exit(numberOfCPUs);
getSystemInfo(SystemInfo);
numberOfCPUs:=SystemInfo.dwNumberOfProcessors;
result:=numberOfCPUs;
end;
{$else}
VAR param:T_arrayOfString;
output: TStringList;
i:longint;
begin
if numberOfCPUs>0 then exit(numberOfCPUs);
param:='-c';
append(param,'nproc');
runCommand('sh',param,output);
result:=-1;
for i:=0 to output.count-1 do if result<0 then result:=strToIntDef(output[i],-1);
if result<=0 then result:=1;
numberOfCPUs:=result;
output.destroy;
end;
{$endif}
FUNCTION getEnvironment: T_arrayOfString;
VAR i:longint;
s:string;
begin
initialize(result);
setLength(result,0);
for i:=1 to GetEnvironmentVariableCount do begin
s:=GetEnvironmentString(i);
if copy(s,1,1)<>'=' then append(result,s);
end;
end;
FUNCTION findDeeply(CONST rootPath, searchPattern: ansistring): ansistring;
PROCEDURE recursePath(CONST path: ansistring);
VAR info: TSearchRec;
FUNCTION deeper:ansistring;
begin
if (pos('?',path)>=0) or (pos('*',path)>=0)
then result:=ExtractFileDir(path)+DirectorySeparator+info.name+DirectorySeparator
else result:=path+info.name+DirectorySeparator;
end;
begin
if (result='') and (findFirst(path+searchPattern, faAnyFile, info) = 0) then result:=path+info.name;
sysutils.findClose(info);
if findFirst(path+'*', faDirectory, info) = 0 then repeat
if ((info.Attr and faDirectory) = faDirectory) and
(info.name<>'.') and
(info.name<>'..')
then recursePath(deeper);
until (findNext(info)<>0) or (result<>'');
sysutils.findClose(info);
end;
begin
result:='';
recursePath(rootPath);
end;
FUNCTION findOne(CONST searchPattern: ansistring): ansistring;
VAR info: TSearchRec;
begin
if findFirst(searchPattern,faAnyFile,info)=0
then result:=info.name
else result:='';
sysutils.findClose(info);
end;
FUNCTION runProcess(CONST Process:TProcess; OUT output: TStringList): boolean;
CONST
READ_BYTES = 2048;
VAR
memStream: TMemoryStream;
n: longint;
BytesRead: longint;
sleepTime: longint = 1;
begin
memStream := TMemoryStream.create;
BytesRead := 0;
Process.options := [poUsePipes, poStderrToOutPut];
Process.ShowWindow := swoHIDE;
try
Process.execute;
Process.CloseInput;
while Process.running do begin
memStream.setSize(BytesRead+READ_BYTES);
n := Process.output.read((memStream.memory+BytesRead)^, READ_BYTES);
if n>0 then begin sleepTime:=1; inc(BytesRead, n); end
else begin inc(sleepTime); sleep(sleepTime); end;
end;
if Process.running then Process.Terminate(999);
repeat
memStream.setSize(BytesRead+READ_BYTES);
n := Process.output.read((memStream.memory+BytesRead)^, READ_BYTES);
if n>0 then inc(BytesRead, n);
until n<=0;
result := (Process.exitStatus = 0);
except
result := false;
end;
memStream.setSize(BytesRead);
output := TStringList.create;
output.loadFromStream(memStream);
memStream.free;
end;
FUNCTION runCommand(CONST executable: ansistring; CONST parameters: T_arrayOfString; OUT output: TStringList): boolean;
VAR tempProcess: TProcess;
n:longint;
begin
tempProcess := TProcess.create(nil);
tempProcess.executable := {$ifdef Windows}UTF8ToWinCP{$endif}(executable);
for n := 0 to length(parameters)-1 do
tempProcess.parameters.add(UTF8ToWinCP(parameters[n]));
tempProcess.options := [poUsePipes, poStderrToOutPut];
tempProcess.ShowWindow := swoHIDE;
result:=runProcess(tempProcess,output);
tempProcess.free;
end;
PROCEDURE runDetachedCommand(CONST executable: ansistring; CONST parameters: T_arrayOfString);
VAR tempProcess: TProcess;
n:longint;
begin
tempProcess := TProcess.create(nil);
tempProcess.executable := {$ifdef Windows}UTF8ToWinCP{$endif}(executable);
for n := 0 to length(parameters)-1 do
tempProcess.parameters.add(UTF8ToWinCP(parameters[n]));
tempProcess.ShowWindow := swoShowNormal;
tempProcess.execute;
tempProcess.free;
end;
FUNCTION myCommandLineParameters: T_arrayOfString;
VAR i:longint;
begin
initialize(result);
setLength(result,paramCount);
for i:=1 to paramCount do result[i-1]:=paramStr(i);
end;
VAR clearConsoleProcess:TProcess=nil;
PROCEDURE clearConsole;
{$ifdef Windows}
CONST origin: COORD=(x:0;y:0);
VAR
hStdOut: handle;
csbi:TCONSOLESCREENBUFFERINFO;
conSize,written: dword;
{$endif}
begin
if FileTruncate(StdOutputHandle,0) then exit;
{$ifdef Windows}
flush(StdOut);
hStdOut:=GetStdHandle(STD_OUTPUT_HANDLE);
if not GetConsoleScreenBufferInfo(hStdOut,csbi) then exit;
conSize:=dword(csbi.dwSize.x)*dword(csbi.dwSize.Y);
if not FillConsoleOutputCharacter(hStdOut,' ',conSize,origin,written) then exit;
if not FillConsoleOutputAttribute(hStdOut,csbi.wAttributes,conSize,origin,written) then exit;
SetConsoleCursorPosition(hStdOut,origin);
{$endif}
{$ifdef LINUX}
if clearConsoleProcess=nil then begin
clearConsoleProcess := TProcess.create(nil);
clearConsoleProcess.options:=clearConsoleProcess.options+[poWaitOnExit];
clearConsoleProcess.executable := 'sh';
clearConsoleProcess.parameters.add('-c');
clearConsoleProcess.parameters.add('clear');
end;
try
flush(StdOut);
clearConsoleProcess.execute;
except end;
{$endif}
end;
FUNCTION containsPlaceholder(CONST S: string): boolean;
begin
result:=(pos('*',s)>0) or (pos('?',s)>0);
end;
FUNCTION findFileInfo(CONST pathOrPattern: string): T_fileInfoArray;
VAR info: TSearchRec;
path: ansistring;
begin
path := extractFilePath(pathOrPattern);
initialize(result);
setLength(result, 0);
if findFirst(pathOrPattern, faAnyFile, info) = 0 then repeat
if (info.name<>'.') and (info.name<>'..') then begin
setLength(result, length(result)+1);
with result[length(result)-1] do begin
filePath:=path+info.name;
try
time:=FileDateToDateTime(info.time);
except
{$ifdef debugMode}
writeln('Could not convert file time to datetime. Value is: ',info.time);
{$endif}
time:=0;
end;
size:=info.size;
attributes:=[aExistent];
if info.Attr and faReadOnly >0 then include(attributes,aReadOnly );
if info.Attr and faDirectory>0 then include(attributes,aDirectory);
if info.Attr and faArchive >0 then include(attributes,aArchive );
{$ifdef Windows}
if info.Attr and faHidden >0 then include(attributes,aHidden );
if info.Attr and faSysFile >0 then include(attributes,aSysFile );
if info.Attr and faSymLink >0 then include(attributes,aSymLink );
{$endif}
end;
end;
until (findNext(info)<>0);
if (length(result)=0) and not(containsPlaceholder(pathOrPattern)) then begin
setLength(result,1);
with result[0] do begin
filePath:=pathOrPattern;
time:=0;
size:=-1;
attributes:=[];
end;
end;
sysutils.findClose(info);
end;
VAR consoleShowing:longint=1;
FUNCTION isConsoleShowing: boolean;
begin
result:={$ifdef Windows}consoleShowing>=1{$else}true{$endif};
end;
FUNCTION showConsole:boolean;
begin
inc(consoleShowing);
if consoleShowing<1 then consoleShowing:=1;
result:=true;
{$ifdef Windows}{$ifndef debugMode}
ShowWindow(GetConsoleWindow, SW_SHOW);
{$endif}{$endif}
end;
FUNCTION hideConsole:boolean;
begin
dec(consoleShowing);
if consoleShowing<=0 then begin
{$ifdef Windows}{$ifndef debugMode}
ShowWindow(GetConsoleWindow, SW_HIDE);
{$endif}{$endif}
if consoleShowing<0 then consoleShowing:=0;
result:=true;
end else result:=false;
end;
FUNCTION isValidFilename(CONST fileName: string; CONST requirePathExistence:boolean=true) : boolean;
CONST ForbiddenChars : set of char = ['<', '>', '|', '"', '\', ':', '*', '?'];
VAR i:integer;
name,path:string;
begin
if requirePathExistence then begin
path:=extractFilePath(fileName);
name:=extractFileName(fileName);
result:=(name<>'') and (DirectoryExists(path));
for i:=1 to length(name)-1 do result:=result and not(name[i] in ForbiddenChars) and not(name[i]='\');
end else begin
name:=fileName;
result:=(fileName<>'');
for i:=1 to length(name)-1 do result:=result and not(name[i] in ForbiddenChars);
end;
end;
FUNCTION dateToSortable(t:TDateTime):ansistring;
begin
DateTimeToString(result,'YYYYMMDD_HHmmss',t);
end;
{$ifdef Windows}
PROCEDURE deleteMyselfOnExit;
VAR handle:text;
batName:string;
counter:longint;
proc:TProcess;
begin
counter:=0;
repeat
batName:=paramStr(0)+'delete'+intToStr(counter)+'.bat';
inc(counter);
until not(fileExists(batName));
assign(handle,batName);
rewrite(handle);
writeln(handle,':Repeat');
writeln(handle,'@ping -n 2 127.0.0.1 > NUL');
writeln(handle,'@del "',paramStr(0),'"');
writeln(handle,'@if exist "',paramStr(0),'" goto Repeat');
writeln(handle,'@del %0');
close(handle);
proc:=TProcess.create(nil);
proc.executable:='cmd';
proc.parameters.add('/C');
proc.parameters.add(batName);
proc.execute;
end;
FUNCTION getTaskInfo: T_taskInfoArray;
CONST
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
VAR
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
tmp : longword;
void : PVOID=nil;
newEntry : T_taskInfo;
begin;
initialize(result);
setLength(result,0);
CoInitialize(void);
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM Win32_Process','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumvariant;
while oEnum.next(1, FWbemObject, tmp) = 0 do
begin
initialize(newEntry);
newEntry.caption := VarToStr(FWbemObject.Properties_.item('Caption').value);
newEntry.pid := FWbemObject.Properties_.item('ProcessId').value;
newEntry.parentPID := FWbemObject.Properties_.item('ParentProcessId').value;
newEntry.workingSetSize:= FWbemObject.Properties_.item('WorkingSetSize').value;
newEntry.userModeTime := FWbemObject.Properties_.item('UserModeTime').value;
newEntry.commandLine := VarToStr(FWbemObject.Properties_.item('CommandLine').value);
setLength(result,length(result)+1);
result[length(result)-1]:=newEntry;
FWbemObject:=Unassigned;
end;
end;
FUNCTION getCPULoadPercentage: longint;
CONST
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
VAR FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
tmp : longword;
void : PVOID=nil;
begin
CoInitialize(void);
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
try
FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE name=''_Total''','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumvariant;
if oEnum.next(1, FWbemObject, tmp) = 0 then begin
result := FWbemObject.Properties_.item('PercentProcessorTime').value;
FWbemObject:=Unassigned;
end else begin
FWbemObjectSet:= FWMIService.ExecQuery('SELECT LoadPercentage FROM Win32_Processor','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumvariant;
if oEnum.next(1, FWbemObject, tmp) = 0 then begin
result := FWbemObject.Properties_.item('LoadPercentage').value;
FWbemObject:=Unassigned;
end else result:=-1;
end;
except
result:=-1;
end;
end;
{$endif}
PROCEDURE writeFile(CONST fileName: string; CONST lines: T_arrayOfString);
VAR handle:text;
i:longint;
begin
assign(handle,fileName);
rewrite(handle);
for i:=0 to length(lines)-1 do writeln(handle,lines[i]);
close(handle);
end;
FUNCTION readFile(CONST fileName: string): T_arrayOfString;
VAR handle:text;
begin
if not(fileExists(fileName)) then exit(C_EMPTY_STRING_ARRAY);
assign(handle,fileName);
reset(handle);
setLength(result,0);
while not(eof(handle)) do begin
setLength(result,length(result)+1);
readln(handle,result[length(result)-1]);
end;
close(handle);
end;
CONSTRUCTOR T_xosPrng.create;
begin
initCriticalSection(criticalSection);
w:=521288629;
x:=0;
y:=0;
z:=362436069;
end;
DESTRUCTOR T_xosPrng.destroy;
begin
doneCriticalSection(criticalSection);
end;
FUNCTION T_xosPrng.XOS:dword;
VAR tmp:dword;
begin
tmp:=(x xor (x<<15));
x:=y;
y:=z;
z:=w;
w:=(w xor (w>>21)) xor (tmp xor(tmp>>4));
result := w;
end;
PROCEDURE T_xosPrng.resetSeed(CONST newSeed:dword);
CONST P:array[0..31] of dword=(102334155, 433494437,3185141890, 695895453,1845853122,4009959909, 887448560,2713352312,
4204349121,1490993585,1919601489,1252772578,1126134829,1407432322,2942850377,1798021602,
2032742589, 663677033, 447430277,1407736169,2048113432,2516238737,2570330033, 510369096,
4127319575,3313982129, 668544240, 976072482,1798380843,3210299713,3471333957,3014961506);
begin
enterCriticalSection(criticalSection);
try
{$Q-}{$R-}
w:=newSeed;
x:=(w xor P[ w and 31]);
y:=(w xor P[(w+1) and 31]);
z:=(w xor P[(w+2) and 31]);
{$Q+}{$R+}
finally
leaveCriticalSection(criticalSection);
end;
end;
PROCEDURE T_xosPrng.resetSeed(CONST s:array of byte);
VAR fullBytes:array[0..15] of byte;
k:longint;
begin
if length(s)=0 then begin
resetSeed(0);
exit;
end;
enterCriticalSection(criticalSection);
try
for k:=0 to 15 do fullBytes[k]:=0;
if length(s)<length(fullBytes)
then for k:=0 to length(fullBytes)-1 do fullBytes[k]:=s[k mod length(s)]
else for k:=0 to length(s)-1 do fullBytes[k mod length(fullBytes)]:=fullBytes[k mod length(fullBytes)] xor s[k];
move(fullBytes[ 0],w,4);
move(fullBytes[ 4],x,4);
move(fullBytes[ 8],y,4);
move(fullBytes[12],z,4);
finally
leaveCriticalSection(criticalSection);
end;
end;
PROCEDURE T_xosPrng.randomize;
begin
resetSeed(GetTickCount64);
end;
FUNCTION T_xosPrng.intRandom(CONST imax:int64):int64;
begin
if imax<=1 then exit(0);
enterCriticalSection(criticalSection);
try
{$Q-}{$R-}
if imax<=4294967296
then result:= XOS mod imax
else result:=(int64(XOS) xor (int64(XOS) shl 31)) mod imax;
{$Q+}{$R+}
finally
leaveCriticalSection(criticalSection);
end;
end;
FUNCTION T_xosPrng.realRandom:double;
begin
enterCriticalSection(criticalSection);
try
result:=XOS*2.3283064365386963E-10;
finally
leaveCriticalSection(criticalSection);
end;
end;
FUNCTION T_xosPrng.dwordRandom:dword;
begin
enterCriticalSection(criticalSection);
try
result:=XOS;
finally
leaveCriticalSection(criticalSection);
end;
end;
PROCEDURE T_memoryCleaner.execute;
CONST MEM_CHECK_KILL_INTERVAL_MS=100;
minCleanupInterval=10/(24*60*60); //=10 seconds
maxSleepMillis ={$ifdef Windows}2000{$else}10000{$endif}; //=2 or 10 seconds
VAR {$ifdef UNIX}
Process:TProcess;
output: TStringList;
i:longint;
tempMem:ptrint;
{$endif}
lastCleanupCall:double=0;
sleepMillis :longint;
cleanupLevel :T_cleanupLevel=0;
relUse :double;
relGrowth :double;
previouslyUsed :ptrint=0;
{$ifdef Windows}
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
workingSetSizeQuery: OLEVariant;
PROCEDURE initializeWMI;
CONST WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
void:PVOID=nil;
begin
try
CoInitialize(void);
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
workingSetSizeQuery:='SELECT WorkingSetSize FROM Win32_Process WHERE ProcessId='+intToStr(GetProcessID);
except
//ignore all exceptions - memory checker is broken if WMI is not accessible
Terminate;
end;
end;
FUNCTION getMyWorkingSetSize:int64;
CONST wbemFlagForwardOnly = $00000020;
VAR FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
tmp : longword;
begin
try
FWbemObjectSet:= FWMIService.ExecQuery(workingSetSizeQuery,'WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumvariant;
if oEnum.next(1, FWbemObject, tmp) = 0 then begin
result := FWbemObject.Properties_.item('WorkingSetSize').value;
FWbemObject:=Unassigned;
end else result:=-1;
except
//ignore all exceptions - memory checker is broken if WMI is not accessible
Terminate;
result:=-1;
end;
end;
{$endif}
begin
{$ifdef Windows}
initializeWMI;
{$endif}
{$ifdef UNIX}
Process:=TProcess.create(nil);
Process.executable:='ps';
Process.parameters.add('o');
Process.parameters.add('rss');
Process.parameters.add('-p');
Process.parameters.add(intToStr(GetProcessID));
{$endif}
threadStartsSleeping; //this one is considered idle
while not(Terminated) do begin
{$ifdef UNIX}
runProcess(Process,output);
tempMem:=-1;
for i:=0 to output.count-1 do if tempMem<0 then tempMem:=StrToInt64Def(trim(output[i]),-1);
if tempMem<0 then MemoryUsed:=GetHeapStatus.TotalAllocated
else MemoryUsed:=tempMem*1024;
output.destroy;
{$endif}
{$ifdef Windows}
MemoryUsed:=getMyWorkingSetSize;
{$endif}
if (MemoryUsed>memoryComfortThreshold) then begin
if (now>lastCleanupCall+minCleanupInterval) then begin
{$ifdef debugMode}
writeln(stdErr,'Memory panic (',MemoryUsed,' | ',MemoryUsed/memoryComfortThreshold*100:0:3,'% used) - calling cleanup methods');
{$endif}
memoryCleaner.callCleanupMethods(cleanupLevel);
if cleanupLevel<high(T_cleanupLevel) then inc(cleanupLevel);
lastCleanupCall:=now;
end;
sleepMillis:=0;
end else begin
cleanupLevel:=0;
relUse := MemoryUsed /memoryComfortThreshold;
relGrowth:=10.0*(MemoryUsed-previouslyUsed)/memoryComfortThreshold;
previouslyUsed:=MemoryUsed;
if relGrowth>relUse then relUse:=relGrowth;
if relUse<0 then relUse:=0 else if (relUse>1) then relUse:=1;
relUse:=1-relUse;
sleepMillis:=round(maxSleepMillis*relUse);
end;
while (sleepMillis>0) and not(Terminated) do begin
ThreadSwitch;
if sleepMillis>MEM_CHECK_KILL_INTERVAL_MS
then sleep(MEM_CHECK_KILL_INTERVAL_MS)
else sleep(sleepMillis);
dec(sleepMillis,MEM_CHECK_KILL_INTERVAL_MS);
end;
end;
{$ifdef UNIX}
Process.destroy;
{$endif}
threadStopsSleeping;
Terminate;
end;
FUNCTION T_memoryCleaner.getMemoryUsedInBytes: int64;
begin
result:=memoryCleaner.MemoryUsed;
end;
FUNCTION T_memoryCleaner.getMemoryUsedAsString(OUT fractionOfThreshold: double): string;
VAR val:ptrint;
begin
fractionOfThreshold:=MemoryUsed/memoryComfortThreshold;
val:=MemoryUsed; if val<8192 then exit(intToStr(val)+' B');
val:=val shr 10; if val<8192 then exit(intToStr(val)+' kB');
val:=val shr 10; if val<8192 then exit(intToStr(val)+' MB');
val:=val shr 10; result:=intToStr(val)+' GB';
end;
FUNCTION T_memoryCleaner.isMemoryInComfortZone: boolean;
begin
result:=MemoryUsed<memoryComfortThreshold;
end;
PROCEDURE finalizeGracefully;
begin
memoryCleaner.Terminate;
if clearConsoleProcess<>nil then clearConsoleProcess.destroy;
while not(memoryCleaner.Finished) do sleep(1);
FreeAndNil(memoryCleaner);
end;
INITIALIZATION
memoryCleaner:=T_memoryCleaner.create;
FINALIZATION
finalizeGracefully;
end.
|
unit SortIntArrayBenchmark2Unit;
{$mode delphi}
interface
uses Windows, BenchmarkClassUnit, Classes, Math;
type
TQuickSortIntArrayThreads = class(TFastcodeMMBenchmark)
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses SysUtils;
type
TSortIntArrayThread = class(TThread)
FBenchmark: TFastcodeMMBenchmark;
procedure Execute; override;
end;
function SortCompareInt(Item1, Item2: Pointer): Integer;
begin
Result := Integer(Item1) - Integer(Item2);
end;
procedure TSortIntArrayThread.Execute;
var
I, J, Size: Integer;
List: TList;
const
MINSIZE : Integer = 500;
MAXSIZE : Integer = 1500;
RepeatCount = 20;
begin
for J := 1 to RepeatCount do
begin
for Size := MINSIZE to MAXSIZE do
begin
List := TList.Create;
try
List.Count := Size;
for I := 0 to Size-1 do
List[I] := Pointer(Random(100));
List.Sort(SortCompareInt);
finally
List.Free;
end;
end;
FBenchmark.UpdateUsageStatistics;
end;
end;
class function TQuickSortIntArrayThreads.GetBenchmarkDescription:
string;
begin
Result := 'A benchmark that measures read and write speed to an array of Integer. '
+ 'Access pattern is created by selection sorting array of random values using the QuickSort algorithm implemented in TList.. '
+ 'Measures memory usage after all blocks have been freed. '
+ 'Benchmark submitted by Avatar Zondertau, based on a benchmark by Dennis Kjaer Christensen.';
end;
class function TQuickSortIntArrayThreads.GetBenchmarkName: string;
begin
Result := 'QuickSortIntegerArrayBenchmark';
end;
class function TQuickSortIntArrayThreads.GetCategory:
TBenchmarkCategory;
begin
Result := bmMemoryAccessSpeed;
end;
class function TQuickSortIntArrayThreads.GetSpeedWeight: Double;
begin
Result := 0.75;
end;
procedure TQuickSortIntArrayThreads.RunBenchmark;
var
SortIntArrayThread : TSortIntArrayThread;
begin
inherited;
SortIntArrayThread := TSortIntArrayThread.Create(True);
SortIntArrayThread.FreeOnTerminate := False;
SortIntArrayThread.FBenchmark := Self;
SortIntArrayThread.Resume;
SortIntArrayThread.WaitFor;
SortIntArrayThread.Free;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.