text stringlengths 14 6.51M |
|---|
unit SessaoUsuario;
interface
uses Classes, Forms, Windows, IniFiles, SysUtils, UsuarioVO, EmpresaVO, EmpresaEnderecoVO,
Biblioteca, md5, VO;
type
TSessaoUsuario = class
private
FUrl: String;
FIdSessao: String;
FCamadas: Integer;
FUsuario: TUsuarioVO;
FEmpresa: TEmpresaVO;
class var FInstance: TSessaoUsuario;
public
constructor Create;
destructor Destroy; override;
class function Instance: TSessaoUsuario;
function AutenticaUsuario(pLogin, pSenha: String): Boolean;
//Permissőes
function Autenticado: Boolean;
property URL: String read FUrl;
property IdSessao: String read FIdSessao;
property Camadas: Integer read FCamadas write FCamadas;
property Usuario: TUsuarioVO read FUsuario;
property Empresa: TEmpresaVO read FEmpresa write FEmpresa;
end;
implementation
uses EmpresaController;
{ TSessaoUsuario }
constructor TSessaoUsuario.Create;
var
Ini: TIniFile;
Servidor: String;
Porta: Integer;
begin
inherited Create;
Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Conexao.ini');
try
with Ini do
begin
if not SectionExists('ServidorApp') then
begin
WriteString('ServidorApp','Servidor','localhost');
WriteInteger('ServidorApp','Porta',8090);
end;
Servidor := ReadString('ServidorApp','Servidor','localhost');
Porta := ReadInteger('ServidorApp','Porta',8090);
Camadas := ReadInteger('ServidorApp', 'Camadas', 2);
end;
finally
Ini.Free;
end;
FUrl := 'http://' + Servidor + ':' + IntToStr(Porta) + '/cgi-bin/servidorT2Ti.cgi/';
end;
destructor TSessaoUsuario.Destroy;
begin
FUsuario.Free;
FEmpresa.Free;
inherited;
end;
class function TSessaoUsuario.Instance: TSessaoUsuario;
begin
if not Assigned(FInstance) then
begin
FInstance := TSessaoUsuario.Create;
FInstance.Empresa := TEmpresaController.ConsultaObjeto('ID=1');
end;
Result := FInstance;
end;
function TSessaoUsuario.Autenticado: Boolean;
begin
Result := Assigned(FUsuario);
end;
function TSessaoUsuario.AutenticaUsuario(pLogin, pSenha: String): Boolean;
var
SenhaCript: String;
begin
FIdSessao := CriaGuidStr;
FIdSessao := MD5Print(MD5String(FIdSessao));
try
//Senha é criptografada com a senha digitada + login
// SenhaCript := TUsuarioController.CriptografarLoginSenha(pLogin,pSenha);
//FUsuario := TUsuarioController.Usuario(pLogin,pSenha);
FUsuario := TUsuarioVO.Create;
FUsuario.Id := 1;
FUsuario.IdColaborador := 1;
FUsuario.Login := pLogin;
FUsuario.Senha := pSenha;
Result := Assigned(FUsuario);
except
Application.MessageBox('Erro ao autenticar usuário.','Erro de Login', MB_OK+MB_ICONERROR);
raise;
end;
end;
end.
|
{
@abstract Implements @link(TNtLanguageDialog) dialog that lets the user to choose a new language.
VCL only.
You don't have to manually create a dialog and call its ShowModal function but
you can use @link(TNtLanguageDialog.Select) function that creates a language dialog,
shows it, and finally turn on the selected language. If you want only to select the
language but not turn it on call @link(TNtLanguageDialog.Choose) function.
Then you have to call @link(TNtTranslator.SetNew) to turn on the language.
By default the dialog shows the language names in native language. So German
will appear as Deutsch. You can change this by passing languageName parameter to
@link(TNtLanguageDialog.Select) or set @link(TNtLanguageDialog.LanguageName).
In order to show the language names in the current language each language name
must be found from the resource string. To add language names into resource
you have to create a .rc file that contains the language names in a string table.
@longCode(#
STRINGTABLE
BEGIN
0x07 "German";
0x09 "English";
0x0c "French";
0x11 "Japanese";
END
#)
The id of each string must match the locale id of the lanugage. Add the .rc
file into the project and recompile. Next time you scan your project the above
strings will appear and you will be able to translate them. If you do not add
the language name strings then dialog shows the language names in the language
of the operating system.
@italic(Library\Delphi\Languages.rc) is a string table resource file that
contains all languages and locales supported by Windows. You can copy paste
those languages that your project uses into your own Languages.rc file.
}
unit NtLanguageDlg;
{$I NtVer.inc}
interface
uses
Classes, Controls, StdCtrls, Forms, NtBase, NtLocalization;
type
// Specifies options for @link(TNtLanguageDialog).
TNtLanguageDialogOption =
(
ldShowErrorIfNoDll, //< Show an error if no resource DLL exists
ldCompatible, //< Show only languages that are compatible to the system. Not used in Delphi 2009 and later.
ldCheckVersion //< Show only languages that are compatible to the current version of the application.
);
// Set of language dialog options.
TNtLanguageDialogOptions = set of TNtLanguageDialogOption;
{ @abstract Dialog that shows the languages of the available resource files.
Dialog shows available languages and lets you choose a new language.
@seealso(NtLanguageDlg) }
TNtLanguageDialog = class(TForm)
LanguageList: TListBox;
OkButton: TButton;
CancelButton: TButton;
procedure FormCreate(sender: TObject);
procedure FormShow(sender: TObject);
procedure LanguageListDblClick(sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FCheckVersion: Boolean;
FCompatible: Boolean;
FLanguageName: TNtLanguageName;
FLanguageNameCase: TNtLanguageNameCase;
FOriginalLanguage: String;
FOriginalLanguageName: String;
function GetLanguage(i: Integer): String;
function GetLanguageCount: Integer;
function GetSelectedLanguage: String;
procedure SetSelectedLanguage(const value: String);
public
{ Shows a dialog that contains a list of available languages. After user
has selected a new language the function turns that language active.
@param languageName Language name kind.
@param dialogOptions Dialog options.
@param languageOptions Language change options.
@param position Initial position of the form.
@param languageNameCase Specifies what case to use in language names.
@return @true on success, @false if cancelled by user. }
class function Select(
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TPosition = poMainFormCenter;
languageNameCase: TNtLanguageNameCase = lcDefault): Boolean; overload;
{ Shows a dialog that contains a list of available languages. After user
has selected a new language the function turns that language active.
@param language Returns the selected language.
@param originalLanguage Language used in the original application. If empty original language is not shown.
@param originalLanguageName Name of the original language. If empty the default name is used.
@param languageName Language name kind.
@param dialogOptions Dialog options.
@param languageOptions Language change options.
@param position Initial position of the form.
@param languageNameCase Specifies what case to use in language names.
@return @true on success, @false if cancelled by user. }
class function Select(
var language: String;
const originalLanguage: String;
const originalLanguageName: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TPosition = poMainFormCenter;
languageNameCase: TNtLanguageNameCase = lcDefault): Boolean; overload;
{ As @link(TNtLanguageDialog.Select) but no language parameter.}
class function Select(
const originalLanguage: String;
const originalLanguageName: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TPosition = poMainFormCenter;
languageNameCase: TNtLanguageNameCase = lcDefault): Boolean; overload;
{ As @link(TNtLanguageDialog.Select) but does not turn on the selected language active.
This function just shows a dialog that let you choose a new language. }
class function Choose(
var language: String;
const originalLanguage: String = '';
const originalLanguageName: String = '';
languageName: TNtLanguageName = lnNative;
options: TNtLanguageDialogOptions = [];
position: TPosition = poMainFormCenter;
languageNameCase: TNtLanguageNameCase = lcDefault): Boolean;
{ If @true the dialog shows only those languages that are compatible to the current version of the application.
If @false all languages are shown. }
property CheckVersion: Boolean read FCheckVersion write FCheckVersion;
{ If @true the dialog shows only those languages that are compatible to the system.
If @false all languages are shown. Not used in Delphi 2009 and later. }
property Compatible: Boolean read FCompatible write FCompatible;
{ The amount of available languages. }
property LanguageCount: Integer read GetLanguageCount;
{ Array of available languages. First language index is 0. }
property Languages[i: Integer]: String read GetLanguage;
{ Original language of the application. }
property OriginalLanguage: String read FOriginalLanguage write FOriginalLanguage;
{ Display name of the oOriginal language of the application. }
property OriginalLanguageName: String read FOriginalLanguageName write FOriginalLanguageName;
{ Language that is currently selected in the dialog. }
property SelectedLanguage: String read GetSelectedLanguage write SetSelectedLanguage;
{ Specifies how language names are shown. }
property LanguageName: TNtLanguageName read FLanguageName write FLanguageName;
{ Specifies what language name case is used. }
property LanguageNameCase: TNtLanguageNameCase read FLanguageNameCase write FLanguageNameCase;
end;
implementation
{$R *.dfm}
uses
SysUtils,
NtTranslator;
type
TLanguageCode = class(TObject)
private
FValue: String;
public
constructor Create(const value: String);
property Value: String read FValue;
end;
constructor TLanguageCode.Create(const value: String);
begin
inherited Create;
FValue := value;
end;
// TNtLanguageDialog
function TNtLanguageDialog.GetLanguageCount: Integer;
begin
Result := LanguageList.Items.Count;
end;
function TNtLanguageDialog.GetLanguage(i: Integer): String;
begin
Result := TLanguageCode(LanguageList.Items.Objects[i]).Value;
end;
function TNtLanguageDialog.GetSelectedLanguage: String;
begin
if LanguageList.ItemIndex >= 0 then
Result := Languages[LanguageList.ItemIndex]
else
Result := '';
end;
procedure TNtLanguageDialog.SetSelectedLanguage(const value: String);
var
i: Integer;
begin
for i := 0 to LanguageCount - 1 do
if Languages[i] = value then
begin
LanguageList.ItemIndex := i;
Break;
end;
end;
class function TNtLanguageDialog.Select(
var language: String;
const originalLanguage: String;
const originalLanguageName: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TPosition;
languageNameCase: TNtLanguageNameCase): Boolean;
begin
Result := Choose(language, originalLanguage, originalLanguageName, languageName, dialogOptions, position, languageNameCase);
if Result then
begin
if language = originalLanguage then
language := '';
Result := TNtTranslator.SetNew(language, languageOptions, originalLanguage);
end;
end;
class function TNtLanguageDialog.Select(
const originalLanguage: String;
const originalLanguageName: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TPosition;
languageNameCase: TNtLanguageNameCase): Boolean;
var
language: String;
begin
Result := Select(
language,
originalLanguage,
originalLanguageName,
languageName,
dialogOptions,
languageOptions,
position,
languageNameCase);
end;
class function TNtLanguageDialog.Select(
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TPosition;
languageNameCase: TNtLanguageNameCase): Boolean;
var
language: String;
begin
Result := Select(
language,
DefaultLocale,
'',
languageName,
dialogOptions,
languageOptions,
position,
languageNameCase);
end;
class function TNtLanguageDialog.Choose(
var language: String;
const originalLanguage: String;
const originalLanguageName: String;
languageName: TNtLanguageName;
options: TNtLanguageDialogOptions;
position: TPosition;
languageNameCase: TNtLanguageNameCase): Boolean;
var
dialog: TNtLanguageDialog;
begin
if ldShowErrorIfNoDll in options then
TNtBase.CheckThatDllsExist;
dialog := TNtLanguageDialog.Create(nil);
try
dialog.CheckVersion := ldCheckVersion in options;
dialog.Compatible := ldCompatible in options;
dialog.CheckVersion := ldCheckVersion in options;
dialog.OriginalLanguage := originalLanguage;
dialog.OriginalLanguageName := originalLanguageName;
dialog.Position := position;
dialog.LanguageName := languageName;
dialog.LanguageNameCase := languageNameCase;
if dialog.ShowModal = mrOk then
begin
language := dialog.SelectedLanguage;
Result := True;
end
else
begin
language := '';
Result := False;
end;
finally
dialog.Free;
end;
end;
procedure TNtLanguageDialog.FormCreate(Sender: TObject);
begin
FCheckVersion := False;
FCompatible := False;
FOriginalLanguage := '';
FLanguageName := lnNative;
FLanguageNameCase := lcDefault;
if roFlipChildren in ResourceOptions then
TNtTranslator.InitializeForm(Self);
end;
procedure TNtLanguageDialog.FormShow(Sender: TObject);
procedure Add(language: TNtLanguage);
begin
if not CheckVersion or TNtResource.DoesLocaleVersionMatch(language.Code) then
LanguageList.Items.AddObject(
language.Names[FLanguageName],
TLanguageCode.Create(language.ActiveCode));
end;
var
i: Integer;
language: TNtLanguage;
availableLanguages: TNtLanguages;
begin
availableLanguages := TNtLanguages.Create;
try
if OriginalLanguage <> '' then
begin
if OriginalLanguageName <> '' then
LanguageList.Items.AddObject(
OriginalLanguageName,
TLanguageCode.Create(OriginalLanguage))
else
availableLanguages.Add(OriginalLanguage);
end;
TNtBase.GetAvailable(availableLanguages, '', FCompatible, FCheckVersion);
for i := 0 to availableLanguages.Count - 1 do
begin
language := availableLanguages[i];
language.LanguageNameCase := FLanguageNameCase;
Add(language);
end;
finally
availableLanguages.Free;
end;
if TNtBase.GetActiveLocale <> '' then
begin
for i := 0 to LanguageCount - 1 do
begin
if SameText(Languages[i], TNtBase.GetActiveLocale) then
begin
LanguageList.ItemIndex := i;
Exit;
end;
end;
end
else
begin
for i := 0 to LanguageCount - 1 do
begin
if SameText(Languages[i], OriginalLanguage) then
begin
LanguageList.ItemIndex := i;
Exit;
end;
end;
end;
if (LanguageList.ItemIndex = -1) and (LanguageList.Items.Count > 0) then
LanguageList.ItemIndex := 0;
end;
procedure TNtLanguageDialog.FormDestroy(Sender: TObject);
var
i: Integer;
begin
for i := 0 to LanguageList.Items.Count - 1 do
TLanguageCode(LanguageList.Items.Objects[i]).Free;
end;
procedure TNtLanguageDialog.LanguageListDblClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
unit Kitto.Ext.SendQR;
{$I Kitto.Defines.inc}
interface
uses
SysUtils, Ext, ExtForm, ExtPascal,
Kitto.Ext.Base, EF.Tree, Kitto.Ext.BorderPanel;
type
TKExtSendQRFormPanel = class(TExtFormFormPanel)
private
FUserName: TExtFormTextField;
FEmailAddress: TExtFormTextField;
FSendButton: TKExtButton;
FStatusBar: TKExtStatusBar;
FAfterSend: TProc;
function GetEnableButtonJS: string;
function GetSubmitJS: string;
protected
procedure InitDefaults; override;
public
property AfterSend: TProc read FAfterSend write FAfterSend;
procedure Display(const AEditWidth: Integer; const AConfig: TEFNode; var ACurrentHeight: Integer);
published
procedure DoSend;
end;
// A send QR panel, suitable for embedding into HTML code.
// requires the ContainerElementId config property to be set,
// otherwise it is not displayed.
TKExtSendQRPanel = class(TKExtPanelControllerBase)
strict protected
procedure DoDisplay; override;
end;
implementation
uses
Math,
ExtPascalUtils,
EF.Classes, EF.Localization, EF.Macros,
Kitto.Types,
Kitto.Ext.Session, Kitto.Ext.Controller;
{ TKExtSendQRPanel }
procedure TKExtSendQRPanel.DoDisplay;
var
LDummyHeight: Integer;
LFormPanel: TKExtSendQRFormPanel;
LFormPanelBodyStyle: string;
LBorderPanelConfigNode: TEFNode;
LBorderPanel: TKExtBorderPanelController;
begin
inherited;
Frame := False;
Border := False;
Layout := lyFit;
Title := Config.GetString('Title');
Width := Config.GetInteger('Width', 600);
Height := Config.GetInteger('Height', 190);
PaddingString := Config.GetString('Padding', '0px');
RenderTo := Config.GetString('ContainerElementId');
//If BorderPanel configuration Node exists, use a BorderPanelController
LBorderPanelConfigNode := Config.FindNode('BorderPanel');
if Assigned(LBorderPanelConfigNode) then
begin
LBorderPanel := TKExtBorderPanelController.CreateAndAddTo(Items);
LBorderPanel.Config.Assign(LBorderPanelConfigNode);
//FBorderPanel.Border := False;
LBorderPanel.Frame := False;
LBorderPanel.View := View;
LBorderPanel.Display;
LFormPanel := TKExtSendQRFormPanel.CreateAndAddTo(LBorderPanel.Items);
LFormPanel.Region := rgCenter;
end
else
LFormPanel := TKExtSendQRFormPanel.CreateAndAddTo(Items);
LFormPanel.LabelWidth := Config.GetInteger('FormPanel/LabelWidth', 150);
LFormPanelBodyStyle := Config.GetString('FormPanel/BodyStyle');
if LFormPanelBodyStyle <> '' then
LFormPanel.BodyStyle := LFormPanelBodyStyle;
LFormPanel.AfterSend :=
procedure
begin
Delete;
NotifyObservers('SendQRDone'); /////////////////////////////////////////////////
NotifyObservers('Closed');
end;
LDummyHeight := 0;
LFormPanel.Display(Config.GetInteger('FormPanel/EditWidth', 200), Config, LDummyHeight);
end;
{ TKExtSendQRFormPanel }
function TKExtSendQRFormPanel.GetEnableButtonJS: string;
begin
Result := Format(
'%0:s.setDisabled((%1:s.getValue() == "") || !Ext.form.VTypes.email(%1:s.getValue()) || (%2:s.getValue() == "") );',
[FSendButton.JSName, FEmailAddress.JSName, FUserName.JSName]);
end;
function TKExtSendQRFormPanel.GetSubmitJS: string;
begin
Result := Format(
// For some reason != does not survive rendering.
'if (e.getKey() == 13 && !(%s.getValue() == "") && !(%s.getValue() == "")) %s.handler.call(%s.scope, %s);',
[FUserName.JSName, FEmailAddress.JSName, FSendButton.JSName, FSendButton.JSName, FSendButton.JSName]);
end;
procedure TKExtSendQRFormPanel.Display(const AEditWidth: Integer; const AConfig: TEFNode;
var ACurrentHeight: Integer);
const
CONTROL_HEIGHT = 30;
function AddFormTextField(const AName, ALabel: string): TExtFormTextField;
begin
Result := TExtFormTextField.CreateAndAddTo(Items);
Result.Name := AName;
Result.FieldLabel := AConfig.GetString('FormPanel/'+AName, ALabel);
Result.AllowBlank := False;
Result.EnableKeyEvents := True;
Result.SelectOnFocus := True;
Result.Width := AEditWidth;
Inc(ACurrentHeight, CONTROL_HEIGHT);
end;
begin
FStatusBar := TKExtStatusBar.Create(Self);
FStatusBar.DefaultText := '';
FStatusBar.BusyText := _('Generating QR code...');
Bbar := FStatusBar;
FSendButton := TKExtButton.CreateAndAddTo(FStatusBar.Items);
FSendButton.SetIconAndScale('email_go', 'medium');
FSendButton.Text := _('Send');
with TExtBoxComponent.CreateAndAddTo(Items) do
Height := 10;
FUserName := AddFormTextField('UserName', _('User Name'));
FEmailAddress := AddFormTextField('EmailAddress', _('Email address'));
FUserName.On('specialkey', JSFunction('field, e', GetSubmitJS));
FEmailAddress.On('specialkey', JSFunction('field, e', GetSubmitJS));
Session.ResponseItems.ExecuteJSCode(Self, Format(
'%s.enableTask = Ext.TaskMgr.start({ ' + sLineBreak +
' run: function() {' + GetEnableButtonJS + '},' + sLineBreak +
' interval: 500});', [JSName]));
On('beforedestroy', JSFunction(Format('Ext.TaskMgr.stop(%s.enableTask);', [JSName])));
FSendButton.Handler := Ajax(DoSend, ['Dummy', FStatusBar.ShowBusy, 'UserName', FUserName.GetValue, 'EmailAddress', FEmailAddress.GetValue]);
FSendButton.Disabled := (FEmailAddress.Value = '') or (FUserName.Value = '');
FUserName.Focus(False, 750);
end;
procedure TKExtSendQRFormPanel.InitDefaults;
begin
inherited;
LabelAlign := laRight;
Border := False;
Frame := False;
AutoScroll := True;
MonitorValid := True;
end;
procedure TKExtSendQRFormPanel.DoSend;
var
LParams: TEFNode;
begin
LParams := TEFNode.Create;
try
LParams.SetString('UserName', Session.Query['UserName']);
LParams.SetString('EmailAddress', Session.Query['EmailAddress']);
try
Session.Config.Authenticator.QRGenerate(LParams);
Session.ShowMessage(emtInfo, _('Send QR code'), _('The QR code for your account was generated and sent to the specified e-mail address.'));
Assert(Assigned(FAfterSend));
FAfterSend();
except
on E: Exception do
begin
FStatusBar.SetErrorStatus(E.Message);
FEmailAddress.Focus(False, 750);
end;
end;
finally
FreeAndNil(LParams);
end;
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('SendQR', TKExtSendQRPanel);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('SendQR');
end.
|
unit UnitOpenGLShadingShader;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpuamd64}
{$define cpux86_64}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$asmmode intel}
{$endif}
{$ifdef cpux86_64}
{$define cpux64}
{$define cpu64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$ifdef cpux64}
{$define cpux86_64}
{$define cpu64}
{$else}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$endif}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$ifdef conditionalexpressions}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$undef HAS_TYPE_UTF8STRING}
{$endif}
{$legacyifend on}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
interface
uses SysUtils,Classes,{$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader;
type TShadingShader=class(TShader)
public
const uboFrameGlobals=0;
uboMaterial=1;
ssboJointMatrices=2;
ssboMorphTargetVertices=3;
ssboNodeMeshPrimitiveMetaData=4;
ssboLightData=5;
{$ifdef PasGLTFUseExternalData}
ssboExternalData=6;
{$endif}
public
uBRDFLUTTexture:glInt;
uNormalShadowMapArrayTexture:glInt;
uCubeMapShadowMapArrayTexture:glInt;
uEnvMapTexture:glInt;
{$if not defined(PasGLTFBindlessTextures)}
uTextures:glInt;
{$ifend}
uEnvMapMaxLevel:glInt;
uShadows:glInt;
constructor Create(const aSkinned,aAlphaTest,aShadowMap:boolean);
destructor Destroy; override;
procedure BindAttributes; override;
procedure BindVariables; override;
end;
implementation
constructor TShadingShader.Create(const aSkinned,aAlphaTest,aShadowMap:boolean);
var f0,f1,f2,f,v:ansistring;
begin
if aSkinned then begin
f0:='layout(std140, binding = '+IntToStr(ssboJointMatrices)+') buffer ssboJointMatrices {'+#13#10+
' mat4 jointMatrices[];'+#13#10+
'};'+#13#10;
f1:=' uint jointMatrixOffset = primitiveMetaData.y;'+#13#10+
' mat4 inverseMatrix = inverse(nodeMatrix);'+#13#10+
' mat4 skinMatrix = ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints0.x)]) * aWeights0.x) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints0.y)]) * aWeights0.y) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints0.z)]) * aWeights0.z) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints0.w)]) * aWeights0.w);'+#13#10+
' if(any(not(equal(aWeights1, vec4(0.0))))){'+#13#10+
' skinMatrix += ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints1.x)]) * aWeights1.x) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints1.y)]) * aWeights1.y) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints1.z)]) * aWeights1.z) +'+#13#10+
' ((inverseMatrix * jointMatrices[jointMatrixOffset + uint(aJoints1.w)]) * aWeights1.w);'+#13#10+
' }'+#13#10;
f2:=' * skinMatrix';
end else begin
f0:='';
f1:='';
f2:='';
end;
v:='#version 430'+#13#10+
'layout(location = 0) in vec3 aPosition;'+#13#10+
'layout(location = 1) in vec3 aNormal;'+#13#10+
'layout(location = 2) in vec4 aTangent;'+#13#10+
'layout(location = 3) in vec2 aTexCoord0;'+#13#10+
'layout(location = 4) in vec2 aTexCoord1;'+#13#10+
'layout(location = 5) in vec4 aColor0;'+#13#10+
'layout(location = 6) in uvec4 aJoints0;'+#13#10+
'layout(location = 7) in uvec4 aJoints1;'+#13#10+
'layout(location = 8) in vec4 aWeights0;'+#13#10+
'layout(location = 9) in vec4 aWeights1;'+#13#10+
'layout(location = 10) in uint aVertexIndex;'+#13#10+
'out vec3 vWorldSpacePosition;'+#13#10;
if not aShadowMap then begin
v:=v+'out vec3 vCameraRelativePosition;'+#13#10;
end;
v:=v+
'out vec2 vTexCoord0;'+#13#10+
'out vec2 vTexCoord1;'+#13#10+
'out vec3 vNormal;'+#13#10+
'out vec3 vTangent;'+#13#10+
'out vec3 vBitangent;'+#13#10+
'out vec4 vColor;'+#13#10+
'layout(std140, binding = '+IntToStr(uboFrameGlobals)+') uniform uboFrameGlobals {'+#13#10+
' mat4 inverseViewMatrix;'+#13#10+
' mat4 modelMatrix;'+#13#10+
' mat4 viewProjectionMatrix;'+#13#10+
' mat4 normalMatrix;'+#13#10+
'} uFrameGlobals;'+#13#10+
'struct MorphTargetVertex {'+#13#10+
' vec4 position;'+#13#10+
' vec4 normal;'+#13#10+
' vec4 tangent;'+#13#10+
' vec4 reversed;'+#13#10+
'};'+#13#10+
'layout(std430, binding = '+IntToStr(ssboMorphTargetVertices)+') buffer ssboMorphTargetVertices {'+#13#10+
' MorphTargetVertex morphTargetVertices[];'+#13#10+
'};'+#13#10+
'layout(std430, binding = '+IntToStr(ssboNodeMeshPrimitiveMetaData)+') buffer ssboNodeMeshPrimitiveMetaData {'+#13#10+
' mat4 nodeMatrix;'+#13#10+
' uvec4 primitiveMetaData;'+#13#10+
' float morphTargetWeights[];'+#13#10+
'};'+#13#10+
{$ifdef PasGLTFUseExternalData}
'layout(std430, binding = '+IntToStr(ssboExternalData)+') buffer ssboExternalData {'+#13#10+
' mat4 externalModelMatrix;'+#13#10+
'};'+#13#10+
{$endif}
f0+
'void main(){'+#13#10+
f1+
' vec3 position = aPosition,'+#13#10+
' normal = aNormal,'+#13#10+
' tangent = aTangent.xyz;'+#13#10+
' for(uint index = 0, count = primitiveMetaData.w; index < count; index++){'+#13#10+
' float morphTargetWeight = morphTargetWeights[index];'+#13#10+
' uint morphTargetVertexIndex = (index * primitiveMetaData.z) + uint(aVertexIndex);'+#13#10+
' position += morphTargetVertices[morphTargetVertexIndex].position.xyz * morphTargetWeight;'+#13#10+
' normal += morphTargetVertices[morphTargetVertexIndex].normal.xyz * morphTargetWeight;'+#13#10+
' tangent += morphTargetVertices[morphTargetVertexIndex].tangent.xyz * morphTargetWeight;'+#13#10+
' }'+#13#10+
' mat4 modelMatrix = uFrameGlobals.modelMatrix * nodeMatrix'+f2+';'+#13#10+
{$ifdef PasGLTFUseExternalData}
' modelMatrix = externalModelMatrix * modelMatrix;'+#13#10+
{$endif}
' mat3 normalMatrix = transpose(inverse(mat3(modelMatrix)));'+#13#10+
' vNormal = normalize(normalMatrix * normal);'+#13#10+
' vTangent = normalize(normalMatrix * tangent);'+#13#10+
' vBitangent = cross(vNormal, vTangent) * aTangent.w;'+#13#10+
' vTexCoord0 = aTexCoord0;'+#13#10+
' vTexCoord1 = aTexCoord1;'+#13#10+
' vColor = aColor0;'+#13#10+
' vec4 worldSpacePosition = modelMatrix * vec4(position, 1.0);'+#13#10+
' vWorldSpacePosition = worldSpacePosition.xyz / worldSpacePosition.w;'+#13#10;
if not aShadowMap then begin
v:=v+' vCameraRelativePosition = (worldSpacePosition.xyz / worldSpacePosition.w) - uFrameGlobals.inverseViewMatrix[3].xyz;'+#13#10;
end;
v:=v+
' gl_Position = uFrameGlobals.viewProjectionMatrix * worldSpacePosition;'+#13#10+
'}'+#13#10;
f:='#version 430'+#13#10+
{$ifdef PasGLTFBindlessTextures}
'#extension GL_ARB_bindless_texture : require'+#13#10+
{$endif}
'layout(location = 0) out vec4 oOutput;'+#13#10+
{$ifdef PasGLTFExtraEmissionOutput}
'layout(location = 1) out vec4 oEmission;'+#13#10+
{$endif}
'in vec3 vWorldSpacePosition;'+#13#10;
if aShadowMap then begin
end else begin
f:=f+'in vec3 vCameraRelativePosition;'+#13#10;
end;
f:=f+
'in vec2 vTexCoord0;'+#13#10+
'in vec2 vTexCoord1;'+#13#10+
'in vec3 vNormal;'+#13#10+
'in vec3 vTangent;'+#13#10+
'in vec3 vBitangent;'+#13#10+
'in vec4 vColor;'+#13#10+
'uniform sampler2D uBRDFLUTTexture;'+#13#10+
'uniform samplerCube uEnvMapTexture;'+#13#10+
'uniform sampler2DArray uNormalShadowMapArrayTexture;'+#13#10+
'uniform samplerCubeArray uCubeMapShadowMapArrayTexture;'+#13#10+
'uniform sampler2D uTextures[16];'+#13#10+
'uniform int uEnvMapMaxLevel;'+#13#10+
'uniform int uShadows;'+#13#10+
'layout(std140, binding = '+IntToStr(uboFrameGlobals)+') uniform uboFrameGlobals {'+#13#10+
' mat4 inverseViewMatrix;'+#13#10+
' mat4 modelMatrix;'+#13#10+
' mat4 viewProjectionMatrix;'+#13#10+
' mat4 normalMatrix;'+#13#10+
'} uFrameGlobals;'+#13#10+
'layout(std140, binding = '+IntToStr(uboMaterial)+') uniform uboMaterial {'+#13#10+
' vec4 baseColorFactor;'+#13#10+
' vec4 specularFactor;'+#13#10+
' vec4 emissiveFactor;'+#13#10+
' vec4 metallicRoughnessNormalScaleOcclusionStrengthFactor;'+#13#10+
' vec4 sheenColorFactorSheenIntensityFactor;'+#13#10+
' vec4 clearcoatFactorClearcoatRoughnessFactor;'+#13#10+
' uvec4 alphaCutOffFlagsTex0Tex1;'+#13#10+
' mat4 textureTransforms[16];'+#13#10+
{$if defined(PasGLTFBindlessTextures)}
' uvec4 textureHandles[8];'+#13#10+
{$elseif defined(PasGLTFIndicatedTextures) and not defined(PasGLTFBindlessTextures)}
' ivec4 textureIndices[4];'+#13#10+
{$ifend}
'} uMaterial;'+#13#10+
'struct Light {'+#13#10+
' uvec4 metaData;'+#13#10+
' vec4 colorIntensity;'+#13#10+
' vec4 positionRange;'+#13#10+
' vec4 directionZFar;'+#13#10+
' mat4 shadowMapMatrix;'+#13#10+
'};'+#13#10+
'layout(std430, binding = '+IntToStr(ssboLightData)+') buffer ssboLightData {'+#13#10+
' uvec4 lightMetaData;'+#13#10+
' Light lights[];'+#13#10+
'};'+#13#10+
'vec3 convertLinearRGBToSRGB(vec3 c){'+#13#10+
' return mix((pow(c, vec3(1.0 / 2.4)) * vec3(1.055)) - vec3(5.5e-2),'+#13#10+
' c * vec3(12.92),'+#13#10+
' lessThan(c, vec3(3.1308e-3)));'+#13#10+
'}'+#13#10+
'vec3 convertSRGBToLinearRGB(vec3 c){'+#13#10+
' return mix(pow((c + vec3(5.5e-2)) / vec3(1.055), vec3(2.4)),'+#13#10+
' c / vec3(12.92),'+#13#10+
' lessThan(c, vec3(4.045e-2)));'+#13#10+
'}'+#13#10+
'const float PI = 3.14159265358979323846,'+#13#10+
' PI2 = 6.283185307179586476925286766559,'+#13#10+
' OneOverPI = 1.0 / PI;'+#13#10+
'float sheenRoughness, cavity, transparency, refractiveAngle, ambientOcclusion,'+#13#10+
' shadow, reflectance, clearcoatFactor, clearcoatRoughness;'+#13#10+
'vec4 sheenColorIntensityFactor;'+#13#10+
'vec3 clearcoatF0, clearcoatNormal, imageLightBasedLightDirection;'+#13#10+
'uint flags, shadingModel;'+#13#10+
'vec3 diffuseLambert(vec3 diffuseColor){'+#13#10+
' return diffuseColor * OneOverPI;'+#13#10+
'}'+#13#10+
'vec3 diffuseFunction(vec3 diffuseColor, float roughness, float nDotV, float nDotL, float vDotH){'+#13#10+
' float FD90 = 0.5 + (2.0 * (vDotH * vDotH * roughness)),'+#13#10+
' FdV = 1.0 + ((FD90 - 1.0) * pow(1.0 - nDotV, 5.0)),'+#13#10+
' FdL = 1.0 + ((FD90 - 1.0) * pow(1.0 - nDotL, 5.0));'+#13#10+
' return diffuseColor * (OneOverPI * FdV * FdL);'+#13#10+
'}'+#13#10+
'vec3 specularF(const in vec3 specularColor, const in float vDotH){'+#13#10+
' float fc = pow(1.0 - vDotH, 5.0);'+#13#10+
' return vec3(clamp(max(max(specularColor.x, specularColor.y), specularColor.z) * 50.0, 0.0, 1.0) * fc) + ((1.0 - fc) * specularColor);'+#13#10+
'}'+#13#10+
'float specularD(const in float roughness, const in float nDotH){'+#13#10+
' float a = roughness * roughness;'+#13#10+
' float a2 = a * a;'+#13#10+
' float d = (((nDotH * a2) - nDotH) * nDotH) + 1.0;'+#13#10+
' return a2 / (PI * (d * d));'+#13#10+
'}'+#13#10+
'float specularG(const in float roughness, const in float nDotV, const in float nDotL){'+#13#10+
' float k = (roughness * roughness) * 0.5;'+#13#10+
' vec2 GVL = (vec2(nDotV, nDotL) * (1.0 - k)) + vec2(k);'+#13#10+
' return 0.25 / (GVL.x * GVL.y);'+#13#10+
'}'+#13#10+
'float visibilityNeubelt(float NdotL, float NdotV){'+#13#10+
' return clamp(1.0 / (4.0 * ((NdotL + NdotV) - (NdotL * NdotV))), 0.0, 1.0);'+#13#10+
'}'+#13#10+
'float sheenDistributionCarlie(float sheenRoughness, float NdotH){'+#13#10+
' float invR = 1.0 / (sheenRoughness * sheenRoughness);'+#13#10+
' return (2.0 + invR) * pow(1.0 - (NdotH * NdotH), invR * 0.5) / PI2;'+#13#10+
'}'+#13#10+
'vec3 diffuseOutput, specularOutput, sheenOutput, clearcoatOutput, clearcoatBlendFactor;'+#13#10+
'void doSingleLight(const in vec3 lightColor,'+#13#10+
' const in vec3 lightLit,'+#13#10+
' const in vec3 lightDirection,'+#13#10+
' const in vec3 normal,'+#13#10+
' const in vec3 diffuseColor,'+#13#10+
' const in vec3 specularColor,'+#13#10+
' const in vec3 viewDirection,'+#13#10+
' const in float refractiveAngle,'+#13#10+
' const in float materialTransparency,'+#13#10+
' const in float materialRoughness,'+#13#10+
' const in float materialCavity){'+#13#10+
' vec3 halfVector = normalize(viewDirection + lightDirection);'+#13#10+
' float nDotL = clamp(dot(normal, lightDirection), 1e-5, 1.0);'+#13#10+
' float nDotV = clamp(abs(dot(normal, viewDirection)) + 1e-5, 0.0, 1.0);'+#13#10+
' float nDotH = clamp(dot(normal, halfVector), 0.0, 1.0);'+#13#10+
' float vDotH = clamp(dot(viewDirection, halfVector), 0.0, 1.0);'+#13#10+
' vec3 lit = vec3((materialCavity * nDotL * lightColor) * lightLit);'+#13#10+
' diffuseOutput += diffuseFunction(diffuseColor, materialRoughness, nDotV, nDotL, vDotH) * (1.0 - materialTransparency) * lit;'+#13#10+
' specularOutput += specularF(specularColor, max(vDotH, refractiveAngle)) *'+#13#10+
' specularD(materialRoughness, nDotH) *'+#13#10+
' specularG(materialRoughness, nDotV, nDotL) *'+#13#10+
' lit;'+#13#10+
' if((flags & (1u << 6u)) != 0u){'+#13#10+
' float sheenDistribution = sheenDistributionCarlie(sheenRoughness, nDotH);'+#13#10+
' float sheenVisibility = visibilityNeubelt(nDotL, nDotV);'+#13#10+
' sheenOutput += (sheenColorIntensityFactor.xyz * sheenColorIntensityFactor.w * sheenDistribution * sheenVisibility * PI) * lit;'+#13#10+
' }'+#13#10+
' if((flags & (1u << 7u)) != 0u){'+#13#10+
' float nDotL = clamp(dot(clearcoatNormal, lightDirection), 1e-5, 1.0);'+#13#10+
' float nDotV = clamp(abs(dot(clearcoatNormal, viewDirection)) + 1e-5, 0.0, 1.0);'+#13#10+
' float nDotH = clamp(dot(clearcoatNormal, halfVector), 0.0, 1.0);'+#13#10+
' vec3 lit = vec3((materialCavity * nDotL * lightColor) * lightLit);'+#13#10+
' clearcoatOutput += specularF(clearcoatF0, max(vDotH, refractiveAngle)) *'+#13#10+
' specularD(clearcoatRoughness, nDotH) *'+#13#10+
' specularG(clearcoatRoughness, nDotV, nDotL) *'+#13#10+
' lit;'+#13#10+
' }'+#13#10+
'}'+#13#10+
'vec4 getEnvMap(sampler2D texEnvMap, float texLOD, vec3 rayDirection){'+#13#10+
' rayDirection = normalize(rayDirection);'+#13#10+
' return textureLod(texEnvMap, (vec2((atan(rayDirection.z, rayDirection.x) / PI2) + 0.5, acos(rayDirection.y) / 3.1415926535897932384626433832795)), texLOD);'+#13#10+
'}'+#13#10+
'vec3 getDiffuseImageBasedLight(const in vec3 normal, const in vec3 diffuseColor){'+#13#10+
' float ao = cavity * ambientOcclusion;'+#13#10+
' return (textureLod(uEnvMapTexture, normal.xyz, float(uEnvMapMaxLevel)).xyz * diffuseColor * ao) * OneOverPI;'+#13#10+
'}'+#13#10+
'vec3 getSpecularImageBasedLight(const in vec3 normal, const in vec3 specularColor, const in float roughness, const in vec3 viewDirection, const in float litIntensity){'+#13#10+
' vec3 reflectionVector = normalize(reflect(viewDirection, normal.xyz));'+#13#10+
' float NdotV = clamp(abs(dot(normal.xyz, viewDirection)) + 1e-5, 0.0, 1.0),'+#13#10+
' ao = cavity * ambientOcclusion,'+#13#10+
' lit = mix(1.0, litIntensity, max(0.0, dot(reflectionVector, -imageLightBasedLightDirection) * (1.0 - (roughness * roughness)))),'+#13#10+
' specularOcclusion = clamp((pow(NdotV + (ao * lit), roughness * roughness) - 1.0) + (ao * lit), 0.0, 1.0);'+#13#10+
' vec2 brdf = textureLod(uBRDFLUTTexture, vec2(roughness, NdotV), 0.0).xy;'+#13#10+
' return (textureLod(uEnvMapTexture, reflectionVector,'+' clamp((float(uEnvMapMaxLevel) - 1.0) - (1.0 - (1.2 * log2(roughness))), 0.0, float(uEnvMapMaxLevel))).xyz * ((specularColor.xyz * brdf.x) +'+' (brdf.yyy * clamp(max(max(specularColor.x, specularColor.y), specularColor.z) * 50.0, 0.0, 1.0))) * specularOcclusion) * OneOverPI;'+#13#10+
'}'+#13#10+
'float computeMSM(in vec4 moments, in float fragmentDepth, in float depthBias, in float momentBias){'+#13#10+
' vec4 b = mix(moments, vec4(0.5), momentBias);'+#13#10+
' vec3 z;'+#13#10+
' z[0] = fragmentDepth - depthBias;'+#13#10+
' float L32D22 = fma(-b[0], b[1], b[2]);'+#13#10+
' float D22 = fma(-b[0], b[0], b[1]);'+#13#10+
' float squaredDepthVariance = fma(-b[1], b[1], b[3]);'+#13#10+
' float D33D22 = dot(vec2(squaredDepthVariance, -L32D22), vec2(D22, L32D22));'+#13#10+
' float InvD22 = 1.0 / D22;'+#13#10+
' float L32 = L32D22 * InvD22;'+#13#10+
' vec3 c = vec3(1.0, z[0], z[0] * z[0]);'+#13#10+
' c[1] -= b.x;'+#13#10+
' c[2] -= b.y + (L32 * c[1]);'+#13#10+
' c[1] *= InvD22;'+#13#10+
' c[2] *= D22 / D33D22;'+#13#10+
' c[1] -= L32 * c[2];'+#13#10+
' c[0] -= dot(c.yz, b.xy);'+#13#10+
' float InvC2 = 1.0 / c[2];'+#13#10+
' float p = c[1] * InvC2;'+#13#10+
' float q = c[0] * InvC2;'+#13#10+
' float D = (p * p * 0.25) - q;'+#13#10+
' float r = sqrt(D);'+#13#10+
' z[1] = (p * -0.5) - r;'+#13#10+
' z[2] = (p * -0.5) + r;'+#13#10+
' vec4 switchVal = (z[2] < z[0]) ? vec4(z[1], z[0], 1.0, 1.0) :'+#13#10+
' ((z[1] < z[0]) ? vec4(z[0], z[1], 0.0, 1.0) :'+#13#10+
' vec4(0.0));'+#13#10+
' float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1])/((z[2] - switchVal[1]) * (z[0] - z[1]));'+#13#10+
' return clamp((switchVal[2] + (switchVal[3] * quotient)), 0.0, 1.0);'+#13#10+
'}'+#13#10+
'vec2 getShadowOffsets(const in vec3 p, const in vec3 N, const in vec3 L){'+#13#10+
' float cos_alpha = clamp(dot(N, L), 0.0, 1.0);'+#13#10+
' float offset_scale_N = sqrt(1.0 - (cos_alpha * cos_alpha));'+#13#10+ // sin(acos(L?N))
' float offset_scale_L = offset_scale_N / cos_alpha;'+#13#10+ // tan(acos(L?N))
' return (vec2(offset_scale_N, min(2.0, offset_scale_L)) * vec2(0.0002, 0.00005)) + vec2(0.0, 0.0);'+#13#10+
'}'+#13#10+
'float linearStep(float a, float b, float v){'+#13#10+
' return clamp((v - a) / (b - a), 0.0, 1.0);'+#13#10+
'}'+#13#10+
'float reduceLightBleeding(float pMax, float amount){'+#13#10+
' return linearStep(amount, 1.0, pMax);'+#13#10+
'}'+#13#10+
'float getMSMShadowIntensity(vec4 moments, float depth, float depthBias, float momentBias){'+#13#10+
' vec4 b = mix(moments, vec4(0.5), momentBias);'+#13#10+
' float d = depth - depthBias,'+#13#10+
' l32d22 = fma(-b.x, b.y, b.z),'+#13#10+
' d22 = fma(-b.x, b.x, b.y),'+#13#10+
' squaredDepthVariance = fma(-b.y, b.y, b.w),'+#13#10+
' d33d22 = dot(vec2(squaredDepthVariance, -l32d22), vec2(d22, l32d22)),'+#13#10+
' invD22 = 1.0 / d22,'+#13#10+
' l32 = l32d22 * invD22;'+#13#10+
' vec3 c = vec3(1.0, d - b.x, d * d);'+#13#10+
' c.z -= b.y + (l32 * c.y);'+#13#10+
' c.yz *= vec2(invD22, d22 / d33d22);'+#13#10+
' c.y -= l32 * c.z;'+#13#10+
' c.x -= dot(c.yz, b.xy);'+#13#10+
' vec2 pq = c.yx / c.z;'+#13#10+
' vec3 z = vec3(d, vec2(-(pq.x * 0.5)) + (vec2(-1.0, 1.0) * sqrt(((pq.x * pq.x) * 0.25) - pq.y)));'+#13#10+
' vec4 s = (z.z < z.x)'+#13#10+
' ? vec3(z.y, z.x, 1.0).xyzz'+#13#10+
' : ((z.y < z.x)'+#13#10+
' ? vec4(z.x, z.y, 0.0, 1.0)'+#13#10+
' : vec4(0.0));'+#13#10+
' return clamp((s.z + (s.w * ((((s.x * z.z) - (b.x * (s.x + z.z))) + b.y) / ((z.z - s.y) * (z.x - z.y))))) * 1.03, 0.0, 1.0);'+#13#10+
'}'+#13#10+
'const uint smPBRMetallicRoughness = 0u,'+#13#10+
' smPBRSpecularGlossiness = 1u,'+#13#10+
' smUnlit = 2u;'+#13#10+
'uvec2 texCoordIndices = uMaterial.alphaCutOffFlagsTex0Tex1.zw;'+#13#10+
'vec2 texCoords[2] = vec2[2](vTexCoord0, vTexCoord1);'+#13#10+
'vec4 textureFetch(const in int textureIndex, const in vec4 defaultValue){'+#13#10+
' uint which = (texCoordIndices[textureIndex >> 3] >> ((uint(textureIndex) & 7u) << 2u)) & 0xfu;'+#13#10+
{$if defined(PasGLTFBindlessTextures)}
' uvec4 textureHandleContainer = uMaterial.textureHandles[textureIndex >> 1];'+#13#10+
' int textureHandleBaseIndex = (textureIndex & 1) << 1;'+#13#10+
' uvec2 textureHandleUVec2 = uvec2(textureHandleContainer[textureHandleBaseIndex], textureHandleContainer[textureHandleBaseIndex + 1]);'+#13#10+
' return (which < 0x2u) ? texture(sampler2D(textureHandleUVec2), (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy) : defaultValue;'+#13#10+
{$elseif defined(PasGLTFIndicatedTextures) and not defined(PasGLTFBindlessTextures)}
' return (which < 0x2u) ? texture(uTextures[uMaterial.textureIndices[textureIndex >> 2][textureIndex & 3]], (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy) : defaultValue;'+#13#10+
{$else}
' return (which < 0x2u) ? texture(uTextures[textureIndex], (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy) : defaultValue;'+#13#10+
{$ifend}
'}'+#13#10+
'vec4 textureFetchSRGB(const in int textureIndex, const in vec4 defaultValue){'+#13#10+
' uint which = (texCoordIndices[textureIndex >> 3] >> ((uint(textureIndex) & 7u) << 2u)) & 0xfu;'+#13#10+
' vec4 texel;'+#13#10+
' if(which < 0x2u){'+#13#10+
{$if defined(PasGLTFBindlessTextures)}
' uvec4 textureHandleContainer = uMaterial.textureHandles[textureIndex >> 1];'+#13#10+
' int textureHandleBaseIndex = (textureIndex & 1) << 1;'+#13#10+
' uvec2 textureHandleUVec2 = uvec2(textureHandleContainer[textureHandleBaseIndex], textureHandleContainer[textureHandleBaseIndex + 1]);'+#13#10+
' texel = texture(sampler2D(textureHandleUVec2), (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy);'+#13#10+
{$elseif defined(PasGLTFIndicatedTextures) and not defined(PasGLTFBindlessTextures)}
' texel = texture(uTextures[uMaterial.textureIndices[textureIndex >> 2][textureIndex & 3]], (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy);'+#13#10+
{$else}
' texel = texture(uTextures[textureIndex], (uMaterial.textureTransforms[textureIndex] * vec3(texCoords[int(which)], 1.0).xyzz).xy);'+#13#10+
{$ifend}
' texel.xyz = convertSRGBToLinearRGB(texel.xyz);'+#13#10+
' }else{'+#13#10+
' texel = defaultValue;'+#13#10+
' }'+#13#10+
' return texel;'+#13#10+
'}'+#13#10+
'void main(){'+#13#10+
' flags = uMaterial.alphaCutOffFlagsTex0Tex1.y;'+#13#10+
' shadingModel = (flags >> 0u) & 0xfu;'+#13#10;
if aShadowMap then begin
f:=f+
' vec4 t = uFrameGlobals.viewProjectionMatrix * vec4(vWorldSpacePosition, 1.0);'+#13#10+
' float d = fma(t.z / t.w, 0.5, 0.5);'+#13#10+
' float s = d * d;'+#13#10+
' vec4 m = vec4(d, s, s * d, s * s);'+#13#10+
' oOutput = m;'+#13#10+
' float alpha = textureFetch(0, vec4(1.0)).w * uMaterial.baseColorFactor.w * vColor.w;'+#13#10;
end else begin
f:=f+' vec4 color = vec4(0.0);'+#13#10;
{$ifdef PasGLTFExtraEmissionOutput}
f:=f+' vec4 emissionColor = vec4(0.0);'+#13#10;
{$endif}
f:=f+
' float litIntensity = 1.0;'+#13#10+
' switch(shadingModel){'+#13#10+
' case smPBRMetallicRoughness:'+#13#10+
' case smPBRSpecularGlossiness:{'+#13#10+
' vec4 diffuseColorAlpha, specularColorRoughness;'+#13#10+
' switch(shadingModel){'+#13#10+
' case smPBRMetallicRoughness:{'+#13#10+
' const vec3 f0 = vec3(0.04);'+#13#10+ // dielectricSpecular
' vec4 baseColor = textureFetchSRGB(0, vec4(1.0)) *'+#13#10+
' uMaterial.baseColorFactor;'+#13#10+
' vec2 metallicRoughness = clamp(textureFetch(1, vec4(1.0)).zy *'+#13#10+
' uMaterial.metallicRoughnessNormalScaleOcclusionStrengthFactor.xy,'+#13#10+
' vec2(0.0, 1e-3),'+#13#10+
' vec2(1.0));'+#13#10+
' diffuseColorAlpha = vec4((baseColor.xyz * (vec3(1.0) - f0) * (1.0 - metallicRoughness.x)) * PI,'+#13#10+
' baseColor.w);'+#13#10+
' specularColorRoughness = vec4(mix(f0, baseColor.xyz, metallicRoughness.x) * PI,'+#13#10+
' metallicRoughness.y);'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' case smPBRSpecularGlossiness:{'+#13#10+
' vec4 specularGlossiness = textureFetchSRGB(1, vec4(1.0)) *'+#13#10+
' vec4(uMaterial.specularFactor.xyz,'+#13#10+
' uMaterial.metallicRoughnessNormalScaleOcclusionStrengthFactor.y);'+#13#10+
' diffuseColorAlpha = textureFetchSRGB(0, vec4(1.0)) *'+#13#10+
' uMaterial.baseColorFactor *'+#13#10+
' vec2((1.0 - max(max(specularGlossiness.x,'+#13#10+
' specularGlossiness.y),'+#13#10+
' specularGlossiness.z)) * PI,'+#13#10+
' 1.0).xxxy;'+#13#10+
' specularColorRoughness = vec4(specularGlossiness.xyz * PI,'+#13#10+
' clamp(1.0 - specularGlossiness.w, 1e-3, 1.0));'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' vec3 normal;'+#13#10+
' if((texCoordIndices.x & 0x00000f00u) != 0x00000f00u){'+#13#10+
' vec4 normalTexture = textureFetch(2, vec2(0.0, 1.0).xxyx);'+#13#10+
' normal = normalize(mat3(normalize(vTangent), normalize(vBitangent), normalize(vNormal)) * normalize((normalTexture.xyz - vec3(0.5)) * (vec2(uMaterial.metallicRoughnessNormalScaleOcclusionStrengthFactor.z, 1.0).xxy * 2.0)));'+#13#10+
' }else{'+#13#10+
' normal = normalize(vNormal);'+#13#10+
' }'+#13#10+
' normal *= (((flags & (1u << 5u)) != 0u) && !gl_FrontFacing) ? -1.0 : 1.0;'+#13#10+
' vec4 occlusionTexture = textureFetch(3, vec4(1.0));'+#13#10+
' vec4 emissiveTexture = textureFetchSRGB(4, vec4(1.0)); '+#13#10+
' cavity = clamp(mix(1.0, occlusionTexture.x, uMaterial.metallicRoughnessNormalScaleOcclusionStrengthFactor.w), 0.0, 1.0);'+#13#10+
' transparency = 0.0;'+#13#10+
' refractiveAngle = 0.0;'+#13#10+
' ambientOcclusion = 1.0;'+#13#10+
' shadow = 1.0;'+#13#10+
' reflectance = max(max(specularColorRoughness.x, specularColorRoughness.y), specularColorRoughness.z);'+#13#10+
' vec3 viewDirection = normalize(vCameraRelativePosition);'+#13#10+
' imageLightBasedLightDirection = (lightMetaData.x != 0u) ? lights[0].directionZFar.xyz : vec3(0.0, 0.0, -1.0);'+#13#10+
' diffuseOutput = specularOutput = sheenOutput = clearcoatOutput = vec3(0.0);'+#13#10+
' if((flags & (1u << 6u)) != 0u){'+#13#10+
' sheenColorIntensityFactor = uMaterial.sheenColorFactorSheenIntensityFactor;'+#13#10+
' if((texCoordIndices.x & 0x00f00000u) != 0x00f00000u){'+#13#10+
' sheenColorIntensityFactor *= textureFetchSRGB(5, vec4(1.0));'+#13#10+
' }'+#13#10+
' sheenRoughness = max(specularColorRoughness.w, 1e-7);'+#13#10+
' }'+#13#10+
' if((flags & (1u << 7u)) != 0u){'+#13#10+
' clearcoatFactor = uMaterial.clearcoatFactorClearcoatRoughnessFactor.x;'+#13#10+
' clearcoatRoughness = uMaterial.clearcoatFactorClearcoatRoughnessFactor.y;'+#13#10+
' clearcoatF0 = vec3(0.04);'+#13#10+
' if((texCoordIndices.x & 0x0f000000u) != 0x0f000000u){'+#13#10+
' clearcoatFactor *= textureFetch(6, vec4(1.0)).x;'+#13#10+
' }'+#13#10+
' if((texCoordIndices.x & 0xf0000000u) != 0xf0000000u){'+#13#10+
' clearcoatRoughness *= textureFetch(7, vec4(1.0)).y;'+#13#10+
' }'+#13#10+
' if((texCoordIndices.y & 0x0000000fu) != 0x0000000fu){'+#13#10+
' vec4 normalTexture = textureFetch(8, vec2(0.0, 1.0).xxyx);'+#13#10+
' clearcoatNormal = normalize(mat3(normalize(vTangent), normalize(vBitangent), normalize(vNormal)) * normalize((normalTexture.xyz - vec3(0.5)) * (vec2(uMaterial.metallicRoughnessNormalScaleOcclusionStrengthFactor.z, 1.0).xxy * 2.0)));'+#13#10+
' }else{'+#13#10+
' clearcoatNormal = normalize(vNormal);'+#13#10+
' }'+#13#10+
' clearcoatNormal *= (((flags & (1u << 5u)) != 0u) && !gl_FrontFacing) ? -1.0 : 1.0;'+#13#10+
' clearcoatRoughness = clamp(clearcoatRoughness, 0.0, 1.0);'+#13#10+
' }'+#13#10+
' if(lightMetaData.x != 0u){'+#13#10+
' for(int lightIndex = 0, lightCount = int(lightMetaData.x); lightIndex < lightCount; lightIndex++){'+#13#10+
' Light light = lights[lightIndex];'+#13#10+
' float lightAttenuation = 1.0;'+#13#10+
' vec3 lightDirection;'+#13#10+
' vec3 lightVector = light.positionRange.xyz - vWorldSpacePosition.xyz;'+#13#10+
' vec3 normalizedLightVector = normalize(lightVector);'+#13#10+
' if((uShadows != 0) && ((light.metaData.y & 0x80000000u) == 0u)){'+#13#10+
' switch(light.metaData.x){'+#13#10+
' case 1u:'+#13#10+ // Directional
' case 3u:{'+#13#10+ // Spot
' vec4 shadowNDC = light.shadowMapMatrix * vec4(vWorldSpacePosition, 1.0);'+#13#10+
' shadowNDC /= shadowNDC.w;'+#13#10+
' if(all(greaterThanEqual(shadowNDC, vec4(-1.0))) && all(lessThanEqual(shadowNDC, vec4(1.0)))){'+#13#10+
' shadowNDC.xyz = fma(shadowNDC.xyz, vec3(0.5), vec3(0.5));'+#13#10+
' vec4 moments = (textureLod(uNormalShadowMapArrayTexture, vec3(shadowNDC.xy, float(int(light.metaData.y))), 0.0) + vec2(-0.035955884801, 0.0).xyyy) *'+#13#10+
' mat4(0.2227744146, 0.0771972861, 0.7926986636, 0.0319417555,'+#13#10+
' 0.1549679261, 0.1394629426, 0.7963415838, -0.172282317,'+#13#10+
' 0.1451988946, 0.2120202157, 0.7258694464, -0.2758014811,'+#13#10+
' 0.163127443, 0.2591432266, 0.6539092497, -0.3376131734);'+#13#10+
' lightAttenuation *= 1.0 - reduceLightBleeding(getMSMShadowIntensity(moments, shadowNDC.z, 5e-3, 1e-2), 0.0);'+#13#10+
' }'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' case 2u:{'+#13#10+ // Point
' float znear = 1e-2, zfar = max(1.0, light.directionZFar.w);'+#13#10+
' vec3 vector = light.positionRange.xyz - vWorldSpacePosition;'+#13#10+
' vec4 moments = (textureLod(uCubeMapShadowMapArrayTexture, vec4(vec3(normalize(vector)), float(int(light.metaData.y))), 0.0) + vec2(-0.035955884801, 0.0).xyyy) *'+#13#10+
' mat4(0.2227744146, 0.0771972861, 0.7926986636, 0.0319417555,'+#13#10+
' 0.1549679261, 0.1394629426, 0.7963415838, -0.172282317,'+#13#10+
' 0.1451988946, 0.2120202157, 0.7258694464, -0.2758014811,'+#13#10+
' 0.163127443, 0.2591432266, 0.6539092497, -0.3376131734);'+#13#10+
' lightAttenuation *= 1.0 - reduceLightBleeding(getMSMShadowIntensity(moments, clamp((length(vector) - znear) / (zfar - znear), 0.0, 1.0), 5e-3, 1e-2), 0.0);'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' if(lightIndex == 0){'+#13#10+
' litIntensity = lightAttenuation;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' switch(light.metaData.x){'+#13#10+
' case 1u:{'+#13#10+ // Directional
' lightDirection = -light.directionZFar.xyz;'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' case 2u:{'+#13#10+ // Point
' lightDirection = normalizedLightVector;'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' case 3u:{'+#13#10+ // Spot
{$if true}
' float angularAttenuation = clamp(fma(dot(normalize(light.directionZFar.xyz), -normalizedLightVector), uintBitsToFloat(light.metaData.z), uintBitsToFloat(light.metaData.w)), 0.0, 1.0);'+#13#10+
{$else}
// Just for as reference
' float innerConeCosinus = uintBitsToFloat(light.metaData.z);'+#13#10+
' float outerConeCosinus = uintBitsToFloat(light.metaData.w);'+#13#10+
' float actualCosinus = dot(normalize(light.directionZFar.xyz), -normalizedLightVector);'+#13#10+
' float angularAttenuation = mix(0.0, mix(smoothstep(outerConeCosinus, innerConeCosinus, actualCosinus), 1.0, step(innerConeCosinus, actualCosinus)), step(outerConeCosinus, actualCosinus));'+#13#10+
{$ifend}
' lightAttenuation *= angularAttenuation * angularAttenuation;'+#13#10+
' lightDirection = normalizedLightVector;'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' default:{'+#13#10+
' continue;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' switch(light.metaData.x){'+#13#10+
' case 2u:'+#13#10+ // Point
' case 3u:{'+#13#10+ // Spot
' if(light.positionRange.w >= 0.0){'+#13#10+
' float currentDistance = length(lightVector);'+#13#10+
' if(currentDistance > 0.0){'+#13#10+
' lightAttenuation *= 1.0 / (currentDistance * currentDistance);'+#13#10+
' if(light.positionRange.w > 0.0){'+#13#10+
' float distanceByRange = currentDistance / light.positionRange.w;'+#13#10+
' lightAttenuation *= clamp(1.0 - (distanceByRange * distanceByRange * distanceByRange * distanceByRange), 0.0, 1.0);'+#13#10+
' }'+#13#10+
' }'+#13#10+
' }'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' if(lightAttenuation > 0.0){'+#13#10+
' doSingleLight(light.colorIntensity.xyz * light.colorIntensity.w,'+#13#10+
' vec3(lightAttenuation),'+#13#10+
' lightDirection,'+#13#10+
' normal.xyz,'+#13#10+
' diffuseColorAlpha.xyz,'+#13#10+
' specularColorRoughness.xyz,'+#13#10+
' -viewDirection,'+#13#10+
' refractiveAngle,'+#13#10+
' transparency,'+#13#10+
' specularColorRoughness.w,'+#13#10+
' cavity);'+#13#10+
' }'+#13#10+
' }'+#13#10+
' }'+#13#10+
' diffuseOutput += getDiffuseImageBasedLight(normal.xyz, diffuseColorAlpha.xyz);'+#13#10+
' specularOutput += getSpecularImageBasedLight(normal.xyz, specularColorRoughness.xyz, specularColorRoughness.w, viewDirection, litIntensity);'+#13#10+
' if((flags & (1u << 7u)) != 0u){'+#13#10+
' clearcoatOutput += getSpecularImageBasedLight(clearcoatNormal.xyz, clearcoatF0.xyz, clearcoatRoughness, viewDirection, litIntensity);'+#13#10+
' clearcoatBlendFactor = vec3(clearcoatFactor * specularF(clearcoatF0, clamp(dot(clearcoatNormal, -viewDirection), 0.0, 1.0)));'+#13#10+
' }'+#13#10+
' color = vec4(vec3(((diffuseOutput +'+#13#10+
{$ifndef PasGLTFExtraEmissionOutput}
' (emissiveTexture.xyz * uMaterial.emissiveFactor.xyz) +'+#13#10+
{$endif}
' (sheenOutput * (1.0 - reflectance))) * '+#13#10+
' (vec3(1.0) - clearcoatBlendFactor)) +'+#13#10+
' mix(specularOutput,'+#13#10+
' clearcoatOutput,'+#13#10+
' clearcoatBlendFactor)),'+#13#10+
' diffuseColorAlpha.w);'+#13#10+
// ' color = vec4(clearcoatOutput * clearcoatBlendFactor, diffuseColorAlpha.w);'+#13#10+
{$ifdef PasGLTFExtraEmissionOutput}
' emissionColor.xyz = vec4((emissiveTexture.xyz * uMaterial.emissiveFactor.xyz) * (vec3(1.0) - clearcoatBlendFactor), 1.0);'+#13#10+
{$endif}
' break;'+#13#10+
' }'+#13#10+
' case smUnlit:{'+#13#10+
' color = textureFetchSRGB(0, vec4(1.0)) * uMaterial.baseColorFactor * vec2((litIntensity * 0.25) + 0.75, 1.0).xxxy;'+#13#10+
' break;'+#13#10+
' }'+#13#10+
' }'+#13#10+
' float alpha = color.w * vColor.w, outputAlpha = mix(1.0, color.w * vColor.w, float(int(uint((flags >> 4u) & 1u))));'+#13#10+
' oOutput = vec4(color.xyz * vColor.xyz, outputAlpha);'+#13#10+
{$ifdef PasGLTFExtraEmissionOutput}
' oEmission = vec4(emissionColor.xyz * vColor.xyz, outputAlpha);'+#13#10+
{$endif}
'';
end;
if aAlphaTest then begin
f:=f+' if(alpha < uintBitsToFloat(uMaterial.alphaCutOffFlagsTex0Tex1.x)){'+#13#10+
' discard;'+#13#10+
' }'+#13#10;
end;
f:=f+'}'+#13#10;
inherited Create(v,f);
end;
destructor TShadingShader.Destroy;
begin
inherited Destroy;
end;
procedure TShadingShader.BindAttributes;
begin
inherited BindAttributes;
glBindAttribLocation(ProgramHandle,0,'aPosition');
glBindAttribLocation(ProgramHandle,1,'aNormal');
glBindAttribLocation(ProgramHandle,2,'aTangent');
glBindAttribLocation(ProgramHandle,3,'aTexCoord0');
glBindAttribLocation(ProgramHandle,4,'aTexCoord1');
glBindAttribLocation(ProgramHandle,5,'aColor0');
glBindAttribLocation(ProgramHandle,6,'aJoints0');
glBindAttribLocation(ProgramHandle,7,'aJoints1');
glBindAttribLocation(ProgramHandle,8,'aWeights0');
glBindAttribLocation(ProgramHandle,9,'aWeights1');
glBindAttribLocation(ProgramHandle,10,'aVertexIndex');
end;
procedure TShadingShader.BindVariables;
{$if not defined(PasGLTFBindlessTextures)}
const Textures:array[0..15] of glInt=(4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
{$ifend}
begin
inherited BindVariables;
uBRDFLUTTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uBRDFLUTTexture')));
uNormalShadowMapArrayTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uNormalShadowMapArrayTexture')));
uCubeMapShadowMapArrayTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uCubeMapShadowMapArrayTexture')));
uEnvMapTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uEnvMapTexture')));
{$if not defined(PasGLTFBindlessTextures)}
uTextures:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTextures')));
{$ifend}
uEnvMapMaxLevel:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uEnvMapMaxLevel')));
uShadows:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uShadows')));
glUniform1i(uBRDFLUTTexture,0);
glUniform1i(uEnvMapTexture,1);
glUniform1i(uNormalShadowMapArrayTexture,2);
glUniform1i(uCubeMapShadowMapArrayTexture,3);
{$if not defined(PasGLTFBindlessTextures)}
glUniform1iv(uTextures,16,@Textures[0]);
{$ifend}
end;
end.
|
unit TiWaitForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, ExtCtrls;
type TWaitFormType = (wfLoadPackage,wfLocateFunction,wfSelectData,wfPrepareData, wfImportData);
type
TWaitForm = class(TForm)
Panel: TPanel;
Memo: TcxMemo;
private
{ Private declarations }
public
{ Public declarations }
end;
function ShowWaitForm(AOwner: TForm;WaitFormType:TWaitFormType): TForm;
procedure CloseWaitForm(wf: TForm);
implementation
const wfLoadPackage_Const = 'Чекайте: йде пошук та загрузка пакету!';
const wfLocateFunction_Const = 'Чекайте: йде пошук функції!';
const wfSelectData_Const = 'Чекайте: йде відбор даних!';
const wfPrepareData_Const = 'Чекайте: йде підготовка даних!';
const wfImportData_Const = 'Чекайте: йде імпорт даних!';
{$R *.dfm}
function ShowWaitForm(AOwner: TForm;WaitFormType:TWaitFormType): TForm;
var
wf : TWaitForm;
begin
wf := TWaitForm.Create(AOwner);
case WaitFormType of
wfLoadPackage: Wf.Memo.Lines.Text:=#13+wfLoadPackage_Const;
wfLocateFunction: Wf.Memo.Lines.Text:=#13+wfLocateFunction_Const;
wfSelectData: Wf.Memo.Lines.Text:=#13+wfSelectData_Const;
wfPrepareData: Wf.Memo.Lines.Text:=#13+wfPrepareData_Const;
wfImportData: Wf.Memo.Lines.Text:=#13+wfImportData_Const;
end;
Result := wf;
if AOwner <> nil then AOwner.Enabled := False;
Result.Show;
Result.Update;
end;
procedure CloseWaitForm(wf: TForm);
begin
if wf.Owner <> nil then (wf.Owner as TForm).Enabled := True;
wf.Free;
end;
end.
|
unit UMensagem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, pngimage;
Type
TImagens = (ImPergunta, ImInfo, ImErro, ImAlert);
type
TFrMensagem = class(TForm)
Panel1: TPanel;
PnMensagem: TPanel;
BtConfirma: TSpeedButton;
BtNao: TSpeedButton;
BtCancelar: TSpeedButton;
ImAlerta: TImage;
ImInformacao: TImage;
ImError: TImage;
ImPergunta: TImage;
lbMensagem: TLabel;
procedure BtConfirmaClick(Sender: TObject);
procedure BtNaoClick(Sender: TObject);
procedure BtCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Mensagem(Texto: String; Imagem: array of TImagens);
function Pergunta(Texto: String; Imagem: array of TImagens): boolean;
end;
var
FrMensagem: TFrMensagem;
lstatus: boolean;
implementation
{$R *.dfm}
{ TFrMensagem }
procedure TFrMensagem.BtNaoClick(Sender: TObject);
begin
lstatus := false;
close;
end;
procedure TFrMensagem.Mensagem(Texto: String; Imagem: array of TImagens);
var
frm: TFrMensagem;
i: integer;
begin
frm := TFrMensagem.Create(nil);
frm.lbMensagem.Caption := Texto;
frm.BtCancelar.Visible := false;
frm.BtNao.Visible := false;
frm.BtConfirma.Caption := 'Ok';
for i := 0 to Length(Imagem) - 1 do
begin
case (Imagem[i]) of
ImInfo:
begin
frm.ImInformacao.Visible := true;
frm.ImInformacao.Align := alLeft;
end;
ImErro:
begin
frm.ImError.Visible := true;
frm.ImError.Align := alLeft;
end;
ImAlert:
begin
frm.ImAlerta.Visible := true;
frm.ImAlerta.Align := alLeft;
end;
end;
end;
frm.ShowModal;
end;
function TFrMensagem.Pergunta(Texto: String; Imagem: array of TImagens)
: boolean;
var
frm: TFrMensagem;
begin
frm := TFrMensagem.Create(nil);
frm.lbMensagem.Caption := Texto;
frm.ImPergunta.Visible := true;
frm.ImPergunta.Align := alLeft;
frm.ShowModal;
result := lstatus;
end;
procedure TFrMensagem.BtCancelarClick(Sender: TObject);
begin
lstatus := false;
close;
end;
procedure TFrMensagem.BtConfirmaClick(Sender: TObject);
begin
lstatus := true;
close;
end;
end.
|
unit common;
interface
uses Windows, Classes, SysUtils, Forms, ScktComp;
const
ServerPort = 49999;
MSG_REQUEST_FILE = $00010001;
MSG_FILE_FOLLOWS = $00010002;
MSG_REQUEST_LIST = $00020001;
MSG_LIST_FOLLOWS = $00020002;
MSG_ERR_DOES_NOT_EXIST = $00030001;
MSG_ERR_NO_FILES = $00030002;
MSG_ERR_ILLEGAL_CODE = $00030003;
MSG_ERR_CANNOT_SEND = $00030004;
type
TMsgHeader = packed record
OpCode : DWORD;
PayLoadLen: DWORD;
end;
procedure SendData( Sock: TCustomWinSocket; Code: DWORD; PayLoad: string );
procedure Log( Destination: TStrings; Txt: string );
function SendFile( Socket: TCustomWinSocket; FName: string ): boolean;
procedure SendFileList( Socket: TCustomWinSocket; DirPath: string;
WildCard: string );
procedure SendError( Socket: TCustomWinSocket; Error: DWORD );
procedure EnumFiles( WildCard: string;
FileList: TStrings;
StripExtensions: boolean );
function MessageComplete( var SockBuf: string; var Header: TMsgHeader;
var PayLoad: string ): boolean;
implementation
//*****************************************************************************
procedure EnumFiles( WildCard: string;
FileList: TStrings;
StripExtensions: boolean );
var
SRec : TSearchRec;
Error : DWORD;
begin
try
FileList.Clear;
Error := FindFirst( WildCard, faANYFILE, SRec );
while Error = 0 do
begin
if SRec.Attr and faDIRECTORY = 0 then
if not StripExtensions then
FileList.Add( lowercase( SRec.Name ) )
else
FileList.Add( ChangeFileExt( lowercase( SRec.Name ), '' ) );
Error := FindNext( SRec );
end;
Sysutils.FindClose( SRec );
except
messagebeep( 0 );
end;
end;
//*****************************************************************************
procedure SendData( Sock: TCustomWinSocket; Code: DWORD; PayLoad: string );
var
S : TMemoryStream;
Header : TMsgHeader;
begin
// set up the header
with Header do
begin
OpCode := Code;
PayLoadLen := Length( PayLoad );
end;
S := TMemoryStream.Create;
S.Write( Header, SizeOf( Header ) );
// in case of messages without payload...
if Header.PayLoadLen > 0 then
S.Write( PayLoad[1], Header.PayLoadLen );
S.Position := 0;
Sock.SendStream( S ); // **note** stream will be freed by socket !!
end;
//*****************************************************************************
procedure Log( Destination: TStrings; Txt: string );
begin
if not Assigned( Destination ) then EXIT;
if length( Destination.Text ) > 20000 then
Destination.Clear;
Destination.Add( TimeToStr( Now ) + ' : ' + Txt );
end;
//*****************************************************************************
function SendFile( Socket: TCustomWinSocket; FName: string ): boolean;
var
Header : TMsgHeader;
Fs : TFileStream;
S : TMemoryStream;
begin
Result := false;
if FileExists( FName ) then
try
// open file
Fs := TFileStream.Create( FName, fmOPENREAD );
Fs.Position := 0;
// create the header
S := TMemoryStream.Create;
Header.OpCode := MSG_FILE_FOLLOWS;
Header.PayLoadLen := Fs.Size;
// first write the header
S.Write( Header, SizeOf( Header ) );
// then append file contents to stream
S.CopyFrom( Fs, Fs.Size );
S.Position := 0; // important...
// send to socket
Result := Socket.SendStream( S ); // **NOTE** socket will free memorystream!
Fs.Free;
except
SendError( Socket, MSG_ERR_CANNOT_SEND );
end
else
SendError( Socket, MSG_ERR_DOES_NOT_EXIST );
end;
//*****************************************************************************
procedure SendFileList( Socket: TCustomWinSocket;
DirPath: string;
WildCard: string );
var
Buf : TStringList;
begin
Buf := TStringList.Create;
if not ( DirPath[Length( DirPath )] in ['/', '\'] ) then
DirPath := DirPath + '/';
EnumFiles( DirPath + WildCard, Buf, false );
SendData( Socket, MSG_LIST_FOLLOWS, Buf.Text );
Buf.Free;
end;
//*****************************************************************************
procedure SendError( Socket: TCustomWinSocket; Error: DWORD );
begin
SendData( Socket, Error, '' );
end;
//*****************************************************************************
function MessageComplete( var SockBuf: string;
var Header: TMsgHeader;
var PayLoad: string ): boolean;
begin
Result := false;
if Length( SockBuf ) > SizeOf( Header ) then // paranoia striking...
begin
Move( SockBuf[1], Header, SizeOf( Header ) );
// do we have at least one complete message ?
if length( SockBuf ) >= Header.PayLoadLen + SizeOf( Header ) then
begin
// if so, delete header
Delete( SockBuf, 1, SizeOf( Header ) );
// copy from buf to payload
PayLoad := Copy( SockBuf, 1, Header.PayLoadLen );
// just in case another message is already in the pipeline!
Delete( SockBuf, 1, Header.PayLoadLen );
Result := true;
end;
end;
end;
end.
|
{
ItemStroage 및 CommandManager를 컨트롤
Form등의 외부인터페이스에서 접근하여 처리 하는 클래스
}
unit ThothController;
interface
uses
System.Classes,
ThTypes, ThClasses, ThCommandManager, ThItemStorage;
type
TThothController = class(TThInterfacedObject, IThSubject)
private
FObservers: TInterfaceList;
FItemStorage: TThItemStorage;
FCommandManager: TThCommandManager;
function GetRedoCount: Integer;
function GetUndoCount: Integer;
function GetItemCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Subject(ASource: IThObserver; ACommand: IThCommand);
procedure RegistObserver(AObserver: IThObserver);
procedure UnregistObserver(AObserver: IThObserver);
procedure Undo;
procedure Redo;
property UndoCount: Integer read GetUndoCount;
property RedoCount: Integer read GetRedoCount;
property ItemCount: Integer read GetItemCount;
end;
implementation
{ TMainController }
constructor TThothController.Create;
begin
FObservers := TInterfaceList.Create;
FItemStorage := TThItemStorage.Create;
FItemStorage.SetSubject(Self);
FCommandManager := TThCommandManager.Create;
FCommandManager.SetSubject(Self);
end;
destructor TThothController.Destroy;
begin
FCommandManager.Free;
FItemStorage.Free;
FObservers.Clear;
FObservers := nil;
inherited;
end;
function TThothController.GetItemCount: Integer;
begin
Result := FItemStorage.ItemCount;
end;
function TThothController.GetRedoCount: Integer;
begin
Result := FCommandManager.RedoCount;
end;
function TThothController.GetUndoCount: Integer;
begin
Result := FCommandManager.UndoCount;
end;
procedure TThothController.RegistObserver(AObserver: IThObserver);
begin
FObservers.Add(AObserver);
end;
procedure TThothController.UnregistObserver(AObserver: IThObserver);
begin
FObservers.Remove(AObserver);
end;
procedure TThothController.Subject(ASource: IThObserver; ACommand: IThCommand);
var
I: Integer;
begin
for I := 0 to FObservers.Count - 1 do
if ASource <> IThObserver(FObservers[I]) then
IThObserver(FObservers[I]).Notifycation(ACommand);
end;
procedure TThothController.Undo;
begin
FCommandManager.UndoAction;
end;
procedure TThothController.Redo;
begin
FCommandManager.RedoAction;
end;
end.
|
unit Antlr.Runtime.Tree;
(*
[The "BSD licence"]
Copyright (c) 2008 Erik van Bilsen
Copyright (c) 2005-2007 Kunle Odutola
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code MUST RETAIN the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form MUST REPRODUCE the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior WRITTEN permission.
4. Unless explicitly state otherwise, any contribution intentionally
submitted for inclusion in this work to the copyright owner or licensor
shall be under the terms and conditions of this license, without any
additional terms or conditions.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
interface
{$IF CompilerVersion < 20}
{$MESSAGE ERROR 'You need Delphi 2009 or higher to use the Antlr runtime'}
{$IFEND}
uses
Classes,
SysUtils,
Antlr.Runtime,
Antlr.Runtime.Tools,
Antlr.Runtime.Collections;
type
/// <summary>
/// How to create and navigate trees. Rather than have a separate factory
/// and adaptor, I've merged them. Makes sense to encapsulate.
///
/// This takes the place of the tree construction code generated in the
/// generated code in 2.x and the ASTFactory.
///
/// I do not need to know the type of a tree at all so they are all
/// generic Objects. This may increase the amount of typecasting needed. :(
/// </summary>
ITreeAdaptor = interface(IANTLRInterface)
['{F9DEB286-F555-4CC8-A51A-93F3F649B248}']
{ Methods }
// C o n s t r u c t i o n
/// <summary>
/// Create a tree node from Token object; for CommonTree type trees,
/// then the token just becomes the payload.
/// </summary>
/// <remarks>
/// This is the most common create call. Override if you want another kind of node to be built.
/// </remarks>
function CreateNode(const Payload: IToken): IANTLRInterface; overload;
/// <summary>Duplicate a single tree node </summary>
/// <remarks> Override if you want another kind of node to be built.</remarks>
function DupNode(const TreeNode: IANTLRInterface): IANTLRInterface;
/// <summary>Duplicate tree recursively, using DupNode() for each node </summary>
function DupTree(const Tree: IANTLRInterface): IANTLRInterface;
/// <summary>
/// Return a nil node (an empty but non-null node) that can hold
/// a list of element as the children. If you want a flat tree (a list)
/// use "t=adaptor.nil(); t.AddChild(x); t.AddChild(y);"
/// </summary>
function GetNilNode: IANTLRInterface;
/// <summary>
/// Return a tree node representing an error. This node records the
/// tokens consumed during error recovery. The start token indicates the
/// input symbol at which the error was detected. The stop token indicates
/// the last symbol consumed during recovery.
/// </summary>
/// <remarks>
/// <para>You must specify the input stream so that the erroneous text can
/// be packaged up in the error node. The exception could be useful
/// to some applications; default implementation stores ptr to it in
/// the CommonErrorNode.</para>
///
/// <para>This only makes sense during token parsing, not tree parsing.
/// Tree parsing should happen only when parsing and tree construction
/// succeed.</para>
/// </remarks>
function ErrorNode(const Input: ITokenStream; const Start, Stop: IToken;
const E: ERecognitionException): IANTLRInterface;
/// <summary>
/// Is tree considered a nil node used to make lists of child nodes?
/// </summary>
function IsNil(const Tree: IANTLRInterface): Boolean;
/// <summary>
/// Add a child to the tree t. If child is a flat tree (a list), make all
/// in list children of t.
/// </summary>
/// <remarks>
/// <para>
/// Warning: if t has no children, but child does and child isNil then you
/// can decide it is ok to move children to t via t.children = child.children;
/// i.e., without copying the array. Just make sure that this is consistent
/// with have the user will build ASTs. Do nothing if t or child is null.
/// </para>
/// <para>
/// This is for construction and I'm not sure it's completely general for
/// a tree's addChild method to work this way. Make sure you differentiate
/// between your tree's addChild and this parser tree construction addChild
/// if it's not ok to move children to t with a simple assignment.
/// </para>
/// </remarks>
procedure AddChild(const T, Child: IANTLRInterface);
/// <summary>
/// If oldRoot is a nil root, just copy or move the children to newRoot.
/// If not a nil root, make oldRoot a child of newRoot.
/// </summary>
/// <remarks>
///
/// old=^(nil a b c), new=r yields ^(r a b c)
/// old=^(a b c), new=r yields ^(r ^(a b c))
///
/// If newRoot is a nil-rooted single child tree, use the single
/// child as the new root node.
///
/// old=^(nil a b c), new=^(nil r) yields ^(r a b c)
/// old=^(a b c), new=^(nil r) yields ^(r ^(a b c))
///
/// If oldRoot was null, it's ok, just return newRoot (even if isNil).
///
/// old=null, new=r yields r
/// old=null, new=^(nil r) yields ^(nil r)
///
/// Return newRoot. Throw an exception if newRoot is not a
/// simple node or nil root with a single child node--it must be a root
/// node. If newRoot is ^(nil x) return x as newRoot.
///
/// Be advised that it's ok for newRoot to point at oldRoot's
/// children; i.e., you don't have to copy the list. We are
/// constructing these nodes so we should have this control for
/// efficiency.
/// </remarks>
function BecomeRoot(const NewRoot, OldRoot: IANTLRInterface): IANTLRInterface; overload;
/// <summary>
/// Given the root of the subtree created for this rule, post process
/// it to do any simplifications or whatever you want. A required
/// behavior is to convert ^(nil singleSubtree) to singleSubtree
/// as the setting of start/stop indexes relies on a single non-nil root
/// for non-flat trees.
///
/// Flat trees such as for lists like "idlist : ID+ ;" are left alone
/// unless there is only one ID. For a list, the start/stop indexes
/// are set in the nil node.
///
/// This method is executed after all rule tree construction and right
/// before SetTokenBoundaries().
/// </summary>
function RulePostProcessing(const Root: IANTLRInterface): IANTLRInterface;
/// <summary>
/// For identifying trees. How to identify nodes so we can say "add node
/// to a prior node"?
/// </summary>
/// <remarks>
/// Even BecomeRoot is an issue. Ok, we could:
/// <list type="number">
/// <item>Number the nodes as they are created?</item>
/// <item>
/// Use the original framework assigned hashcode that's unique
/// across instances of a given type.
/// WARNING: This is usually implemented either as IL to make a
/// non-virt call to object.GetHashCode() or by via a call to
/// System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode().
/// Both have issues especially on .NET 1.x and Mono.
/// </item>
/// </list>
/// </remarks>
function GetUniqueID(const Node: IANTLRInterface): Integer;
// R e w r i t e R u l e s
/// <summary>
/// Create a node for newRoot make it the root of oldRoot.
/// If oldRoot is a nil root, just copy or move the children to newRoot.
/// If not a nil root, make oldRoot a child of newRoot.
///
/// Return node created for newRoot.
/// </summary>
function BecomeRoot(const NewRoot: IToken; const OldRoot: IANTLRInterface): IANTLRInterface; overload;
/// <summary>Create a new node derived from a token, with a new token type.
/// This is invoked from an imaginary node ref on right side of a
/// rewrite rule as IMAG[$tokenLabel].
///
/// This should invoke createToken(Token).
/// </summary>
function CreateNode(const TokenType: Integer; const FromToken: IToken): IANTLRInterface; overload;
/// <summary>Same as Create(tokenType,fromToken) except set the text too.
/// This is invoked from an imaginary node ref on right side of a
/// rewrite rule as IMAG[$tokenLabel, "IMAG"].
///
/// This should invoke createToken(Token).
/// </summary>
function CreateNode(const TokenType: Integer; const FromToken: IToken;
const Text: String): IANTLRInterface; overload;
/// <summary>Create a new node derived from a token, with a new token type.
/// This is invoked from an imaginary node ref on right side of a
/// rewrite rule as IMAG["IMAG"].
///
/// This should invoke createToken(int,String).
/// </summary>
function CreateNode(const TokenType: Integer; const Text: String): IANTLRInterface; overload;
// C o n t e n t
/// <summary>For tree parsing, I need to know the token type of a node </summary>
function GetNodeType(const T: IANTLRInterface): Integer;
/// <summary>Node constructors can set the type of a node </summary>
procedure SetNodeType(const T: IANTLRInterface; const NodeType: Integer);
function GetNodeText(const T: IANTLRInterface): String;
/// <summary>Node constructors can set the text of a node </summary>
procedure SetNodeText(const T: IANTLRInterface; const Text: String);
/// <summary>
/// Return the token object from which this node was created.
/// </summary>
/// <remarks>
/// Currently used only for printing an error message. The error
/// display routine in BaseRecognizer needs to display where the
/// input the error occurred. If your tree of limitation does not
/// store information that can lead you to the token, you can create
/// a token filled with the appropriate information and pass that back.
/// <see cref="BaseRecognizer.GetErrorMessage"/>
/// </remarks>
function GetToken(const TreeNode: IANTLRInterface): IToken;
/// <summary>
/// Where are the bounds in the input token stream for this node and
/// all children?
/// </summary>
/// <remarks>
/// Each rule that creates AST nodes will call this
/// method right before returning. Flat trees (i.e., lists) will
/// still usually have a nil root node just to hold the children list.
/// That node would contain the start/stop indexes then.
/// </remarks>
procedure SetTokenBoundaries(const T: IANTLRInterface; const StartToken,
StopToken: IToken);
/// <summary>
/// Get the token start index for this subtree; return -1 if no such index
/// </summary>
function GetTokenStartIndex(const T: IANTLRInterface): Integer;
/// <summary>
/// Get the token stop index for this subtree; return -1 if no such index
/// </summary>
function GetTokenStopIndex(const T: IANTLRInterface): Integer;
// N a v i g a t i o n / T r e e P a r s i n g
/// <summary>Get a child 0..n-1 node </summary>
function GetChild(const T: IANTLRInterface; const I: Integer): IANTLRInterface;
/// <summary>Set ith child (0..n-1) to t; t must be non-null and non-nil node</summary>
procedure SetChild(const T: IANTLRInterface; const I: Integer; const Child: IANTLRInterface);
/// <summary>Remove ith child and shift children down from right.</summary>
function DeleteChild(const T: IANTLRInterface; const I: Integer): IANTLRInterface;
/// <summary>How many children? If 0, then this is a leaf node </summary>
function GetChildCount(const T: IANTLRInterface): Integer;
/// <summary>
/// Who is the parent node of this node; if null, implies node is root.
/// </summary>
/// <remarks>
/// If your node type doesn't handle this, it's ok but the tree rewrites
/// in tree parsers need this functionality.
/// </remarks>
function GetParent(const T: IANTLRInterface): IANTLRInterface;
procedure SetParent(const T, Parent: IANTLRInterface);
/// <summary>
/// What index is this node in the child list? Range: 0..n-1
/// </summary>
/// <remarks>
/// If your node type doesn't handle this, it's ok but the tree rewrites
/// in tree parsers need this functionality.
/// </remarks>
function GetChildIndex(const T: IANTLRInterface): Integer;
procedure SetChildIdex(const T: IANTLRInterface; const Index: Integer);
/// <summary>
/// Replace from start to stop child index of parent with t, which might
/// be a list. Number of children may be different after this call.
/// </summary>
/// <remarks>
/// If parent is null, don't do anything; must be at root of overall tree.
/// Can't replace whatever points to the parent externally. Do nothing.
/// </remarks>
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface);
end;
/// <summary>A stream of tree nodes, accessing nodes from a tree of some kind </summary>
ITreeNodeStream = interface(IIntStream)
['{75EA5C06-8145-48F5-9A56-43E481CE86C6}']
{ Property accessors }
function GetTreeSource: IANTLRInterface;
function GetTokenStream: ITokenStream;
function GetTreeAdaptor: ITreeAdaptor;
procedure SetHasUniqueNavigationNodes(const Value: Boolean);
{ Methods }
/// <summary>Get a tree node at an absolute index i; 0..n-1.</summary>
/// <remarks>
/// If you don't want to buffer up nodes, then this method makes no
/// sense for you.
/// </remarks>
function Get(const I: Integer): IANTLRInterface;
/// <summary>
/// Get tree node at current input pointer + i ahead where i=1 is next node.
/// i<0 indicates nodes in the past. So LT(-1) is previous node, but
/// implementations are not required to provide results for k < -1.
/// LT(0) is undefined. For i>=n, return null.
/// Return null for LT(0) and any index that results in an absolute address
/// that is negative.
///
/// This is analogus to the LT() method of the TokenStream, but this
/// returns a tree node instead of a token. Makes code gen identical
/// for both parser and tree grammars. :)
/// </summary>
function LT(const K: Integer): IANTLRInterface;
/// <summary>Return the text of all nodes from start to stop, inclusive.
/// If the stream does not buffer all the nodes then it can still
/// walk recursively from start until stop. You can always return
/// null or "" too, but users should not access $ruleLabel.text in
/// an action of course in that case.
/// </summary>
function ToString(const Start, Stop: IANTLRInterface): String; overload;
function ToString: String; overload;
// REWRITING TREES (used by tree parser)
/// <summary>
/// Replace from start to stop child index of parent with t, which might
/// be a list. Number of children may be different after this call.
/// </summary>
/// <remarks>
/// The stream is notified because it is walking the tree and might need
/// to know you are monkeying with the underlying tree. Also, it might be
/// able to modify the node stream to avoid restreaming for future phases.
///
/// If parent is null, don't do anything; must be at root of overall tree.
/// Can't replace whatever points to the parent externally. Do nothing.
/// </remarks>
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface);
{ Properties }
/// <summary>
/// Where is this stream pulling nodes from? This is not the name, but
/// the object that provides node objects.
///
/// TODO: do we really need this?
/// </summary>
property TreeSource: IANTLRInterface read GetTreeSource;
/// <summary>
/// Get the ITokenStream from which this stream's Tree was created
/// (may be null)
/// </summary>
/// <remarks>
/// If the tree associated with this stream was created from a
/// TokenStream, you can specify it here. Used to do rule $text
/// attribute in tree parser. Optional unless you use tree parser
/// rule text attribute or output=template and rewrite=true options.
/// </remarks>
property TokenStream: ITokenStream read GetTokenStream;
/// <summary>
/// What adaptor can tell me how to interpret/navigate nodes and trees.
/// E.g., get text of a node.
/// </summary>
property TreeAdaptor: ITreeAdaptor read GetTreeAdaptor;
/// <summary>
/// As we flatten the tree, we use UP, DOWN nodes to represent
/// the tree structure. When debugging we need unique nodes
/// so we have to instantiate new ones. When doing normal tree
/// parsing, it's slow and a waste of memory to create unique
/// navigation nodes. Default should be false;
/// </summary>
property HasUniqueNavigationNodes: Boolean write SetHasUniqueNavigationNodes;
end;
/// <summary>
/// What does a tree look like? ANTLR has a number of support classes
/// such as CommonTreeNodeStream that work on these kinds of trees. You
/// don't have to make your trees implement this interface, but if you do,
/// you'll be able to use more support code.
///
/// NOTE: When constructing trees, ANTLR can build any kind of tree; it can
/// even use Token objects as trees if you add a child list to your tokens.
///
/// This is a tree node without any payload; just navigation and factory stuff.
/// </summary>
ITree = interface(IANTLRInterface)
['{4B6EFB53-EBF6-4647-BA4D-48B68134DC2A}']
{ Property accessors }
function GetChildCount: Integer;
function GetParent: ITree;
procedure SetParent(const Value: ITree);
function GetChildIndex: Integer;
procedure SetChildIndex(const Value: Integer);
function GetIsNil: Boolean;
function GetTokenType: Integer;
function GetText: String;
function GetLine: Integer;
function GetCharPositionInLine: Integer;
function GetTokenStartIndex: Integer;
procedure SetTokenStartIndex(const Value: Integer);
function GetTokenStopIndex: Integer;
procedure SetTokenStopIndex(const Value: Integer);
{ Methods }
/// <summary>Set (or reset) the parent and child index values for all children</summary>
procedure FreshenParentAndChildIndexes;
function GetChild(const I: Integer): ITree;
/// <summary>
/// Add t as a child to this node. If t is null, do nothing. If t
/// is nil, add all children of t to this' children.
/// </summary>
/// <param name="t">Tree to add</param>
procedure AddChild(const T: ITree);
/// <summary>Set ith child (0..n-1) to t; t must be non-null and non-nil node</summary>
procedure SetChild(const I: Integer; const T: ITree);
function DeleteChild(const I: Integer): IANTLRInterface;
/// <summary>
/// Delete children from start to stop and replace with t even if t is
/// a list (nil-root tree). num of children can increase or decrease.
/// For huge child lists, inserting children can force walking rest of
/// children to set their childindex; could be slow.
/// </summary>
procedure ReplaceChildren(const StartChildIndex, StopChildIndex: Integer;
const T: IANTLRInterface);
function DupNode: ITree;
function ToStringTree: String;
function ToString: String;
{ Properties }
property ChildCount: Integer read GetChildCount;
// Tree tracks parent and child index now > 3.0
property Parent: ITree read GetParent write SetParent;
/// <summary>This node is what child index? 0..n-1</summary>
property ChildIndex: Integer read GetChildIndex write SetChildIndex;
/// <summary>
/// Indicates the node is a nil node but may still have children, meaning
/// the tree is a flat list.
/// </summary>
property IsNil: Boolean read GetIsNil;
/// <summary>Return a token type; needed for tree parsing </summary>
property TokenType: Integer read GetTokenType;
property Text: String read GetText;
/// <summary>In case we don't have a token payload, what is the line for errors? </summary>
property Line: Integer read GetLine;
property CharPositionInLine: Integer read GetCharPositionInLine;
/// <summary>
/// What is the smallest token index (indexing from 0) for this node
/// and its children?
/// </summary>
property TokenStartIndex: Integer read GetTokenStartIndex write SetTokenStartIndex;
/// <summary>
/// What is the largest token index (indexing from 0) for this node
/// and its children?
/// </summary>
property TokenStopIndex: Integer read GetTokenStopIndex write SetTokenStopIndex;
end;
/// <summary>
/// A generic tree implementation with no payload. You must subclass to
/// actually have any user data. ANTLR v3 uses a list of children approach
/// instead of the child-sibling approach in v2. A flat tree (a list) is
/// an empty node whose children represent the list. An empty, but
/// non-null node is called "nil".
/// </summary>
IBaseTree = interface(ITree)
['{6772F6EA-5FE0-40C6-BE5C-800AB2540E55}']
{ Property accessors }
function GetChildren: IList<IBaseTree>;
function GetChildIndex: Integer;
procedure SetChildIndex(const Value: Integer);
function GetParent: ITree;
procedure SetParent(const Value: ITree);
function GetTokenType: Integer;
function GetTokenStartIndex: Integer;
procedure SetTokenStartIndex(const Value: Integer);
function GetTokenStopIndex: Integer;
procedure SetTokenStopIndex(const Value: Integer);
function GetText: String;
{ Methods }
/// <summary>
/// Add all elements of kids list as children of this node
/// </summary>
/// <param name="kids"></param>
procedure AddChildren(const Kids: IList<IBaseTree>);
procedure SetChild(const I: Integer; const T: ITree);
procedure FreshenParentAndChildIndexes(const Offset: Integer);
procedure SanityCheckParentAndChildIndexes; overload;
procedure SanityCheckParentAndChildIndexes(const Parent: ITree;
const I: Integer); overload;
/// <summary>
/// Print out a whole tree not just a node
/// </summary>
function ToStringTree: String;
function DupNode: ITree;
{ Properties }
/// <summary>
/// Get the children internal list of children. Manipulating the list
/// directly is not a supported operation (i.e. you do so at your own risk)
/// </summary>
property Children: IList<IBaseTree> read GetChildren;
/// <summary>BaseTree doesn't track child indexes.</summary>
property ChildIndex: Integer read GetChildIndex write SetChildIndex;
/// <summary>BaseTree doesn't track parent pointers.</summary>
property Parent: ITree read GetParent write SetParent;
/// <summary>Return a token type; needed for tree parsing </summary>
property TokenType: Integer read GetTokenType;
/// <summary>
/// What is the smallest token index (indexing from 0) for this node
/// and its children?
/// </summary>
property TokenStartIndex: Integer read GetTokenStartIndex write SetTokenStartIndex;
/// <summary>
/// What is the largest token index (indexing from 0) for this node
/// and its children?
/// </summary>
property TokenStopIndex: Integer read GetTokenStopIndex write SetTokenStopIndex;
property Text: String read GetText;
end;
/// <summary>A tree node that is wrapper for a Token object. </summary>
/// <remarks>
/// After 3.0 release while building tree rewrite stuff, it became clear
/// that computing parent and child index is very difficult and cumbersome.
/// Better to spend the space in every tree node. If you don't want these
/// extra fields, it's easy to cut them out in your own BaseTree subclass.
/// </remarks>
ICommonTree = interface(IBaseTree)
['{791C0EA6-1E4D-443E-83E2-CC1EFEAECC8B}']
{ Property accessors }
function GetToken: IToken;
function GetStartIndex: Integer;
procedure SetStartIndex(const Value: Integer);
function GetStopIndex: Integer;
procedure SetStopIndex(const Value: Integer);
{ Properties }
property Token: IToken read GetToken;
property StartIndex: Integer read GetStartIndex write SetStartIndex;
property StopIndex: Integer read GetStopIndex write SetStopIndex;
end;
// A node representing erroneous token range in token stream
ICommonErrorNode = interface(ICommonTree)
['{20FF30BA-C055-4E8F-B3E7-7FFF6313853E}']
end;
/// <summary>
/// A TreeAdaptor that works with any Tree implementation
/// </summary>
IBaseTreeAdaptor = interface(ITreeAdaptor)
['{B9CE670A-E53F-494C-B700-E4A3DF42D482}']
/// <summary>
/// This is generic in the sense that it will work with any kind of
/// tree (not just the ITree interface). It invokes the adaptor routines
/// not the tree node routines to do the construction.
/// </summary>
function DupTree(const Tree: IANTLRInterface): IANTLRInterface; overload;
function DupTree(const T, Parent: IANTLRInterface): IANTLRInterface; overload;
/// <summary>
/// Tell me how to create a token for use with imaginary token nodes.
/// For example, there is probably no input symbol associated with imaginary
/// token DECL, but you need to create it as a payload or whatever for
/// the DECL node as in ^(DECL type ID).
///
/// If you care what the token payload objects' type is, you should
/// override this method and any other createToken variant.
/// </summary>
function CreateToken(const TokenType: Integer; const Text: String): IToken; overload;
/// <summary>
/// Tell me how to create a token for use with imaginary token nodes.
/// For example, there is probably no input symbol associated with imaginary
/// token DECL, but you need to create it as a payload or whatever for
/// the DECL node as in ^(DECL type ID).
///
/// This is a variant of createToken where the new token is derived from
/// an actual real input token. Typically this is for converting '{'
/// tokens to BLOCK etc... You'll see
///
/// r : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ;
///
/// If you care what the token payload objects' type is, you should
/// override this method and any other createToken variant.
/// </summary>
function CreateToken(const FromToken: IToken): IToken; overload;
end;
/// <summary>
/// A TreeAdaptor that works with any Tree implementation. It provides
/// really just factory methods; all the work is done by BaseTreeAdaptor.
/// If you would like to have different tokens created than ClassicToken
/// objects, you need to override this and then set the parser tree adaptor to
/// use your subclass.
///
/// To get your parser to build nodes of a different type, override
/// Create(Token).
/// </summary>
ICommonTreeAdaptor = interface(IBaseTreeAdaptor)
['{B067EE7A-38EB-4156-9447-CDD6DDD6D13B}']
end;
/// <summary>
/// A buffered stream of tree nodes. Nodes can be from a tree of ANY kind.
/// </summary>
/// <remarks>
/// This node stream sucks all nodes out of the tree specified in the
/// constructor during construction and makes pointers into the tree
/// using an array of Object pointers. The stream necessarily includes
/// pointers to DOWN and UP and EOF nodes.
///
/// This stream knows how to mark/release for backtracking.
///
/// This stream is most suitable for tree interpreters that need to
/// jump around a lot or for tree parsers requiring speed (at cost of memory).
/// There is some duplicated functionality here with UnBufferedTreeNodeStream
/// but just in bookkeeping, not tree walking etc...
///
/// <see cref="UnBufferedTreeNodeStream"/>
///
/// </remarks>
ICommonTreeNodeStream = interface(ITreeNodeStream)
['{0112FB31-AA1E-471C-ADC3-D97AC5D77E05}']
{ Property accessors }
function GetCurrentSymbol: IANTLRInterface;
function GetTreeSource: IANTLRInterface;
function GetSourceName: String;
function GetTokenStream: ITokenStream;
procedure SetTokenStream(const Value: ITokenStream);
function GetTreeAdaptor: ITreeAdaptor;
procedure SetTreeAdaptor(const Value: ITreeAdaptor);
function GetHasUniqueNavigationNodes: Boolean;
procedure SetHasUniqueNavigationNodes(const Value: Boolean);
{ Methods }
/// <summary>
/// Walk tree with depth-first-search and fill nodes buffer.
/// Don't do DOWN, UP nodes if its a list (t is isNil).
/// </summary>
procedure FillBuffer(const T: IANTLRInterface);
function Get(const I: Integer): IANTLRInterface;
function LT(const K: Integer): IANTLRInterface;
/// <summary>
/// Look backwards k nodes
/// </summary>
function LB(const K: Integer): IANTLRInterface;
/// <summary>
/// Make stream jump to a new location, saving old location.
/// Switch back with pop().
/// </summary>
procedure Push(const Index: Integer);
/// <summary>
/// Seek back to previous index saved during last Push() call.
/// Return top of stack (return index).
/// </summary>
function Pop: Integer;
procedure Reset;
// Debugging
function ToTokenString(const Start, Stop: Integer): String;
function ToString(const Start, Stop: IANTLRInterface): String; overload;
function ToString: String; overload;
{ Properties }
property CurrentSymbol: IANTLRInterface read GetCurrentSymbol;
/// <summary>
/// Where is this stream pulling nodes from? This is not the name, but
/// the object that provides node objects.
/// </summary>
property TreeSource: IANTLRInterface read GetTreeSource;
property SourceName: String read GetSourceName;
property TokenStream: ITokenStream read GetTokenStream write SetTokenStream;
property TreeAdaptor: ITreeAdaptor read GetTreeAdaptor write SetTreeAdaptor;
property HasUniqueNavigationNodes: Boolean read GetHasUniqueNavigationNodes write SetHasUniqueNavigationNodes;
end;
/// <summary>
/// A record of the rules used to Match a token sequence. The tokens
/// end up as the leaves of this tree and rule nodes are the interior nodes.
/// This really adds no functionality, it is just an alias for CommonTree
/// that is more meaningful (specific) and holds a String to display for a node.
/// </summary>
IParseTree = interface(IANTLRInterface)
['{1558F260-CAF8-4488-A242-3559BCE4E573}']
{ Methods }
// Emit a token and all hidden nodes before. EOF node holds all
// hidden tokens after last real token.
function ToStringWithHiddenTokens: String;
// Print out the leaves of this tree, which means printing original
// input back out.
function ToInputString: String;
procedure _ToStringLeaves(const Buf: TStringBuilder);
end;
/// <summary>
/// A generic list of elements tracked in an alternative to be used in
/// a -> rewrite rule. We need to subclass to fill in the next() method,
/// which returns either an AST node wrapped around a token payload or
/// an existing subtree.
///
/// Once you start next()ing, do not try to add more elements. It will
/// break the cursor tracking I believe.
///
/// <see cref="RewriteRuleSubtreeStream"/>
/// <see cref="RewriteRuleTokenStream"/>
///
/// TODO: add mechanism to detect/puke on modification after reading from stream
/// </summary>
IRewriteRuleElementStream = interface(IANTLRInterface)
['{3CB6C521-F583-40DC-A1E3-4D7D57B98C74}']
{ Property accessors }
function GetDescription: String;
{ Methods }
procedure Add(const El: IANTLRInterface);
/// <summary>
/// Reset the condition of this stream so that it appears we have
/// not consumed any of its elements. Elements themselves are untouched.
/// </summary>
/// <remarks>
/// Once we reset the stream, any future use will need duplicates. Set
/// the dirty bit.
/// </remarks>
procedure Reset;
function HasNext: Boolean;
/// <summary>
/// Return the next element in the stream.
/// </summary>
function NextTree: IANTLRInterface;
function NextNode: IANTLRInterface;
function Size: Integer;
{ Properties }
property Description: String read GetDescription;
end;
/// <summary>
/// Queues up nodes matched on left side of -> in a tree parser. This is
/// the analog of RewriteRuleTokenStream for normal parsers.
/// </summary>
IRewriteRuleNodeStream = interface(IRewriteRuleElementStream)
['{F60D1D36-FE13-4312-99DA-11E5F4BEBB66}']
{ Methods }
function NextNode: IANTLRInterface;
end;
IRewriteRuleSubtreeStream = interface(IRewriteRuleElementStream)
['{C6BDA145-D926-45BC-B293-67490D72829B}']
{ Methods }
/// <summary>
/// Treat next element as a single node even if it's a subtree.
/// </summary>
/// <remarks>
/// This is used instead of next() when the result has to be a
/// tree root node. Also prevents us from duplicating recently-added
/// children; e.g., ^(type ID)+ adds ID to type and then 2nd iteration
/// must dup the type node, but ID has been added.
///
/// Referencing a rule result twice is ok; dup entire tree as
/// we can't be adding trees as root; e.g., expr expr.
/// </remarks>
function NextNode: IANTLRInterface;
end;
IRewriteRuleTokenStream = interface(IRewriteRuleElementStream)
['{4D46AB00-7A19-4F69-B159-1EF09DB8C09C}']
/// <summary>
/// Get next token from stream and make a node for it.
/// </summary>
/// <remarks>
/// ITreeAdaptor.Create() returns an object, so no further restrictions possible.
/// </remarks>
function NextNode: IANTLRInterface;
function NextToken: IToken;
end;
/// <summary>
/// A parser for a stream of tree nodes. "tree grammars" result in a subclass
/// of this. All the error reporting and recovery is shared with Parser via
/// the BaseRecognizer superclass.
/// </summary>
ITreeParser = interface(IBaseRecognizer)
['{20611FB3-9830-444D-B385-E8C2D094484B}']
{ Property accessors }
function GetTreeNodeStream: ITreeNodeStream;
procedure SetTreeNodeStream(const Value: ITreeNodeStream);
{ Methods }
procedure TraceIn(const RuleName: String; const RuleIndex: Integer);
procedure TraceOut(const RuleName: String; const RuleIndex: Integer);
{ Properties }
property TreeNodeStream: ITreeNodeStream read GetTreeNodeStream write SetTreeNodeStream;
end;
ITreePatternLexer = interface(IANTLRInterface)
['{C3FEC614-9E6F-48D2-ABAB-59FC83D8BC2F}']
{ Methods }
function NextToken: Integer;
function SVal: String;
end;
IContextVisitor = interface(IANTLRInterface)
['{92B80D23-C63E-48B4-A9CD-EC2639317E43}']
{ Methods }
procedure Visit(const T, Parent: IANTLRInterface; const ChildIndex: Integer;
const Labels: IDictionary<String, IANTLRInterface>);
end;
/// <summary>
/// Build and navigate trees with this object. Must know about the names
/// of tokens so you have to pass in a map or array of token names (from which
/// this class can build the map). I.e., Token DECL means nothing unless the
/// class can translate it to a token type.
/// </summary>
/// <remarks>
/// In order to create nodes and navigate, this class needs a TreeAdaptor.
///
/// This class can build a token type -> node index for repeated use or for
/// iterating over the various nodes with a particular type.
///
/// This class works in conjunction with the TreeAdaptor rather than moving
/// all this functionality into the adaptor. An adaptor helps build and
/// navigate trees using methods. This class helps you do it with string
/// patterns like "(A B C)". You can create a tree from that pattern or
/// match subtrees against it.
/// </remarks>
ITreeWizard = interface(IANTLRInterface)
['{4F440E19-893A-4E52-A979-E5377EAFA3B8}']
{ Methods }
/// <summary>
/// Compute a Map<String, Integer> that is an inverted index of
/// tokenNames (which maps int token types to names).
/// </summary>
function ComputeTokenTypes(const TokenNames: TStringArray): IDictionary<String, Integer>;
/// <summary>
/// Using the map of token names to token types, return the type.
/// </summary>
function GetTokenType(const TokenName: String): Integer;
/// <summary>
/// Walk the entire tree and make a node name to nodes mapping.
/// </summary>
/// <remarks>
/// For now, use recursion but later nonrecursive version may be
/// more efficient. Returns Map<Integer, List> where the List is
/// of your AST node type. The Integer is the token type of the node.
///
/// TODO: save this index so that find and visit are faster
/// </remarks>
function Index(const T: IANTLRInterface): IDictionary<Integer, IList<IANTLRInterface>>;
/// <summary>Return a List of tree nodes with token type ttype</summary>
function Find(const T: IANTLRInterface; const TokenType: Integer): IList<IANTLRInterface>; overload;
/// <summary>Return a List of subtrees matching pattern</summary>
function Find(const T: IANTLRInterface; const Pattern: String): IList<IANTLRInterface>; overload;
function FindFirst(const T: IANTLRInterface; const TokenType: Integer): IANTLRInterface; overload;
function FindFirst(const T: IANTLRInterface; const Pattern: String): IANTLRInterface; overload;
/// <summary>
/// Visit every ttype node in t, invoking the visitor.
/// </summary>
/// <remarks>
/// This is a quicker
/// version of the general visit(t, pattern) method. The labels arg
/// of the visitor action method is never set (it's null) since using
/// a token type rather than a pattern doesn't let us set a label.
/// </remarks>
procedure Visit(const T: IANTLRInterface; const TokenType: Integer;
const Visitor: IContextVisitor); overload;
/// <summary>
/// For all subtrees that match the pattern, execute the visit action.
/// </summary>
/// <remarks>
/// The implementation uses the root node of the pattern in combination
/// with visit(t, ttype, visitor) so nil-rooted patterns are not allowed.
/// Patterns with wildcard roots are also not allowed.
/// </remarks>
procedure Visit(const T: IANTLRInterface; const Pattern: String;
const Visitor: IContextVisitor); overload;
/// <summary>
/// Given a pattern like (ASSIGN %lhs:ID %rhs:.) with optional labels
/// on the various nodes and '.' (dot) as the node/subtree wildcard,
/// return true if the pattern matches and fill the labels Map with
/// the labels pointing at the appropriate nodes. Return false if
/// the pattern is malformed or the tree does not match.
/// </summary>
/// <remarks>
/// If a node specifies a text arg in pattern, then that must match
/// for that node in t.
///
/// TODO: what's a better way to indicate bad pattern? Exceptions are a hassle
/// </remarks>
function Parse(const T: IANTLRInterface; const Pattern: String;
const Labels: IDictionary<String, IANTLRInterface>): Boolean; overload;
function Parse(const T: IANTLRInterface; const Pattern: String): Boolean; overload;
/// <summary>
/// Create a tree or node from the indicated tree pattern that closely
/// follows ANTLR tree grammar tree element syntax:
///
/// (root child1 ... child2).
///
/// </summary>
/// <remarks>
/// You can also just pass in a node: ID
///
/// Any node can have a text argument: ID[foo]
/// (notice there are no quotes around foo--it's clear it's a string).
///
/// nil is a special name meaning "give me a nil node". Useful for
/// making lists: (nil A B C) is a list of A B C.
/// </remarks>
function CreateTreeOrNode(const Pattern: String): IANTLRInterface;
/// <summary>
/// Compare type, structure, and text of two trees, assuming adaptor in
/// this instance of a TreeWizard.
/// </summary>
function Equals(const T1, T2: IANTLRInterface): Boolean; overload;
/// <summary>
/// Compare t1 and t2; return true if token types/text, structure match exactly.
/// The trees are examined in their entirety so that (A B) does not match
/// (A B C) nor (A (B C)).
/// </summary>
/// <remarks>
/// TODO: allow them to pass in a comparator
/// TODO: have a version that is nonstatic so it can use instance adaptor
///
/// I cannot rely on the tree node's equals() implementation as I make
/// no constraints at all on the node types nor interface etc...
/// </remarks>
function Equals(const T1, T2: IANTLRInterface; const Adaptor: ITreeAdaptor): Boolean; overload;
end;
ITreePatternParser = interface(IANTLRInterface)
['{0CE3DF2A-7E4C-4A7C-8FE8-F1D7AFF97CAE}']
{ Methods }
function Pattern: IANTLRInterface;
function ParseTree: IANTLRInterface;
function ParseNode: IANTLRInterface;
end;
/// <summary>
/// This is identical to the ParserRuleReturnScope except that
/// the start property is a tree node and not a Token object
/// when you are parsing trees. To be generic the tree node types
/// have to be Object :(
/// </summary>
ITreeRuleReturnScope = interface(IRuleReturnScope)
['{FA2B1766-34E5-4D92-8996-371D5CFED999}']
end;
/// <summary>
/// A stream of tree nodes, accessing nodes from a tree of ANY kind.
/// </summary>
/// <remarks>
/// No new nodes should be created in tree during the walk. A small buffer
/// of tokens is kept to efficiently and easily handle LT(i) calls, though
/// the lookahead mechanism is fairly complicated.
///
/// For tree rewriting during tree parsing, this must also be able
/// to replace a set of children without "losing its place".
/// That part is not yet implemented. Will permit a rule to return
/// a different tree and have it stitched into the output tree probably.
///
/// <see cref="CommonTreeNodeStream"/>
///
/// </remarks>
IUnBufferedTreeNodeStream = interface(ITreeNodeStream)
['{E46367AD-ED41-4D97-824E-575A48F7435D}']
{ Property accessors }
function GetHasUniqueNavigationNodes: Boolean;
procedure SetHasUniqueNavigationNodes(const Value: Boolean);
function GetCurrent: IANTLRInterface;
function GetTokenStream: ITokenStream;
procedure SetTokenStream(const Value: ITokenStream);
{ Methods }
procedure Reset;
function MoveNext: Boolean;
{ Properties }
property HasUniqueNavigationNodes: Boolean read GetHasUniqueNavigationNodes write SetHasUniqueNavigationNodes;
property Current: IANTLRInterface read GetCurrent;
property TokenStream: ITokenStream read GetTokenStream write SetTokenStream;
end;
/// <summary>Base class for all exceptions thrown during AST rewrite construction.</summary>
/// <remarks>
/// This signifies a case where the cardinality of two or more elements
/// in a subrule are different: (ID INT)+ where |ID|!=|INT|
/// </remarks>
ERewriteCardinalityException = class(Exception)
strict private
FElementDescription: String;
public
constructor Create(const AElementDescription: String);
property ElementDescription: String read FElementDescription write FElementDescription;
end;
/// <summary>
/// No elements within a (...)+ in a rewrite rule
/// </summary>
ERewriteEarlyExitException = class(ERewriteCardinalityException)
// No new declarations
end;
/// <summary>
/// Ref to ID or expr but no tokens in ID stream or subtrees in expr stream
/// </summary>
ERewriteEmptyStreamException = class(ERewriteCardinalityException)
// No new declarations
end;
type
TTree = class sealed
strict private
class var
FINVALID_NODE: ITree;
private
class procedure Initialize; static;
public
class property INVALID_NODE: ITree read FINVALID_NODE;
end;
TBaseTree = class abstract(TANTLRObject, IBaseTree, ITree)
protected
{ ITree / IBaseTree }
function GetParent: ITree; virtual;
procedure SetParent(const Value: ITree); virtual;
function GetChildIndex: Integer; virtual;
procedure SetChildIndex(const Value: Integer); virtual;
function GetTokenType: Integer; virtual; abstract;
function GetText: String; virtual; abstract;
function GetTokenStartIndex: Integer; virtual; abstract;
procedure SetTokenStartIndex(const Value: Integer); virtual; abstract;
function GetTokenStopIndex: Integer; virtual; abstract;
procedure SetTokenStopIndex(const Value: Integer); virtual; abstract;
function DupNode: ITree; virtual; abstract;
function ToStringTree: String; virtual;
function GetChildCount: Integer; virtual;
function GetIsNil: Boolean; virtual;
function GetLine: Integer; virtual;
function GetCharPositionInLine: Integer; virtual;
function GetChild(const I: Integer): ITree; virtual;
procedure AddChild(const T: ITree);
function DeleteChild(const I: Integer): IANTLRInterface;
procedure FreshenParentAndChildIndexes; overload;
procedure ReplaceChildren(const StartChildIndex, StopChildIndex: Integer;
const T: IANTLRInterface);
protected
{ IBaseTree }
function GetChildren: IList<IBaseTree>;
procedure AddChildren(const Kids: IList<IBaseTree>);
procedure SetChild(const I: Integer; const T: ITree); virtual;
procedure FreshenParentAndChildIndexes(const Offset: Integer); overload;
procedure SanityCheckParentAndChildIndexes; overload; virtual;
procedure SanityCheckParentAndChildIndexes(const Parent: ITree;
const I: Integer); overload; virtual;
strict protected
FChildren: IList<IBaseTree>;
/// <summary>Override in a subclass to change the impl of children list </summary>
function CreateChildrenList: IList<IBaseTree>; virtual;
public
constructor Create; overload;
/// <summary>Create a new node from an existing node does nothing for BaseTree
/// as there are no fields other than the children list, which cannot
/// be copied as the children are not considered part of this node.
/// </summary>
constructor Create(const ANode: ITree); overload;
function ToString: String; override; abstract;
end;
TCommonTree = class(TBaseTree, ICommonTree)
strict protected
/// <summary>A single token is the payload </summary>
FToken: IToken;
/// <summary>
/// What token indexes bracket all tokens associated with this node
/// and below?
/// </summary>
FStartIndex: Integer;
FStopIndex: Integer;
/// <summary>Who is the parent node of this node; if null, implies node is root</summary>
/// <remarks>
/// FParent should be of type ICommonTree, but that would introduce a
/// circular reference because the tree also maintains links to it's
/// children. This circular reference would cause a memory leak because
/// the reference count will never reach 0. This is avoided by making
/// FParent a regular pointer and letting the GetParent and SetParent
/// property accessors do the conversion to/from ICommonTree.
/// </remarks>
FParent: Pointer; { ICommonTree ; }
/// <summary>What index is this node in the child list? Range: 0..n-1</summary>
FChildIndex: Integer;
protected
{ ITree / IBaseTree }
function GetIsNil: Boolean; override;
function GetTokenType: Integer; override;
function GetText: String; override;
function GetLine: Integer; override;
function GetCharPositionInLine: Integer; override;
function GetTokenStartIndex: Integer; override;
procedure SetTokenStartIndex(const Value: Integer); override;
function GetTokenStopIndex: Integer; override;
procedure SetTokenStopIndex(const Value: Integer); override;
function GetChildIndex: Integer; override;
procedure SetChildIndex(const Value: Integer); override;
function GetParent: ITree; override;
procedure SetParent(const Value: ITree); override;
function DupNode: ITree; override;
protected
{ ICommonTree }
function GetToken: IToken;
function GetStartIndex: Integer;
procedure SetStartIndex(const Value: Integer);
function GetStopIndex: Integer;
procedure SetStopIndex(const Value: Integer);
public
constructor Create; overload;
constructor Create(const ANode: ICommonTree); overload;
constructor Create(const AToken: IToken); overload;
function ToString: String; override;
end;
TCommonErrorNode = class(TCommonTree, ICommonErrorNode)
strict private
FInput: IIntStream;
FStart: IToken;
FStop: IToken;
FTrappedException: ERecognitionException;
protected
{ ITree / IBaseTree }
function GetIsNil: Boolean; override;
function GetTokenType: Integer; override;
function GetText: String; override;
public
constructor Create(const AInput: ITokenStream; const AStart, AStop: IToken;
const AException: ERecognitionException);
function ToString: String; override;
end;
TBaseTreeAdaptor = class abstract(TANTLRObject, IBaseTreeAdaptor, ITreeAdaptor)
strict private
/// <summary>A map of tree node to unique IDs.</summary>
FTreeToUniqueIDMap: IDictionary<IANTLRInterface, Integer>;
/// <summary>Next available unique ID.</summary>
FUniqueNodeID: Integer;
protected
{ ITreeAdaptor }
function CreateNode(const Payload: IToken): IANTLRInterface; overload; virtual; abstract;
function DupNode(const TreeNode: IANTLRInterface): IANTLRInterface; virtual; abstract;
function DupTree(const Tree: IANTLRInterface): IANTLRInterface; overload; virtual;
function GetNilNode: IANTLRInterface; virtual;
function ErrorNode(const Input: ITokenStream; const Start, Stop: IToken;
const E: ERecognitionException): IANTLRInterface; virtual;
function IsNil(const Tree: IANTLRInterface): Boolean; virtual;
procedure AddChild(const T, Child: IANTLRInterface); virtual;
function BecomeRoot(const NewRoot, OldRoot: IANTLRInterface): IANTLRInterface; overload; virtual;
function RulePostProcessing(const Root: IANTLRInterface): IANTLRInterface; virtual;
function GetUniqueID(const Node: IANTLRInterface): Integer;
function BecomeRoot(const NewRoot: IToken; const OldRoot: IANTLRInterface): IANTLRInterface; overload; virtual;
function CreateNode(const TokenType: Integer; const FromToken: IToken): IANTLRInterface; overload; virtual;
function CreateNode(const TokenType: Integer; const FromToken: IToken;
const Text: String): IANTLRInterface; overload; virtual;
function CreateNode(const TokenType: Integer; const Text: String): IANTLRInterface; overload; virtual;
function GetNodeType(const T: IANTLRInterface): Integer; virtual;
procedure SetNodeType(const T: IANTLRInterface; const NodeType: Integer); virtual;
function GetNodeText(const T: IANTLRInterface): String; virtual;
procedure SetNodeText(const T: IANTLRInterface; const Text: String); virtual;
function GetToken(const TreeNode: IANTLRInterface): IToken; virtual; abstract;
procedure SetTokenBoundaries(const T: IANTLRInterface; const StartToken,
StopToken: IToken); virtual; abstract;
function GetTokenStartIndex(const T: IANTLRInterface): Integer; virtual; abstract;
function GetTokenStopIndex(const T: IANTLRInterface): Integer; virtual; abstract;
function GetChild(const T: IANTLRInterface; const I: Integer): IANTLRInterface; virtual;
procedure SetChild(const T: IANTLRInterface; const I: Integer; const Child: IANTLRInterface); virtual;
function DeleteChild(const T: IANTLRInterface; const I: Integer): IANTLRInterface; virtual;
function GetChildCount(const T: IANTLRInterface): Integer; virtual;
function GetParent(const T: IANTLRInterface): IANTLRInterface; virtual; abstract;
procedure SetParent(const T, Parent: IANTLRInterface); virtual; abstract;
function GetChildIndex(const T: IANTLRInterface): Integer; virtual; abstract;
procedure SetChildIdex(const T: IANTLRInterface; const Index: Integer); virtual; abstract;
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface); virtual; abstract;
protected
{ IBaseTreeAdaptor }
function DupTree(const T, Parent: IANTLRInterface): IANTLRInterface; overload; virtual;
function CreateToken(const TokenType: Integer; const Text: String): IToken; overload; virtual; abstract;
function CreateToken(const FromToken: IToken): IToken; overload; virtual; abstract;
public
constructor Create;
end;
TCommonTreeAdaptor = class(TBaseTreeAdaptor, ICommonTreeAdaptor)
protected
{ ITreeAdaptor }
function DupNode(const TreeNode: IANTLRInterface): IANTLRInterface; override;
function CreateNode(const Payload: IToken): IANTLRInterface; overload; override;
procedure SetTokenBoundaries(const T: IANTLRInterface; const StartToken,
StopToken: IToken); override;
function GetTokenStartIndex(const T: IANTLRInterface): Integer; override;
function GetTokenStopIndex(const T: IANTLRInterface): Integer; override;
function GetNodeText(const T: IANTLRInterface): String; override;
function GetToken(const TreeNode: IANTLRInterface): IToken; override;
function GetNodeType(const T: IANTLRInterface): Integer; override;
function GetChild(const T: IANTLRInterface; const I: Integer): IANTLRInterface; override;
function GetChildCount(const T: IANTLRInterface): Integer; override;
function GetParent(const T: IANTLRInterface): IANTLRInterface; override;
procedure SetParent(const T, Parent: IANTLRInterface); override;
function GetChildIndex(const T: IANTLRInterface): Integer; override;
procedure SetChildIdex(const T: IANTLRInterface; const Index: Integer); override;
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface); override;
protected
{ IBaseTreeAdaptor }
function CreateToken(const TokenType: Integer; const Text: String): IToken; overload; override;
function CreateToken(const FromToken: IToken): IToken; overload; override;
end;
TCommonTreeNodeStream = class(TANTLRObject, ICommonTreeNodeStream, ITreeNodeStream)
public
const
DEFAULT_INITIAL_BUFFER_SIZE = 100;
INITIAL_CALL_STACK_SIZE = 10;
strict private
// all these navigation nodes are shared and hence they
// cannot contain any line/column info
FDown: IANTLRInterface;
FUp: IANTLRInterface;
FEof: IANTLRInterface;
/// <summary>
/// The complete mapping from stream index to tree node. This buffer
/// includes pointers to DOWN, UP, and EOF nodes.
///
/// It is built upon ctor invocation. The elements are type Object
/// as we don't what the trees look like. Load upon first need of
/// the buffer so we can set token types of interest for reverseIndexing.
/// Slows us down a wee bit to do all of the if p==-1 testing everywhere though.
/// </summary>
FNodes: IList<IANTLRInterface>;
/// <summary>Pull nodes from which tree? </summary>
FRoot: IANTLRInterface;
/// <summary>IF this tree (root) was created from a token stream, track it</summary>
FTokens: ITokenStream;
/// <summary>What tree adaptor was used to build these trees</summary>
FAdaptor: ITreeAdaptor;
/// <summary>
/// Reuse same DOWN, UP navigation nodes unless this is true
/// </summary>
FUniqueNavigationNodes: Boolean;
/// <summary>
/// The index into the nodes list of the current node (next node
/// to consume). If -1, nodes array not filled yet.
/// </summary>
FP: Integer;
/// <summary>
/// Track the last mark() call result value for use in rewind().
/// </summary>
FLastMarker: Integer;
/// <summary>
/// Stack of indexes used for push/pop calls
/// </summary>
FCalls: IStackList<Integer>;
protected
{ IIntStream }
function GetSourceName: String; virtual;
procedure Consume; virtual;
function LA(I: Integer): Integer; virtual;
function LAChar(I: Integer): Char;
function Mark: Integer; virtual;
function Index: Integer; virtual;
procedure Rewind(const Marker: Integer); overload; virtual;
procedure Rewind; overload;
procedure Release(const Marker: Integer); virtual;
procedure Seek(const Index: Integer); virtual;
function Size: Integer; virtual;
protected
{ ITreeNodeStream }
function GetTreeSource: IANTLRInterface; virtual;
function GetTokenStream: ITokenStream; virtual;
function GetTreeAdaptor: ITreeAdaptor;
procedure SetHasUniqueNavigationNodes(const Value: Boolean);
function Get(const I: Integer): IANTLRInterface;
function LT(const K: Integer): IANTLRInterface;
function ToString(const Start, Stop: IANTLRInterface): String; reintroduce; overload;
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface);
protected
{ ICommonTreeNodeStream }
function GetCurrentSymbol: IANTLRInterface; virtual;
procedure SetTokenStream(const Value: ITokenStream); virtual;
procedure SetTreeAdaptor(const Value: ITreeAdaptor);
function GetHasUniqueNavigationNodes: Boolean;
procedure FillBuffer(const T: IANTLRInterface); overload;
function LB(const K: Integer): IANTLRInterface;
procedure Push(const Index: Integer);
function Pop: Integer;
procedure Reset;
function ToTokenString(const Start, Stop: Integer): String;
strict protected
/// <summary>
/// Walk tree with depth-first-search and fill nodes buffer.
/// Don't do DOWN, UP nodes if its a list (t is isNil).
/// </summary>
procedure FillBuffer; overload;
/// <summary>
/// As we flatten the tree, we use UP, DOWN nodes to represent
/// the tree structure. When debugging we need unique nodes
/// so instantiate new ones when uniqueNavigationNodes is true.
/// </summary>
procedure AddNavigationNode(const TokenType: Integer);
/// <summary>
/// Returns the stream index for the spcified node in the range 0..n-1 or,
/// -1 if node not found.
/// </summary>
function GetNodeIndex(const Node: IANTLRInterface): Integer;
public
constructor Create; overload;
constructor Create(const ATree: IANTLRInterface); overload;
constructor Create(const AAdaptor: ITreeAdaptor;
const ATree: IANTLRInterface); overload;
constructor Create(const AAdaptor: ITreeAdaptor;
const ATree: IANTLRInterface; const AInitialBufferSize: Integer); overload;
function ToString: String; overload; override;
end;
TParseTree = class(TBaseTree, IParseTree)
strict private
FPayload: IANTLRInterface;
FHiddenTokens: IList<IToken>;
protected
{ ITree / IBaseTree }
function GetTokenType: Integer; override;
function GetText: String; override;
function GetTokenStartIndex: Integer; override;
procedure SetTokenStartIndex(const Value: Integer); override;
function GetTokenStopIndex: Integer; override;
procedure SetTokenStopIndex(const Value: Integer); override;
function DupNode: ITree; override;
protected
{ IParseTree }
function ToStringWithHiddenTokens: String;
function ToInputString: String;
procedure _ToStringLeaves(const Buf: TStringBuilder);
public
constructor Create(const ALabel: IANTLRInterface);
function ToString: String; override;
end;
TRewriteRuleElementStream = class abstract(TANTLRObject, IRewriteRuleElementStream)
private
/// <summary>
/// Cursor 0..n-1. If singleElement!=null, cursor is 0 until you next(),
/// which bumps it to 1 meaning no more elements.
/// </summary>
FCursor: Integer;
/// <summary>
/// Track single elements w/o creating a list. Upon 2nd add, alloc list
/// </summary>
FSingleElement: IANTLRInterface;
/// <summary>
/// The list of tokens or subtrees we are tracking
/// </summary>
FElements: IList<IANTLRInterface>;
/// <summary>
/// Tracks whether a node or subtree has been used in a stream
/// </summary>
/// <remarks>
/// Once a node or subtree has been used in a stream, it must be dup'd
/// from then on. Streams are reset after subrules so that the streams
/// can be reused in future subrules. So, reset must set a dirty bit.
/// If dirty, then next() always returns a dup.
/// </remarks>
FDirty: Boolean;
/// <summary>
/// The element or stream description; usually has name of the token or
/// rule reference that this list tracks. Can include rulename too, but
/// the exception would track that info.
/// </summary>
FElementDescription: String;
FAdaptor: ITreeAdaptor;
protected
{ IRewriteRuleElementStream }
function GetDescription: String;
procedure Add(const El: IANTLRInterface);
procedure Reset; virtual;
function HasNext: Boolean;
function NextTree: IANTLRInterface; virtual;
function NextNode: IANTLRInterface; virtual; abstract;
function Size: Integer;
strict protected
/// <summary>
/// Do the work of getting the next element, making sure that
/// it's a tree node or subtree.
/// </summary>
/// <remarks>
/// Deal with the optimization of single-element list versus
/// list of size > 1. Throw an exception if the stream is
/// empty or we're out of elements and size>1.
/// </remarks>
function _Next: IANTLRInterface;
/// <summary>
/// Ensure stream emits trees; tokens must be converted to AST nodes.
/// AST nodes can be passed through unmolested.
/// </summary>
function ToTree(const El: IANTLRInterface): IANTLRInterface; virtual;
public
constructor Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String); overload;
/// <summary>
/// Create a stream with one element
/// </summary>
constructor Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String; const AOneElement: IANTLRInterface); overload;
/// <summary>
/// Create a stream, but feed off an existing list
/// </summary>
constructor Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String; const AElements: IList<IANTLRInterface>); overload;
end;
TRewriteRuleNodeStream = class(TRewriteRuleElementStream, IRewriteRuleNodeStream)
protected
{ IRewriteRuleElementStream }
function NextNode: IANTLRInterface; override;
function ToTree(const El: IANTLRInterface): IANTLRInterface; override;
end;
TRewriteRuleSubtreeStream = class(TRewriteRuleElementStream, IRewriteRuleSubtreeStream)
public
type
/// <summary>
/// This delegate is used to allow the outfactoring of some common code.
/// </summary>
/// <param name="o">The to be processed object</param>
TProcessHandler = function(const O: IANTLRInterface): IANTLRInterface of Object;
strict private
/// <summary>
/// This method has the common code of two other methods, which differed in only one
/// function call.
/// </summary>
/// <param name="ph">The delegate, which has the chosen function</param>
/// <returns>The required object</returns>
function FetchObject(const PH: TProcessHandler): IANTLRInterface;
function DupNode(const O: IANTLRInterface): IANTLRInterface;
/// <summary>
/// Tests, if the to be returned object requires duplication
/// </summary>
/// <returns><code>true</code>, if positive, <code>false</code>, if negative.</returns>
function RequiresDuplication: Boolean;
/// <summary>
/// When constructing trees, sometimes we need to dup a token or AST
/// subtree. Dup'ing a token means just creating another AST node
/// around it. For trees, you must call the adaptor.dupTree()
/// unless the element is for a tree root; then it must be a node dup
/// </summary>
function Dup(const O: IANTLRInterface): IANTLRInterface;
protected
{ IRewriteRuleElementStream }
function NextNode: IANTLRInterface; override;
function NextTree: IANTLRInterface; override;
end;
TRewriteRuleTokenStream = class(TRewriteRuleElementStream, IRewriteRuleTokenStream)
protected
{ IRewriteRuleElementStream }
function NextNode: IANTLRInterface; override;
function NextToken: IToken;
function ToTree(const El: IANTLRInterface): IANTLRInterface; override;
end;
TTreeParser = class(TBaseRecognizer, ITreeParser)
public
const
DOWN = TToken.DOWN;
UP = TToken.UP;
strict private
FInput: ITreeNodeStream;
strict protected
property Input: ITreeNodeStream read FInput;
protected
{ IBaseRecognizer }
function GetSourceName: String; override;
procedure Reset; override;
procedure MatchAny(const Input: IIntStream); override;
function GetInput: IIntStream; override;
function GetErrorHeader(const E: ERecognitionException): String; override;
function GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String; override;
protected
{ ITreeParser }
function GetTreeNodeStream: ITreeNodeStream; virtual;
procedure SetTreeNodeStream(const Value: ITreeNodeStream); virtual;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer); reintroduce; overload; virtual;
procedure TraceOut(const RuleName: String; const RuleIndex: Integer); reintroduce; overload; virtual;
strict protected
function GetCurrentInputSymbol(const Input: IIntStream): IANTLRInterface; override;
function GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface; override;
procedure Mismatch(const Input: IIntStream; const TokenType: Integer;
const Follow: IBitSet); override;
public
constructor Create(const AInput: ITreeNodeStream); overload;
constructor Create(const AInput: ITreeNodeStream;
const AState: IRecognizerSharedState); overload;
end;
TTreePatternLexer = class(TANTLRObject, ITreePatternLexer)
public
const
EOF = -1;
START = 1;
STOP = 2;
ID = 3;
ARG = 4;
PERCENT = 5;
COLON = 6;
DOT = 7;
strict private
/// <summary>The tree pattern to lex like "(A B C)"</summary>
FPattern: String;
/// <summary>Index into input string</summary>
FP: Integer;
/// <summary>Current char</summary>
FC: Integer;
/// <summary>How long is the pattern in char?</summary>
FN: Integer;
/// <summary>
/// Set when token type is ID or ARG (name mimics Java's StreamTokenizer)
/// </summary>
FSVal: TStringBuilder;
FError: Boolean;
protected
{ ITreePatternLexer }
function NextToken: Integer;
function SVal: String;
strict protected
procedure Consume;
public
constructor Create; overload;
constructor Create(const APattern: String); overload;
destructor Destroy; override;
end;
TTreeWizard = class(TANTLRObject, ITreeWizard)
strict private
FAdaptor: ITreeAdaptor;
FTokenNameToTypeMap: IDictionary<String, Integer>;
public
type
/// <summary>
/// When using %label:TOKENNAME in a tree for parse(), we must track the label.
/// </summary>
ITreePattern = interface(ICommonTree)
['{893C6B4E-8474-4A1E-BEAA-8B704868401B}']
{ Property accessors }
function GetHasTextArg: Boolean;
procedure SetHasTextArg(const Value: Boolean);
function GetTokenLabel: String;
procedure SetTokenLabel(const Value: String);
{ Properties }
property HasTextArg: Boolean read GetHasTextArg write SetHasTextArg;
property TokenLabel: String read GetTokenLabel write SetTokenLabel;
end;
IWildcardTreePattern = interface(ITreePattern)
['{4778789A-5EAB-47E3-A05B-7F35CD87ECE4}']
end;
type
TVisitor = class abstract(TANTLRObject, IContextVisitor)
protected
{ IContextVisitor }
procedure Visit(const T, Parent: IANTLRInterface; const ChildIndex: Integer;
const Labels: IDictionary<String, IANTLRInterface>); overload;
strict protected
procedure Visit(const T: IANTLRInterface); overload; virtual; abstract;
end;
TTreePattern = class(TCommonTree, ITreePattern)
strict private
FLabel: String;
FHasTextArg: Boolean;
protected
{ ITreePattern }
function GetHasTextArg: Boolean;
procedure SetHasTextArg(const Value: Boolean);
function GetTokenLabel: String;
procedure SetTokenLabel(const Value: String);
public
function ToString: String; override;
end;
TWildcardTreePattern = class(TTreePattern, IWildcardTreePattern)
end;
/// <summary>
/// This adaptor creates TreePattern objects for use during scan()
/// </summary>
TTreePatternTreeAdaptor = class(TCommonTreeAdaptor)
protected
{ ITreeAdaptor }
function CreateNode(const Payload: IToken): IANTLRInterface; overload; override;
end;
strict private
type
TRecordAllElementsVisitor = class sealed(TVisitor)
strict private
FList: IList<IANTLRInterface>;
strict protected
procedure Visit(const T: IANTLRInterface); override;
public
constructor Create(const AList: IList<IANTLRInterface>);
end;
type
TPatternMatchingContextVisitor = class sealed(TANTLRObject, IContextVisitor)
strict private
FOwner: TTreeWizard;
FPattern: ITreePattern;
FList: IList<IANTLRInterface>;
protected
{ IContextVisitor }
procedure Visit(const T, Parent: IANTLRInterface; const ChildIndex: Integer;
const Labels: IDictionary<String, IANTLRInterface>); overload;
public
constructor Create(const AOwner: TTreeWizard; const APattern: ITreePattern;
const AList: IList<IANTLRInterface>);
end;
type
TInvokeVisitorOnPatternMatchContextVisitor = class sealed(TANTLRObject, IContextVisitor)
strict private
FOwner: TTreeWizard;
FPattern: ITreePattern;
FVisitor: IContextVisitor;
FLabels: IDictionary<String, IANTLRInterface>;
protected
{ IContextVisitor }
procedure Visit(const T, Parent: IANTLRInterface; const ChildIndex: Integer;
const UnusedLabels: IDictionary<String, IANTLRInterface>); overload;
public
constructor Create(const AOwner: TTreeWizard; const APattern: ITreePattern;
const AVisitor: IContextVisitor);
end;
protected
{ ITreeWizard }
function ComputeTokenTypes(const TokenNames: TStringArray): IDictionary<String, Integer>;
function GetTokenType(const TokenName: String): Integer;
function Index(const T: IANTLRInterface): IDictionary<Integer, IList<IANTLRInterface>>;
function Find(const T: IANTLRInterface; const TokenType: Integer): IList<IANTLRInterface>; overload;
function Find(const T: IANTLRInterface; const Pattern: String): IList<IANTLRInterface>; overload;
function FindFirst(const T: IANTLRInterface; const TokenType: Integer): IANTLRInterface; overload;
function FindFirst(const T: IANTLRInterface; const Pattern: String): IANTLRInterface; overload;
procedure Visit(const T: IANTLRInterface; const TokenType: Integer;
const Visitor: IContextVisitor); overload;
procedure Visit(const T: IANTLRInterface; const Pattern: String;
const Visitor: IContextVisitor); overload;
function Parse(const T: IANTLRInterface; const Pattern: String;
const Labels: IDictionary<String, IANTLRInterface>): Boolean; overload;
function Parse(const T: IANTLRInterface; const Pattern: String): Boolean; overload;
function CreateTreeOrNode(const Pattern: String): IANTLRInterface;
function Equals(const T1, T2: IANTLRInterface): Boolean; reintroduce; overload;
function Equals(const T1, T2: IANTLRInterface;
const Adaptor: ITreeAdaptor): Boolean; reintroduce; overload;
strict protected
function _Parse(const T1: IANTLRInterface; const T2: ITreePattern;
const Labels: IDictionary<String, IANTLRInterface>): Boolean;
/// <summary>Do the work for index</summary>
procedure _Index(const T: IANTLRInterface;
const M: IDictionary<Integer, IList<IANTLRInterface>>);
/// <summary>Do the recursive work for visit</summary>
procedure _Visit(const T, Parent: IANTLRInterface; const ChildIndex,
TokenType: Integer; const Visitor: IContextVisitor);
class function _Equals(const T1, T2: IANTLRInterface;
const Adaptor: ITreeAdaptor): Boolean; static;
public
constructor Create(const AAdaptor: ITreeAdaptor); overload;
constructor Create(const AAdaptor: ITreeAdaptor;
const ATokenNameToTypeMap: IDictionary<String, Integer>); overload;
constructor Create(const AAdaptor: ITreeAdaptor;
const TokenNames: TStringArray); overload;
constructor Create(const TokenNames: TStringArray); overload;
end;
TTreePatternParser = class(TANTLRObject, ITreePatternParser)
strict private
FTokenizer: ITreePatternLexer;
FTokenType: Integer;
FWizard: ITreeWizard;
FAdaptor: ITreeAdaptor;
protected
{ ITreePatternParser }
function Pattern: IANTLRInterface;
function ParseTree: IANTLRInterface;
function ParseNode: IANTLRInterface;
public
constructor Create(const ATokenizer: ITreePatternLexer;
const AWizard: ITreeWizard; const AAdaptor: ITreeAdaptor);
end;
TTreeRuleReturnScope = class(TRuleReturnScope, ITreeRuleReturnScope)
strict private
/// <summary>First node or root node of tree matched for this rule.</summary>
FStart: IANTLRInterface;
protected
{ IRuleReturnScope }
function GetStart: IANTLRInterface; override;
procedure SetStart(const Value: IANTLRInterface); override;
end;
TUnBufferedTreeNodeStream = class(TANTLRObject, IUnBufferedTreeNodeStream, ITreeNodeStream)
public
const
INITIAL_LOOKAHEAD_BUFFER_SIZE = 5;
strict protected
type
/// <summary>
/// When walking ahead with cyclic DFA or for syntactic predicates,
/// we need to record the state of the tree node stream. This
/// class wraps up the current state of the UnBufferedTreeNodeStream.
/// Calling Mark() will push another of these on the markers stack.
/// </summary>
ITreeWalkState = interface(IANTLRInterface)
['{506D1014-53CF-4B9D-BE0E-1666E9C22091}']
{ Property accessors }
function GetCurrentChildIndex: Integer;
procedure SetCurrentChildIndex(const Value: Integer);
function GetAbsoluteNodeIndex: Integer;
procedure SetAbsoluteNodeIndex(const Value: Integer);
function GetCurrentNode: IANTLRInterface;
procedure SetCurrentNode(const Value: IANTLRInterface);
function GetPreviousNode: IANTLRInterface;
procedure SetPreviousNode(const Value: IANTLRInterface);
function GetNodeStackSize: Integer;
procedure SetNodeStackSize(const Value: Integer);
function GetIndexStackSize: integer;
procedure SetIndexStackSize(const Value: integer);
function GetLookAhead: TANTLRInterfaceArray;
procedure SetLookAhead(const Value: TANTLRInterfaceArray);
{ Properties }
property CurrentChildIndex: Integer read GetCurrentChildIndex write SetCurrentChildIndex;
property AbsoluteNodeIndex: Integer read GetAbsoluteNodeIndex write SetAbsoluteNodeIndex;
property CurrentNode: IANTLRInterface read GetCurrentNode write SetCurrentNode;
property PreviousNode: IANTLRInterface read GetPreviousNode write SetPreviousNode;
///<summary>Record state of the nodeStack</summary>
property NodeStackSize: Integer read GetNodeStackSize write SetNodeStackSize;
///<summary>Record state of the indexStack</summary>
property IndexStackSize: integer read GetIndexStackSize write SetIndexStackSize;
property LookAhead: TANTLRInterfaceArray read GetLookAhead write SetLookAhead;
end;
TTreeWalkState = class(TANTLRObject, ITreeWalkState)
strict private
FCurrentChildIndex: Integer;
FAbsoluteNodeIndex: Integer;
FCurrentNode: IANTLRInterface;
FPreviousNode: IANTLRInterface;
///<summary>Record state of the nodeStack</summary>
FNodeStackSize: Integer;
///<summary>Record state of the indexStack</summary>
FIndexStackSize: integer;
FLookAhead: TANTLRInterfaceArray;
protected
{ ITreeWalkState }
function GetCurrentChildIndex: Integer;
procedure SetCurrentChildIndex(const Value: Integer);
function GetAbsoluteNodeIndex: Integer;
procedure SetAbsoluteNodeIndex(const Value: Integer);
function GetCurrentNode: IANTLRInterface;
procedure SetCurrentNode(const Value: IANTLRInterface);
function GetPreviousNode: IANTLRInterface;
procedure SetPreviousNode(const Value: IANTLRInterface);
function GetNodeStackSize: Integer;
procedure SetNodeStackSize(const Value: Integer);
function GetIndexStackSize: integer;
procedure SetIndexStackSize(const Value: integer);
function GetLookAhead: TANTLRInterfaceArray;
procedure SetLookAhead(const Value: TANTLRInterfaceArray);
end;
strict private
/// <summary>Reuse same DOWN, UP navigation nodes unless this is true</summary>
FUniqueNavigationNodes: Boolean;
/// <summary>Pull nodes from which tree? </summary>
FRoot: IANTLRInterface;
/// <summary>IF this tree (root) was created from a token stream, track it.</summary>
FTokens: ITokenStream;
/// <summary>What tree adaptor was used to build these trees</summary>
FAdaptor: ITreeAdaptor;
/// <summary>
/// As we walk down the nodes, we must track parent nodes so we know
/// where to go after walking the last child of a node. When visiting
/// a child, push current node and current index.
/// </summary>
FNodeStack: IStackList<IANTLRInterface>;
/// <summary>
/// Track which child index you are visiting for each node we push.
/// TODO: pretty inefficient...use int[] when you have time
/// </summary>
FIndexStack: IStackList<Integer>;
/// <summary>Which node are we currently visiting? </summary>
FCurrentNode: IANTLRInterface;
/// <summary>Which node did we visit last? Used for LT(-1) calls. </summary>
FPreviousNode: IANTLRInterface;
/// <summary>
/// Which child are we currently visiting? If -1 we have not visited
/// this node yet; next Consume() request will set currentIndex to 0.
/// </summary>
FCurrentChildIndex: Integer;
/// <summary>
/// What node index did we just consume? i=0..n-1 for n node trees.
/// IntStream.next is hence 1 + this value. Size will be same.
/// </summary>
FAbsoluteNodeIndex: Integer;
/// <summary>
/// Buffer tree node stream for use with LT(i). This list grows
/// to fit new lookahead depths, but Consume() wraps like a circular
/// buffer.
/// </summary>
FLookahead: TANTLRInterfaceArray;
/// <summary>lookahead[head] is the first symbol of lookahead, LT(1). </summary>
FHead: Integer;
/// <summary>
/// Add new lookahead at lookahead[tail]. tail wraps around at the
/// end of the lookahead buffer so tail could be less than head.
/// </summary>
FTail: Integer;
/// <summary>
/// Calls to Mark() may be nested so we have to track a stack of them.
/// The marker is an index into this stack. This is a List<TreeWalkState>.
/// Indexed from 1..markDepth. A null is kept at index 0. It is created
/// upon first call to Mark().
/// </summary>
FMarkers: IList<ITreeWalkState>;
///<summary>
/// tracks how deep Mark() calls are nested
/// </summary>
FMarkDepth: Integer;
///<summary>
/// Track the last Mark() call result value for use in Rewind().
/// </summary>
FLastMarker: Integer;
// navigation nodes
FDown: IANTLRInterface;
FUp: IANTLRInterface;
FEof: IANTLRInterface;
FCurrentEnumerationNode: ITree;
protected
{ IIntStream }
function GetSourceName: String;
procedure Consume; virtual;
function LA(I: Integer): Integer; virtual;
function LAChar(I: Integer): Char;
function Mark: Integer; virtual;
function Index: Integer; virtual;
procedure Rewind(const Marker: Integer); overload; virtual;
procedure Rewind; overload;
procedure Release(const Marker: Integer); virtual;
procedure Seek(const Index: Integer); virtual;
function Size: Integer; virtual;
protected
{ ITreeNodeStream }
function GetTreeSource: IANTLRInterface; virtual;
function GetTokenStream: ITokenStream;
function GetTreeAdaptor: ITreeAdaptor;
function Get(const I: Integer): IANTLRInterface; virtual;
function LT(const K: Integer): IANTLRInterface; virtual;
function ToString(const Start, Stop: IANTLRInterface): String; reintroduce; overload; virtual;
procedure ReplaceChildren(const Parent: IANTLRInterface; const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface);
protected
{ IUnBufferedTreeNodeStream }
function GetHasUniqueNavigationNodes: Boolean;
procedure SetHasUniqueNavigationNodes(const Value: Boolean);
function GetCurrent: IANTLRInterface; virtual;
procedure SetTokenStream(const Value: ITokenStream);
procedure Reset; virtual;
/// <summary>
/// Navigates to the next node found during a depth-first walk of root.
/// Also, adds these nodes and DOWN/UP imaginary nodes into the lokoahead
/// buffer as a side-effect. Normally side-effects are bad, but because
/// we can Emit many tokens for every MoveNext() call, it's pretty hard to
/// use a single return value for that. We must add these tokens to
/// the lookahead buffer.
///
/// This routine does *not* cause the 'Current' property to ever return the
/// DOWN/UP nodes; those are only returned by the LT() method.
///
/// Ugh. This mechanism is much more complicated than a recursive
/// solution, but it's the only way to provide nodes on-demand instead
/// of walking once completely through and buffering up the nodes. :(
/// </summary>
function MoveNext: Boolean; virtual;
strict protected
/// <summary>Make sure we have at least k symbols in lookahead buffer </summary>
procedure Fill(const K: Integer); virtual;
function LookaheadSize: Integer;
/// <summary>
/// Add a node to the lookahead buffer. Add at lookahead[tail].
/// If you tail+1 == head, then we must create a bigger buffer
/// and copy all the nodes over plus reset head, tail. After
/// this method, LT(1) will be lookahead[0].
/// </summary>
procedure AddLookahead(const Node: IANTLRInterface); virtual;
procedure ToStringWork(const P, Stop: IANTLRInterface;
const Buf: TStringBuilder); virtual;
function HandleRootNode: IANTLRInterface; virtual;
function VisitChild(const Child: Integer): IANTLRInterface; virtual;
/// <summary>
/// Walk upwards looking for a node with more children to walk.
/// </summary>
procedure WalkBackToMostRecentNodeWithUnvisitedChildren; virtual;
/// <summary>
/// As we flatten the tree, we use UP, DOWN nodes to represent
/// the tree structure. When debugging we need unique nodes
/// so instantiate new ones when uniqueNavigationNodes is true.
/// </summary>
procedure AddNavigationNode(const TokenType: Integer); virtual;
public
constructor Create; overload;
constructor Create(const ATree: IANTLRInterface); overload;
constructor Create(const AAdaptor: ITreeAdaptor; const ATree: IANTLRInterface); overload;
function ToString: String; overload; override;
end;
{ These functions return X or, if X = nil, an empty default instance }
function Def(const X: ICommonTree): ICommonTree; overload;
implementation
uses
Math;
{ TTree }
class procedure TTree.Initialize;
begin
FINVALID_NODE := TCommonTree.Create(TToken.INVALID_TOKEN);
end;
{ TBaseTree }
constructor TBaseTree.Create;
begin
inherited;
end;
procedure TBaseTree.AddChild(const T: ITree);
var
ChildTree: IBaseTree;
C: IBaseTree;
begin
if (T = nil) then
Exit;
ChildTree := T as IBaseTree;
if ChildTree.IsNil then // t is an empty node possibly with children
begin
if Assigned(FChildren) and SameObj(FChildren, ChildTree.Children) then
raise EInvalidOperation.Create('Attempt to add child list to itself');
// just add all of childTree's children to this
if Assigned(ChildTree.Children) then
begin
if Assigned(FChildren) then // must copy, this has children already
begin
for C in ChildTree.Children do
begin
FChildren.Add(C);
// handle double-link stuff for each child of nil root
C.Parent := Self;
C.ChildIndex := FChildren.Count - 1;
end;
end
else begin
// no children for this but t has children; just set pointer
// call general freshener routine
FChildren := ChildTree.Children;
FreshenParentAndChildIndexes;
end;
end;
end
else
begin
// child is not nil (don't care about children)
if (FChildren = nil) then
begin
FChildren := CreateChildrenList; // create children list on demand
end;
FChildren.Add(ChildTree);
ChildTree.Parent := Self;
ChildTree.ChildIndex := FChildren.Count - 1;
end;
end;
procedure TBaseTree.AddChildren(const Kids: IList<IBaseTree>);
var
T: IBaseTree;
begin
for T in Kids do
AddChild(T);
end;
constructor TBaseTree.Create(const ANode: ITree);
begin
Create;
// No default implementation
end;
function TBaseTree.CreateChildrenList: IList<IBaseTree>;
begin
Result := TList<IBaseTree>.Create;
end;
function TBaseTree.DeleteChild(const I: Integer): IANTLRInterface;
begin
if (FChildren = nil) then
Result := nil
else
begin
Result := FChildren[I];
FChildren.Delete(I);
// walk rest and decrement their child indexes
FreshenParentAndChildIndexes(I);
end;
end;
procedure TBaseTree.FreshenParentAndChildIndexes(const Offset: Integer);
var
N, C: Integer;
Child: ITree;
begin
N := GetChildCount;
for C := Offset to N - 1 do
begin
Child := GetChild(C);
Child.ChildIndex := C;
Child.Parent := Self;
end;
end;
procedure TBaseTree.FreshenParentAndChildIndexes;
begin
FreshenParentAndChildIndexes(0);
end;
function TBaseTree.GetCharPositionInLine: Integer;
begin
Result := 0;
end;
function TBaseTree.GetChild(const I: Integer): ITree;
begin
if (FChildren = nil) or (I >= FChildren.Count) then
Result := nil
else
Result := FChildren[I];
end;
function TBaseTree.GetChildCount: Integer;
begin
if Assigned(FChildren) then
Result := FChildren.Count
else
Result := 0;
end;
function TBaseTree.GetChildIndex: Integer;
begin
// No default implementation
Result := 0;
end;
function TBaseTree.GetChildren: IList<IBaseTree>;
begin
Result := FChildren;
end;
function TBaseTree.GetIsNil: Boolean;
begin
Result := False;
end;
function TBaseTree.GetLine: Integer;
begin
Result := 0;
end;
function TBaseTree.GetParent: ITree;
begin
// No default implementation
Result := nil;
end;
procedure TBaseTree.ReplaceChildren(const StartChildIndex,
StopChildIndex: Integer; const T: IANTLRInterface);
var
ReplacingHowMany, ReplacingWithHowMany, NumNewChildren, Delta, I, J: Integer;
IndexToDelete, C, ReplacedSoFar: Integer;
NewTree, Killed: IBaseTree;
NewChildren: IList<IBaseTree>;
Child: IBaseTree;
begin
if (FChildren = nil) then
raise EArgumentException.Create('indexes invalid; no children in list');
ReplacingHowMany := StopChildIndex - StartChildIndex + 1;
NewTree := T as IBaseTree;
// normalize to a list of children to add: newChildren
if (NewTree.IsNil) then
NewChildren := NewTree.Children
else
begin
NewChildren := TList<IBaseTree>.Create;
NewChildren.Add(NewTree);
end;
ReplacingWithHowMany := NewChildren.Count;
NumNewChildren := NewChildren.Count;
Delta := ReplacingHowMany - ReplacingWithHowMany;
// if same number of nodes, do direct replace
if (Delta = 0) then
begin
J := 0; // index into new children
for I := StartChildIndex to StopChildIndex do
begin
Child := NewChildren[J];
FChildren[I] := Child;
Child.Parent := Self;
Child.ChildIndex := I;
Inc(J);
end;
end
else
if (Delta > 0) then
begin
// fewer new nodes than there were
// set children and then delete extra
for J := 0 to NumNewChildren - 1 do
FChildren[StartChildIndex + J] := NewChildren[J];
IndexToDelete := StartChildIndex + NumNewChildren;
for C := IndexToDelete to StopChildIndex do
begin
// delete same index, shifting everybody down each time
Killed := FChildren[IndexToDelete];
FChildren.Delete(IndexToDelete);
end;
FreshenParentAndChildIndexes(StartChildIndex);
end
else
begin
// more new nodes than were there before
// fill in as many children as we can (replacingHowMany) w/o moving data
ReplacedSoFar := 0;
while (ReplacedSoFar < ReplacingHowMany) do
begin
FChildren[StartChildIndex + ReplacedSoFar] := NewChildren[ReplacedSoFar];
Inc(ReplacedSoFar);
end;
// replacedSoFar has correct index for children to add
while (ReplacedSoFar < ReplacingWithHowMany) do
begin
FChildren.Insert(StartChildIndex + ReplacedSoFar,NewChildren[ReplacedSoFar]);
Inc(ReplacedSoFar);
end;
FreshenParentAndChildIndexes(StartChildIndex);
end;
end;
procedure TBaseTree.SanityCheckParentAndChildIndexes;
begin
SanityCheckParentAndChildIndexes(nil, -1);
end;
procedure TBaseTree.SanityCheckParentAndChildIndexes(const Parent: ITree;
const I: Integer);
var
N, C: Integer;
Child: ICommonTree;
begin
if not SameObj(Parent, GetParent) then
raise EArgumentException.Create('parents don''t match; expected '
+ Parent.ToString + ' found ' + GetParent.ToString);
if (I <> GetChildIndex) then
raise EArgumentException.Create('child indexes don''t match; expected '
+ IntToStr(I) + ' found ' + IntToStr(GetChildIndex));
N := GetChildCount;
for C := 0 to N - 1 do
begin
Child := GetChild(C) as ICommonTree;
Child.SanityCheckParentAndChildIndexes(Self, C);
end;
end;
procedure TBaseTree.SetChild(const I: Integer; const T: ITree);
begin
if (T = nil) then
Exit;
if T.IsNil then
raise EArgumentException.Create('Cannot set single child to a list');
if (FChildren = nil) then
begin
FChildren := CreateChildrenList;
end;
FChildren[I] := T as IBaseTree;
T.Parent := Self;
T.ChildIndex := I;
end;
procedure TBaseTree.SetChildIndex(const Value: Integer);
begin
// No default implementation
end;
procedure TBaseTree.SetParent(const Value: ITree);
begin
// No default implementation
end;
function TBaseTree.ToStringTree: String;
var
Buf: TStringBuilder;
I: Integer;
T: IBaseTree;
begin
if (FChildren = nil) or (FChildren.Count = 0) then
Result := ToString
else
begin
Buf := TStringBuilder.Create;
try
if (not GetIsNil) then
begin
Buf.Append('(');
Buf.Append(ToString);
Buf.Append(' ');
end;
for I := 0 to FChildren.Count - 1 do
begin
T := FChildren[I];
if (I > 0) then
Buf.Append(' ');
Buf.Append(T.ToStringTree);
end;
if (not GetIsNil) then
Buf.Append(')');
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
end;
{ TCommonTree }
constructor TCommonTree.Create;
begin
inherited;
FStartIndex := -1;
FStopIndex := -1;
FChildIndex := -1;
end;
constructor TCommonTree.Create(const ANode: ICommonTree);
begin
inherited Create(ANode);
FToken := ANode.Token;
FStartIndex := ANode.StartIndex;
FStopIndex := ANode.StopIndex;
FChildIndex := -1;
end;
constructor TCommonTree.Create(const AToken: IToken);
begin
Create;
FToken := AToken;
end;
function TCommonTree.DupNode: ITree;
begin
Result := TCommonTree.Create(Self) as ICommonTree;
end;
function TCommonTree.GetCharPositionInLine: Integer;
begin
if (FToken = nil) or (FToken.CharPositionInLine = -1) then
begin
if (GetChildCount > 0) then
Result := GetChild(0).CharPositionInLine
else
Result := 0;
end
else
Result := FToken.CharPositionInLine;
end;
function TCommonTree.GetChildIndex: Integer;
begin
Result := FChildIndex;
end;
function TCommonTree.GetIsNil: Boolean;
begin
Result := (FToken = nil);
end;
function TCommonTree.GetLine: Integer;
begin
if (FToken = nil) or (FToken.Line = 0) then
begin
if (GetChildCount > 0) then
Result := GetChild(0).Line
else
Result := 0
end
else
Result := FToken.Line;
end;
function TCommonTree.GetParent: ITree;
begin
Result := ITree(FParent);
end;
function TCommonTree.GetStartIndex: Integer;
begin
Result := FStartIndex;
end;
function TCommonTree.GetStopIndex: Integer;
begin
Result := FStopIndex;
end;
function TCommonTree.GetText: String;
begin
if (FToken = nil) then
Result := ''
else
Result := FToken.Text;
end;
function TCommonTree.GetToken: IToken;
begin
Result := FToken;
end;
function TCommonTree.GetTokenStartIndex: Integer;
begin
if (FStartIndex = -1) and (FToken <> nil) then
Result := FToken.TokenIndex
else
Result := FStartIndex;
end;
function TCommonTree.GetTokenStopIndex: Integer;
begin
if (FStopIndex = -1) and (FToken <> nil) then
Result := FToken.TokenIndex
else
Result := FStopIndex;
end;
function TCommonTree.GetTokenType: Integer;
begin
if (FToken = nil) then
Result := TToken.INVALID_TOKEN_TYPE
else
Result := FToken.TokenType;
end;
procedure TCommonTree.SetChildIndex(const Value: Integer);
begin
FChildIndex := Value;
end;
procedure TCommonTree.SetParent(const Value: ITree);
begin
FParent := Pointer(Value as ICommonTree);
end;
procedure TCommonTree.SetStartIndex(const Value: Integer);
begin
FStartIndex := Value;
end;
procedure TCommonTree.SetStopIndex(const Value: Integer);
begin
FStopIndex := Value;
end;
procedure TCommonTree.SetTokenStartIndex(const Value: Integer);
begin
FStartIndex := Value;
end;
procedure TCommonTree.SetTokenStopIndex(const Value: Integer);
begin
FStopIndex := Value;
end;
function TCommonTree.ToString: String;
begin
if (GetIsNil) then
Result := 'nil'
else
if (GetTokenType = TToken.INVALID_TOKEN_TYPE) then
Result := '<errornode>'
else
if (FToken = nil) then
Result := ''
else
Result := FToken.Text;
end;
{ TCommonErrorNode }
constructor TCommonErrorNode.Create(const AInput: ITokenStream; const AStart,
AStop: IToken; const AException: ERecognitionException);
begin
inherited Create;
if (AStop = nil) or ((AStop.TokenIndex < AStart.TokenIndex)
and (AStop.TokenType <> TToken.EOF))
then
// sometimes resync does not consume a token (when LT(1) is
// in follow set). So, stop will be 1 to left to start. adjust.
// Also handle case where start is the first token and no token
// is consumed during recovery; LT(-1) will return null.
FStop := AStart
else
FStop := AStop;
FInput := AInput;
FStart := AStart;
FTrappedException := AException;
end;
function TCommonErrorNode.GetIsNil: Boolean;
begin
Result := False;
end;
function TCommonErrorNode.GetText: String;
var
I, J: Integer;
begin
I := FStart.TokenIndex;
if (FStop.TokenType = TToken.EOF) then
J := (FInput as ITokenStream).Size
else
J := FStop.TokenIndex;
Result := (FInput as ITokenStream).ToString(I, J);
end;
function TCommonErrorNode.GetTokenType: Integer;
begin
Result := TToken.INVALID_TOKEN_TYPE;
end;
function TCommonErrorNode.ToString: String;
begin
if (FTrappedException is EMissingTokenException) then
Result := '<missing type: '
+ IntToStr(EMissingTokenException(FTrappedException).MissingType) + '>'
else
if (FTrappedException is EUnwantedTokenException) then
Result := '<extraneous: '
+ EUnwantedTokenException(FTrappedException).UnexpectedToken.ToString
+ ', resync=' + GetText + '>'
else
if (FTrappedException is EMismatchedTokenException) then
Result := '<mismatched token: ' + FTrappedException.Token.ToString
+ ', resync=' + GetText + '>'
else
if (FTrappedException is ENoViableAltException) then
Result := '<unexpected: ' + FTrappedException.Token.ToString
+ ', resync=' + GetText + '>'
else
Result := '<error: ' + GetText + '>';
end;
{ TBaseTreeAdaptor }
procedure TBaseTreeAdaptor.AddChild(const T, Child: IANTLRInterface);
begin
if Assigned(T) and Assigned(Child) then
(T as ITree).AddChild(Child as ITree);
end;
function TBaseTreeAdaptor.BecomeRoot(const NewRoot,
OldRoot: IANTLRInterface): IANTLRInterface;
var
NewRootTree, OldRootTree: ITree;
NC: Integer;
begin
NewRootTree := NewRoot as ITree;
OldRootTree := OldRoot as ITree;
if (OldRoot = nil) then
Result := NewRoot
else
begin
// handle ^(nil real-node)
if (NewRootTree.IsNil) then
begin
NC := NewRootTree.ChildCount;
if (NC = 1) then
NewRootTree := NewRootTree.GetChild(0)
else
if (NC > 1) then
raise Exception.Create('more than one node as root');
end;
// add oldRoot to newRoot; AddChild takes care of case where oldRoot
// is a flat list (i.e., nil-rooted tree). All children of oldRoot
// are added to newRoot.
NewRootTree.AddChild(OldRootTree);
Result := NewRootTree;
end;
end;
function TBaseTreeAdaptor.BecomeRoot(const NewRoot: IToken;
const OldRoot: IANTLRInterface): IANTLRInterface;
begin
Result := BecomeRoot(CreateNode(NewRoot), OldRoot);
end;
function TBaseTreeAdaptor.CreateNode(const TokenType: Integer;
const FromToken: IToken): IANTLRInterface;
var
Token: IToken;
begin
Token := CreateToken(FromToken);
Token.TokenType := TokenType;
Result := CreateNode(Token);
end;
function TBaseTreeAdaptor.CreateNode(const TokenType: Integer;
const Text: String): IANTLRInterface;
var
Token: IToken;
begin
Token := CreateToken(TokenType, Text);
Result := CreateNode(Token);
end;
function TBaseTreeAdaptor.CreateNode(const TokenType: Integer;
const FromToken: IToken; const Text: String): IANTLRInterface;
var
Token: IToken;
begin
Token := CreateToken(FromToken);
Token.TokenType := TokenType;
Token.Text := Text;
Result := CreateNode(Token);
end;
constructor TBaseTreeAdaptor.Create;
begin
inherited Create;
FUniqueNodeID := 1;
end;
function TBaseTreeAdaptor.DeleteChild(const T: IANTLRInterface;
const I: Integer): IANTLRInterface;
begin
Result := (T as ITree).DeleteChild(I);
end;
function TBaseTreeAdaptor.DupTree(const T,
Parent: IANTLRInterface): IANTLRInterface;
var
I, N: Integer;
Child, NewSubTree: IANTLRInterface;
begin
if (T = nil) then
Result := nil
else
begin
Result := DupNode(T);
// ensure new subtree root has parent/child index set
SetChildIdex(Result, GetChildIndex(T));
SetParent(Result, Parent);
N := GetChildCount(T);
for I := 0 to N - 1 do
begin
Child := GetChild(T, I);
NewSubTree := DupTree(Child, T);
AddChild(Result, NewSubTree);
end;
end;
end;
function TBaseTreeAdaptor.DupTree(const Tree: IANTLRInterface): IANTLRInterface;
begin
Result := DupTree(Tree, nil);
end;
function TBaseTreeAdaptor.ErrorNode(const Input: ITokenStream; const Start,
Stop: IToken; const E: ERecognitionException): IANTLRInterface;
begin
Result := TCommonErrorNode.Create(Input, Start, Stop, E);
end;
function TBaseTreeAdaptor.GetChild(const T: IANTLRInterface;
const I: Integer): IANTLRInterface;
begin
Result := (T as ITree).GetChild(I);
end;
function TBaseTreeAdaptor.GetChildCount(const T: IANTLRInterface): Integer;
begin
Result := (T as ITree).ChildCount;
end;
function TBaseTreeAdaptor.GetNilNode: IANTLRInterface;
begin
Result := CreateNode(nil);
end;
function TBaseTreeAdaptor.GetNodeText(const T: IANTLRInterface): String;
begin
Result := (T as ITree).Text;
end;
function TBaseTreeAdaptor.GetNodeType(const T: IANTLRInterface): Integer;
begin
Result := 0;
end;
function TBaseTreeAdaptor.GetUniqueID(const Node: IANTLRInterface): Integer;
begin
if (FTreeToUniqueIDMap = nil) then
FTreeToUniqueIDMap := TDictionary<IANTLRInterface, Integer>.Create;
if (not FTreeToUniqueIDMap.TryGetValue(Node, Result)) then
begin
Result := FUniqueNodeID;
FTreeToUniqueIDMap[Node] := Result;
Inc(FUniqueNodeID);
end;
end;
function TBaseTreeAdaptor.IsNil(const Tree: IANTLRInterface): Boolean;
begin
Result := (Tree as ITree).IsNil;
end;
function TBaseTreeAdaptor.RulePostProcessing(
const Root: IANTLRInterface): IANTLRInterface;
var
R: ITree;
begin
R := Root as ITree;
if Assigned(R) and (R.IsNil) then
begin
if (R.ChildCount = 0) then
R := nil
else
if (R.ChildCount = 1) then
begin
R := R.GetChild(0);
// whoever invokes rule will set parent and child index
R.Parent := nil;
R.ChildIndex := -1;
end;
end;
Result := R;
end;
procedure TBaseTreeAdaptor.SetChild(const T: IANTLRInterface; const I: Integer;
const Child: IANTLRInterface);
begin
(T as ITree).SetChild(I, Child as ITree);
end;
procedure TBaseTreeAdaptor.SetNodeText(const T: IANTLRInterface;
const Text: String);
begin
raise EInvalidOperation.Create('don''t know enough about Tree node');
end;
procedure TBaseTreeAdaptor.SetNodeType(const T: IANTLRInterface;
const NodeType: Integer);
begin
raise EInvalidOperation.Create('don''t know enough about Tree node');
end;
{ TCommonTreeAdaptor }
function TCommonTreeAdaptor.CreateNode(const Payload: IToken): IANTLRInterface;
begin
Result := TCommonTree.Create(Payload);
end;
function TCommonTreeAdaptor.CreateToken(const TokenType: Integer;
const Text: String): IToken;
begin
Result := TCommonToken.Create(TokenType, Text);
end;
function TCommonTreeAdaptor.CreateToken(const FromToken: IToken): IToken;
begin
Result := TCommonToken.Create(FromToken);
end;
function TCommonTreeAdaptor.DupNode(
const TreeNode: IANTLRInterface): IANTLRInterface;
begin
if (TreeNode = nil) then
Result := nil
else
Result := (TreeNode as ITree).DupNode;
end;
function TCommonTreeAdaptor.GetChild(const T: IANTLRInterface;
const I: Integer): IANTLRInterface;
begin
if (T = nil) then
Result := nil
else
Result := (T as ITree).GetChild(I);
end;
function TCommonTreeAdaptor.GetChildCount(const T: IANTLRInterface): Integer;
begin
if (T = nil) then
Result := 0
else
Result := (T as ITree).ChildCount;
end;
function TCommonTreeAdaptor.GetChildIndex(const T: IANTLRInterface): Integer;
begin
Result := (T as ITree).ChildIndex;
end;
function TCommonTreeAdaptor.GetNodeText(const T: IANTLRInterface): String;
begin
if (T = nil) then
Result := ''
else
Result := (T as ITree).Text;
end;
function TCommonTreeAdaptor.GetNodeType(const T: IANTLRInterface): Integer;
begin
if (T = nil) then
Result := TToken.INVALID_TOKEN_TYPE
else
Result := (T as ITree).TokenType;
end;
function TCommonTreeAdaptor.GetParent(
const T: IANTLRInterface): IANTLRInterface;
begin
Result := (T as ITree).Parent;
end;
function TCommonTreeAdaptor.GetToken(const TreeNode: IANTLRInterface): IToken;
var
CommonTree: ICommonTree;
begin
if Supports(TreeNode, ICommonTree, CommonTree) then
Result := CommonTree.Token
else
Result := nil; // no idea what to do
end;
function TCommonTreeAdaptor.GetTokenStartIndex(
const T: IANTLRInterface): Integer;
begin
if (T = nil) then
Result := -1
else
Result := (T as ITree).TokenStartIndex;
end;
function TCommonTreeAdaptor.GetTokenStopIndex(
const T: IANTLRInterface): Integer;
begin
if (T = nil) then
Result := -1
else
Result := (T as ITree).TokenStopIndex;
end;
procedure TCommonTreeAdaptor.ReplaceChildren(const Parent: IANTLRInterface;
const StartChildIndex, StopChildIndex: Integer; const T: IANTLRInterface);
begin
if Assigned(Parent) then
(Parent as ITree).ReplaceChildren(StartChildIndex, StopChildIndex, T);
end;
procedure TCommonTreeAdaptor.SetChildIdex(const T: IANTLRInterface;
const Index: Integer);
begin
(T as ITree).ChildIndex := Index;
end;
procedure TCommonTreeAdaptor.SetParent(const T, Parent: IANTLRInterface);
begin
(T as ITree).Parent := (Parent as ITree);
end;
procedure TCommonTreeAdaptor.SetTokenBoundaries(const T: IANTLRInterface;
const StartToken, StopToken: IToken);
var
Start, Stop: Integer;
begin
if Assigned(T) then
begin
if Assigned(StartToken) then
Start := StartToken.TokenIndex
else
Start := 0;
if Assigned(StopToken) then
Stop := StopToken.TokenIndex
else
Stop := 0;
(T as ITree).TokenStartIndex := Start;
(T as ITree).TokenStopIndex := Stop;
end;
end;
{ TCommonTreeNodeStream }
procedure TCommonTreeNodeStream.AddNavigationNode(const TokenType: Integer);
var
NavNode: IANTLRInterface;
begin
if (TokenType = TToken.DOWN) then
begin
if (GetHasUniqueNavigationNodes) then
NavNode := FAdaptor.CreateNode(TToken.DOWN, 'DOWN')
else
NavNode := FDown;
end
else
begin
if (GetHasUniqueNavigationNodes) then
NavNode := FAdaptor.CreateNode(TToken.UP, 'UP')
else
NavNode := FUp;
end;
FNodes.Add(NavNode);
end;
procedure TCommonTreeNodeStream.Consume;
begin
if (FP = -1) then
FillBuffer;
Inc(FP);
end;
constructor TCommonTreeNodeStream.Create;
begin
inherited;
FP := -1;
end;
constructor TCommonTreeNodeStream.Create(const ATree: IANTLRInterface);
begin
Create(TCommonTreeAdaptor.Create, ATree);
end;
constructor TCommonTreeNodeStream.Create(const AAdaptor: ITreeAdaptor;
const ATree: IANTLRInterface);
begin
Create(AAdaptor, ATree, DEFAULT_INITIAL_BUFFER_SIZE);
end;
constructor TCommonTreeNodeStream.Create(const AAdaptor: ITreeAdaptor;
const ATree: IANTLRInterface; const AInitialBufferSize: Integer);
begin
Create;
FRoot := ATree;
FAdaptor := AAdaptor;
FNodes := TList<IANTLRInterface>.Create;
FNodes.Capacity := AInitialBufferSize;
FDown := FAdaptor.CreateNode(TToken.DOWN, 'DOWN');
FUp := FAdaptor.CreateNode(TToken.UP, 'UP');
FEof := FAdaptor.CreateNode(TToken.EOF, 'EOF');
end;
procedure TCommonTreeNodeStream.FillBuffer;
begin
FillBuffer(FRoot);
FP := 0; // buffer of nodes intialized now
end;
procedure TCommonTreeNodeStream.FillBuffer(const T: IANTLRInterface);
var
IsNil: Boolean;
C, N: Integer;
begin
IsNil := FAdaptor.IsNil(T);
if (not IsNil) then
FNodes.Add(T); // add this node
// add DOWN node if t has children
N := FAdaptor.GetChildCount(T);
if (not IsNil) and (N > 0) then
AddNavigationNode(TToken.DOWN);
// and now add all its children
for C := 0 to N - 1 do
FillBuffer(FAdaptor.GetChild(T, C));
// add UP node if t has children
if (not IsNil) and (N > 0) then
AddNavigationNode(TToken.UP);
end;
function TCommonTreeNodeStream.Get(const I: Integer): IANTLRInterface;
begin
if (FP = -1) then
FillBuffer;
Result := FNodes[I];
end;
function TCommonTreeNodeStream.GetCurrentSymbol: IANTLRInterface;
begin
Result := LT(1);
end;
function TCommonTreeNodeStream.GetHasUniqueNavigationNodes: Boolean;
begin
Result := FUniqueNavigationNodes;
end;
function TCommonTreeNodeStream.GetNodeIndex(
const Node: IANTLRInterface): Integer;
var
T: IANTLRInterface;
begin
if (FP = -1) then
FillBuffer;
for Result := 0 to FNodes.Count - 1 do
begin
T := FNodes[Result];
if (T = Node) then
Exit;
end;
Result := -1;
end;
function TCommonTreeNodeStream.GetSourceName: String;
begin
Result := GetTokenStream.SourceName;
end;
function TCommonTreeNodeStream.GetTokenStream: ITokenStream;
begin
Result := FTokens;
end;
function TCommonTreeNodeStream.GetTreeAdaptor: ITreeAdaptor;
begin
Result := FAdaptor;
end;
function TCommonTreeNodeStream.GetTreeSource: IANTLRInterface;
begin
Result := FRoot;
end;
function TCommonTreeNodeStream.Index: Integer;
begin
Result := FP;
end;
function TCommonTreeNodeStream.LA(I: Integer): Integer;
begin
Result := FAdaptor.GetNodeType(LT(I));
end;
function TCommonTreeNodeStream.LAChar(I: Integer): Char;
begin
Result := Char(LA(I));
end;
function TCommonTreeNodeStream.LB(const K: Integer): IANTLRInterface;
begin
if (K = 0) then
Result := nil
else
if ((FP - K) < 0) then
Result := nil
else
Result := FNodes[FP - K];
end;
function TCommonTreeNodeStream.LT(const K: Integer): IANTLRInterface;
begin
if (FP = -1) then
FillBuffer;
if (K = 0) then
Result := nil
else
if (K < 0) then
Result := LB(-K)
else
if ((FP + K - 1) >= FNodes.Count) then
Result := FEof
else
Result := FNodes[FP + K - 1];
end;
function TCommonTreeNodeStream.Mark: Integer;
begin
if (FP = -1) then
FillBuffer;
FLastMarker := Index;
Result := FLastMarker;
end;
function TCommonTreeNodeStream.Pop: Integer;
begin
Result := FCalls.Pop;
Seek(Result);
end;
procedure TCommonTreeNodeStream.Push(const Index: Integer);
begin
if (FCalls = nil) then
FCalls := TStackList<Integer>.Create;
FCalls.Push(FP); // save current index
Seek(Index);
end;
procedure TCommonTreeNodeStream.Release(const Marker: Integer);
begin
// no resources to release
end;
procedure TCommonTreeNodeStream.ReplaceChildren(const Parent: IANTLRInterface;
const StartChildIndex, StopChildIndex: Integer; const T: IANTLRInterface);
begin
if Assigned(Parent) then
FAdaptor.ReplaceChildren(Parent, StartChildIndex, StopChildIndex, T);
end;
procedure TCommonTreeNodeStream.Reset;
begin
FP := -1;
FLastMarker := 0;
if Assigned(FCalls) then
FCalls.Clear;
end;
procedure TCommonTreeNodeStream.Rewind(const Marker: Integer);
begin
Seek(Marker);
end;
procedure TCommonTreeNodeStream.Rewind;
begin
Seek(FLastMarker);
end;
procedure TCommonTreeNodeStream.Seek(const Index: Integer);
begin
if (FP = -1) then
FillBuffer;
FP := Index;
end;
procedure TCommonTreeNodeStream.SetHasUniqueNavigationNodes(
const Value: Boolean);
begin
FUniqueNavigationNodes := Value;
end;
procedure TCommonTreeNodeStream.SetTokenStream(const Value: ITokenStream);
begin
FTokens := Value;
end;
procedure TCommonTreeNodeStream.SetTreeAdaptor(const Value: ITreeAdaptor);
begin
FAdaptor := Value;
end;
function TCommonTreeNodeStream.Size: Integer;
begin
if (FP = -1) then
FillBuffer;
Result := FNodes.Count;
end;
function TCommonTreeNodeStream.ToString(const Start,
Stop: IANTLRInterface): String;
var
CommonTree: ICommonTree;
I, BeginTokenIndex, EndTokenIndex: Integer;
T: IANTLRInterface;
Buf: TStringBuilder;
Text: String;
begin
WriteLn('ToString');
if (Start = nil) or (Stop = nil) then
Exit;
if (FP = -1) then
FillBuffer;
if Supports(Start, ICommonTree, CommonTree) then
Write('ToString: ' + CommonTree.Token.ToString + ', ')
else
WriteLn(Start.ToString);
if Supports(Stop, ICommonTree, CommonTree) then
WriteLn(CommonTree.Token.ToString)
else
WriteLn(Stop.ToString);
// if we have the token stream, use that to dump text in order
if Assigned(FTokens) then
begin
BeginTokenIndex := FAdaptor.GetTokenStartIndex(Start);
EndTokenIndex := FAdaptor.GetTokenStartIndex(Stop);
// if it's a tree, use start/stop index from start node
// else use token range from start/stop nodes
if (FAdaptor.GetNodeType(Stop) = TToken.UP) then
EndTokenIndex := FAdaptor.GetTokenStopIndex(Start)
else
if (FAdaptor.GetNodeType(Stop) = TToken.EOF) then
EndTokenIndex := Size - 2; // don't use EOF
Result := FTokens.ToString(BeginTokenIndex, EndTokenIndex);
Exit;
end;
// walk nodes looking for start
T := nil;
I := 0;
while (I < FNodes.Count) do
begin
T := FNodes[I];
if SameObj(T, Start) then
Break;
Inc(I);
end;
// now walk until we see stop, filling string buffer with text
Buf := TStringBuilder.Create;
try
T := FNodes[I];
while (T <> Stop) do
begin
Text := FAdaptor.GetNodeText(T);
if (Text = '') then
Text := ' ' + IntToStr(FAdaptor.GetNodeType(T));
Buf.Append(Text);
Inc(I);
T := FNodes[I];
end;
// include stop node too
Text := FAdaptor.GetNodeText(Stop);
if (Text = '') then
Text := ' ' + IntToStr(FAdaptor.GetNodeType(Stop));
Buf.Append(Text);
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
function TCommonTreeNodeStream.ToString: String;
var
Buf: TStringBuilder;
T: IANTLRInterface;
begin
if (FP = -1) then
FillBuffer;
Buf := TStringBuilder.Create;
try
for T in FNodes do
begin
Buf.Append(' ');
Buf.Append(FAdaptor.GetNodeType(T));
end;
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
function TCommonTreeNodeStream.ToTokenString(const Start,
Stop: Integer): String;
var
I: Integer;
T: IANTLRInterface;
Buf: TStringBuilder;
begin
if (FP = -1) then
FillBuffer;
Buf := TStringBuilder.Create;
try
for I := Stop to Min(FNodes.Count - 1, Stop) do
begin
T := FNodes[I];
Buf.Append(' ');
Buf.Append(FAdaptor.GetToken(T).ToString);
end;
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
{ TParseTree }
constructor TParseTree.Create(const ALabel: IANTLRInterface);
begin
inherited Create;
FPayload := ALabel;
end;
function TParseTree.DupNode: ITree;
begin
Result := nil;
end;
function TParseTree.GetText: String;
begin
Result := ToString;
end;
function TParseTree.GetTokenStartIndex: Integer;
begin
Result := 0;
end;
function TParseTree.GetTokenStopIndex: Integer;
begin
Result := 0;
end;
function TParseTree.GetTokenType: Integer;
begin
Result := 0;
end;
procedure TParseTree.SetTokenStartIndex(const Value: Integer);
begin
// No implementation
end;
procedure TParseTree.SetTokenStopIndex(const Value: Integer);
begin
// No implementation
end;
function TParseTree.ToInputString: String;
var
Buf: TStringBuilder;
begin
Buf := TStringBuilder.Create;
try
_ToStringLeaves(Buf);
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
function TParseTree.ToString: String;
var
T: IToken;
begin
if Supports(FPayload, IToken, T) then
begin
if (T.TokenType = TToken.EOF) then
Result := '<EOF>'
else
Result := T.Text;
end
else
Result := FPayload.ToString;
end;
function TParseTree.ToStringWithHiddenTokens: String;
var
Buf: TStringBuilder;
Hidden: IToken;
NodeText: String;
begin
Buf := TStringBuilder.Create;
try
if Assigned(FHiddenTokens) then
begin
for Hidden in FHiddenTokens do
Buf.Append(Hidden.Text);
end;
NodeText := ToString;
if (NodeText <> '<EOF>') then
Buf.Append(NodeText);
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
procedure TParseTree._ToStringLeaves(const Buf: TStringBuilder);
var
T: IBaseTree;
begin
if Supports(FPayload, IToken) then
begin
// leaf node token?
Buf.Append(ToStringWithHiddenTokens);
Exit;
end;
if Assigned(FChildren) then
for T in FChildren do
(T as IParseTree)._ToStringLeaves(Buf);
end;
{ ERewriteCardinalityException }
constructor ERewriteCardinalityException.Create(
const AElementDescription: String);
begin
inherited Create(AElementDescription);
FElementDescription := AElementDescription;
end;
{ TRewriteRuleElementStream }
procedure TRewriteRuleElementStream.Add(const El: IANTLRInterface);
begin
if (El = nil) then
Exit;
if Assigned(FElements) then
// if in list, just add
FElements.Add(El)
else
if (FSingleElement = nil) then
// no elements yet, track w/o list
FSingleElement := El
else
begin
// adding 2nd element, move to list
FElements := TList<IANTLRInterface>.Create;
FElements.Capacity := 5;
FElements.Add(FSingleElement);
FSingleElement := nil;
FElements.Add(El);
end;
end;
constructor TRewriteRuleElementStream.Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String);
begin
inherited Create;
FAdaptor := AAdaptor;
FElementDescription := AElementDescription;
end;
constructor TRewriteRuleElementStream.Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String; const AOneElement: IANTLRInterface);
begin
Create(AAdaptor, AElementDescription);
Add(AOneElement);
end;
constructor TRewriteRuleElementStream.Create(const AAdaptor: ITreeAdaptor;
const AElementDescription: String; const AElements: IList<IANTLRInterface>);
begin
Create(AAdaptor, AElementDescription);
FElements := AElements;
end;
function TRewriteRuleElementStream.GetDescription: String;
begin
Result := FElementDescription;
end;
function TRewriteRuleElementStream.HasNext: Boolean;
begin
Result := ((FSingleElement <> nil) and (FCursor < 1))
or ((FElements <> nil) and (FCursor < FElements.Count));
end;
function TRewriteRuleElementStream.NextTree: IANTLRInterface;
begin
Result := _Next;
end;
procedure TRewriteRuleElementStream.Reset;
begin
FCursor := 0;
FDirty := True;
end;
function TRewriteRuleElementStream.Size: Integer;
begin
if Assigned(FSingleElement) then
Result := 1
else
if Assigned(FElements) then
Result := FElements.Count
else
Result := 0;
end;
function TRewriteRuleElementStream.ToTree(const El: IANTLRInterface): IANTLRInterface;
begin
Result := El;
end;
function TRewriteRuleElementStream._Next: IANTLRInterface;
var
Size: Integer;
begin
Size := Self.Size;
if (Size = 0) then
raise ERewriteEmptyStreamException.Create(FElementDescription);
if (FCursor >= Size) then
begin
// out of elements?
if (Size = 1) then
// if size is 1, it's ok; return and we'll dup
Result := ToTree(FSingleElement)
else
// out of elements and size was not 1, so we can't dup
raise ERewriteCardinalityException.Create(FElementDescription);
end
else
begin
// we have elements
if Assigned(FSingleElement) then
begin
Inc(FCursor); // move cursor even for single element list
Result := ToTree(FSingleElement);
end
else
begin
// must have more than one in list, pull from elements
Result := ToTree(FElements[FCursor]);
Inc(FCursor);
end;
end;
end;
{ TRewriteRuleNodeStream }
function TRewriteRuleNodeStream.NextNode: IANTLRInterface;
begin
Result := _Next;
end;
function TRewriteRuleNodeStream.ToTree(
const El: IANTLRInterface): IANTLRInterface;
begin
Result := FAdaptor.DupNode(El);
end;
{ TRewriteRuleSubtreeStream }
function TRewriteRuleSubtreeStream.Dup(
const O: IANTLRInterface): IANTLRInterface;
begin
Result := FAdaptor.DupTree(O);
end;
function TRewriteRuleSubtreeStream.DupNode(
const O: IANTLRInterface): IANTLRInterface;
begin
Result := FAdaptor.DupNode(O);
end;
function TRewriteRuleSubtreeStream.FetchObject(
const PH: TProcessHandler): IANTLRInterface;
begin
if (RequiresDuplication) then
// process the object
Result := PH(_Next)
else
// test above then fetch
Result := _Next;
end;
function TRewriteRuleSubtreeStream.NextNode: IANTLRInterface;
begin
// if necessary, dup (at most a single node since this is for making root nodes).
Result := FetchObject(DupNode);
end;
function TRewriteRuleSubtreeStream.NextTree: IANTLRInterface;
begin
// if out of elements and size is 1, dup
Result := FetchObject(Dup);
end;
function TRewriteRuleSubtreeStream.RequiresDuplication: Boolean;
var
Size: Integer;
begin
Size := Self.Size;
// if dirty or if out of elements and size is 1
Result := FDirty or ((FCursor >= Size) and (Size = 1));
end;
{ TRewriteRuleTokenStream }
function TRewriteRuleTokenStream.NextNode: IANTLRInterface;
begin
Result := FAdaptor.CreateNode(_Next as IToken)
end;
function TRewriteRuleTokenStream.NextToken: IToken;
begin
Result := _Next as IToken;
end;
function TRewriteRuleTokenStream.ToTree(
const El: IANTLRInterface): IANTLRInterface;
begin
Result := El;
end;
{ TTreeParser }
constructor TTreeParser.Create(const AInput: ITreeNodeStream);
begin
inherited Create; // highlight that we go to super to set state object
SetTreeNodeStream(AInput);
end;
constructor TTreeParser.Create(const AInput: ITreeNodeStream;
const AState: IRecognizerSharedState);
begin
inherited Create(AState); // share the state object with another parser
SetTreeNodeStream(AInput);
end;
function TTreeParser.GetCurrentInputSymbol(
const Input: IIntStream): IANTLRInterface;
begin
Result := FInput.LT(1);
end;
function TTreeParser.GetErrorHeader(const E: ERecognitionException): String;
begin
Result := GetGrammarFileName + ': node from ';
if (E.ApproximateLineInfo) then
Result := Result + 'after ';
Result := Result + 'line ' + IntToStr(E.Line) + ':' + IntToStr(E.CharPositionInLine);
end;
function TTreeParser.GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String;
var
Adaptor: ITreeAdaptor;
begin
if (Self is TTreeParser) then
begin
Adaptor := (E.Input as ITreeNodeStream).TreeAdaptor;
E.Token := Adaptor.GetToken(E.Node);
if (E.Token = nil) then
// could be an UP/DOWN node
E.Token := TCommonToken.Create(Adaptor.GetNodeType(E.Node),
Adaptor.GetNodeText(E.Node));
end;
Result := inherited GetErrorMessage(E, TokenNames);
end;
function TTreeParser.GetInput: IIntStream;
begin
Result := FInput;
end;
function TTreeParser.GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface;
var
TokenText: String;
begin
TokenText := '<missing ' + GetTokenNames[ExpectedTokenType] + '>';
Result := TCommonTree.Create(TCommonToken.Create(ExpectedTokenType, TokenText));
end;
function TTreeParser.GetSourceName: String;
begin
Result := FInput.SourceName;
end;
function TTreeParser.GetTreeNodeStream: ITreeNodeStream;
begin
Result := FInput;
end;
procedure TTreeParser.MatchAny(const Input: IIntStream);
var
Look: IANTLRInterface;
Level, TokenType: Integer;
begin
FState.ErrorRecovery := False;
FState.Failed := False;
Look := FInput.LT(1);
if (FInput.TreeAdaptor.GetChildCount(Look) = 0) then
begin
FInput.Consume; // not subtree, consume 1 node and return
Exit;
end;
// current node is a subtree, skip to corresponding UP.
// must count nesting level to get right UP
Level := 0;
TokenType := FInput.TreeAdaptor.GetNodeType(Look);
while (TokenType <> TToken.EOF) and not ((TokenType = UP) and (Level = 0)) do
begin
FInput.Consume;
Look := FInput.LT(1);
TokenType := FInput.TreeAdaptor.GetNodeType(Look);
if (TokenType = DOWN) then
Inc(Level)
else
if (TokenType = UP) then
Dec(Level);
end;
FInput.Consume; // consume UP
end;
procedure TTreeParser.Mismatch(const Input: IIntStream;
const TokenType: Integer; const Follow: IBitSet);
begin
raise EMismatchedTreeNodeException.Create(TokenType, FInput);
end;
procedure TTreeParser.Reset;
begin
inherited; // reset all recognizer state variables
if Assigned(FInput) then
FInput.Seek(0); // rewind the input
end;
procedure TTreeParser.SetTreeNodeStream(const Value: ITreeNodeStream);
begin
FInput := Value;
end;
procedure TTreeParser.TraceIn(const RuleName: String; const RuleIndex: Integer);
begin
inherited TraceIn(RuleName, RuleIndex, FInput.LT(1).ToString);
end;
procedure TTreeParser.TraceOut(const RuleName: String;
const RuleIndex: Integer);
begin
inherited TraceOut(RuleName, RuleIndex, FInput.LT(1).ToString);
end;
{ TTreePatternLexer }
constructor TTreePatternLexer.Create;
begin
inherited;
FSVal := TStringBuilder.Create;
end;
procedure TTreePatternLexer.Consume;
begin
Inc(FP);
if (FP > FN) then
FC := EOF
else
FC := Integer(FPattern[FP]);
end;
constructor TTreePatternLexer.Create(const APattern: String);
begin
Create;
FPattern := APattern;
FN := Length(FPattern);
Consume;
end;
destructor TTreePatternLexer.Destroy;
begin
FSVal.Free;
inherited;
end;
function TTreePatternLexer.NextToken: Integer;
begin
FSVal.Length := 0; // reset, but reuse buffer
while (FC <> EOF) do
begin
if (FC = 32) or (FC = 10) or (FC = 13) or (FC = 9) then
begin
Consume;
Continue;
end;
if ((FC >= Ord('a')) and (FC <= Ord('z')))
or ((FC >= Ord('A')) and (FC <= Ord('Z')))
or (FC = Ord('_'))
then begin
FSVal.Append(Char(FC));
Consume;
while ((FC >= Ord('a')) and (FC <= Ord('z')))
or ((FC >= Ord('A')) and (FC <= Ord('Z')))
or ((FC >= Ord('0')) and (FC <= Ord('9')))
or (FC = Ord('_')) do
begin
FSVal.Append(Char(FC));
Consume;
end;
Exit(ID);
end;
if (FC = Ord('(')) then
begin
Consume;
Exit(START);
end;
if (FC = Ord(')')) then
begin
Consume;
Exit(STOP);
end;
if (FC = Ord('%')) then
begin
Consume;
Exit(PERCENT);
end;
if (FC = Ord(':')) then
begin
Consume;
Exit(COLON);
end;
if (FC = Ord('.')) then
begin
Consume;
Exit(DOT);
end;
if (FC = Ord('[')) then
begin
// grab [x] as a string, returning x
Consume;
while (FC <> Ord(']')) do
begin
if (FC = Ord('\')) then
begin
Consume;
if (FC <> Ord(']')) then
FSVal.Append('\');
FSVal.Append(Char(FC));
end
else
FSVal.Append(Char(FC));
Consume;
end;
Consume;
Exit(ARG);
end;
Consume;
FError := True;
Exit(EOF);
end;
Result := EOF;
end;
function TTreePatternLexer.SVal: String;
begin
Result := FSVal.ToString;
end;
{ TTreeWizard }
function TTreeWizard.ComputeTokenTypes(
const TokenNames: TStringArray): IDictionary<String, Integer>;
var
TokenType: Integer;
begin
Result := TDictionary<String, Integer>.Create;
if (Length(TokenNames) > 0)then
begin
for TokenType := TToken.MIN_TOKEN_TYPE to Length(TokenNames) - 1 do
Result.Add(TokenNames[TokenType], TokenType);
end;
end;
constructor TTreeWizard.Create(const AAdaptor: ITreeAdaptor);
begin
inherited Create;
FAdaptor := AAdaptor;
end;
constructor TTreeWizard.Create(const AAdaptor: ITreeAdaptor;
const ATokenNameToTypeMap: IDictionary<String, Integer>);
begin
inherited Create;
FAdaptor := AAdaptor;
FTokenNameToTypeMap := ATokenNameToTypeMap;
end;
constructor TTreeWizard.Create(const AAdaptor: ITreeAdaptor;
const TokenNames: TStringArray);
begin
inherited Create;
FAdaptor := AAdaptor;
FTokenNameToTypeMap := ComputeTokenTypes(TokenNames);
end;
function TTreeWizard.CreateTreeOrNode(const Pattern: String): IANTLRInterface;
var
Tokenizer: ITreePatternLexer;
Parser: ITreePatternParser;
begin
Tokenizer := TTreePatternLexer.Create(Pattern);
Parser := TTreePatternParser.Create(Tokenizer, Self, FAdaptor);
Result := Parser.Pattern;
end;
function TTreeWizard.Equals(const T1, T2: IANTLRInterface;
const Adaptor: ITreeAdaptor): Boolean;
begin
Result := _Equals(T1, T2, Adaptor);
end;
function TTreeWizard.Equals(const T1, T2: IANTLRInterface): Boolean;
begin
Result := _Equals(T1, T2, FAdaptor);
end;
function TTreeWizard.Find(const T: IANTLRInterface;
const Pattern: String): IList<IANTLRInterface>;
var
Tokenizer: ITreePatternLexer;
Parser: ITreePatternParser;
TreePattern: ITreePattern;
RootTokenType: Integer;
Visitor: IContextVisitor;
begin
Result := TList<IANTLRInterface>.Create;
// Create a TreePattern from the pattern
Tokenizer := TTreePatternLexer.Create(Pattern);
Parser := TTreePatternParser.Create(Tokenizer, Self, TTreePatternTreeAdaptor.Create);
TreePattern := Parser.Pattern as ITreePattern;
// don't allow invalid patterns
if (TreePattern = nil) or (TreePattern.IsNil)
or Supports(TreePattern, IWildcardTreePattern)
then
Exit(nil);
RootTokenType := TreePattern.TokenType;
Visitor := TPatternMatchingContextVisitor.Create(Self, TreePattern, Result);
Visit(T, RootTokenType, Visitor);
end;
function TTreeWizard.Find(const T: IANTLRInterface;
const TokenType: Integer): IList<IANTLRInterface>;
begin
Result := TList<IANTLRInterface>.Create;
Visit(T, TokenType, TRecordAllElementsVisitor.Create(Result));
end;
function TTreeWizard.FindFirst(const T: IANTLRInterface;
const TokenType: Integer): IANTLRInterface;
begin
Result := nil;
end;
function TTreeWizard.FindFirst(const T: IANTLRInterface;
const Pattern: String): IANTLRInterface;
begin
Result := nil;
end;
function TTreeWizard.GetTokenType(const TokenName: String): Integer;
begin
if (FTokenNameToTypeMap = nil) then
Exit(TToken.INVALID_TOKEN_TYPE);
if (not FTokenNameToTypeMap.TryGetValue(TokenName, Result)) then
Result := TToken.INVALID_TOKEN_TYPE;
end;
function TTreeWizard.Index(
const T: IANTLRInterface): IDictionary<Integer, IList<IANTLRInterface>>;
begin
Result := TDictionary<Integer, IList<IANTLRInterface>>.Create;
_Index(T, Result);
end;
function TTreeWizard.Parse(const T: IANTLRInterface;
const Pattern: String): Boolean;
begin
Result := Parse(T, Pattern, nil);
end;
function TTreeWizard.Parse(const T: IANTLRInterface; const Pattern: String;
const Labels: IDictionary<String, IANTLRInterface>): Boolean;
var
Tokenizer: ITreePatternLexer;
Parser: ITreePatternParser;
TreePattern: ITreePattern;
begin
Tokenizer := TTreePatternLexer.Create(Pattern);
Parser := TTreePatternParser.Create(Tokenizer, Self, TTreePatternTreeAdaptor.Create);
TreePattern := Parser.Pattern as ITreePattern;
Result := _Parse(T, TreePattern, Labels);
end;
procedure TTreeWizard.Visit(const T: IANTLRInterface; const Pattern: String;
const Visitor: IContextVisitor);
var
Tokenizer: ITreePatternLexer;
Parser: ITreePatternParser;
TreePattern: ITreePattern;
RootTokenType: Integer;
PatternVisitor: IContextVisitor;
begin
// Create a TreePattern from the pattern
Tokenizer := TTreePatternLexer.Create(Pattern);
Parser := TTreePatternParser.Create(Tokenizer, Self, TTreePatternTreeAdaptor.Create);
TreePattern := Parser.Pattern as ITreePattern;
if (TreePattern = nil) or (TreePattern.IsNil)
or Supports(TreePattern, IWildcardTreePattern)
then
Exit;
RootTokenType := TreePattern.TokenType;
PatternVisitor := TInvokeVisitorOnPatternMatchContextVisitor.Create(Self, TreePattern, Visitor);
Visit(T, RootTokenType, PatternVisitor);
end;
class function TTreeWizard._Equals(const T1, T2: IANTLRInterface;
const Adaptor: ITreeAdaptor): Boolean;
var
I, N1, N2: Integer;
Child1, Child2: IANTLRInterface;
begin
// make sure both are non-null
if (T1 = nil) or (T2 = nil) then
Exit(False);
// check roots
if (Adaptor.GetNodeType(T1) <> Adaptor.GetNodeType(T2)) then
Exit(False);
if (Adaptor.GetNodeText(T1) <> Adaptor.GetNodeText(T2)) then
Exit(False);
// check children
N1 := Adaptor.GetChildCount(T1);
N2 := Adaptor.GetChildCount(T2);
if (N1 <> N2) then
Exit(False);
for I := 0 to N1 - 1 do
begin
Child1 := Adaptor.GetChild(T1, I);
Child2 := Adaptor.GetChild(T2, I);
if (not _Equals(Child1, Child2, Adaptor)) then
Exit(False);
end;
Result := True;
end;
procedure TTreeWizard._Index(const T: IANTLRInterface;
const M: IDictionary<Integer, IList<IANTLRInterface>>);
var
I, N, TType: Integer;
Elements: IList<IANTLRInterface>;
begin
if (T = nil) then
Exit;
TType := FAdaptor.GetNodeType(T);
if (not M.TryGetValue(TType, Elements)) then
Elements := nil;
if (Elements = nil) then
begin
Elements := TList<IANTLRInterface>.Create;
M.Add(TType, Elements);
end;
Elements.Add(T);
N := FAdaptor.GetChildCount(T);
for I := 0 to N - 1 do
_Index(FAdaptor.GetChild(T, I), M);
end;
function TTreeWizard._Parse(const T1: IANTLRInterface; const T2: ITreePattern;
const Labels: IDictionary<String, IANTLRInterface>): Boolean;
var
I, N1, N2: Integer;
Child1: IANTLRInterface;
Child2: ITreePattern;
begin
// make sure both are non-null
if (T1 = nil) or (T2 = nil) then
Exit(False);
// check roots (wildcard matches anything)
if (not Supports(T2, IWildcardTreePattern)) then
begin
if (FAdaptor.GetNodeType(T1) <> T2.TokenType) then
Exit(False);
if (T2.HasTextArg) and (FAdaptor.GetNodeText(T1) <> T2.Text) then
Exit(False);
end;
if (T2.TokenLabel <> '') and Assigned(Labels) then
// map label in pattern to node in t1
Labels.AddOrSetValue(T2.TokenLabel, T1);
// check children
N1 := FAdaptor.GetChildCount(T1);
N2 := T2.ChildCount;
if (N1 <> N2) then
Exit(False);
for I := 0 to N1 - 1 do
begin
Child1 := FAdaptor.GetChild(T1, I);
Child2 := T2.GetChild(I) as ITreePattern;
if (not _Parse(Child1, Child2, Labels)) then
Exit(False);
end;
Result := True;
end;
procedure TTreeWizard._Visit(const T, Parent: IANTLRInterface; const ChildIndex,
TokenType: Integer; const Visitor: IContextVisitor);
var
I, N: Integer;
begin
if (T = nil) then
Exit;
if (FAdaptor.GetNodeType(T) = TokenType) then
Visitor.Visit(T, Parent, ChildIndex, nil);
N := FAdaptor.GetChildCount(T);
for I := 0 to N - 1 do
_Visit(FAdaptor.GetChild(T, I), T, I, TokenType, Visitor);
end;
procedure TTreeWizard.Visit(const T: IANTLRInterface; const TokenType: Integer;
const Visitor: IContextVisitor);
begin
_Visit(T, nil, 0, TokenType, Visitor);
end;
constructor TTreeWizard.Create(const TokenNames: TStringArray);
begin
Create(nil, TokenNames);
end;
{ TTreePatternParser }
constructor TTreePatternParser.Create(const ATokenizer: ITreePatternLexer;
const AWizard: ITreeWizard; const AAdaptor: ITreeAdaptor);
begin
inherited Create;
FTokenizer := ATokenizer;
FWizard := AWizard;
FAdaptor := AAdaptor;
FTokenType := FTokenizer.NextToken; // kickstart
end;
function TTreePatternParser.ParseNode: IANTLRInterface;
var
Lbl, TokenName, Text, Arg: String;
WildcardPayload: IToken;
Node: TTreeWizard.ITreePattern;
TreeNodeType: Integer;
begin
// "%label:" prefix
Lbl := '';
if (FTokenType = TTreePatternLexer.PERCENT) then
begin
FTokenType := FTokenizer.NextToken;
if (FTokenType <> TTreePatternLexer.ID) then
Exit(nil);
Lbl := FTokenizer.SVal;
FTokenType := FTokenizer.NextToken;
if (FTokenType <> TTreePatternLexer.COLON) then
Exit(nil);
FTokenType := FTokenizer.NextToken; // move to ID following colon
end;
// Wildcard?
if (FTokenType = TTreePatternLexer.DOT) then
begin
FTokenType := FTokenizer.NextToken;
WildcardPayload := TCommonToken.Create(0, '.');
Node := TTreeWizard.TWildcardTreePattern.Create(WildcardPayload);
if (Lbl <> '') then
Node.TokenLabel := Lbl;
Exit(Node);
end;
// "ID" or "ID[arg]"
if (FTokenType <> TTreePatternLexer.ID) then
Exit(nil);
TokenName := FTokenizer.SVal;
FTokenType := FTokenizer.NextToken;
if (TokenName = 'nil') then
Exit(FAdaptor.GetNilNode);
Text := TokenName;
// check for arg
Arg := '';
if (FTokenType = TTreePatternLexer.ARG) then
begin
Arg := FTokenizer.SVal;
Text := Arg;
FTokenType := FTokenizer.NextToken;
end;
// create node
TreeNodeType := FWizard.GetTokenType(TokenName);
if (TreeNodeType = TToken.INVALID_TOKEN_TYPE) then
Exit(nil);
Result := FAdaptor.CreateNode(TreeNodeType, Text);
if (Lbl <> '') and Supports(Result, TTreeWizard.ITreePattern, Node) then
Node.TokenLabel := Lbl;
if (Arg <> '') and Supports(Result, TTreeWizard.ITreePattern, Node) then
Node.HasTextArg := True;
end;
function TTreePatternParser.ParseTree: IANTLRInterface;
var
Subtree, Child: IANTLRInterface;
begin
if (FTokenType <> TTreePatternLexer.START) then
begin
WriteLn('no BEGIN');
Exit(nil);
end;
FTokenType := FTokenizer.NextToken;
Result := ParseNode;
if (Result = nil) then
Exit;
while (FTokenType in [TTreePatternLexer.START, TTreePatternLexer.ID,
TTreePatternLexer.PERCENT, TTreePatternLexer.DOT]) do
begin
if (FTokenType = TTreePatternLexer.START) then
begin
Subtree := ParseTree;
FAdaptor.AddChild(Result, Subtree);
end
else
begin
Child := ParseNode;
if (Child = nil) then
Exit(nil);
FAdaptor.AddChild(Result, Child);
end;
end;
if (FTokenType <> TTreePatternLexer.STOP) then
begin
WriteLn('no END');
Exit(nil);
end;
FTokenType := FTokenizer.NextToken;
end;
function TTreePatternParser.Pattern: IANTLRInterface;
var
Node: IANTLRInterface;
begin
if (FTokenType = TTreePatternLexer.START) then
Exit(ParseTree);
if (FTokenType = TTreePatternLexer.ID) then
begin
Node := ParseNode;
if (FTokenType = TTreePatternLexer.EOF) then
Result := Node
else
Result := nil; // extra junk on end
end
else
Result := nil;
end;
{ TTreeWizard.TVisitor }
procedure TTreeWizard.TVisitor.Visit(const T, Parent: IANTLRInterface;
const ChildIndex: Integer;
const Labels: IDictionary<String, IANTLRInterface>);
begin
Visit(T);
end;
{ TTreeWizard.TRecordAllElementsVisitor }
constructor TTreeWizard.TRecordAllElementsVisitor.Create(
const AList: IList<IANTLRInterface>);
begin
inherited Create;
FList := AList;
end;
procedure TTreeWizard.TRecordAllElementsVisitor.Visit(const T: IANTLRInterface);
begin
FList.Add(T);
end;
{ TTreeWizard.TPatternMatchingContextVisitor }
constructor TTreeWizard.TPatternMatchingContextVisitor.Create(
const AOwner: TTreeWizard; const APattern: ITreePattern;
const AList: IList<IANTLRInterface>);
begin
inherited Create;
FOwner := AOwner;
FPattern := APattern;
FList := AList;
end;
procedure TTreeWizard.TPatternMatchingContextVisitor.Visit(const T,
Parent: IANTLRInterface; const ChildIndex: Integer;
const Labels: IDictionary<String, IANTLRInterface>);
begin
if (FOwner._Parse(T, FPattern, nil)) then
FList.Add(T);
end;
{ TTreeWizard.TInvokeVisitorOnPatternMatchContextVisitor }
constructor TTreeWizard.TInvokeVisitorOnPatternMatchContextVisitor.Create(
const AOwner: TTreeWizard; const APattern: ITreePattern;
const AVisitor: IContextVisitor);
begin
inherited Create;
FOwner := AOwner;
FPattern := APattern;
FVisitor := AVisitor;
FLabels := TDictionary<String, IANTLRInterface>.Create;
end;
procedure TTreeWizard.TInvokeVisitorOnPatternMatchContextVisitor.Visit(const T,
Parent: IANTLRInterface; const ChildIndex: Integer;
const UnusedLabels: IDictionary<String, IANTLRInterface>);
begin
// the unusedlabels arg is null as visit on token type doesn't set.
FLabels.Clear;
if (FOwner._Parse(T, FPattern, FLabels)) then
FVisitor.Visit(T, Parent, ChildIndex, FLabels);
end;
{ TTreeWizard.TTreePattern }
function TTreeWizard.TTreePattern.GetHasTextArg: Boolean;
begin
Result := FHasTextArg;
end;
function TTreeWizard.TTreePattern.GetTokenLabel: String;
begin
Result := FLabel;
end;
procedure TTreeWizard.TTreePattern.SetHasTextArg(const Value: Boolean);
begin
FHasTextArg := Value;
end;
procedure TTreeWizard.TTreePattern.SetTokenLabel(const Value: String);
begin
FLabel := Value;
end;
function TTreeWizard.TTreePattern.ToString: String;
begin
if (FLabel <> '') then
Result := '%' + FLabel + ':' + inherited ToString
else
Result := inherited ToString;
end;
{ TTreeWizard.TTreePatternTreeAdaptor }
function TTreeWizard.TTreePatternTreeAdaptor.CreateNode(
const Payload: IToken): IANTLRInterface;
begin
Result := TTreePattern.Create(Payload);
end;
{ TTreeRuleReturnScope }
function TTreeRuleReturnScope.GetStart: IANTLRInterface;
begin
Result := FStart;
end;
procedure TTreeRuleReturnScope.SetStart(const Value: IANTLRInterface);
begin
FStart := Value;
end;
{ TUnBufferedTreeNodeStream }
procedure TUnBufferedTreeNodeStream.AddLookahead(const Node: IANTLRInterface);
var
Bigger: TANTLRInterfaceArray;
I, RemainderHeadToEnd: Integer;
begin
FLookahead[FTail] := Node;
FTail := (FTail + 1) mod Length(FLookahead);
if (FTail = FHead) then
begin
// buffer overflow: tail caught up with head
// allocate a buffer 2x as big
SetLength(Bigger,2 * Length(FLookahead));
// copy head to end of buffer to beginning of bigger buffer
RemainderHeadToEnd := Length(FLookahead) - FHead;
for I := 0 to RemainderHeadToEnd - 1 do
Bigger[I] := FLookahead[FHead + I];
// copy 0..tail to after that
for I := 0 to FTail - 1 do
Bigger[RemainderHeadToEnd + I] := FLookahead[I];
FLookahead := Bigger; // reset to bigger buffer
FHead := 0;
Inc(FTail,RemainderHeadToEnd);
end;
end;
procedure TUnBufferedTreeNodeStream.AddNavigationNode(const TokenType: Integer);
var
NavNode: IANTLRInterface;
begin
if (TokenType = TToken.DOWN) then
begin
if (GetHasUniqueNavigationNodes) then
NavNode := FAdaptor.CreateNode(TToken.DOWN,'DOWN')
else
NavNode := FDown;
end
else
begin
if (GetHasUniqueNavigationNodes) then
NavNode := FAdaptor.CreateNode(TToken.UP,'UP')
else
NavNode := FUp;
end;
AddLookahead(NavNode);
end;
procedure TUnBufferedTreeNodeStream.Consume;
begin
// make sure there is something in lookahead buf, which might call next()
Fill(1);
Inc(FAbsoluteNodeIndex);
FPreviousNode := FLookahead[FHead]; // track previous node before moving on
FHead := (FHead + 1) mod Length(FLookahead);
end;
constructor TUnBufferedTreeNodeStream.Create;
begin
inherited;
SetLength(FLookAhead,INITIAL_LOOKAHEAD_BUFFER_SIZE);
FNodeStack := TStackList<IANTLRInterface>.Create;
FIndexStack := TStackList<Integer>.Create;
end;
constructor TUnBufferedTreeNodeStream.Create(const ATree: IANTLRInterface);
begin
Create(TCommonTreeAdaptor.Create, ATree);
end;
constructor TUnBufferedTreeNodeStream.Create(const AAdaptor: ITreeAdaptor;
const ATree: IANTLRInterface);
begin
Create;
FRoot := ATree;
FAdaptor := AAdaptor;
Reset;
FDown := FAdaptor.CreateNode(TToken.DOWN, 'DOWN');
FUp := FAdaptor.CreateNode(TToken.UP, 'UP');
FEof := FAdaptor.CreateNode(TToken.EOF, 'EOF');
end;
procedure TUnBufferedTreeNodeStream.Fill(const K: Integer);
var
I, N: Integer;
begin
N := LookaheadSize;
for I := 1 to K - N do
MoveNext; // get at least k-depth lookahead nodes
end;
function TUnBufferedTreeNodeStream.Get(const I: Integer): IANTLRInterface;
begin
raise EInvalidOperation.Create('stream is unbuffered');
end;
function TUnBufferedTreeNodeStream.GetCurrent: IANTLRInterface;
begin
Result := FCurrentEnumerationNode;
end;
function TUnBufferedTreeNodeStream.GetHasUniqueNavigationNodes: Boolean;
begin
Result := FUniqueNavigationNodes;
end;
function TUnBufferedTreeNodeStream.GetSourceName: String;
begin
Result := GetTokenStream.SourceName;
end;
function TUnBufferedTreeNodeStream.GetTokenStream: ITokenStream;
begin
Result := FTokens;
end;
function TUnBufferedTreeNodeStream.GetTreeAdaptor: ITreeAdaptor;
begin
Result := FAdaptor;
end;
function TUnBufferedTreeNodeStream.GetTreeSource: IANTLRInterface;
begin
Result := FRoot;
end;
function TUnBufferedTreeNodeStream.HandleRootNode: IANTLRInterface;
begin
Result := FCurrentNode;
// point to first child in prep for subsequent next()
FCurrentChildIndex := 0;
if (FAdaptor.IsNil(Result)) then
// don't count this root nil node
Result := VisitChild(FCurrentChildIndex)
else
begin
AddLookahead(Result);
if (FAdaptor.GetChildCount(FCurrentNode) = 0) then
// single node case
Result := nil; // say we're done
end;
end;
function TUnBufferedTreeNodeStream.Index: Integer;
begin
Result := FAbsoluteNodeIndex + 1;
end;
function TUnBufferedTreeNodeStream.LA(I: Integer): Integer;
var
T: IANTLRInterface;
begin
T := LT(I);
if (T = nil) then
Result := TToken.INVALID_TOKEN_TYPE
else
Result := FAdaptor.GetNodeType(T);
end;
function TUnBufferedTreeNodeStream.LAChar(I: Integer): Char;
begin
Result := Char(LA(I));
end;
function TUnBufferedTreeNodeStream.LookaheadSize: Integer;
begin
if (FTail < FHead) then
Result := Length(FLookahead) - FHead + FTail
else
Result := FTail - FHead;
end;
function TUnBufferedTreeNodeStream.LT(const K: Integer): IANTLRInterface;
begin
if (K = -1) then
Exit(FPreviousNode);
if (K < 0) then
raise EArgumentException.Create('tree node streams cannot look backwards more than 1 node');
if (K = 0) then
Exit(TTree.INVALID_NODE);
Fill(K);
Result := FLookahead[(FHead + K - 1) mod Length(FLookahead)];
end;
function TUnBufferedTreeNodeStream.Mark: Integer;
var
State: ITreeWalkState;
I, N, K: Integer;
LA: TANTLRInterfaceArray;
begin
if (FMarkers = nil) then
begin
FMarkers := TList<ITreeWalkState>.Create;
FMarkers.Add(nil); // depth 0 means no backtracking, leave blank
end;
Inc(FMarkDepth);
State := nil;
if (FMarkDepth >= FMarkers.Count) then
begin
State := TTreeWalkState.Create;
FMarkers.Add(State);
end
else
State := FMarkers[FMarkDepth];
State.AbsoluteNodeIndex := FAbsoluteNodeIndex;
State.CurrentChildIndex := FCurrentChildIndex;
State.CurrentNode := FCurrentNode;
State.PreviousNode := FPreviousNode;
State.NodeStackSize := FNodeStack.Count;
State.IndexStackSize := FIndexStack.Count;
// take snapshot of lookahead buffer
N := LookaheadSize;
I := 0;
SetLength(LA,N);
for K := 1 to N do
begin
LA[I] := LT(K);
Inc(I);
end;
State.LookAhead := LA;
FLastMarker := FMarkDepth;
Result := FMarkDepth;
end;
function TUnBufferedTreeNodeStream.MoveNext: Boolean;
begin
// already walked entire tree; nothing to return
if (FCurrentNode = nil) then
begin
AddLookahead(FEof);
FCurrentEnumerationNode := nil;
// this is infinite stream returning EOF at end forever
// so don't throw NoSuchElementException
Exit(False);
end;
// initial condition (first time method is called)
if (FCurrentChildIndex = -1) then
begin
FCurrentEnumerationNode := HandleRootNode as ITree;
Exit(True);
end;
// index is in the child list?
if (FCurrentChildIndex < FAdaptor.GetChildCount(FCurrentNode)) then
begin
FCurrentEnumerationNode := VisitChild(FCurrentChildIndex) as ITree;
Exit(True);
end;
// hit end of child list, return to parent node or its parent ...
WalkBackToMostRecentNodeWithUnvisitedChildren;
if (FCurrentNode <> nil) then
begin
FCurrentEnumerationNode := VisitChild(FCurrentChildIndex) as ITree;
Result := True;
end
else
Result := False;
end;
procedure TUnBufferedTreeNodeStream.Release(const Marker: Integer);
begin
// unwind any other markers made after marker and release marker
FMarkDepth := Marker;
// release this marker
Dec(FMarkDepth);
end;
procedure TUnBufferedTreeNodeStream.ReplaceChildren(
const Parent: IANTLRInterface; const StartChildIndex, StopChildIndex: Integer;
const T: IANTLRInterface);
begin
raise EInvalidOperation.Create('can''t do stream rewrites yet');
end;
procedure TUnBufferedTreeNodeStream.Reset;
begin
FCurrentNode := FRoot;
FPreviousNode := nil;
FCurrentChildIndex := -1;
FAbsoluteNodeIndex := -1;
FHead := 0;
FTail := 0;
end;
procedure TUnBufferedTreeNodeStream.Rewind(const Marker: Integer);
var
State: ITreeWalkState;
begin
if (FMarkers = nil) then
Exit;
State := FMarkers[Marker];
FAbsoluteNodeIndex := State.AbsoluteNodeIndex;
FCurrentChildIndex := State.CurrentChildIndex;
FCurrentNode := State.CurrentNode;
FPreviousNode := State.PreviousNode;
// drop node and index stacks back to old size
FNodeStack.Capacity := State.NodeStackSize;
FIndexStack.Capacity := State.IndexStackSize;
FHead := 0; // wack lookahead buffer and then refill
FTail := 0;
while (FTail < Length(State.LookAhead)) do
begin
FLookahead[FTail] := State.LookAhead[FTail];
Inc(FTail);
end;
Release(Marker);
end;
procedure TUnBufferedTreeNodeStream.Rewind;
begin
Rewind(FLastMarker);
end;
procedure TUnBufferedTreeNodeStream.Seek(const Index: Integer);
begin
if (Index < Self.Index) then
raise EArgumentOutOfRangeException.Create('can''t seek backwards in node stream');
// seek forward, consume until we hit index
while (Self.Index < Index) do
Consume;
end;
procedure TUnBufferedTreeNodeStream.SetHasUniqueNavigationNodes(
const Value: Boolean);
begin
FUniqueNavigationNodes := Value;
end;
procedure TUnBufferedTreeNodeStream.SetTokenStream(const Value: ITokenStream);
begin
FTokens := Value;
end;
function TUnBufferedTreeNodeStream.Size: Integer;
var
S: ICommonTreeNodeStream;
begin
S := TCommonTreeNodeStream.Create(FRoot);
Result := S.Size;
end;
function TUnBufferedTreeNodeStream.ToString: String;
begin
Result := ToString(FRoot, nil);
end;
procedure TUnBufferedTreeNodeStream.ToStringWork(const P, Stop: IANTLRInterface;
const Buf: TStringBuilder);
var
Text: String;
C, N: Integer;
begin
if (not FAdaptor.IsNil(P)) then
begin
Text := FAdaptor.GetNodeText(P);
if (Text = '') then
Text := ' ' + IntToStr(FAdaptor.GetNodeType(P));
Buf.Append(Text); // ask the node to go to string
end;
if SameObj(P, Stop) then
Exit;
N := FAdaptor.GetChildCount(P);
if (N > 0) and (not FAdaptor.IsNil(P)) then
begin
Buf.Append(' ');
Buf.Append(TToken.DOWN);
end;
for C := 0 to N - 1 do
ToStringWork(FAdaptor.GetChild(P, C), Stop, Buf);
if (N > 0) and (not FAdaptor.IsNil(P)) then
begin
Buf.Append(' ');
Buf.Append(TToken.UP);
end;
end;
function TUnBufferedTreeNodeStream.VisitChild(
const Child: Integer): IANTLRInterface;
begin
Result := nil;
// save state
FNodeStack.Push(FCurrentNode);
FIndexStack.Push(Child);
if (Child = 0) and (not FAdaptor.IsNil(FCurrentNode)) then
AddNavigationNode(TToken.DOWN);
// visit child
FCurrentNode := FAdaptor.GetChild(FCurrentNode, Child);
FCurrentChildIndex := 0;
Result := FCurrentNode;
AddLookahead(Result);
WalkBackToMostRecentNodeWithUnvisitedChildren;
end;
procedure TUnBufferedTreeNodeStream.WalkBackToMostRecentNodeWithUnvisitedChildren;
begin
while (FCurrentNode <> nil) and (FCurrentChildIndex >= FAdaptor.GetChildCount(FCurrentNode)) do
begin
FCurrentNode := FNodeStack.Pop;
if (FCurrentNode = nil) then
// hit the root?
Exit;
FCurrentChildIndex := FIndexStack.Pop;
Inc(FCurrentChildIndex); // move to next child
if (FCurrentChildIndex >= FAdaptor.GetChildCount(FCurrentNode)) then
begin
if (not FAdaptor.IsNil(FCurrentNode)) then
AddNavigationNode(TToken.UP);
if SameObj(FCurrentNode, FRoot) then
// we done yet?
FCurrentNode := nil;
end;
end;
end;
function TUnBufferedTreeNodeStream.ToString(const Start,
Stop: IANTLRInterface): String;
var
BeginTokenIndex, EndTokenIndex: Integer;
Buf: TStringBuilder;
begin
if (Start = nil) then
Exit('');
// if we have the token stream, use that to dump text in order
if (FTokens <> nil) then
begin
// don't trust stop node as it's often an UP node etc...
// walk backwards until you find a non-UP, non-DOWN node
// and ask for it's token index.
BeginTokenIndex := FAdaptor.GetTokenStartIndex(Start);
if (Stop <> nil) and (FAdaptor.GetNodeType(Stop) = TToken.UP) then
EndTokenIndex := FAdaptor.GetTokenStopIndex(Start)
else
EndTokenIndex := Size - 1;
Exit(FTokens.ToString(BeginTokenIndex, EndTokenIndex));
end;
Buf := TStringBuilder.Create;
try
ToStringWork(Start, Stop, Buf);
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
{ TUnBufferedTreeNodeStream.TTreeWalkState }
function TUnBufferedTreeNodeStream.TTreeWalkState.GetAbsoluteNodeIndex: Integer;
begin
Result := FAbsoluteNodeIndex;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetCurrentChildIndex: Integer;
begin
Result := FCurrentChildIndex;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetCurrentNode: IANTLRInterface;
begin
Result := FCurrentNode;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetIndexStackSize: integer;
begin
Result := FIndexStackSize;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetLookAhead: TANTLRInterfaceArray;
begin
Result := FLookAhead;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetNodeStackSize: Integer;
begin
Result := FNodeStackSize;
end;
function TUnBufferedTreeNodeStream.TTreeWalkState.GetPreviousNode: IANTLRInterface;
begin
Result := FPreviousNode;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetAbsoluteNodeIndex(
const Value: Integer);
begin
FAbsoluteNodeIndex := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetCurrentChildIndex(
const Value: Integer);
begin
FCurrentChildIndex := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetCurrentNode(
const Value: IANTLRInterface);
begin
FCurrentNode := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetIndexStackSize(
const Value: integer);
begin
FIndexStackSize := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetLookAhead(
const Value: TANTLRInterfaceArray);
begin
FLookAhead := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetNodeStackSize(
const Value: Integer);
begin
FNodeStackSize := Value;
end;
procedure TUnBufferedTreeNodeStream.TTreeWalkState.SetPreviousNode(
const Value: IANTLRInterface);
begin
FPreviousNode := Value;
end;
{ Utilities }
var
EmptyCommonTree: ICommonTree = nil;
function Def(const X: ICommonTree): ICommonTree; overload;
begin
if Assigned(X) then
Result := X
else
begin
if (EmptyCommonTree = nil) then
EmptyCommonTree := TCommonTree.Create;
Result := EmptyCommonTree;
end;
end;
initialization
TTree.Initialize;
end.
|
{
//
// Components : TwwPictureValidator
//
// Copyright (c) 1996 by Woll2Woll Software
//
// Components : TwwPictureValidator
//
// Description: Implement Paradox style PictureMask support
//
}
unit Wwpict;
interface
type
TwwPicResult = (prComplete, prIncomplete, prEmpty, prError, prSyntax,
prAmbiguous, prIncompNoFill);
TwwPictureValidator = class
Status: Word;
Options: Word;
Pic: PString;
public
constructor Create(const APic: string; AutoFill: Boolean);
destructor Destroy; override; { add override 7/12/96}
function IsValidInput(var S: string;
SuppressFill: Boolean): Boolean; virtual;
function IsValid(const S: string): Boolean; virtual;
function Picture(var Input: string;
AutoFill: Boolean): TwwPicResult; virtual;
function isSyntaxError: boolean;
end;
implementation
uses WinTypes, WinProcs, SysUtils;
const
vsSyntax = 1; { Error in the syntax }
{ Validator option flags }
voFill = $0001;
voTransfer = $0002;
voOnAppend = $0004;
Function LowCase(Ch: char): Char;
var s: string[1];
begin
s:= lowercase(ch);
result:= s[1];
end;
constructor TwwPictureValidator.Create(const APic: string;
AutoFill: Boolean);
var
S: String;
begin
Status := 0;
Options := 0;
Pic := NewStr(APic);
Options := voOnAppend;
if AutoFill then Options := Options or voFill;
S := '';
if Picture(S, False) <> prEmpty then
Status := vsSyntax;
end;
destructor TwwPictureValidator.Destroy;
begin
DisposeStr(Pic);
inherited Destroy;
end;
function TwwPictureValidator.isSyntaxError: boolean;
begin
result:= (status=vsSyntax);
end;
function TwwPictureValidator.IsValidInput(var S: string;
SuppressFill: Boolean): Boolean;
begin
IsValidInput := (Pic = nil) or
(Picture(S, (Options and voFill <> 0) and not SuppressFill) <> prError);
end;
function TwwPictureValidator.IsValid(const S: string): Boolean;
var
Str: String;
Rslt: TwwPicResult;
begin
Str := S;
Rslt := Picture(Str, False);
IsValid := (Pic = nil) or (Rslt = prComplete) or (Rslt = prEmpty);
end;
function IsNumber(ch: Char): Boolean;
begin
result:= (ch>='0') and (ch<='9');
end;
function IsLetter(Ch: Char): Boolean;
begin
result:= ((ch>='A') and (ch<='Z')) or
((ch>='a') and (ch<='z'));
end;
{function AnsiUpper(ch: char): boolean;
var temp: string[1];
begin
temp:= AnsiUpperCase(ch);
Ch := temp[1];
end;
}
function IsIntlLetter(Ch:char):Boolean;
begin
result:= (IsLetter(Ch)) or (ord(ch)>128)
end;
function IsComplete(Rslt: TwwPicResult): Boolean;
begin
IsComplete := Rslt in [prComplete, prAmbiguous];
end;
function IsIncomplete(Rslt: TwwPicResult): Boolean;
begin
IsIncomplete := Rslt in [prIncomplete, prIncompNoFill];
end;
function TwwPictureValidator.Picture(var Input: string;
AutoFill: Boolean): TwwPicResult;
var
I, J: Byte;
Rslt: TwwPicResult;
Reprocess: Boolean;
function Process(TermCh: Byte): TwwPicResult;
var
Rslt: TwwPicResult;
Incomp: Boolean;
OldI, OldJ, IncompJ, IncompI: Byte;
skipAutoFill: Boolean; {9/27/96 - Added to handle autofill and spaces in picture mask}
{ Consume input }
procedure Consume(Ch: Char);
begin
Input[J] := Ch;
Inc(J);
Inc(I);
end;
{ Skip a character or a picture group }
procedure ToGroupEnd(var I: Byte; TermCh: Byte);
var
BrkLevel, BrcLevel: Integer;
begin
BrkLevel := 0;
BrcLevel := 0;
repeat
if I = TermCh then Exit;
case Pic^[I] of
'[': Inc(BrkLevel);
']': Dec(BrkLevel);
'{': Inc(BrcLevel);
'}': Dec(BrcLevel);
';': Inc(I);
'*':
begin
Inc(I);
while IsNumber(Pic^[I]) do Inc(I);
ToGroupEnd(I, Termch);
Continue;
end;
end;
Inc(I);
until (BrkLevel <= 0) and (BrcLevel <= 0);
end;
procedure ToParensEnd(var I: Byte);
var
BrkLevel, BrcLevel: Integer;
begin
BrkLevel := 0;
BrcLevel := 1;
repeat
if I = TermCh then Exit;
case Pic^[I] of
'[': Inc(BrkLevel);
']': Dec(BrkLevel);
'{': Inc(BrcLevel);
'}': Dec(BrcLevel);
';': Inc(I);
'*':
begin
Inc(I);
while IsNumber(Pic^[I]) do Inc(I);
ToGroupEnd(I, TermCh);
Continue;
end;
end;
Inc(I);
until (BrkLevel = 0) and (BrcLevel = 0);
end;
{ Find the a comma separator }
function SkipToComma: Boolean;
begin
repeat ToGroupEnd(I, TermCh) until (I = TermCh) or (Pic^[I] = ',');
if Pic^[I] = ',' then Inc(I);
SkipToComma := I < TermCh;
end;
{ Calclate the end of a group }
function CalcTerm: Byte;
var
K: Byte;
begin
K := I;
ToGroupEnd(K, TermCh);
CalcTerm := K;
end;
{ The next group is repeated X times }
function Iteration: TwwPicResult;
var
Itr, K, L: Byte;
Rslt: TwwPicResult;
NewTermCh: Byte;
LastJ: Byte;
begin
Itr := 0;
Rslt:= prEmpty; { Make compiler happy about being initialized }
{ Iteration := prError;}
Inc(I); { Skip '*' }
{ Retrieve number }
while IsNumber(Pic^[I]) do
begin
Itr := Itr * 10 + Byte(Pic^[I]) - Byte('0');
Inc(I);
end;
if I > TermCh then
begin
Result:= prSyntax;
Exit;
end;
K := I;
NewTermCh := CalcTerm;
{ If Itr is 0 allow any number, otherwise enforce the number }
if Itr <> 0 then
begin
for L := 1 to Itr do
begin
I := K;
Rslt := Process(NewTermCh);
if not IsComplete(Rslt) then
begin
{ Empty means incomplete since all are required }
if (Rslt = prEmpty) then
begin
if(Pic^[i]='[') then Rslt:= prComplete {Whole Iteration is Optional - !!!}
else Rslt := prIncomplete;
end;
Result:= Rslt;
Exit;
end;
end;
end
else
begin
repeat
I := K;
LastJ:= J;
Rslt := Process(NewTermCh);
if (J=LastJ) then break; { Have not consumed any }
until not IsComplete(Rslt);
if (Rslt = prEmpty) or (Rslt = prError) then
begin
Inc(I);
Rslt := prAmbiguous;
end;
end;
I := NewTermCh;
Result:= Rslt;
end;
{ Process a picture group }
function Group: TwwPicResult;
var
Rslt: TwwPicResult;
TermCh: Byte;
begin
TermCh := CalcTerm;
Inc(I);
Rslt := Process(TermCh - 1);
if not IsIncomplete(Rslt) then I := TermCh;
Group := Rslt;
end;
function CheckComplete(Rslt: TwwPicResult; startGroup, EndGroup: integer): TwwPicResult; forward;
function isOptionalParensGroup(startGroup, EndGroup: integer): boolean;
var tempStartGroup, tempEndGroup: integer;
function GetSubGroup(startGroup: integer; var tempEndGroup: integer): Boolean;
var curPos: byte;
begin
curPos:= startGroup;
repeat
ToGroupEnd(curPos, endGroup)
until (curPos >= EndGroup) or (Pic^[curPos] = ',');
result := curPos <= endGroup;
tempEndGroup:= curPos-1;
end;
begin
tempStartGroup:= startGroup;
tempEndGroup:= endGroup;
tempStartGroup:= tempStartGroup + 1; { Skip opening parens }
result:= False; { Make compiler happy }
while True do begin
if not GetSubGroup(tempStartGroup, tempEndGroup) then
begin
result:= False;
break;
end
else if (CheckComplete(prIncomplete, tempStartGroup, tempEndGroup)=prAmbiguous) then
begin
result:= True;
break;
end
else begin
tempStartGroup:= tempEndGroup + 2;
if tempStartGroup>endGroup then
begin
result:= False;
break;
end
end
end
end;
function CheckComplete(Rslt: TwwPicResult; startGroup, EndGroup: integer): TwwPicResult;
var
J, EndJ: Byte;
begin
J := startGroup;
if IsIncomplete(Rslt) then
begin
{ Skip optional pieces }
while True do begin
case Pic^[J] of
'[': ToGroupEnd(J, EndGroup);
'*':
if not IsNumber(Pic^[J + 1]) then
begin
Inc(J);
ToGroupEnd(J, EndGroup);
end
else begin
if (J+2<EndGroup) and (Pic^[J + 2]='[') then {Whole iteration is Optional!!!}
begin
j:= j+2;
ToGroupEnd(J, EndGroup)
end
else
Break;
end;
',': ToParensEnd(J); { Scan until encounter ending parens }
'{': begin
EndJ:= j;
ToGroupEnd(EndJ, EndGroup);
if isOptionalParensGroup(j, EndJ-1) then j:= EndJ
else break; { has a required character}
end
else begin
CheckComplete:= Rslt; {Not complete }
exit;
end
end;
if J >= EndGroup then break; { Nothing required in current Group }
end;
if (J >= EndGroup) then Rslt := prAmbiguous;
end;
CheckComplete := Rslt;
end;
function Scan: TwwPicResult;
var
Ch: Char;
temp:string;
Rslt: TwwPicResult;
begin
Scan := prError;
Rslt := prEmpty;
while (I <> TermCh) and (Pic^[I] <> ',') do
begin
if J > Length(Input) then
begin
Scan := CheckComplete(Rslt, I, TermCh);
Exit;
end;
Ch := Input[J];
case Pic^[I] of
'#': if not IsNumber(Ch) then Exit
else Consume(Ch);
'?': if not IsIntlLetter(Ch) then Exit
else Consume(Ch);
'&': if not IsIntlLetter(Ch) then Exit
else begin
temp := AnsiUpperCase(ch);
Ch := temp[1];
Consume(Ch);
end;
'~': if not IsIntlLetter(Ch) then Exit
else begin
temp := AnsiLowerCase(ch);
Ch := temp[1];
Consume(Ch);
end;
'!': begin
temp := AnsiUpperCase(ch);
Ch := temp[1];
Consume(Ch);
end;
'@': Consume(Ch);
'*':
begin
Rslt := Iteration;
if not IsComplete(Rslt) then
begin
Scan := Rslt;
Exit;
end;
if Rslt = prError then Rslt := prAmbiguous;
end;
'{':
begin
Rslt := Group;
if not IsComplete(Rslt) then
begin
Scan := Rslt;
Exit;
end;
end;
'[':
begin
Rslt := Group;
if IsIncomplete(Rslt) then
begin
Scan := Rslt;
Exit;
end;
if Rslt = prError then Rslt := prAmbiguous;
end;
else
if Pic^[I] = ';' then Inc(I);
if UpCase(Pic^[I]) <> UpCase(Ch) then begin
if (not SkipAutofill) and (Ch = ' ') and (j = length(input)) then
{ Ch := Pic^[I]}
else Exit;
end
else begin
if (Ch = ' ') and (j = length(input)) then
SkipAutoFill := True;
end;
Consume(Pic^[I]);
end;
if Rslt = prAmbiguous then
Rslt := prIncompNoFill
else
Rslt := prIncomplete;
end;
if Rslt = prIncompNoFill then
Scan := prAmbiguous
else
Scan := prComplete;
end;
begin
Incomp := False;
Incompi:= 0; Incompj:= 0; {Make compiler happy}
OldI := I;
OldJ := J;
skipAutoFill := False;
repeat
Rslt := Scan;
{ Only accept completes if they make it farther in the input
stream from the last incomplete }
if (Rslt in [prComplete, prAmbiguous]) and Incomp and (J < IncompJ) then
begin
Rslt := prIncomplete;
J := IncompJ;
end;
if (Rslt = prError) or (Rslt = prIncomplete) then
begin
Process := Rslt;
if not Incomp and (Rslt = prIncomplete) then
begin
Incomp := True;
IncompI := I;
IncompJ := J;
end;
I := OldI;
J := OldJ;
if not SkipToComma then
begin
if Incomp then
begin
Process := prIncomplete;
I := IncompI;
J := IncompJ;
end;
Exit;
end;
OldI := I;
end;
until (Rslt <> prError) and (Rslt <> prIncomplete);
if (Rslt = prComplete) and Incomp then
Process := prAmbiguous
else
Process := Rslt;
end;
function SyntaxCheck: Boolean;
var
I: Integer;
BrkLevel, BrcLevel: Integer;
begin
SyntaxCheck := False;
if Pic^ = '' then Exit;
if Pic^[Length(Pic^)] = ';' then Exit;
if (Pic^[Length(Pic^)] = '*') and (Pic^[Length(Pic^) - 1] <> ';') then
Exit;
I := 1;
BrkLevel := 0;
BrcLevel := 0;
while I <= Length(Pic^) do
begin
case Pic^[I] of
'[': Inc(BrkLevel);
']': Dec(BrkLevel);
'{': Inc(BrcLevel);
'}': Dec(BrcLevel);
';': Inc(I);
end;
Inc(I);
end;
if (BrkLevel <> 0) or (BrcLevel <> 0) then Exit;
SyntaxCheck := True;
end;
begin
Picture := prSyntax;
if not SyntaxCheck then Exit;
Picture := prEmpty;
if Input = '' then Exit;
J := 1;
I := 1;
Rslt := Process(Length(Pic^) + 1);
if (Rslt <> prError) and (Rslt <> prSyntax) and (J <= Length(Input)) then
Rslt := prError;
if (Rslt = prIncomplete) and AutoFill then
begin
Reprocess := False;
while (I <= Length(Pic^)) and
not (Pic^[I] in ['#','?','&', '~', '!', '@', '*', '{', '}', '[', ']', ',', #0]) do
begin
if Pic^[I] = ';' then Inc(I);
Input := Input + Pic^[I];
Inc(I);
Reprocess := True;
end;
J := 1;
I := 1;
if Reprocess then
Rslt := Process(Length(Pic^) + 1)
end;
if Rslt = prAmbiguous then
Picture := prComplete
else if Rslt = prIncompNoFill then
Picture := prIncomplete
else
Picture := Rslt;
end;
end.
|
unit uFrmModelImage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, ExtCtrls, DB, ADODB, Buttons,
StdCtrls, ExtDlgs, uParentAll;
type
TSubModelImage = class(TFrmParentAll)
imgItem: TImage;
quModelImage: TADODataSet;
quModelImageLargeImage: TStringField;
Bevel1: TBevel;
pnlButtom: TPanel;
hhh: TPanel;
btClose: TButton;
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCloseClick(Sender: TObject);
private
{ Private declarations }
fLargeImagePath : String;
fIDModel : Integer;
procedure LoadImage;
procedure SetImage;
procedure RefreshImage;
procedure DataSetRefresh;
procedure DataSetOpen;
procedure DataSetClose;
protected
public
{ Public declarations }
procedure Start(IDModel:String);
end;
implementation
uses uDM, uParamFunctions;
{$R *.dfm}
procedure TSubModelImage.LoadImage;
begin
If FileExists(fLargeImagePath) then
imgItem.Picture.LoadFromFile(fLargeImagePath)
else
imgItem.Picture := nil;
end;
procedure TSubModelImage.RefreshImage;
begin
SetImage;
LoadImage;
end;
procedure TSubModelImage.Start(IDModel:String);
var
fStartImage : String;
fColor : String;
begin
fIDModel := StrToInt(IDModel);
DataSetRefresh;
RefreshImage;
ShowModal;
end;
procedure TSubModelImage.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubModelImage.SetImage;
begin
fLargeImagePath := quModelImageLargeImage.AsString;
end;
procedure TSubModelImage.DataSetOpen;
begin
with quModelImage do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := fIDModel;
Open;
end;
end;
procedure TSubModelImage.DataSetClose;
begin
with quModelImage do
if Active then
Close;
end;
procedure TSubModelImage.FormDestroy(Sender: TObject);
begin
inherited;
DataSetClose;
end;
procedure TSubModelImage.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TSubModelImage.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
{******************************************************************}
{ GDIPPathText }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 30-11-2007 }
{ }
{ version : 1.0 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2007 Martin Walter }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit GDIPPathText;
interface
uses
Winapi.GDIPAPI, Winapi.GDIPOBJ, GDIPKerning;
type
TPathPosition = Single;
TGPPathText = class(TObject)
strict private
FRotation: Single;
FGuidePath: TGPGraphicsPath;
FFamily: TGPFontFamily;
FStyle: Integer;
FSize: Single;
FFormat: TGPStringFormat;
FDistanceFactor: Single;
FKerningFactor: Single;
FAdditionalMatrix: TGPMatrix;
function AddGlyphToPath(const Path: TGPGraphicsPath; const Char: WideChar;
const Family: TGPFontFamily; const Style: Integer; const Size: Single;
const Origin: TGPPointF; const Format: TGPStringFormat): TStatus;
function AddCharacter(const Current, Next: WideChar;
const Path: TGPGraphicsPath; const Position: TPathPosition): TPathPosition;
function GetPathPoint(const Position: TPathPosition): TGPPointF;
function GetPathPointLength(const Position: TPathPosition): Single;
function GetPathPosition(Indent: Single): TPathPosition;
function FindRightPosition(CenterPos: TPathPosition;
const Radius: Single): TPathPosition;
protected
public
constructor Create(const GuidePath: TGPGraphicsPath;
const Flatness: Single = 10 * FlatnessDefault);
destructor Destroy; override;
function AddPathText(const Path: TGPGraphicsPath;
const Text: string; const Indent: Single;
const Family: TGPFontFamily; Style: Integer;
const Size: Single; const Format: TGPStringFormat;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): Single;
class function GetPathLength(const Path: TGPGraphicsPath): Single;
property Rotation: Single read FRotation write FRotation;
property AdditionalMatrix: TGPMatrix read FAdditionalMatrix write FAdditionalMatrix;
end;
implementation
uses
System.Math, System.SysUtils;
function GetPoint(P: PGPPointF; Index: Integer): TGPPointF;
begin
Inc(P, Index);
Result := P^;
end;
function AddPoint(A, B: TGPPointF): TGPPointF;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
function SubPoint(A, B: TGPPointF): TGPPointF;
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
function GetIntersectionFromCircle(PtA, PtB, Center: TGPPointF;
const R2: Single): Single;
var
Diff: TGPPointF;
rA2, rB2: Single;
A, B, C, D, T, T1, T2, SqrtD: Single;
begin
PtA := SubPoint(PtA, Center);
PtB := SubPoint(PtB, Center);
rA2 := Sqr(PtA.X) + Sqr(PtA.Y);
rB2 := Sqr(PtB.X) + Sqr(PtB.Y);
if (rA2 > R2) and (rB2 > R2) then
begin
Result := -1;
Exit;
end;
if (rA2 < R2) and (rB2 < R2) then
begin
Result := -1;
Exit;
end;
Diff := SubPoint(PtB, PtA);
A := Sqr(Diff.X) + Sqr(Diff.Y);
B := 2 * (PtA.X * Diff.X + PtA.Y * Diff.Y);
C := rA2 - R2;
D := Sqr(B) - 4 * A * C;
T := -1;
A := 2 * A;
if (D = 0) then
T := -B / A
else
if (D > 0) then
begin
SqrtD := Sqrt(D);
T1 := (-B + SqrtD) / A;
T2 := (-B - SqrtD) / A;
if (T1 >= 0) and (T1 <= 1) then
begin
if (T2 > 0) and (T2 < T1) then
T := T2
else
T := T1;
end
else
if (T2 >= 0) and (T2 <= 1) then
T := T2;
end;
Result := T;
end;
{ TPathText }
function TGPPathText.AddCharacter(const Current, Next: WideChar;
const Path: TGPGraphicsPath; const Position: TPathPosition): TPathPosition;
var
CharWidth: Single;
GlyphPath: TGPGraphicsPath;
Left, Right, Diff: TGPPointF;
SinAngle, CosAngle: Single;
Matrix: TGPMatrix;
PosRight: TPathPosition;
begin
GlyphPath := TGPGraphicsPath.Create;
try
CharWidth := KerningText.GetCellWidth(Word(Current), Word(Next),
FDistanceFactor, FKerningFactor);
if (CharWidth = 0) then
begin
Result := -1;
Exit;
end;
PosRight := FindRightPosition(Position, CharWidth);
if (PosRight < 0) then
begin
Result := PosRight;
Exit;
end;
Left := GetPathPoint(Position);
Right := GetPathPoint(PosRight);
Diff := SubPoint(Right, Left);
CosAngle := Diff.X / CharWidth;
SinAngle := Diff.Y / CharWidth;
AddGlyphToPath(GlyphPath, Current, FFamily, FStyle, FSize,
MakePoint(0, -FSize), FFormat);
if Assigned(FAdditionalMatrix) then
GlyphPath.Transform(FAdditionalMatrix);
Matrix := TGPMatrix.Create(CosAngle, SinAngle,
- Rotation * SinAngle, 1 + Rotation * (CosAngle - 1),
Left.X, Left.Y);
try
GlyphPath.Transform(Matrix);
finally
Matrix.Free;
end;
Path.AddPath(GlyphPath, False);
Result := PosRight;
finally
GlyphPath.Free;
end;
end;
function TGPPathText.AddGlyphToPath(const Path: TGPGraphicsPath;
const Char: WideChar; const Family: TGPFontFamily; const Style: Integer;
const Size: Single; const Origin: TGPPointF;
const Format: TGPStringFormat): TStatus;
begin
Result := Path.AddString(Char, -1, Family, Style, Size, Origin, Format);
end;
function TGPPathText.AddPathText(const Path: TGPGraphicsPath;
const Text: string; const Indent: Single;
const Family: TGPFontFamily; Style: Integer;
const Size: Single; const Format: TGPStringFormat;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): Single;
var
IndentPosition, Position: TPathPosition;
Current, Next: PWideChar;
begin
Result := 0;
Path.SetFillMode(FillModeWinding);
IndentPosition := GetPathPosition(Indent);
Position := IndentPosition;
Current := PWideChar(Text);
FFamily := Family;
FStyle := Style;
FSize := Size;
FFormat := Format;
FDistanceFactor := DistanceFactor;
FKerningFactor := KerningFactor;
KerningText.Prepare(FFamily, FStyle, FSize, FFormat);
try
while (Current^ <> #0) and (Position >= 0) do
begin
Next := Current + 1;
Position := AddCharacter(Current^, Next^, Path, Position);
if Position >= 0 then
Result := Position;
Inc(Current);
end;
finally
KerningText.Unprepare;
end;
if Result > 0 then
Result := GetPathPointLength(Result - IndentPosition);
end;
constructor TGPPathText.Create(const GuidePath: TGPGraphicsPath;
const Flatness: Single);
begin
if not Assigned(GuidePath) then
Exception.Create('Path is invalid');
inherited Create;
FGuidePath := GuidePath.Clone;
FRotation := 1;
FGuidePath.Flatten(nil, Flatness);
end;
destructor TGPPathText.Destroy;
begin
FGuidePath.Free;
inherited;
end;
function TGPPathText.FindRightPosition(CenterPos: TPathPosition;
const Radius: Single): TPathPosition;
var
StartSegment: Integer;
PD: TPathData;
DistLeft, DistRight: Single;
Start: TGPPointF;
Diff: TGPPointF;
P1, P2: TGPPointF;
C, PointCount: Integer;
Intersection: Single;
begin
if (CenterPos < 0) then
begin
Result := -1;
Exit;
end;
StartSegment := Floor(CenterPos);
PointCount := FGuidePath.GetPointCount;
if (StartSegment >= PointCount - 1) then
begin
Result := -1;
Exit;
end;
PD := TPathData.Create;
try
if (FGuidePath.GetPathData(PD) = Ok) then
begin
Start := GetPathPoint(CenterPos);
P1 := GetPoint(PD.Points, StartSegment + 1);
Diff := SubPoint(Start, P1);
DistRight := Sqrt(Sqr(Diff.X) + Sqr(Diff.Y));
if (Radius < DistRight) then
begin
Diff := SubPoint(Start, GetPoint(PD.Points, StartSegment));
DistLeft := Sqrt(Sqr(Diff.X) + Sqr(Diff.Y));
Result := StartSegment + 1 - (DistRight - Radius) / (DistRight + DistLeft);
Exit;
end;
for C := StartSegment + 1 to PointCount - 2 do
begin
P2 := GetPoint(PD.Points, C + 1);
Intersection := GetIntersectionFromCircle(P1, P2, Start, Sqr(Radius));
P1 := P2;
if (Intersection >= 0) then
begin
Result := C + Intersection;
Exit;
end;
end;
end;
Result := -1;
finally
PD.Free;
end;
end;
class function TGPPathText.GetPathLength(const Path: TGPGraphicsPath): Single;
var
P: TGPGraphicsPath;
Count, C: Integer;
PD: TPathData;
P1, P2: TGPPointF;
begin
Result := 0;
P := Path.Clone;
try
P.Flatten(nil, 10 * FlatnessDefault);
Count := P.GetPointCount;
if Count > 0 then
begin
PD := TPathData.Create;
try
if (P.GetPathData(PD) = Ok) then
begin
P1 := GetPoint(PD.Points, 0);
for C := 0 to Count - 2 do
begin
P2 := GetPoint(PD.Points, C + 1);
P1 := SubPoint(P2, P1);
Result := Result + Sqrt(Sqr(P1.X) + Sqr(P1.Y));
P1 := P2;
end;
end;
finally
PD.Free;
end;
end;
finally
P.Free;
end;
end;
function TGPPathText.GetPathPoint(const Position: TPathPosition): TGPPointF;
var
R: TGPPointF;
Segment, Count: Integer;
PD: TPathData;
Diff: TGPPointF;
T: Single;
begin
R := MakePoint(0.0, 0);
if Position < 0 then
begin
Result := R;
Exit;
end;
Segment := Floor(Position);
Count := FGuidePath.GetPointCount;
if (Segment < Count - 1) then
begin
PD := TPathData.Create;
if (FGuidePath.GetPathData(PD) = Ok) then
begin
R := GetPoint(PD.Points, Segment);
Diff := GetPoint(PD.Points, Segment + 1);
Diff := SubPoint(Diff, R);
T := Frac(Position);
R.X := R.X + T * Diff.X;
R.Y := R.Y + T * Diff.Y;
end;
PD.Free;
end;
Result := R;
end;
function TGPPathText.GetPathPointLength(const Position: TPathPosition): Single;
var
P1, P2: TGPPointF;
Diff: TGPPointF;
C, Segment, Count: Integer;
PD: TPathData;
begin
if Position < 0 then
begin
Result := 0;
Exit;
end;
Segment := Floor(Position);
Result := 0;
Count := FGuidePath.GetPointCount;
if (Segment < Count - 1) then
begin
PD := TPathData.Create;
try
if (FGuidePath.GetPathData(PD) = Ok) then
begin
P1 := GetPoint(PD.Points, 0);
for C := 0 to Segment - 1 do
begin
P2 := GetPoint(PD.Points, C + 1);
Diff := SubPoint(P2, P1);
Result := Result + Sqrt(Sqr(Diff.X) + Sqr(Diff.Y));
P1 := P2;
end;
P2 := GetPoint(PD.Points, Segment + 1);
Diff := SubPoint(P2, P1);
Result := Result + Sqrt(Sqr(Diff.X) + Sqr(Diff.Y)) * Frac(Position);
end;
finally
PD.Free;
end;
end;
end;
function TGPPathText.GetPathPosition(Indent: Single): TPathPosition;
var
PD: TPathData;
C, Count: Integer;
A, B: TGPPointF;
Distance: Single;
begin
PD := TPathData.Create;
try
if (FGuidePath.GetPathData(PD) = Ok) then
begin
Count := FGuidePath.GetPointCount;
A := GetPoint(PD.Points, 0);
for C := 0 to Count - 2 do
begin
B := GetPoint(PD.Points, C + 1);
Distance := Sqrt(Sqr(B.X - A.X) + Sqr(B.Y - A.Y));
A := B;
if (Indent < Distance) then
begin
Result := C + Indent / Distance;
Exit;
end;
Indent := Indent - Distance;
end;
end;
finally
PD.Free;
end;
Result := -1;
end;
end.
|
unit svm_grabber;
{$mode objfpc}
{$inline on}
interface
uses
SysUtils, Classes, svm_common;
const
GrabberStackBlockSize = 1024 * 8;
type
TGrabberStack = object
public
items: array of pointer;
size, i_pos: cardinal;
procedure init;
procedure push(p: pointer); inline;
procedure pop; inline;
procedure drop; inline;
procedure free; inline;
end;
TGrabber = class
public
Stack: TGrabberStack;
ChkCnt: byte;
LastChk: cardinal;
Delta: cardinal;
Skipped: word;
constructor Create;
destructor Destroy; override;
procedure Reg(value: pointer);
procedure Run(offset: word = 32);
procedure RunFull(GlobalLocked: boolean = false);
procedure Term;
end;
implementation
uses svm_mem;
{***** stack *****}
procedure TGrabberStack.init;
begin
SetLength(items, GrabberStackBlockSize);
i_pos := 0;
size := GrabberStackBlockSize;
end;
procedure TGrabberStack.push(p: pointer); inline;
begin
items[i_pos] := p;
Inc(i_pos);
if i_pos >= size then
begin
size := size + GrabberStackBlockSize;
SetLength(items, size);
end;
end;
procedure TGrabberStack.pop; inline;
begin
Dec(i_pos);
if size - i_pos > GrabberStackBlockSize then
begin
size := size - GrabberStackBlockSize;
SetLength(items, size);
end;
end;
procedure TGrabberStack.drop; inline;
begin
SetLength(items, GrabberStackBlockSize);
size := GrabberStackBlockSize;
i_pos := 0;
end;
procedure TGrabberStack.free; inline;
begin
SetLength(items, 0);
size := 0;
i_pos := 0;
end;
{***** grabber *****}
constructor TGrabber.Create;
begin
Stack.Init;
ChkCnt := 0;
LastChk := 0;
Delta := 0;
Skipped := 0;
end;
destructor TGrabber.Destroy;
begin
Stack.Free;
inherited;
end;
procedure TGrabber.Reg(value: pointer);
begin
if (Delta > 1024) and (Stack.i_pos > 1024*8) or (Skipped > 1024*8) then
begin
Delta := Stack.i_pos;
Run;
Delta := Delta - Stack.i_pos;
Skipped := 0;
end
else
Inc(Skipped);
Stack.push(value);
end;
procedure TGrabber.Run(offset: word = 32);
var
i: integer;
c, l, tm: cardinal;
r: TSVMMem;
begin
tm := GetTickCount;
if ChkCnt < 32 then
begin
i := stack.i_pos * 2 div 3;
Inc(ChkCnt);
end
else
begin
i := 0;
ChkCnt := 0;
end;
//i := 0;
while i < stack.i_pos - offset do
begin
r := TSVMMem(stack.items[i]);
if (r.m_rcnt < 1) {and (tm - r.t_created > 10)} then
begin
stack.items[i] := stack.items[stack.i_pos - offset];
c := stack.i_pos - offset;
while (c < stack.i_pos - 1) and (offset > 0) do
begin
stack.items[c] := stack.items[c + 1];
Inc(c);
end;
stack.pop;
if r.m_type in [svmtArr, svmtClass] then
begin
c := 0;
l := Length(PMemArray(r.m_val)^);
while c < l do
begin
InterlockedDecrement(TSVMMem(PMemArray(r.m_val)^[c]).m_rcnt);
Inc(c);
end;
end;
FreeAndNil(r);
Dec(i);
end;
inc(i);
end;
end;
procedure TGrabber.RunFull(GlobalLocked: boolean = false);
var
i: integer;
c, l, tm: cardinal;
r: TSVMMem;
begin
tm := GetTickCount;
if not GlobalLocked then
GlobalLock.Acquire;
i := 0;
while i < stack.i_pos do
begin
r := TSVMMem(stack.items[i]);
if (r.m_rcnt < 1) {and (tm - r.t_created > 10)} then
begin
stack.items[i] := stack.items[stack.i_pos - 1];
stack.pop;
if r.m_type in [svmtArr, svmtClass] then
begin
c := 0;
l := Length(PMemArray(r.m_val)^);
while c < l do
begin
InterlockedDecrement(TSVMMem(PMemArray(r.m_val)^[c]).m_rcnt);
Inc(c);
end;
end;
FreeAndNil(r);
Dec(i);
end;
inc(i);
end;
if not GlobalLocked then
GlobalLock.Release;
end;
procedure TGrabber.Term;
var
c: cardinal;
r: TSVMMem;
begin
c := 0;
while c < stack.i_pos do
begin
r := TSVMMem(stack.items[c]);
FreeAndNil(r);
Inc(c);
end;
end;
end.
|
// A Unit that provides classes and functions for using periods of times
// inluding workdays etc...
// NOTE: The periods are sometimes called "weeks" in the code, but dont have
// to be a real world week. They are just a list of (maybe random) days.
unit workdays;
interface
uses Classes, SysUtils, DateUtils, fgl, Grids, StdCtrls;
var
txtWeekDays: array[1..7] of string = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
type
//############################################ CockTime ###########################################################
TClockTime = class
private
FHours: Integer; // hh:mm
FMinutes: Integer;
public
constructor Create; overload;
constructor Create(AClockTime: TClockTime); overload;
constructor Create(AHours, AMinutes: Integer); overload;
procedure Clear; // initializes or clears the instance
procedure Assign(AClockTime: TClockTime); overload;
procedure Assign(AHours, AMinutes: Integer); overload;
procedure AddTime(AHours, AMinutes: Integer); overload; // adds some time to the instance
procedure AddTime(AClockTime: TClockTime); overload; // adds the time of another instance to this instance
procedure SubstractTime(AHours, AMinutes: Integer);
function ToText: String; // returns the time as a text, e.g. 0:00
property getHours: Integer read FHours; // only readable
property getMinutes: Integer read FMinutes;
end;
//############################################ DAY ###########################################################
TWorkDay = class
private
FStartTime: TClockTime;
FEndTime: TClockTime;
FTimeOff: Double; // hours that are taken off - freetime
FWeekDay: integer; // Weekday 1 - 7
FDate: TDate; // Date of the specific Day
FAdditionalTime: double; // Time to add or substract additional time e.g. if you took 1 hour off
FTag: String; // add a tag to the specifig day e.g. "offical holiday", "ignore"...
public
constructor Create; overload; // normal day constructor
constructor Create(ADay: TWorkDay); overload; // Creates a new day and copies the values from ADay
destructor Destroy;
procedure Clear;
procedure Assign(ADay: TWorkDay);
function WeekDayToText: String;
function getAmountOfTime: Double;
property StartTime: TClockTime read FStartTime write FStartTime;
property EndTime: TClockTime read FEndTime write FEndTime;
property Date: TDate read FDate write FDate;
property Weekday: integer read FWeekday write FWeekday;
property TimeOff: Double read FTimeOff write FTimeOff;
property AdditionalTime: double read FAdditionaltime write FAdditionaltime;
property Tag: String read FTag write FTag;
end;
TWorkDays = specialize TFPGObjectList<TWorkDay>;
//############################################ Period ###########################################################
TWorkWeek = class
private
// Remember to also change the assign-method when adding/deleting variables
FWeekLabel: String; // The "Name" of the week shown in grid
FDays: TWorkDays; // The Days related to this period
FFromDate: TDate; // The lowest Date of the week
FToDate: TDate; // The highest Date of the week
FWeekLength: integer; // Workdays in that particular week
FIntendedTimePerDay: double; // The time you intend to work per day
FPausePerDay: Double; // Obligatory Pause Time, time you need to stay at work additionally
FDescriptionText: TStringList; // Description Text
public
constructor Create;
constructor Create(AFromDate, AToDate: TDate); overload;
constructor Create(AWorkWeek: TWorkWeek); overload; // Creates a week and copies the values from AWorkWeek
destructor Destroy;
procedure Clear;
procedure assign(AWeek: TWorkWeek); // Assign the values of AWeek to this instance
function getSum: Double; // come here and getsum - calculate the sum of working time of the week
function getAmountOfVacation: Double; // Returns the number of days a person has taken off
function getGoalHours: Double; // Returns the number of hours that have to be achieved
function getDayOfLatestQuitting: TWorkDay;// Returns the Date of the latest qutting
function getDayOfEarliestBegin: TWorkDay; // Returns the Date of the earliest begin
property WeekLength: Integer read FWeekLength write FWeekLength;
property IntendedTimePerDay: Double read FIntendedTimePerDay write FIntendedTimePerDay;
property PausePerDay: Double read FPausePerDay write FPausePerDay;
property FromDate: TDate read FFromDate write FFromDate;
property ToDate: TDate read FToDate write FToDate;
property Days: TWorkDays read FDays write FDays;
property WeekLabel: String read FWeekLabel write FWeekLabel;
property DescriptionText: TStringList read FDescriptionText write FDescriptionText;
end;
TWeekList = specialize TFPGObjectList<TWorkWeek>;
// ############################################### additional Functions ################################################
procedure ClearStringGrid(AGrid: TStringGrid);
procedure WeeksToStringGrid(AGrid: TStringGrid; AWeeklist: TWeekList; SelectionIndex: Integer);
procedure WeekDaysToStringGrid(AGrid: TStringGrid; AWeek: TWorkWeek);
procedure WeeksToComboBox(AComboBox: TComboBox; AWeekList: TWeekList);
function timeToText(AHour, AMinute: integer): string;
function periodToText(AWeekList: TWeekList): String;
function RealDayOfWeek(ADate: TDate): integer; // only needed because I used a 1-based String instead of a 0 based
function getHour(time: string): integer;
function getMinute(time: string): integer;
function getDayOfEarliestBegin(AWeekList: TWeekList): TWorkDay;
function getDayOfLatestQuitting(AWeekList: TWeekList): TWorkDay;
function getLongestDay(AWeekList: TWeekList): TWorkDay;
function isTimeEarliest(AHour, AMinute, earliestHour, earliestMinute: Integer): Boolean;
function isTimeLatest(AHour, AMinute, latestHour, latestMinute: Integer): Boolean;
implementation
uses CoyoteDefaults, people;
//############################################ ClockTime ###########################################################
constructor TClockTime.Create;
begin
Clear;
end;
constructor TClockTime.Create(AClockTime: TClockTime);
begin
Clear;
self.Assign(AClockTime);
end;
constructor TClockTime.Create(AHours, AMinutes: Integer);
begin
Clear;
AddTime(AHours, AMinutes);
end;
procedure TClockTime.Clear;
begin
Fhours := 0;
FMinutes := 0;
end;
procedure TClockTime.Assign(AClockTime: TClockTime);
begin
FHours := AClockTime.getHours;
FMinutes := AClockTime.getMinutes;
end;
procedure TClockTime.Assign(AHours, AMinutes: Integer);
begin
FHours := AHours;
FMinutes := AMinutes;
end;
function TClockTime.ToText: String;
begin
Result := TimeToText(FHours, FMinutes);
end;
procedure TClockTime.AddTime(AHours, AMinutes: Integer);
var
I: Integer;
begin
FHours := (FHours + Ahours) mod 24;
for I := 0 to AMinutes - 1 do
begin
FMinutes += 1;//AMinutes;
if (FMinutes > 59) then
begin
FHours := (FHours + 1) mod 24;
FMinutes := 0;
end;
end;
end;
procedure TClockTime.AddTime(AClockTime: TClockTime);
begin
self.AddTime(AClockTime.getHours, AClockTime.getMinutes);
end;
procedure TClockTime.SubstractTime(AHours, AMinutes: Integer);
var
I: Integer;
begin
FHours := (FHours - Ahours) mod 24;
for I := 0 to AMinutes - 1 do
begin
FMinutes -= 1;//AMinutes;
if (FMinutes < 0) then
begin
FHours := (FHours - 1) mod 24;
FMinutes := 59;
end;
end;
end;
//############################################ DAY ###########################################################
constructor TWorkDay.Create;
begin
FTag := '';
FStartTime := TClockTime.Create;
FEndTime := TClockTime.Create;
end;
constructor TWorkDay.Create(ADay: TWorkDay);
begin
self.Assign(ADay);
end;
destructor TWorkDay.Destroy;
begin
FStartTime.Free;
FEndTime.Free;
end;
procedure TWorkDay.Assign(ADay: TWorkDay);
begin
FStartTime.Assign(ADay.StartTime);
FEndTime.Assign(ADay.EndTime);
FDate := ADay.Date;
FWeekDay := RealDayOfWeek(FDate);
FAdditionalTime := ADay.AdditionalTime;
FTag := ADay.Tag;
end;
procedure TWorkDay.Clear;
begin
FStartTime.Clear;
FEndTime.Clear;
FDate := 0;
FAdditionalTime := 0;
FTag := '';
end;
function TWorkDay.WeekDayToText(): string;
begin
if (FWeekday > 0) then
Result := txtWeekdays[FWeekday] + FormatDateTime('dd.mm.yyyy', FDate)
else
Result := FormatDateTime('dd.mm.yyyy', FDate);
end;
function TWorkDay.getAmountOfTime: Double;
var
locStartTime: TDateTime;
locEndTime: TDateTime;
begin
locStartTime := self.FDate;
locEndTime := self.FDate;
locStartTime := locStartTime + (60*60*FStartTime.getHours) + (60*FStartTime.getMinutes{FStartMinute});
locEndTime := locEndTime + (60*60*FEndTime.getHours) + (60*FEndTime.getMinutes);
Result := {self.TimeOff +} (locEndTime - locStartTime)/3600;
if (Result >= defHoursUntilPause) then
begin
Result := Result - defPausePerDay;
end;
end;
//############################################ Week ###########################################################
constructor TWorkWeek.Create;
begin
FDays := TWorkDays.Create(true);
FWeekLabel := 'empty week';
FWeekLength := 0;
FIntendedTimePerDay := defHoursPerDay;
FPausePerDay := defPausePerDay;
FDescriptionText := TStringList.Create;
end;
constructor TWorkWeek.Create(AFromDate, AToDate: TDate);
var
I: Integer;
begin
FFromDate := AFromDate;
FToDate := AToDate;
FWeekLength := DaysBetween(FToDate,FFromDate)+ 1;
FIntendedTimePerDay := defHoursPerDay;
FPausePerDay := defPausePerDay;
FDays := TWorkDays.Create(true);
FWeekLabel := FormatDateTime('dd.mm.yyyy', FromDate) + ' to ' + FormatDateTime('dd.mm.yyyy', ToDate);
for I := 0 to FWeekLength-1 do
begin
FDays.Add(TWorkDay.Create);
FDays[I].Weekday := RealDayOfWeek(AFromDate + I);
FDays[I].Date := AFromDate + I;
end;
FDescriptionText := TStringList.Create;
end;
constructor TWorkWeek.Create(AWorkWeek: TWorkWeek);
begin
FDays := TWorkDays.Create(true);
self.assign(AWorkWeek);
end;
destructor TWorkWeek.Destroy;
begin
FDays.Free;
FDescriptionText.Free;
end;
procedure TWorkWeek.assign(AWeek: TWorkWeek);
var
I: Integer;
begin
FFromDate := AWeek.FromDate;
FToDate := AWeek.ToDate;
FWeekLength := AWeek.WeekLength;
FWeekLabel := AWeek.WeekLabel;
FIntendedTimePerDay := AWeek.IntendedTimePerDay;
FPausePerDay := AWeek.PausePerDay;
FDescriptionText := AWeek.DescriptionText;
FDays.Clear;
for I := 0 to self.WeekLength -1 do
begin
FDays.Add(TWorkDay.Create);
FDays[I].Date := AWeek.Days[I].Date;
FDays[I].Weekday := AWeek.Days[I].Weekday;
FDays[I].StartTime.Assign(AWeek.Days[I].StartTime);
FDays[I].EndTime.Assign(AWeek.Days[I].EndTime);
FDays[I].TimeOff := AWeek.Days[I].TimeOff;
FDays[I].Tag := AWeek.Days[I].Tag;
end;
end;
function TWorkWeek.getSum: Double;
var
I: Integer;
begin
Result := 0;
for I := 0 to self.Days.Count-1 do
begin
if (self.Days[I].Tag = '') then
begin
Result := Result + self.Days[I].getAmountOfTime;
end;
end;
end;
function TWorkWeek.getGoalHours: Double;
var
sum: Double;
I: Integer;
begin
sum := 0;
for I := 0 to FDays.Count - 1 do
begin
if (Days[I].Tag = '') then
begin
sum := sum + FIntendedTimePerDay - FDays[I].TimeOff;
end;
end;
Result := sum;
end;
procedure TWorkWeek.Clear;
begin
FDays.Clear;
FFromDate := 0;
FToDate := 0;
FWeekLength := 0;
FIntendedTimePerDay := 8;
end;
function TWorkWeek.getAmountOfVacation: Double;
var
I: Integer;
sum: Double;
begin
sum := 0;
for I := 0 to FDays.Count - 1 do
begin
if (FIntendedTimePerDay > 0) then
begin
sum := sum + (FDays.Items[I].TimeOff/FIntendedTimePerDay);
end;
end;
Result := sum;
end;
function TWorkWeek.getDayOfEarliestBegin: TWorkDay;
var
I: Integer;
begin
Result := nil;
for I := 0 to FDays.Count - 1 do
begin
if (FDays[I].TimeOff < FIntendedTimePerDay) and (FDays[I].Tag = '') then
begin
if (Result <> nil) then
begin
if (FDays[I].StartTime.getHours < Result.StartTime.getHours) or
((FDays[I].StartTime.getHours = Result.StartTime.getHours) and
(FDays[I].StartTime.getMinutes <= Result.StartTime.getMinutes)) then
begin
Result := FDays[I];
end
else
begin
Result := nil;
end;
end
else
begin
Result := FDays[I];
end;
end;
end;
end;
function TWorkWeek.getDayOfLatestQuitting: TWorkDay;
var
I: Integer;
begin
Result := nil;
for I := 0 to FDays.Count - 1 do
begin
if (FDays[I].TimeOff < FIntendedTimePerDay) and (FDays[I].Tag = '') then
begin
if (Result <> nil) then
begin
if isTimeLatest(FDays[I].EndTime.getHours, FDays[I].EndTime.getMinutes, Result.EndTime.getHours, Result.EndTime.getMinutes) then
begin
Result := FDays[I];
end;
end
else
begin
Result := FDays[I];
end;
end;
end;
end;
// ############################################### External Functions ################################################
function isTimeEarliest(AHour, AMinute, earliestHour, earliestMinute: Integer): Boolean;
begin
Result := False;
if (AHour < earliestHour) then
begin
Result := True;
end;
if (AHour = earliestHour) then
begin
Result := (AHour < earliestMinute);
end;
end;
function isTimeLatest(AHour, AMinute, latestHour, latestMinute: Integer): Boolean;
begin
Result := False;
if (AHour > latestHour) then
begin
Result := True
end
else if (AHour = latestHour) then
begin
if (AMinute >= latestMinute) then
begin
Result := True;
end;
end;
end;
function timeToText(AHour, AMinute: integer): string;
begin
if (AMinute >= 0) and (AMinute < 60) and (AHour >= 0) and (AHour < 24) then
begin
if (AMinute < 10) then
begin
Result := IntToStr(AHour) + ':0' + IntToStr(AMinute);
end
else
begin
Result := IntToStr(AHour) + ':' + IntToStr(AMinute);
end;
end
else
begin
Result := 'time not convertable!';
end;
end;
procedure WeeksToStringGrid(AGrid: TStringGrid; AWeeklist: TWeekList; SelectionIndex: Integer);
var
I: Integer;
diff: Double;
begin
clearStringGrid(AGrid);
AGrid.RowCount := 1 + AWeekList.Count;
for I := 0 to AWeekList.Count - 1 do
begin
AGrid.Cells[0,1+I] := IntToStr(I+1);
AGrid.Cells[1,1+I] := AWeekList.Items[I].WeekLabel;
AGrid.Cells[2,1+I] := IntToStr(AWeekList.Items[I].WeekLength);
AGrid.Cells[3,1+I] := FormatFloat('0.00', AWeekList.Items[I].getSum);
AGrid.Cells[4,1+I] := FormatFloat('0.00', AWeekList.Items[I].getGoalHours);
diff := (AWeekList.Items[I].getSum - AWeekList.Items[I].getGoalHours);
AGrid.Cells[5,1+I] := FormatFloat('0.00', diff);
end;
end;
procedure ClearStringGrid(AGrid: TStringGrid);
begin
while (AGrid.RowCount > 1) do
begin
AGrid.DeleteRow(AGrid.RowCount-1);
end;
end;
procedure WeekDaysToStringGrid(AGrid: TStringGrid; AWeek: TWorkWeek);
var
I: Integer;
begin
clearStringGrid(AGrid);
AGrid.RowCount := AWeek.WeekLength+1;
if (AWeek.Days.Count > 0) then
begin
for I := 1 to AWeek.Weeklength do
begin
AGrid.Cells[0,I] := IntToStr(I);
AGrid.Cells[2,I] := FormatDateTime('dd.mm.yyyy', AWeek.Days[I-1].Date);
if (AWeek.Days[I-1].Weekday > 0) and (AWeek.Days[I-1].Weekday < 8) then
begin
AGrid.cells[1,I] := txtWeekdays[Aweek.Days[I-1].Weekday];
end;
AGrid.cells[3,I] := AWeek.Days[I-1].StartTime.ToText;//AWeek.Days[I-1].StartHour, AWeek.Days[I-1].StartMinute);
AGrid.cells[4,I] := AWeek.Days[I-1].EndTime.ToText; // AWeek.Days[I-1].EndMinute);
AGrid.Cells[5,I] := FloatToStr(AWeek.Days[I-1].TimeOff);
AGrid.Cells[6,I] := FormatFloat('0.00', (AWeek.Days[I-1].getAmountOfTime));
// if it is tagges as holiday or ignored, then ignore
if (AWeek.Days[I-1].Tag = '') then
begin
AGrid.Cells[6,I] := FormatFloat('0.00', (AWeek.Days[I-1].getAmountOfTime));
AGrid.Cells[7,I] := FormatFloat('0.00', (AWeek.Days[I-1].getAmountOfTime - (AWeek.IntendedTimePerDay-AWeek.Days[I-1].TimeOff)));
end
else
begin
AGrid.Cells[6,I] := '0.00';
AGrid.Cells[7,I] := '0.00';
end;
AGrid.Cells[8,I] := AWeek.Days[I-1].Tag;
end;
end;
end;
procedure WeeksToComboBox(AComboBox: TComboBox; AWeekList: TWeekList);
var
I: Integer;
begin
AComboBox.Clear;
For I := 0 to AWeekList.Count - 1 do
begin
AComboBox.Items.Add('#'+ IntToStr(I+1) + ': ' + AWeekList.Items[I].WeekLabel);
end;
end;
// Get the real day of the week as 1 = Monday
function RealDayOfWeek(ADate: TDate): integer;
var
day: integer;
begin
day := DayOfWeek(ADate);
if (day = 1) then
begin
day := 7;
end
else
begin
day := day - 1;
end;
Result := day;
end;
// Extract the Hour of a '12:00' - String
function getHour(time: string): integer;
var
I: integer;
pos: integer;
res: integer;
begin
time := trim(time);
for I := 1 to length(time) do
begin
if (time[I] = ':') then
begin
pos := I;
end;
end;
time := trim(LeftStr(time, pos - 1));
if TryStrToInt(time, res) then
begin
if (res > 23) or (res < 0) then
begin
res := 0;
end;
Result := res;
end
else
begin
Result := 0;
end;
end;
// Extract the Minute of a '12:00' - String
function getMinute(time: string): integer;
var
I: integer;
pos: integer;
res: integer;
begin
time := trim(time);
for I := 1 to length(time) do
begin
if (time[I] = ':') then
begin
pos := I;
end;
end;
time := trim(RightStr(time, length(time) - pos));
if TryStrToInt(time, res) then
begin
if (res > 59) or (res < 0) then
begin
res := 0;
end;
Result := res;
end
else
begin
Result := 0;
end;
end;
function getDayOfEarliestBegin(AWeekList: TWeekList): TWorkDay;
var
I,D: Integer;
begin
Result := nil;
for I := 0 to AWeekList.Count -1 do
begin
if (AWeekList[I].getDayOfEarliestBegin <> nil) then
begin
if (Result <> nil) then
begin
if (AWeekList[I].getDayOfEarliestBegin.StartTime.getHours < Result.StartTime.getHours) or
((AWeekList[I].getDayOfEarliestBegin.StartTime.getHours = Result.StartTime.getHours) and
(AWeekList[I].getDayOfEarliestBegin.StartTime.getMinutes <= Result.StartTime.getMinutes)) then
begin
Result := AWeekList[I].getDayOfEarliestBegin;
end;
end
else
begin
Result := AWeekList[I].getDayOfEarliestBegin;
end;
end;
end;
end;
function getDayOfLatestQuitting(AWeekList: TWeekList): TWorkDay;
var
I,D: Integer;
begin
Result := nil;
for I := 0 to AWeekList.Count -1 do
begin
if (AWeekList[I].getDayOfLatestQuitting <> nil) then
begin
if (Result <> nil) then
begin
if IsTimeLatest(AWeekList[I].getDayOfLatestQuitting.EndTime.getHours, AWeekList[I].getDayOfLatestQuitting.EndTime.getMinutes, Result.EndTime.getHours, Result.EndTime.getMinutes) then
begin
Result := AWeekList[I].getDayOfLatestQuitting;
end;
end
else
begin
Result := AWeekList[I].getDayOfLatestQuitting;
end;
end;
end;
end;
function getLongestDay(AWeekList: TWeekList): TWorkDay;
var
I, D: Integer;
pause: Double;
begin
Result := nil;
pause := 0;
for I := 0 to AWeekList.Count - 1 do
begin
for D := 0 to AWeekList.Items[I].Days.Count - 1 do
begin
if (AWeekList.Items[I].Days[D].Tag = '') then
begin
if (Result <> nil) then
begin
if (AWeekList.Items[I].Days[D].getAmountOfTime > Result.getAmountOfTime) then
begin
Result := AWeekList.Items[I].Days[D];
end;
end
else
begin
Result := AWeekList.Items[I].Days[D];
end;
end;
end;
end;
end;
function periodToText(AWeekList: TWeekList): String;
begin
//Result := Result + FormatDateTime('dd.mm.yyyy', AWeekList.Days[0].Date);
end;
end.
|
unit ObsInterfaceUnit;
interface
type
ITimeObservationItem = interface(IUnknown)
function GetName: string;
function GetObservedValue: double;
function GetTime: double;
function GetWeight: Double;
function GetObservationGroup: string;
procedure SetObservedValue(const Value: double);
procedure SetTime(const Value: double);
procedure SetObservationGroup(const Value: string);
property Name: string read GetName;
property ObservedValue: double read GetObservedValue
write SetObservedValue;
property Time: double read GetTime write SetTime;
property Weight: Double read GetWeight;
property ObservationGroup: string read GetObservationGroup
write SetObservationGroup;
end;
implementation
end.
|
unit uFrmStockGoodsIni; //定义基本信息表格的相关数据
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmMDI, ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, dxBar, dxBarExtItems, cxClasses, ImgList,
ActnList, DB, DBClient, cxGridLevel, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGrid, cxContainer, cxTreeView,
ExtCtrls, uModelStockGoodsIntf, uParamObject, StdCtrls;
type
TfrmStockGoodsIni = class(TfrmMDI)
btnModifyIni: TdxBarLargeButton;
actModify: TAction;
actSelectKType: TAction;
btnSelectKType: TdxBarLargeButton;
lblKType: TLabel;
procedure actModifyExecute(Sender: TObject);
procedure gridTVMainShowCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure actSelectKTypeExecute(Sender: TObject);
private
FModelStockGoods: IModelStockGoods;
{ Private declarations }
procedure InitParamList; override;
procedure BeforeFormShow; override;
procedure IniGridField; override;
procedure LoadGridData(ATypeid: string); override;
function GetCurTypeId: string; //获取当前表格选中行的ID
function ModifyRecPTypeIni: Boolean;
public
{ Public declarations }
class function GetMdlDisName: string; override;
end;
var
frmStockGoodsIni: TfrmStockGoodsIni;
implementation
uses uBaseFormPlugin, uSysSvc, uDBIntf, uGridConfig, uMoudleNoDef, uBaseInfoDef, uFactoryFormIntf,
uModelControlIntf, uPubFun, uDefCom, uFrmStockGoodsModifyIni, uModelFunIntf;
{$R *.dfm}
{ TfrmMDI1 }
procedure TfrmStockGoodsIni.BeforeFormShow;
begin
inherited;
Title := '期初库存商品';
FModelStockGoods := IModelStockGoods((SysService as IModelControl).GetModelIntf(IModelStockGoods));
IniGridField();
LoadGridData('');
end;
class function TfrmStockGoodsIni.GetMdlDisName: string;
begin
Result := '期初库存商品';
end;
procedure TfrmStockGoodsIni.IniGridField;
var
aCol: TColInfo;
begin
inherited;
FGridItem.ClearField();
FGridItem.AddField(btPtype);
FGridItem.AddField('Qty', '库存数量', 200, cfQty);
FGridItem.AddField('Price', '成本均价', 200, cfPrice);
FGridItem.AddField('Total', '库存金额', 200, cfTotal);
FGridItem.InitGridData;
FGridItem.BasicType := btPtype;
end;
procedure TfrmStockGoodsIni.InitParamList;
begin
inherited;
MoudleNo := fnMdlStockGoodsIni;
end;
procedure TfrmStockGoodsIni.LoadGridData(ATypeid: string);
var
aList: TParamObject;
begin
inherited;
aList := TParamObject.Create;
try
aList.Add('@ParPTypeId', ATypeid);
aList.Add('@KTypeId', '');
aList.Add('@Operator', OperatorID);
FModelStockGoods.LoadStockGoodsIni(aList, cdsMainShow);
FGridItem.LoadData(cdsMainShow);
finally
aList.Free;
end;
end;
function TfrmStockGoodsIni.GetCurTypeId: string;
var
aRowIndex: Integer;
begin
Result := '';
aRowIndex := FGridItem.RowIndex;
if (aRowIndex < FGridItem.GetFirstRow) or (aRowIndex > FGridItem.GetLastRow) then
Exit;
Result := FGridItem.GetCellValue(GetBaseTypeid(btPtype), aRowIndex);
end;
function TfrmStockGoodsIni.ModifyRecPTypeIni: Boolean;
var
aParam: TParamObject;
aFrm: IFormIntf;
aRowIndex: Integer;
aKTypeId: string;
begin
Result := False;
aKTypeId := Trim(ParamList.AsString('KTypeId'));
if StringEmpty(aKTypeId) or (aKTypeId = ROOT_ID) then
begin
FModelFun.ShowMsgBox('现在为所有仓库合计值,请先选择某一仓库!','提示');
Exit;
end;
aParam := TParamObject.Create;
try
aRowIndex := FGridItem.RowIndex;
if (aRowIndex < FGridItem.GetFirstRow) or (aRowIndex > FGridItem.GetLastRow) then
Exit;
aParam.Add('PTypeId', FGridItem.GetCellValue(GetBaseTypeid(btPtype), aRowIndex));
aParam.Add('KTypeId', aKTypeId);
aParam.Add('Qty', FGridItem.GetCellValue('Qty', aRowIndex));
aParam.Add('Price', FGridItem.GetCellValue('Price', aRowIndex));
aParam.Add('Total', FGridItem.GetCellValue('Total', aRowIndex));
TfrmStockGoodsModifyIni.CreateFrmParamList(Self, aParam).GetInterface(IFormIntf, aFrm);
if aFrm.FrmShowModal = mrOk then
begin
Result := True;
LoadGridData('');
end;
finally
aParam.Free;
end;
end;
procedure TfrmStockGoodsIni.actModifyExecute(Sender: TObject);
begin
inherited;
ModifyRecPTypeIni();
end;
procedure TfrmStockGoodsIni.gridTVMainShowCellDblClick(
Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
ModifyRecPTypeIni();
end;
procedure TfrmStockGoodsIni.actSelectKTypeExecute(Sender: TObject);
var
aSelectParam: TSelectBasicParam;
aSelectOptions: TSelectBasicOptions;
aReturnArray: TSelectBasicDatas;
aReturnCount: Integer;
begin
inherited;
DoSelectBasic(Self, btKtype, aSelectParam, aSelectOptions, aReturnArray, aReturnCount);
if aReturnCount >= 1 then
begin
ParamList.Add('KTypeId', aReturnArray[0].TypeId);
lblKType.Caption := '仓库:' + aReturnArray[0].FullName;
end;
end;
initialization
gFormManage.RegForm(TfrmStockGoodsIni, fnMdlStockGoodsIni);
end.
|
unit ServerMethodsUnit1;
interface
uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, unit1, DBXJSON,
Data.DB, system.JSON, uclasses, dialogs;
type
{$METHODINFO ON}
TServerMethods1 = class(TComponent)
private
{ Private declarations }
public
{ Public declarations }
erro : integer;
function insereVendas(const lista : TlistaVendas; const usuario : String) : String;
function getProdutos() : TJSONValue;
function getProdutos1() : TlistaProdutos;
function getFormas() : TlistaFormas;
function getUsuarios() : TlistaUsuario;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
procedure execSql(const sql : string);
function soma(v1, v2 : currency) : TJSONValue;
function RecordCountProdutosInteger() : Integer;
end;
{$METHODINFO OFF}
implementation
uses System.StrUtils;
function TServerMethods1.insereVendas(const lista : TlistaVendas; const usuario : String) : String;
var
ini, i, fimI, fimV, nota, cliente : integer;
totPrest, totItemV, totItemC, entrada, total : currency;
clienteNome : String;
const sqlVenda : String = 'insert into venda(nota, entrada, desconto, data, cliente, total, vendedor' +
', codhis, usuario) values(:nota, :entrada, :desconto, :data, :cliente, :total, :vendedor, :codhis, :usuario)';
begin
Result := '';
form1.adicionaMemo('Serviço: Sincronização de Vendas');
form1.adicionaMemo('Usuário: ' + usuario);
form1.adicionaMemo('Data:' + FormatDateTime('dd/mm/yyyy hh:mm:ss', now));
form1.adicionaMemo('--------------------------------------');
Result := '';
fimV := Length(lista.listaVenda) -1;
Form1.IBQuery1.Close;
Form1.IBQuery1.SQL.Text := sqlVenda;
//+funcoes.novocod('creceber')+
form1.IBQuery2.Close;
form1.IBQuery2.SQL.Text := 'insert into contasreceber(nota,codgru, cod,formpagto,datamov,vendedor,data,vencimento,documento,codhis,historico,total,valor)' +
'values(:nota, 1, :cod, :codhis, :datamov, :vendedor,:data, :vencimento,:documento,2,:hist,:total,:valor)';
form1.IBQuery3.Close;
form1.IBQuery3.SQL.Text := 'insert into item_venda(data,nota,COD, QUANT, p_venda,total,origem,p_compra,codbar,aliquota, unid)' +
' values(:data,:nota,:cod, :quant, :p_venda,:total,:origem,:p_compra, :codbar,:aliq, :unid)';
if form1.IBTransaction1.InTransaction then form1.IBTransaction1.Commit;
form1.IBTransaction1.StartTransaction;
//ShowMessage('recCount = ' + IntToStr(fimV));
for ini := 0 to fimV do
begin
erro := 0;
entrada := 0;
total := lista.listaVenda[ini].total;
try
nota := StrToIntDef(form1.Incrementa_Generator('venda', 1), 1);
cliente := form1.insereClienteRetornaCodigo(lista.listaVenda[ini].cliente, clienteNome, erro);
if lista.listaVenda[ini].parcelamento <> nil then
begin
entrada := lista.listaVenda[ini].parcelamento.entrada;
total := lista.listaVenda[ini].total - entrada;
totPrest := ((total) / lista.listaVenda[ini].parcelamento.qtdprest);
for I := 1 to lista.listaVenda[ini].parcelamento.qtdprest do
begin
form1.IBQuery2.Close;
form1.IBQuery2.ParamByName('nota').AsInteger := nota;
form1.IBQuery2.ParamByName('cod').AsString := form1.Incrementa_Generator('creceber', 1);
form1.IBQuery2.ParamByName('codhis').AsInteger := lista.listaVenda[ini].codhis;
form1.IBQuery2.ParamByName('datamov').AsDate := now;
form1.IBQuery2.ParamByName('vendedor').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery2.ParamByName('data').AsDate := lista.listaVenda[ini].parcelamento.data;
if i = 1 then form1.IBQuery2.ParamByName('vencimento').AsDate := lista.listaVenda[ini].parcelamento.vencimento
else form1.IBQuery2.ParamByName('vencimento').AsDate := lista.listaVenda[ini].parcelamento.vencimento + lista.listaVenda[ini].parcelamento.periodo;
form1.IBQuery2.ParamByName('documento').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery2.ParamByName('hist').AsString := Form1.CompletaOuRepete(copy(IntToStr(nota) +'-'+clienteNome,1,28 ),Form1.CompletaOuRepete('',IntToStr(i),' ',2)+'/'+
form1.CompletaOuRepete('', IntToStr(lista.listaVenda[ini].parcelamento.qtdprest),' ',2),' ',35);
form1.IBQuery2.ParamByName('total').AsCurrency := totPrest;
form1.IBQuery2.ParamByName('valor').AsCurrency := totPrest;
try
form1.IBQuery2.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' PARCELAMENTO' + #13 + '-----------------------' + #13);
end;
end;
end;
end;
form1.IBQuery1.SQL.Text := sqlVenda;
form1.IBQuery1.Close;
form1.IBQuery1.ParamByName('nota').AsInteger := nota;
form1.IBQuery1.ParamByName('entrada').AsCurrency := entrada;
form1.IBQuery1.ParamByName('desconto').AsCurrency := lista.listaVenda[ini].desconto;
form1.IBQuery1.ParamByName('data').AsDate := lista.listaVenda[ini].data;
form1.IBQuery1.ParamByName('cliente').AsInteger := cliente;
form1.IBQuery1.ParamByName('total').AsCurrency := total;
form1.IBQuery1.ParamByName('vendedor').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery1.ParamByName('codhis').AsInteger := lista.listaVenda[ini].codhis;
form1.IBQuery1.ParamByName('usuario').AsInteger := lista.listaVenda[ini].usuario;
try
form1.IBQuery1.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' na Venda' + #13 + '-----------------------' + #13);
end;
end;
fimI := Length(lista.listaVenda[ini].itensV) - 1;
for I := 0 to fimI do
begin
form1.IBQuery1.Close;
form1.IBQuery1.SQL.Text := 'select codbar, aliquota, unid, p_compra from produto where cod = :cod';
form1.IBQuery1.ParamByName('cod').AsInteger := lista.listaVenda[ini].itensV[i].cod;
form1.IBQuery1.Open;
totItemV := (lista.listaVenda[ini].itensV[i].p_venda * lista.listaVenda[ini].itensV[i].quant);
totItemC := (form1.IBQuery1.FieldByName('p_compra').AsCurrency * lista.listaVenda[ini].itensV[i].quant);
form1.IBQuery3.Close;
form1.IBQuery3.ParamByName('data').AsDateTime := lista.listaVenda[ini].data;
form1.IBQuery3.ParamByName('nota').AsInteger := nota;
form1.IBQuery3.ParamByName('cod').AsInteger := lista.listaVenda[ini].itensV[i].cod;
form1.IBQuery3.ParamByName('quant').AsCurrency := lista.listaVenda[ini].itensV[i].quant;
form1.IBQuery3.ParamByName('p_venda').AsCurrency := lista.listaVenda[ini].itensV[i].p_venda;
form1.IBQuery3.ParamByName('total').AsCurrency := totItemV;
form1.IBQuery3.ParamByName('origem').AsString := '1';
form1.IBQuery3.ParamByName('p_compra').AsCurrency := totItemC;
form1.IBQuery3.ParamByName('codbar').AsString := form1.IBQuery1.FieldByName('codbar').AsString;
form1.IBQuery3.ParamByName('aliq').AsString := copy(form1.IBQuery1.FieldByName('aliquota').AsString, 1, 2);
form1.IBQuery3.ParamByName('unid').AsString := form1.IBQuery1.FieldByName('unid').AsString;
try
form1.IBQuery3.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' ITEM_VENDA' + #13 + '-----------------------' + #13);
end;
end;
form1.IBQuery1.Close;
end;
finally
if erro = 0 then
begin
Result := Result + IntToStr(lista.listaVenda[ini].nota) + '-';
//ShowMessage(Result);
end;
end;
end;
form1.IBTransaction1.Commit;
end;
function TServerMethods1.getUsuarios() : TlistaUsuario;
var
recNo : integer;
lista : TlistaUsuario;
begin
form1.adicionaMemo('Requisição de sincronização de Usuários');
lista := TlistaUsuario.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, usu, senha, vendedor from USUARIO');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaUsuario, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaUsuario[recNo] := TUsuario.Create;
lista.listaUsuario[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaUsuario[recNo].codVendedor := form1.IBQuery1.FieldByName('vendedor').AsInteger;
lista.listaUsuario[recNo].nome := form1.IBQuery1.FieldByName('nome').AsString;
lista.listaUsuario[recNo].senha := form1.DesCriptografar(form1.IBQuery1.FieldByName('senha').AsString);
lista.listaUsuario[recNo].usu := form1.DesCriptografar(form1.IBQuery1.FieldByName('usu').AsString);
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := lista;
end;
function TServerMethods1.getFormas() : TlistaFormas;
var
recNo : integer;
lista : TlistaFormas;
begin
form1.adicionaMemo('Requisição de sincronização de Formas de Pagamento');
lista := TlistaFormas.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome from FORMPAGTO');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaFormas, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaFormas[recNo] := Tforma.Create;
lista.listaFormas[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaFormas[recNo].nome := form1.IBQuery1.FieldByName('nome').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := lista;
end;
function TServerMethods1.getProdutos1() : TlistaProdutos;
var
recNo : integer;
lista : TlistaProdutos;
begin
form1.adicionaMemo('Requisição de sincronização de Produtos');
lista := TlistaProdutos.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, codbar, p_compra, p_venda, obs, p_venda1 from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaProdutos, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaProdutos[recNo] := Tproduto.Create;
lista.listaProdutos[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaProdutos[recNo].nome := copy(form1.IBQuery1.FieldByName('nome').AsString, 1, 40);
lista.listaProdutos[recNo].codbar := form1.IBQuery1.FieldByName('codbar').AsString;
lista.listaProdutos[recNo].p_compra := form1.IBQuery1.FieldByName('p_compra').AsCurrency;
lista.listaProdutos[recNo].p_venda := form1.IBQuery1.FieldByName('p_venda').AsCurrency;
lista.listaProdutos[recNo].p_venda1 := form1.IBQuery1.FieldByName('p_venda1').AsCurrency;
lista.listaProdutos[recNo].obs := form1.IBQuery1.FieldByName('obs').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result :=lista;
end;
function TServerMethods1.RecordCountProdutosInteger() : Integer;
begin
Result := 0;
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
Result := form1.IBQuery1.RecordCount;
form1.IBQuery1.Close;
end;
function TServerMethods1.soma(v1, v2 : currency) : TJSONValue;
begin
exit(TJSONNumber.Create(v1 + v2));
end;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.getProdutos() : TJSONValue;
var
recNo : integer;
lista : TlistaProdutos;
begin
form1.adicionaMemo('Requisição de sincronização de Produtos');
lista := TlistaProdutos.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, codbar, p_compra, p_venda, obs, p_venda1 from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaProdutos, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaProdutos[recNo] := Tproduto.Create;
lista.listaProdutos[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaProdutos[recNo].nome := copy(form1.IBQuery1.FieldByName('nome').AsString, 1, 40);
lista.listaProdutos[recNo].codbar := form1.IBQuery1.FieldByName('codbar').AsString;
lista.listaProdutos[recNo].p_compra := form1.IBQuery1.FieldByName('p_compra').AsCurrency;
lista.listaProdutos[recNo].p_venda := form1.IBQuery1.FieldByName('p_venda').AsCurrency;
lista.listaProdutos[recNo].p_venda1 := form1.IBQuery1.FieldByName('p_venda1').AsCurrency;
lista.listaProdutos[recNo].obs := form1.IBQuery1.FieldByName('obs').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := ListaProdutosToJSON(lista);
end;
procedure TServerMethods1.execSql(const sql : string);
begin
{ if not form1.iBDatabase1.Connected then
begin
ShowMessage('BD não está conectado!');
exit;
end;
}
try
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add(sql);
form1.IBQuery1.ExecSQL;
form1.IBTransaction1.Commit;
except
end;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
unit uFrameFioAbit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls, cxContainer,
cxEdit, cxLabel,uPrK_Resources;
type
TFrameFioAbit = class(TFrame)
cxLabelFioAbit: TcxLabel;
cxButtonEditFioAbit: TcxButtonEdit;
procedure cxButtonEditFioAbitPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxButtonEditFioAbitKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
procedure InicCaptionFrame;
procedure InicDataFrame(rejim :RejimPrK);
end;
implementation
{$R *.dfm}
uses
uPRK_DT_ABIT,uConstants,AllPeopleUnit,
AArray;
{ TFrameFioAbit }
procedure TFrameFioAbit.InicCaptionFrame;
var
i: integer;
begin
i:=TFormPRK_DT_ABIT(self.Owner).IndLangAbit;
cxLabelFioAbit.Caption := nLabelFioAbit[i];
// Из-за этого будут ошибки при изменении данных абитуриента.... 10.12.06
// А может и нет... 19.12.06
cxButtonEditFioAbit.Text := '';
TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['ID_MAN'].AsInt64:=-999;
end;
procedure TFrameFioAbit.cxButtonEditFioAbitPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
res : Variant;
old_ID_MAN:int64;
begin
res:=AllPeopleUnit.GetMan(Self, TFormPRK_DT_ABIT(self.Owner).DataBasePrK_ABIT.Handle, false, true);
if VarArrayDimCount(res) > 0 then
begin
if (res[0]<>null) and (res[1]<>null) then
begin
old_ID_MAN:= TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['ID_MAN'].AsInt64;
TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['ID_MAN'].AsInt64 := res[0];
TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['FIO_MAN'].AsString := VarToStr(res[1]);
TFormPRK_DT_ABIT(self.Owner).cxLabelFioAbit.Caption := res[1];
cxButtonEditFioAbit.Text := res[1];
if old_ID_MAN<> res[0] then
begin
TFormPRK_DT_ABIT(self.Owner).TFrameDocEducation1.SelectTextFrameDocEducation:=true;
TFormPRK_DT_ABIT(self.Owner).TFramePerevagi1.SelectTextFramePerevagi :=true;
TFormPRK_DT_ABIT(self.Owner).TFrameInLang1.SelectTextFrameInLang :=true;
TFormPRK_DT_ABIT(self.Owner).SelectTextFizlAbit :=true;
end;
end;
end;
end;
procedure TFrameFioAbit.InicDataFrame(rejim :RejimPrK);
var
Fio: String;
begin
if (rejim=ViewPrK) or (rejim=ChangePrK) then
begin
TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['ID_MAN'].AsInt64 :=
TFormPRK_DT_ABIT(self.Owner).DataSetPrK_ABIT.FieldValues['ID_MAN']; // Колосов присылает не ID_MAN, а ID_DT_FIZL_ABIT
Fio :=TFormPRK_DT_ABIT(self.Owner).DataSetPrK_ABIT.FieldValues['FIO'];
TFormPRK_DT_ABIT(self.Owner).ResultArray['AbitData']['FIO_MAN'].AsString := Fio;
TFormPRK_DT_ABIT(self.Owner).cxLabelFioAbit.Caption := Fio;
cxButtonEditFioAbit.Text := Fio;
{cxButtonEditFioAbit.Properties.ReadOnly:=true;
cxButtonEditFioAbit.Properties.Buttons[0].Visible :=false;
cxButtonEditFioAbit.Style.Color := TFormPRK_DT_ABIT(self.Owner).TextViewColor; }
cxButtonEditFioAbit.Enabled:=false;
end;
end;
procedure TFrameFioAbit.cxButtonEditFioAbitKeyPress(Sender: TObject;
var Key: Char);
begin
Key:=CHR(0);
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171306
////////////////////////////////////////////////////////////////////////////////
unit android.provider.FontsContract_FontFamilyResult;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.provider.FontsContract_FontInfo;
type
JFontsContract_FontFamilyResult = interface;
JFontsContract_FontFamilyResultClass = interface(JObjectClass)
['{61F8DB83-8FE9-40CB-BADA-51E3900F2FF7}']
function _GetSTATUS_OK : Integer; cdecl; // A: $19
function _GetSTATUS_REJECTED : Integer; cdecl; // A: $19
function _GetSTATUS_UNEXPECTED_DATA_PROVIDED : Integer; cdecl; // A: $19
function _GetSTATUS_WRONG_CERTIFICATES : Integer; cdecl; // A: $19
function getFonts : TJavaArray<JFontsContract_FontInfo>; cdecl; // ()[Landroid/provider/FontsContract$FontInfo; A: $1
function getStatusCode : Integer; cdecl; // ()I A: $1
property STATUS_OK : Integer read _GetSTATUS_OK; // I A: $19
property STATUS_REJECTED : Integer read _GetSTATUS_REJECTED; // I A: $19
property STATUS_UNEXPECTED_DATA_PROVIDED : Integer read _GetSTATUS_UNEXPECTED_DATA_PROVIDED;// I A: $19
property STATUS_WRONG_CERTIFICATES : Integer read _GetSTATUS_WRONG_CERTIFICATES;// I A: $19
end;
[JavaSignature('android/provider/FontsContract_FontFamilyResult')]
JFontsContract_FontFamilyResult = interface(JObject)
['{7AA662D9-A949-4664-B8E4-DADA26458BC4}']
function getFonts : TJavaArray<JFontsContract_FontInfo>; cdecl; // ()[Landroid/provider/FontsContract$FontInfo; A: $1
function getStatusCode : Integer; cdecl; // ()I A: $1
end;
TJFontsContract_FontFamilyResult = class(TJavaGenericImport<JFontsContract_FontFamilyResultClass, JFontsContract_FontFamilyResult>)
end;
const
TJFontsContract_FontFamilyResultSTATUS_OK = 0;
TJFontsContract_FontFamilyResultSTATUS_REJECTED = 3;
TJFontsContract_FontFamilyResultSTATUS_UNEXPECTED_DATA_PROVIDED = 2;
TJFontsContract_FontFamilyResultSTATUS_WRONG_CERTIFICATES = 1;
implementation
end.
|
program QuickSort;
type
arrInt = array[1..50] of integer;
var
arr : arrInt;
n : integer;
procedure arrayInput(var n:integer; var x:arrInt);
var
i : integer;
begin
write('Broj clanova: ');
readln(n);
for i:=1 to n do
begin
write('x[', i, '] = ');
readln(x[i]);
end;
end;
procedure arrayOutput(var n:integer; var x:arrInt);
var
i : integer;
begin
writeln('array output');
for i:=1 to n do
begin
writeln('x[', i, '] = ', x[i]);
end;
end;
procedure Swap(var a:integer; var b:integer);
var
temp : integer;
begin
temp := a;
a := b;
b := temp;
end;
function Partition(p, r : integer; var a:arrInt) : integer;
var
i, j, x : integer;
begin
x := a[r];
i := p - 1;
for j := p to r-1 do
begin
if ( a[j] <= x ) then
begin
i := i + 1;
Swap(a[i], a[j]);
end;
end;
Swap(a[i+1], a[r]);
Partition := i + 1;
end;
procedure QuickSort(low, high : integer; var a:arrInt);
var
j : integer;
begin
if( low < high ) then
begin
j := Partition(low, high, a);
QuickSort(low, j-1, a);
QuickSort(j+1, high, a);
end;
end;
begin
arrayInput(n, arr);
QuickSort(1, n, arr);
arrayOutput(n, arr);
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clDCUtils;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
uses
Classes, SysUtils, clWinInet, Windows;
type
EclInternetError = class(Exception)
private
FErrorCode: Integer;
public
constructor Create(const AErrorText: string; AErrorCode: Integer);
constructor CreateByLastError;
property ErrorCode: Integer read FErrorCode;
end;
TclResourceInfo = class
private
FSize: Integer;
FName: string;
FDate: TDateTime;
FContentType: string;
FStatusCode: Integer;
FAllowsRandomAccess: Boolean;
FContentDisposition: string;
FCompressed: Boolean;
function GetAllowsRandomAccess: Boolean;
protected
procedure SetName(const AValue: string);
procedure SetDate(AValue: TDateTime);
procedure SetSize(AValue: Integer);
procedure SetContentType(const AValue: string);
procedure SetStatusCode(AValue: Integer);
procedure SetAllowsRandomAccess(AValue: Boolean);
procedure SetContentDisposition(const AValue: string);
procedure SetCompressed(AValue: Boolean);
public
constructor Create;
procedure Assign(Source: TclResourceInfo); virtual;
property Name: string read FName;
property Date: TDateTime read FDate;
property Size: Integer read FSize;
property ContentType: string read FContentType;
property StatusCode: Integer read FStatusCode;
property AllowsRandomAccess: Boolean read GetAllowsRandomAccess;
property ContentDisposition: string read FContentDisposition;
property Compressed: Boolean read FCompressed;
end;
const
cMaxThreadCount = 10;
cDefaultThreadCount = 5;
cDefaultChar = #128;
cPreviewCharCount = 256;
cTryCount = 5;
cTimeOut = 5000;
resourcestring
cOperationIsInProgress = 'Operation is in progress';
cUnknownError = 'Unknown error, code = %d';
cResourceAccessError = 'HTTP resource access error occured, code = %d';
cDataStreamAbsent = 'The data source stream is not assigned';
cExtendedErrorInfo = 'Additional info';
cRequestTimeOut = 'Request timeout';
cDataValueName = 'Data';
HTTP_QUERY_STATUS_CODE_Msg = 'Status Code';
HTTP_QUERY_CONTENT_LENGTH_Msg = 'Content Length';
HTTP_QUERY_LAST_MODIFIED_Msg = 'Last Modified';
HTTP_QUERY_CONTENT_TYPE_Msg = 'Content Type';
procedure EnumIECacheEntries(AList: TStrings);
procedure GetIECacheEntryHeader(const AUrl: string; AList: TStrings);
procedure GetIECacheFile(const AUrl: string; AStream: TStream);
function GetLastErrorText(ACode: Integer): string;
implementation
procedure EnumIECacheEntries(AList: TStrings);
var
info: ^TInternetCacheEntryInfo;
size: DWORD;
hCache: THandle;
begin
info := nil;
hCache := 0;
try
size := 0;
GetMem(info, size);
repeat
hCache := FindFirstUrlCacheEntry(nil, info^, size);
if (hCache = 0) then
begin
if (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
begin
raise EclInternetError.CreateByLastError();
end;
end else
begin
Break;
end;
FreeMem(info);
GetMem(info, size);
until False;
if (hCache <> 0) then
begin
AList.Add(string(info^.lpszSourceUrlName));
end;
repeat
if not FindNextUrlCacheEntry(hCache, info^, size) then
begin
if (GetLastError() = ERROR_INSUFFICIENT_BUFFER) then
begin
FreeMem(info);
GetMem(info, size);
end else
if (GetLastError() = ERROR_NO_MORE_ITEMS) then
begin
Break;
end else
begin
raise EclInternetError.CreateByLastError();
end;
end else
begin
AList.Add(string(info^.lpszSourceUrlName));
end;
until False;
finally
FreeMem(info);
if (hCache <> 0) then
begin
FindCloseUrlCache(hCache);
end;
end;
end;
procedure GetIECacheEntryHeader(const AUrl: string; AList: TStrings);
var
info: ^TInternetCacheEntryInfo;
size: DWORD;
begin
size := 0;
info := nil;
if not GetUrlCacheEntryInfo(PChar(AUrl), info^, size)
and (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
begin
raise EclInternetError.CreateByLastError();
end;
GetMem(info, size);
try
if not GetUrlCacheEntryInfo(PChar(AUrl), info^, size) then
begin
raise EclInternetError.CreateByLastError();
end;
if info.dwHeaderInfoSize > 0 then
begin
AList.Text := system.Copy(PChar(info.lpHeaderInfo), 1, info.dwHeaderInfoSize);
end;
finally
FreeMem(info);
end;
end;
procedure GetIECacheFile(const AUrl: string; AStream: TStream);
const
batchSize = 8192;
var
info: ^TInternetCacheEntryInfo;
bytesRead, size: DWORD;
hStream: THandle;
buf: PChar;
begin
size := 0;
info := nil;
hStream := RetrieveUrlCacheEntryStream(PChar(AUrl), info^, size, False, 0);
if (hStream = 0) and (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
begin
raise EclInternetError.CreateByLastError();
end;
GetMem(buf, batchSize);
GetMem(info, size);
try
hStream := RetrieveUrlCacheEntryStream(PChar(AUrl), info^, size, False, 0);
if (hStream = 0) then
begin
raise EclInternetError.CreateByLastError();
end;
bytesRead := 0;
while (bytesRead < info.dwSizeLow) do
begin
size := info.dwSizeLow;
if (size > batchSize) then
begin
size := batchSize;
end;
if not ReadUrlCacheEntryStream(hStream, bytesRead, buf, size, 0) then
begin
raise EclInternetError.CreateByLastError();
end;
AStream.Write(buf^, size);
bytesRead := bytesRead + size;
end;
finally
if (hStream <> 0) then
begin
UnlockUrlCacheEntryStream(hStream, 0);
end;
FreeMem(info);
FreeMem(buf);
end;
end;
function GetLastErrorText(ACode: Integer): string;
var
ExtErr, dwLength: DWORD;
Len: Integer;
Buffer: array[0..255] of Char;
buf: PChar;
begin
Result := '';
Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM,
Pointer(GetModuleHandle('wininet.dll')), ACode, 0, Buffer, SizeOf(Buffer), nil);
while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len);
SetString(Result, Buffer, Len);
if (ACode = ERROR_INTERNET_EXTENDED_ERROR) then
begin
InternetGetLastResponseInfo(ExtErr, nil, dwLength);
if (dwLength > 0) then
begin
GetMem(buf, dwLength);
try
if InternetGetLastResponseInfo(ExtErr, buf, dwLength) then
begin
if (Result <> '') then
begin
Result := Result + '; ' + cExtendedErrorInfo + ': ';
end;
Result := Result + buf;
end;
finally
FreeMem(buf);
end;
end;
end;
if (Result = '') then
begin
Result := Format(cUnknownError, [ACode]);
end;
end;
{ TclResourceInfo }
procedure TclResourceInfo.Assign(Source: TclResourceInfo);
begin
if (Source <> nil) then
begin
FSize := Source.Size;
FName := Source.Name;
FDate := Source.Date;
FContentType := Source.ContentType;
FStatusCode := Source.StatusCode;
FAllowsRandomAccess := Source.AllowsRandomAccess;
FContentDisposition := Source.ContentDisposition;
FCompressed := Source.Compressed;
end else
begin
FSize := 0;
FName := '';
FDate := 0;
FContentType := '';
FStatusCode := 0;
FAllowsRandomAccess := False;
FContentDisposition := '';
FCompressed := False;
end;
end;
constructor TclResourceInfo.Create;
begin
inherited Create();
FSize := 0;
FDate := Now();
end;
function TclResourceInfo.GetAllowsRandomAccess: Boolean;
begin
Result := (Size > 0) and FAllowsRandomAccess;
end;
procedure TclResourceInfo.SetAllowsRandomAccess(AValue: Boolean);
begin
FAllowsRandomAccess := AValue;
end;
procedure TclResourceInfo.SetCompressed(AValue: Boolean);
begin
FCompressed := AValue;
end;
procedure TclResourceInfo.SetContentDisposition(const AValue: string);
begin
FContentDisposition := AValue;
end;
procedure TclResourceInfo.SetContentType(const AValue: string);
begin
FContentType := AValue;
end;
procedure TclResourceInfo.SetDate(AValue: TDateTime);
begin
FDate := AValue;
end;
procedure TclResourceInfo.SetName(const AValue: string);
begin
FName := AValue;
end;
procedure TclResourceInfo.SetSize(AValue: Integer);
begin
FSize := AValue;
end;
procedure TclResourceInfo.SetStatusCode(AValue: Integer);
begin
FStatusCode := AValue;
end;
{ EclInternetError }
constructor EclInternetError.CreateByLastError;
begin
FErrorCode := GetLastError();
inherited Create(GetLastErrorText(FErrorCode));
end;
constructor EclInternetError.Create(const AErrorText: string; AErrorCode: Integer);
begin
inherited Create(AErrorText);
FErrorCode := AErrorCode;
end;
end.
|
unit CreateConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
type
TFormCreateConfig = class(TForm)
Label1: TLabel;
edtType: TEdit;
Label2: TLabel;
edtRelease: TEdit;
Label3: TLabel;
edtDesc: TMemo;
edtPath: TEdit;
Label4: TLabel;
btnSelect: TSpeedButton;
btnCreate: TButton;
OpenDialog1: TOpenDialog;
procedure btnCreateClick(Sender: TObject);
procedure btnSelectClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormCreateConfig: TFormCreateConfig;
implementation
{$R *.dfm}
uses
DateUtils, Main, Common;
procedure TFormCreateConfig.btnCreateClick(Sender: TObject);
var
jsonReq, jsonResp: String;
config: TConfig;
begin
if edtType.Text = '' then raise Exception.Create('type empty');
if edtRelease.Text = '' then raise Exception.Create('release empty');
if edtPath.Text = '' then raise Exception.Create('file empty');
config := TConfig.Create;
config.ne_type := edtType.Text;
config.ne_release := edtRelease.Text;
config.description := edtDesc.Text;
config.createUser := MainForm.cbUser.Text;
config.createDate := IntToStr(DateTimeToUnix(Now()) * 1000);
jsonReq := BuildConfigJSONString(config);
jsonResp := PostJSONRequest(MainForm.edtURL.Text + 'api/create', jsonReq);
if ParseStatusJSONString(jsonResp) <> 'SUCCESS' then raise Exception.Create('create config fail');
UploadFile(MainForm.edtURL.Text + 'api/config/mib', edtType.Text, edtRelease.Text, edtPath.Text);
ModalResult := mrOK;
end;
procedure TFormCreateConfig.btnSelectClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
edtPath.Text := OpenDialog1.FileName;
end;
end;
end.
|
unit SpotCornerUtils;
interface
uses
ThTypes;
const
HORIZON_CORNERS = TSpotCorner(Ord(scLeft) or Ord(scRight));
VERTICAL_CORNERS = TSpotCorner(Ord(scTop) or Ord(scBottom));
function AndSpotCorner(D1, D2: TSpotCorner): TSpotCorner;
function IfThenSpotCorner(AValue: Boolean; const ATrue: TSpotCorner; const AFalse: TSpotCorner): TSpotCorner;
function ContainSpotCorner(Source, SC: TSpotCorner): Boolean;
function SetHorizonSpotCorner(Source, SC: TSpotCorner): TSpotCorner;
function SetVerticalSpotCorner(Source, SC: TSpotCorner): TSpotCorner;
function ChangeHorizonSpotCorner(D1, D2: TSpotCorner): Boolean;
function ChangeVerticalSpotCorner(D1, D2: TSpotCorner): Boolean;
function SupportedHorizonSpotCorner(SC: TSpotCorner): Boolean;
function SupportedVerticalSpotCorner(SC: TSpotCorner): Boolean;
function HorizonSpotCornerExchange(D: TSpotCorner): TSpotCorner;
function VerticalSpotCornerExchange(D: TSpotCorner): TSpotCorner;
function SpotCornerExchange(D: TSpotCorner): TSpotCorner;
implementation
function AndSpotCorner(D1, D2: TSpotCorner): TSpotCorner;
begin
Result := TSpotCorner(Ord(D1) and Ord(D2))
end;
function OrSpotCorner(D1, D2: TSpotCorner): TSpotCorner;
begin
Result := TSpotCorner(Ord(D1) or Ord(D2))
end;
function IfThenSpotCorner(AValue: Boolean; const ATrue: TSpotCorner; const AFalse: TSpotCorner): TSpotCorner;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
function ContainSpotCorner(Source, SC: TSpotCorner): Boolean;
begin
Result := AndSpotCorner(Source, SC) = SC;
end;
function SetHorizonSpotCorner(Source, SC: TSpotCorner): TSpotCorner;
begin
Result := AndSpotCorner(Source, VERTICAL_CORNERS); // Horizon ¹ö¸²
Result := OrSpotCorner(Result, SC);
end;
function SetVerticalSpotCorner(Source, SC: TSpotCorner): TSpotCorner;
begin
Result := AndSpotCorner(Source, HORIZON_CORNERS);
Result := OrSpotCorner(Result, SC);
end;
function ChangeHorizonSpotCorner(D1, D2: TSpotCorner): Boolean;
begin
Result := AndSpotCorner(D1, HORIZON_CORNERS) <> AndSpotCorner(D2, HORIZON_CORNERS);
end;
function ChangeVerticalSpotCorner(D1, D2: TSpotCorner): Boolean;
begin
Result := AndSpotCorner(D1, VERTICAL_CORNERS) <> AndSpotCorner(D2, VERTICAL_CORNERS);
end;
function SupportedHorizonSpotCorner(SC: TSpotCorner): Boolean;
begin
Result := AndSpotCorner(SC, HORIZON_CORNERS) <> scUnknown;
end;
function SupportedVerticalSpotCorner(SC: TSpotCorner): Boolean;
begin
Result := AndSpotCorner(SC, VERTICAL_CORNERS) <> scUnknown;
end;
function HorizonSpotCornerExchange(D: TSpotCorner): TSpotCorner;
begin
Result := D;
if AndSpotCorner(Result, HORIZON_CORNERS) <> scUnknown then
Result := TSpotCorner(Ord(Result) xor Ord(HORIZON_CORNERS))
end;
function VerticalSpotCornerExchange(D: TSpotCorner): TSpotCorner;
begin
Result := D;
if AndSpotCorner(Result, VERTICAL_CORNERS) <> scUnknown then
Result := TSpotCorner(Ord(D) xor Ord(VERTICAL_CORNERS))
end;
function SpotCornerExchange(D: TSpotCorner): TSpotCorner;
begin
Result := D;
Result := HorizonSpotCornerExchange(Result);
Result := VerticalSpotCornerExchange(Result);
end;
end.
|
(*
Category: SWAG Title: POINTERS, LINKING, LISTS, TREES
Original name: 0019.PAS
Description: Linked List Routine
Author: SWAG SUPPORT TEAM
Date: 08-24-94 13:45
*)
type
PDataRec = ^TDataRec;
TDataRec = record
Name: String;
Next: PDataRec;
end;
const
DataRecList: PDataRec = nil;
CurRec :PDataRec = nil;
procedure AddRec(AName: String);
var Temp: PDataRec;
begin
New(CurRec);
CurRec^.Name := AName;
CurRec^.Next := nil;
Temp := DataRecList;
if Temp = nil then
DataRecList := CurRec
else
begin
while Temp^.Next <> nil do Temp := Temp^.Next;
Temp^.Next := CurRec;
end;
end;
procedure PrevRec;
var Temp: PDataRec;
begin
Temp := DataRecList;
if Temp <> CurRec then
while Temp^.Next <> CurRec do Temp := Temp^.Next;
CurRec := Temp;
end;
procedure NextRec;
begin
if CurRec^.Next <> nil then CurRec := CurRec^.Next;
end;
procedure List;
var Temp: PDataRec;
begin
Temp := DataRecList;
while Temp <> nil do
begin
Write(Temp^.Name);
if Temp = CurRec then
Writeln(' <<Current Record>>')
else
Writeln;
Temp := Temp^.Next;
end;
end;
begin
AddRec('Tom'); AddRec('Dick'); AddRec('Harry'); AddRec('Fred');
Writeln('Original List');
List;
Writeln;
Readln;
PrevRec; PrevRec;
Writeln('After Two PrevRec Calls');
List;
Writeln;
Readln;
NextRec;
Writeln('After One NextRec Call');
List;
Writeln;
Readln;
Writeln('End of Program.');
end.
|
unit ImageDocument;
interface
uses
Classes, Graphics,
LrDocument;
type
TImageDocument = class(TLrDocument)
public
Picture: TPicture;
constructor Create; override;
destructor Destroy; override;
procedure Activate; override;
procedure Deactivate; override;
procedure Open(const inFilename: string); override;
end;
implementation
uses
ImageView;
{ TImageDocument }
constructor TImageDocument.Create;
begin
inherited;
Picture := TPicture.Create;
end;
destructor TImageDocument.Destroy;
begin
Picture.Free;
inherited;
end;
procedure TImageDocument.Open(const inFilename: string);
begin
Filename := inFilename;
Picture.LoadFromFile(Filename);
end;
procedure TImageDocument.Activate;
begin
inherited;
ImageViewForm.Image.Picture := Picture;
ImageViewForm.BringToFront;
end;
procedure TImageDocument.Deactivate;
begin
inherited;
ImageViewForm.Image.Picture := nil;
end;
end.
|
unit BMP;
interface
type
TBMP = record
header: record
Signature: string;
FileSize: LongWord;
Reserved: array [0..3] of byte;
DataOffset: LongWord;
end;
info: record
Size: LongWord;
Width: LongWord;
Height: LongWord;
Planes: LongWord;
ColorDepth: LongWord;
Compression: LongWord;
ImageSize: LongWord;
xPixelsPerM: LongWord;
yPixelsPerM: LongWord;
ColorsUsed: LongWord;
ColorsImportant: LongWord;
end;
{ TODO: Include space for color table. }
image: array of array of boolean;
end;
var
Bitmap: TBMP;
procedure PrintHeaders;
procedure PrintImage;
procedure OpenBitmapFile(bmp_file: string);
procedure CloseBitmapFile;
implementation
uses
SysUtils, StrUtils, Math, BitOp;
var
BMPFile: file;
{ Converts a byte array to integer. }
function ByteArrToInt(data: array of byte; length: integer): LongWord;
begin
if length = 2 then
ByteArrToInt := LongWord((data[1] shl 8) or data[0])
else if length = 4 then
ByteArrToInt := LongWord((data[3] shl 24) or (data[2] shl 16) or (data[1] shl 8) or data[0])
else
WriteLn('ByteArrToInt: Unsupported array length');
end;
procedure PrintHeaders;
begin
WriteLn('Header');
WriteLn(' Signature: ' + Bitmap.header.Signature);
WriteLn(' File Size: ' + IntToStr(Bitmap.header.FileSize));
WriteLn(' Reserved: ' + IntToHex(Bitmap.header.Reserved[0], 2) + ' ' + IntToHex(Bitmap.header.Reserved[1], 2) + ' ' + IntToHex(Bitmap.header.Reserved[2], 2) + ' ' + IntToHex(Bitmap.header.Reserved[3], 2));
WriteLn(' Data Offset: ' + IntToStr(Bitmap.header.DataOffset));
WriteLn('Info Header');
WriteLn(' Size: ' + IntToStr(Bitmap.info.Size));
WriteLn(' Width: ' + IntToStr(Bitmap.info.Width) + ' (' + IntToStr(ceil(Bitmap.info.Width / 32)) + ' chunks)');
WriteLn(' Height: ' + IntToStr(Bitmap.info.Height));
WriteLn(' Planes: ' + IntToStr(Bitmap.info.Planes));
WriteLn(' Color Depth: ' + IntToStr(Bitmap.info.ColorDepth));
WriteLn(' Compression: ' + IntToStr(Bitmap.info.Compression));
WriteLn(' Image Size: ' + IntToStr(Bitmap.info.ImageSize));
WriteLn(' xPixelsPerM: ' + IntToStr(Bitmap.info.xPixelsPerM));
WriteLn(' yPixelsPerM: ' + IntToStr(Bitmap.info.yPixelsPerM));
WriteLn(' Colors Used: ' + IntToStr(Bitmap.info.ColorsUsed));
WriteLn(' Colors Important: ' + IntToStr(Bitmap.info.ColorsImportant));
end;
{ Parse the bitmap file headers. }
procedure ParseHeaders;
var
data: array [0..3] of byte;
begin
{ Header }
BlockRead(BMPFile, data, 2);
Bitmap.header.Signature := char(data[0]) + char(data[1]);
BlockRead(BMPFile, data, 4);
Bitmap.header.FileSize := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.header.Reserved := data;
BlockRead(BMPFile, data, 4);
Bitmap.header.DataOffset := ByteArrToInt(data, 4);
{ Info Header }
BlockRead(BMPFile, data, 4);
Bitmap.info.Size := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.Width := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.Height := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 2);
Bitmap.info.Planes := ByteArrToInt(data, 2);
BlockRead(BMPFile, data, 2);
Bitmap.info.ColorDepth := ByteArrToInt(data, 2);
BlockRead(BMPFile, data, 4);
Bitmap.info.Compression := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.ImageSize := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.xPixelsPerM := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.yPixelsPerM := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.ColorsUsed := ByteArrToInt(data, 4);
BlockRead(BMPFile, data, 4);
Bitmap.info.ColorsImportant := ByteArrToInt(data, 4);
end;
procedure ReadImage;
var
scanlineb: array [0..3] of byte;
scanline: LongWord;
line, col: integer;
height: integer;
chunk, chunks: integer;
begin
{ Set the number of rows and seek the file to the image data. }
SetLength(Bitmap.image, Bitmap.info.Height);
Seek(BMPFile, Bitmap.header.DataOffset);
{ Prepare some dimensions. }
height := Bitmap.info.Height - 1;
chunks := ceil(Bitmap.info.Width / 32);
{ Reading the image data. }
for line := 0 to height do
begin
{ Set the size of each row. }
SetLength(Bitmap.image[height - line], Bitmap.info.Width);
for chunk := 0 to chunks - 1 do
begin
{ Read a line (32 bits). }
BlockRead(BMPFile, scanlineb, 4);
{ Reverse the bits since they are LSB-first. }
scanlineb[0] := ReverseBits(scanlineb[0]);
scanlineb[1] := ReverseBits(scanlineb[1]);
scanlineb[2] := ReverseBits(scanlineb[2]);
scanlineb[3] := ReverseBits(scanlineb[3]);
{ Convert the bytes to a integer of pixels. }
scanline := ByteArrToInt(scanlineb, 4);
for col := 0 to 31 do
begin
{ Store the pixel. }
Bitmap.image[height - line][col + (32 * chunk)] := GetBit(scanline, col);
if (col + (32 * chunk)) = Bitmap.info.Width - 1 then
Break;
end;
end;
end;
end;
procedure PrintImage;
var
line, col: integer;
begin
{ Print the top frame. }
Write(#201);
for col := 0 to Bitmap.info.Width - 1 do
begin
Write(#205);
end;
WriteLn(#187);
{ Print the actual image. }
for line := 0 to Bitmap.info.Height - 1 do
begin
Write(#186);
for col := 0 to Bitmap.info.Width - 1 do
begin
if Bitmap.image[line][col] then
Write(' ')
else
Write(#254)
end;
WriteLn(#186);
end;
{ Print the bottom frame. }
Write(#200);
for col := 0 to Bitmap.info.Width - 1 do
begin
Write(#205);
end;
WriteLn(#188);
end;
{ Checks if the image is valid. }
procedure ValidateHeader;
var
fail: boolean;
begin
fail := False;
if Bitmap.info.Planes > 1 then
begin
WriteLn('ERROR: Bitmap file has more than one plane (' + IntToStr(Bitmap.info.Planes) + ').');
fail := True;
end;
if Bitmap.info.ColorDepth > 1 then
begin
WriteLn('ERROR: Bitmap file is not true monochrome (Color depth = ' + IntToStr(Bitmap.info.ColorDepth) + ' bits).');
fail := True;
end;
if Bitmap.info.Compression > 0 then
begin
WriteLn('ERROR: Bitmap file has compression (Compression = ' + IntToStr(Bitmap.info.Compression) + ').');
fail := True;
end;
if fail then
begin
WriteLn;
WriteLn('The bitmap files must be saved as monochrome (1-bit color depth) and have no compression applied. The simplest way to achieve this is to use MS Paint, go to File->Save As... and select "Monochrome Bitmap"');
Halt;
end;
end;
{ Opens the bitmap file and reads the headers. }
procedure OpenBitmapFile(bmp_file: string);
begin
{ Open the file }
Assign(BMPFile, bmp_file);
Reset(BMPFile, 1);
{ Parse the headers and read the image. }
ParseHeaders;
ValidateHeader;
ReadImage;
end;
{ Close the bitmap file. }
procedure CloseBitmapFile;
begin
Close(BMPFile);
end;
end.
|
unit DSA.Tree.Trie;
interface
uses
System.SysUtils,
System.Classes,
DSA.Tree.BSTMap,
DSA.Utils,
DSA.Tree.BSTSet;
type
TTrie = class
private type
TNode = class
private type
TreeMap = TBSTMap<char, TNode>;
public
IsWord: boolean;
Next: TreeMap;
constructor Create(newIsWord: boolean = False);
end;
var
__root: TNode;
__size: integer;
public
constructor Create;
/// <summary> 获取Trie中存储的单词数量 </summary>
function GetSize: integer;
/// <summary> 向Trie中添加一个新的单词word </summary>
procedure Add(words: string);
/// <summary> 查询单词words是否在Trie中 </summary>
function Contains(words: string): boolean;
/// <summary> 查询是否在Trie中有单词以prefix为前缀 </summary>
function IsPerFix(prefix: string): boolean;
end;
procedure Main;
implementation
type
TBSTSet_str = TBSTSet<string>;
procedure Main;
var
words: TArrayList_str;
set_: TBSTSet_str;
startTime, endTime, time: Double;
i: integer;
tr: TTrie;
begin
words := TArrayList_str.Create();
if TDsaUtils.ReadFile(FILE_PATH + A_FILE_NAME, words) then
begin
Writeln(words.GetSize);;
startTime := TThread.GetTickCount;
set_ := TBSTSet_str.Create;
for i := 0 to words.GetSize - 1 do
begin
set_.Add(words[i]);
end;
for i := 0 to words.GetSize - 1 do
begin
set_.Contains(words[i]);
end;
endTime := TThread.GetTickCount;
time := (endTime - startTime) / 1000;
Writeln('Total different words: ', set_.GetSize);
Writeln('TBSTSet: ', time.ToString + ' s');
// ------------
startTime := TThread.GetTickCount;
tr := TTrie.Create;
for i := 0 to words.GetSize - 1 do
begin
tr.Add(words[i]);
end;
for i := 0 to words.GetSize - 1 do
begin
tr.Contains(words[i]);
end;
endTime := TThread.GetTickCount;
time := (endTime - startTime) / 1000;
Writeln('Total different words: ', tr.GetSize);
Writeln('Trie: ', time.ToString, ' s');
end;
end;
{ TTrie.TNode }
constructor TTrie.TNode.Create(newIsWord: boolean);
begin
IsWord := newIsWord;
Next := TreeMap.Create;
end;
{ TTrie }
procedure TTrie.Add(words: string);
var
cur: TNode;
i: integer;
c: char;
begin
cur := __root;
for i := low(words) to high(words) do
begin
c := words[i];
if cur.Next.Contains(c) = False then
cur.Next.Add(c, TNode.Create());
cur := cur.Next.Get(c).PValue^;
end;
if cur.IsWord = False then
begin
cur.IsWord := True;
Inc(__size);
end;
end;
function TTrie.Contains(words: string): boolean;
var
cur: TNode;
i: integer;
c: char;
begin
cur := __root;
for i := 0 to words.Length - 1 do
begin
c := words.Chars[i];
if cur.Next.Contains(c) = False then
Exit(False);
cur := cur.Next.Get(c).PValue^;
end;
Result := cur.IsWord;
end;
constructor TTrie.Create;
begin
__root := TNode.Create();
__size := 0;
end;
function TTrie.GetSize: integer;
begin
Result := __size;
end;
function TTrie.IsPerFix(prefix: string): boolean;
var
cur: TNode;
i: integer;
c: char;
begin
cur := __root;
for i := 0 to prefix.Length - 1 do
begin
c := prefix.Chars[i];
if cur.Next.Get(c).PValue^ = nil then
begin
Exit(False);
end;
cur := cur.Next.Get(c).PValue^;
end;
Result := True;
end;
end.
|
unit TpODBC;
interface
uses
SysUtils, Classes,
ThHtmlDocument, ThHeaderComponent, ThTag,
TpDb, TpControls, TpInterfaces;
type
TTpODBC = class(TTpDb, ITpConfigWriter)
private
FDatabase: string;
FHost: string;
FOnGenerate: TTpEvent;
FPassword: string;
FPersistent: Boolean;
FUserName: string;
protected
procedure SetHost(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
protected
procedure ListPhpIncludes(inIncludes: TStringList); override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Tag(inTag: TThTag); override;
procedure WriteConfig(const inFolder: string);
published
property Database: string read FDatabase write FDatabase;
property DesignConnection;
property Host: string read FHost write SetHost;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property Persistent: Boolean read FPersistent write FPersistent;
end;
//
TTpODBCTable = class(TTpDataTable)
protected
procedure Tag(inTag: TThTag); override;
end;
//
TTpODBCQuery = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
end;
//
TTpODBCDbList = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
end;
//
TTpODBCTableList = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
end;
implementation
{uses
DCPbase64;}
{ TTpODBC }
constructor TTpODBC.Create(inOwner: TComponent);
begin
inherited;
FHost := 'localhost';
end;
destructor TTpODBC.Destroy;
begin
inherited;
end;
procedure TTpODBC.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TTpODBC.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TTpODBC.SetUserName(const Value: string);
begin
FUserName := Value;
end;
procedure TTpODBC.Tag(inTag: TThTag);
begin
with inTag do
begin
//Add('name', Name);
Add(tpClass, 'TTpODBC');
Add('tpName', Name);
//Add('tpDatabase', Database);
if Persistent then
Add('tpPersistent', 'true');
Add('tpOnGenerate', OnGenerate);
end;
end;
procedure TTpODBC.WriteConfig(const inFolder: string);
const
cConfigExt = '.conf.php';
var
n: string;
s: TStringList;
begin
s := nil;
n := inFolder + Name + cConfigExt;
//if not FileExists(n) then
try
s := TStringList.Create;
s.Add('; <?php die("Unauthorized access.<br>" ?>');
s.Add('[ODBC]');
// s.Add('Host=' + Base64EncodeStr(Host));
// s.Add('User=' + Base64EncodeStr(UserName));
// s.Add('Password=' + Base64EncodeStr(Password));
s.Add('Host=' + Host);
s.Add('User=' + UserName);
s.Add('Password=' + Password);
s.SaveToFile(n);
finally
s.Free;
end;
end;
procedure TTpODBC.ListPhpIncludes(inIncludes: TStringList);
begin
inherited;
inIncludes.Add('TpODBC.php');
end;
{ TTpODBCTable }
procedure TTpODBCTable.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpODBCQuery';
end;
{ TTpODBCQuery }
procedure TTpODBCQuery.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpODBCQuery';
end;
{ TTpODBCDbList }
constructor TTpODBCDbList.Create(inOwner: TComponent);
begin
inherited;
SQL.Text := 'SHOW DATABASES';
end;
procedure TTpODBCDbList.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpODBCDbList';
end;
{ TTpODBCTableList }
constructor TTpODBCTableList.Create(inOwner: TComponent);
begin
inherited;
SQL.Text := 'SHOW TABLES';
end;
procedure TTpODBCTableList.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpODBCTableList';
end;
end.
|
unit fre_zfs;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage UTF8}
{$modeswitch nestedprocvars}
interface
uses
Classes, SysUtils,FRE_DB_INTERFACE, FRE_DB_COMMON, FRE_PROCESS, FOS_BASIS_TOOLS, fre_dbbase,
FOS_TOOL_INTERFACES,
//fre_testcase,
fre_system,fre_monitoring,cthreads, ctypes,fos_strutils;
type
TFRE_DB_ZFS_RAID_LEVEL = (zfs_rl_stripe,zfs_rl_mirror,zfs_rl_z1,zfs_rl_z2,zfs_rl_z3,zfs_rl_undefined);
const
CFRE_DB_ZFS_RAID_LEVEL : array [TFRE_DB_ZFS_RAID_LEVEL] of string = ('rl_stripe','rl_mirror','rl_z1','rl_z2','rl_z3','rl_undefined');
CFRE_DB_ZFS_POOL_COLLECTION = 'pool';
CFRE_DB_ZFS_DATASET_COLLECTION = 'dataset';
CFRE_DB_ZFS_SNAPSHOT_COLLECTION = 'snapshot';
CFRE_DB_ZFS_VDEV_COLLECTION = 'vdev';
CFRE_DB_ZFS_BLOCKDEVICE_COLLECTION = 'zfsblockdev';
CFRE_DB_ZFS_IMPORTABLE_POOL_TEMP = 'izpool';
CFRE_DB_FILESHARE_COLLECTION = 'fileshare';
CFRE_FOSCMD_PORT = 44010;
CFRE_FOSCMD = 'foscmd';
type
EFOS_ZFS_Exception=class(Exception);
TFRE_DB_ZFS_SendMode = (zfsSend,zfsSendReplicated,zfsSendRecursive,zfsSendRecursiveProperties);
TFRE_DB_ZFS_POOL=class;
{ TFRE_DB_ZFS_VDEV_STATUS, TODO Should be kind of volatile }
TFRE_DB_ZFS_VDEV_POOL_STATUS=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_IOSTAT }
TFRE_DB_IOSTAT=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure SetBlockdevice (const blockdevice:TFRE_DB_GUID);
function GetBlockdevice : TFRE_DB_GUID;
end;
{ TFRE_DB_ZFSOBJSTATUS_PLUGIN }
TFRE_DB_ZFSOBJSTATUS_PLUGIN=class(TFRE_DB_STATUS_PLUGIN)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure SetZFSState (const avalue: String);
procedure SetVDEVStatus (const vdev : TFRE_DB_ZFS_VDEV_POOL_STATUS);virtual;
function GetVDEVStatus : TFRE_DB_ZFS_VDEV_POOL_STATUS;
procedure ClearVDEVStatus ;
end;
{ TFRE_DB_POOLSTATUS_PLUGIN }
TFRE_DB_POOLSTATUS_PLUGIN=class(TFRE_DB_ZFSOBJSTATUS_PLUGIN)
protected
procedure InternalSetup ;override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure setScrubStatus (const scrubbing: boolean);
function isScrubInProgress : Boolean;
procedure SetVDEVStatus (const vdev : TFRE_DB_ZFS_VDEV_POOL_STATUS);override;
end;
{ TFRE_DB_ZFS_OBJ }
TFRE_DB_ZFS_OBJ=class(TFRE_DB_ObjectEx)
private
function GetIopsRead : TFRE_DB_String;
function GetIopsWrite : TFRE_DB_String;
function GetPoolId : TFRE_DB_GUID; virtual;
function GetSvcPARENTID : TFRE_DB_GUID;
function GetTransferRead : TFRE_DB_String;
function GetTransferWrite : TFRE_DB_String;
function getCaption : TFRE_DB_String; virtual;
function GetZFSPARENTID : TFRE_DB_GUID;
procedure SetSvcPARENTID (AValue: TFRE_DB_GUID);
procedure SetZFSPARENTID (AValue: TFRE_DB_GUID);
procedure SetPoolId (AValue: TFRE_DB_GUID); virtual;
procedure SetMachineID (AValue: TFRE_DB_GUID);
function getIOStat : TFRE_DB_IOSTAT;
procedure setIOStat (const Avalue: TFRE_DB_IOSTAT);
function getMachineID : TFRE_DB_GUID;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure InternalSetup ; override;
procedure removeFromPool ;
function hasPool :Boolean;
function getPool (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_POOL; virtual;
function getZFSParent (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_OBJ;
function getId : TFRE_DB_String; virtual;
function getZFSChildren (const conn: IFRE_DB_CONNECTION): IFRE_DB_ObjectArray; virtual;
function mayHaveZFSChildren : Boolean; virtual;
function acceptsNewZFSChildren (const conn: IFRE_DB_CONNECTION): Boolean; virtual;
function getZFSGuid : string;
function hasParentInZFS : boolean;
procedure setZFSGuid (const avalue:String);
function canIdentify : Boolean; virtual;
procedure embedChildrenRecursive (const conn: IFRE_DB_CONNECTION; const include_os_blockdevices:boolean);
procedure addChildEmbedded (const child : TFRE_DB_ZFS_OBJ);
procedure SetMOSStatus (const status: TFRE_DB_MOS_STATUS_TYPE; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION);
function GetMOSStatus : TFRE_DB_MOS_STATUS_TYPE;
procedure SetName (const avalue:TFRE_DB_String);
property IoStat : TFRE_DB_IOSTAT read getIOStat write setIOStat;
property caption : TFRE_DB_String read GetCaption;
property iopsR : TFRE_DB_String read GetIopsRead;
property iopsW : TFRE_DB_String read GetIopsWrite;
property transferR : TFRE_DB_String read GetTransferRead;
property transferW : TFRE_DB_String read GetTransferWrite;
property poolId : TFRE_DB_GUID read GetPoolId write SetPoolId;
property MachineID : TFRE_DB_GUID read GetMachineID write SetMachineID;
property ZFSPARENTID : TFRE_DB_GUID read GetZFSPARENTID write SetZFSPARENTID;
property SERVICEPARENTID : TFRE_DB_GUID read GetSvcPARENTID write SetSvcPARENTID;
published
function WEB_MOSChildStatusChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_MOSStatus (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
end;
{ TFRE_DB_ZFS_BLOCKDEVICE }
TFRE_DB_ZFS_BLOCKDEVICE=class(TFRE_DB_ZFS_OBJ) { disk or file = is a ZFS VDEV }
private
function getIsOffline : Boolean;
function getisUnassigned : Boolean;
procedure setIsOffline (AValue: Boolean);
procedure setIsUnassgined (AValue: Boolean);
function getCaption : TFRE_DB_String; override;
protected
function getDeviceIdentifier : TFRE_DB_String; //FIXXME START - needed
function getDeviceName : TFRE_DB_String;
procedure setDeviceIdentifier (AValue: TFRE_DB_String);
procedure setDeviceName (AValue: TFRE_DB_String); //FIXXME END - needed
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function GetMachineDeviceIdentifier (const vmachine_uid: TFRE_DB_GUID; const vdeviceIdentifier: TFRE_DB_String): TFRE_DB_String;
class function GetMachineDeviceName (const vmachine_uid: TFRE_DB_GUID; const vdeviceName: TFRE_DB_String): TFRE_DB_String;
function mayHaveZFSChildren: Boolean; override;
function canIdentify : Boolean; override;
property isOffline : Boolean read getIsOffline write setIsOffline;
property DeviceIdentifier : TFRE_DB_String read getDeviceIdentifier write setDeviceIdentifier;
property DeviceName : TFRE_DB_String read getDeviceName write setDeviceName;
property IsUnassigned : Boolean read getisUnassigned write setIsUnassgined;
published
class procedure STAT_TRANSFORM (const transformed_output : IFRE_DB_Object ; const stat_data : IFRE_DB_Object ; const statfieldname : TFRE_DB_Nametype);
end;
TFRE_DB_ZFS_REPLACEDISK=class;
TFRE_DB_ZFS_SPARE=class;
{ TFRE_DB_ZFS_DISKCONTAINER }
TFRE_DB_ZFS_DISKCONTAINER=class(TFRE_DB_ZFS_OBJ)
private
function GetRaidLevel : TFRE_DB_ZFS_RAID_LEVEL; virtual;
procedure SetRaidLevel (AValue: TFRE_DB_ZFS_RAID_LEVEL); virtual;
protected
procedure SetupNameUCTTagsPlugins (const objname : TFRE_DB_NameType ; const zfsguid:TFRE_DB_String);
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
function addBlockdevice (const blockdevice: TFRE_DB_ZFS_BLOCKDEVICE): TFRE_DB_ZFS_BLOCKDEVICE; virtual;
function addBlockdeviceEmbedded (const blockdevice: TFRE_DB_ZFS_BLOCKDEVICE): TFRE_DB_ZFS_BLOCKDEVICE; virtual;
function createBlockdeviceEmbedded (const devicename:TFRE_DB_String): TFRE_DB_ZFS_BLOCKDEVICE; virtual;
function createDiskReplaceContainerEmbedded (const devicename:TFRE_DB_String) : TFRE_DB_ZFS_REPLACEDISK; virtual;
function createDiskSpareContainerEmbedded (const devicename:TFRE_DB_String) : TFRE_DB_ZFS_SPARE; virtual;
function mayHaveZFSChildren : Boolean; override;
function acceptsNewZFSChildren (const conn: IFRE_DB_CONNECTION): Boolean; override;
property raidLevel : TFRE_DB_ZFS_RAID_LEVEL read GetRaidLevel write SetRaidLevel;
end;
{ TFRE_DB_ZFS_VDEV_RAIDMIRROR }
TFRE_DB_ZFS_VDEV_RAIDMIRROR=class(TFRE_DB_ZFS_DISKCONTAINER)
private
function GetRaidLevel : TFRE_DB_ZFS_RAID_LEVEL; override;
procedure SetRaidLevel (AValue: TFRE_DB_ZFS_RAID_LEVEL); override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function acceptsNewZFSChildren (const conn: IFRE_DB_CONNECTION): Boolean; override;
published
class procedure STAT_TRANSFORM (const transformed_output : IFRE_DB_Object ; const stat_data : IFRE_DB_Object ; const statfieldname : TFRE_DB_Nametype);
end;
{ TFRE_DB_ZFS_CONTAINER
Only Baseclass for DATASTORAGE and LOG
}
TFRE_DB_ZFS_CONTAINER=class(TFRE_DB_ZFS_DISKCONTAINER)
private
function GetRaidLevel : TFRE_DB_ZFS_RAID_LEVEL; override;
procedure SetRaidLevel (AValue: TFRE_DB_ZFS_RAID_LEVEL); override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function createVdev : TFRE_DB_ZFS_VDEV_RAIDMIRROR; virtual;
function createVdevEmbedded (const devicename:TFRE_DB_String): TFRE_DB_ZFS_VDEV_RAIDMIRROR; virtual;
end;
{ TFRE_DB_ZFS_DATASTORAGE }
TFRE_DB_ZFS_DATASTORAGE=class(TFRE_DB_ZFS_CONTAINER)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
published
class procedure STAT_TRANSFORM (const transformed_output : IFRE_DB_Object ; const stat_data : IFRE_DB_Object ; const statfieldname : TFRE_DB_Nametype);
end;
{ TFRE_DB_ZFS_SPARE }
TFRE_DB_ZFS_SPARE=class(TFRE_DB_ZFS_DISKCONTAINER)
private
function GetRaidLevel : TFRE_DB_ZFS_RAID_LEVEL; override;
procedure SetRaidLevel (AValue: TFRE_DB_ZFS_RAID_LEVEL); override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_LOG }
TFRE_DB_ZFS_LOG=class(TFRE_DB_ZFS_CONTAINER)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_CACHE }
TFRE_DB_ZFS_CACHE=class(TFRE_DB_ZFS_DISKCONTAINER)
private
function GetRaidLevel : TFRE_DB_ZFS_RAID_LEVEL; override;
procedure SetRaidLevel (AValue: TFRE_DB_ZFS_RAID_LEVEL); override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_REPLACEDISK }
TFRE_DB_ZFS_REPLACEDISK=class(TFRE_DB_ZFS_DISKCONTAINER)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function mayHaveZFSChildren : Boolean; override;
function acceptsNewZFSChildren (const conn: IFRE_DB_CONNECTION): Boolean; override;
end;
{ TFRE_DB_ZFS_POOL }
TFRE_DB_ZFS_DATASET=class;
TFRE_DB_ZFS_POOL=class(TFRE_DB_ZFS_OBJ) { the UCT tag of the pool is P_+name@machineIdHEX, subobjects are dervived }
protected
function GetPoolId : TFRE_DB_GUID; override;
procedure SetPoolId (AValue: TFRE_DB_GUID); override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function getFieldsIgnoredBySync : TFRE_DB_NameTypeArray;
class function CreateEmbeddedPoolObjectfromDB (const conn:IFRE_DB_CONNECTION; const db_zfs_pool_id:TFRE_DB_GUID; const include_os_blockdevices:boolean): TFRE_DB_ZFS_POOL; { EMBED VDEVS }
class function CreateEmbeddedZFSDatasets (const conn:IFRE_DB_CONNECTION; const db_zfs_pool_id:TFRE_DB_GUID): TFRE_DB_ZFS_POOL; { EMBEDDED ZFS DATASETS }
procedure InternalSetup ; override;
function mayHaveZFSChildren : Boolean; override;
function acceptsNewZFSChildren (const conn: IFRE_DB_CONNECTION): Boolean; override;
function getPool (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_POOL; override;
function getPoolName : TFRE_DB_String;
function GetDatastorage (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASTORAGE;
function GetDatastorageEmbedded : TFRE_DB_ZFS_DATASTORAGE;
function GetSpare (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_SPARE;
function GetSpareEmbedded (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_SPARE;
function GetCache (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_CACHE;
function GetCacheEmbedded (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_CACHE;
function GetLog (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_LOG;
function GetLogEmbedded (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_LOG;
function createDatastorage : TFRE_DB_ZFS_DATASTORAGE;
function createDatastorageEmbedded : TFRE_DB_ZFS_DATASTORAGE;
procedure addDataStorageEmbedded (const ds: TFRE_DB_ZFS_DATASTORAGE);
function createCache : TFRE_DB_ZFS_CACHE;
function createCacheEmbedded : TFRE_DB_ZFS_CACHE;
procedure addCacheEmbedded (const ds: TFRE_DB_ZFS_CACHE);
function createLog : TFRE_DB_ZFS_LOG;
function createLogEmbedded : TFRE_DB_ZFS_LOG;
procedure addLogEmbedded (const ds: TFRE_DB_ZFS_LOG);
function createSpare : TFRE_DB_ZFS_SPARE;
function createSpareEmbedded : TFRE_DB_ZFS_SPARE;
procedure addSpareEmbedded (const ds: TFRE_DB_ZFS_SPARE);
procedure SetForceMode (const force : boolean);
function CheckPoolConfigStatus (out error:string):Boolean;
procedure CreatePhysicalPool ; { Process, remote capable }
function getRootDataset (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASET;
procedure embedZFSDatasetsRec (const conn: IFRE_DB_CONNECTION);
procedure SetPoolUCTTags (out status : TFRE_DB_POOLSTATUS_PLUGIN);
class function Build_UCT_TAG (const name:TFRE_DB_String;const machine_id : TFRE_DB_GUID):TFRE_DB_String;
procedure SetSystemSoftwareVersion (const version:string);
published
function WEB_MOSContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
function WEB_ZFSContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;
class procedure STAT_TRANSFORM (const transformed_output : IFRE_DB_Object ; const stat_data : IFRE_DB_Object ; const statfieldname : TFRE_DB_Nametype);
function RIF_CreatePool (const runnning_ctx : TObject) : TFRE_DB_RIF_RESULT; { new pool }
function RIF_CreatePoolInstall (const runnning_ctx : TObject) : IFRE_DB_Object; { new syspool, install software on it }
function RIF_DestroyPool (const runnning_ctx : TObject) : IFRE_DB_Object; { existing pool }
function RIF_ExportPool (const runnning_ctx : TObject) : IFRE_DB_Object; { existing pool }
function RIF_ExtendPool (const runnning_ctx : TObject) : IFRE_DB_Object; { extend mirrors, or stripes, logs, caches }
end;
{ TFRE_DB_ZFS_IMPORTABLE_POOLS }
TFRE_DB_ZFS_IMPORTABLE_POOLS=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS }
TFRE_DB_ZFS = class (TFRE_DB_ObjectEx)//(TFRE_DB_Multiprocess) { helper object, not for db, embedded data }
private
procedure AddParameter (const parameter : string; var params : TFRE_DB_StringArray); { FREDB_AddString2Array ? }
procedure AnalyzeSnapshotsLegacy (const proc_OutputToString : string);deprecated;
//procedure AnalyzeDataSetSpace (const proc : TFRE_DB_Process);
//procedure AnalyzePoolList (const proc : TFRE_DB_Process);
public
procedure SetRemoteSSH (const user : string; const host : string; const keyfilename : string; const port : integer = 22);
function CreateSnapShot { Process } (const dataset: string; const snapshotname : string; out error : string ) : integer;
procedure GetSnapshots { Process } (const dataset: string; const foscmdmode: boolean);
function DestroySnapshot { Process } (const dataset: string; const snapshotname : string; out error : string) : integer;
function SnapShotExists { Process } (const dataset: string; const snapshotname : string; out creation_ts: TFRE_DB_DateTime64; out error : string ; out exists : boolean;const foscmdmode: boolean=false) : integer;
function GetLastSnapShot { Process } (const dataset: string; const snapshotkey : string; out snapshotname : string; out creation_ts: TFRE_DB_DateTime64; out error : string;const foscmdmode: boolean=false) : integer;
procedure TCPGetSnapshots { Process } (const dataset: string; const destinationhost : string; const destinationport: integer=CFRE_FOSCMD_PORT);
function TCPSnapShotExists { Process } (const dataset: string; const snapshotname : string; out creation_ts: TFRE_DB_DateTime64; out error : string ; out exists : boolean;const destinationhost : string; const destinationport: integer=CFRE_FOSCMD_PORT) : integer;
function TCPGetLastSnapShot{ Process } (const dataset: string; const snapshotkey : string; out snapshotname : string; out creation_ts: TFRE_DB_DateTime64; out error : string; const destinationhost : string; const destinationport: integer=CFRE_FOSCMD_PORT) : integer;
function TCPDataSetExists { Process } (const dataset: string; out error : string; out exists : boolean; const destinationhost : string; const destinationport: integer=CFRE_FOSCMD_PORT) : integer;
function TCPSendSnapshot { Process } (const dataset: string; const snapshotname: string; const destinationhost: string; const destinationport: integer; const destinationdataset: string; out error: string; const incrementalsnapshot: string; const sendmode: TFRE_DB_ZFS_Sendmode; const compressed: boolean; const jobid: string): integer;
function CreateDataset { Process } (const dataset: string; out error: string) : integer;
function DestroyDataset { Process } (const dataset: string; out error: string; const recursive: boolean=false; const dependents: boolean=false ; const force : boolean=false) : integer;
function DataSetExists { Process } (const dataset: string; out error : string; out exists : boolean; const foscmdmode :boolean=false) : integer;
function SendSnapshot (const dataset: string; const snapshotname : string; const destinationhost : string; const destinationuser: string; const destinationdataset : string; const destinationkeyfilename :string; out error :string; const incrementalsnapshot: string=''; const sendmode : TFRE_DB_ZFS_Sendmode=zfsSend; const compressed : boolean=true; const destinationport: integer = 22;const foscmdmode: boolean=false) : integer;
function Scrub { Process } (const poolname: string; out error : string) : integer;
function GetPoolStatus { Process } (const poolname: string; out error : string; out pool: IFRE_DB_Object) : integer;
function GetDataset { Process } (const dataset: string; out error : string; out datasetobject: IFRE_DB_Object) : integer;
//function EmbedDatasets : boolean; { embedd all datasets Volumes,Bookmarks,Snapshots ... }
function GetPools { Process } (out error: string; out pools:IFRE_DB_Object) : integer;
function CreateDiskPool { Process } (const pool_definition:IFRE_DB_Object; out output,errorout,zfs_cmd : string) : integer;
end;
{ TFRE_DB_ZFSJob }
TFRE_DB_ZFSJob = class (TFRE_DB_JOB)
private
procedure _SSHSnapShotReplicate (const do_replicate: boolean);
procedure _TCPSnapShotReplicate (const do_replicate: boolean);
procedure _SnapShotCheck ;
procedure _PoolStatus ;
procedure _DataSetSpace ;
procedure _AnalyzePool (const proc : IFRE_DB_Object);
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure InternalSetup ; override;
procedure ExecuteJob ; override;
procedure SetScrub (const poolname: string);
procedure SetPoolStatus (const poolname: string; const scrub_warning_days: integer; const scrub_error_days: integer);
procedure SetDatasetspace (const dataset: string; const warning_percent: integer; const error_percent: integer);
procedure SetSSHReplicate (const sourcedataset: string; const destinationdataset:string; const snapshotkey : string; const destinationhost : string; const destinationuser : string; const destinationkeyfilename : string; const replicationkeyfilename : string; const destinationport: integer=22; const replicationport: integer=22);
procedure SetTCPReplicate (const sourcedataset: string; const destinationdataset:string; const snapshotkey : string; const destinationhost : string; const destinationport: integer=CFRE_FOSCMD_PORT);
procedure SetSnapshot (const dataset: string; const snapshotkey : string);
procedure SetSnapshotCheck (const dataset:string; const snapshotkey : string; const warning_seconds: integer; const error_seconds: integer);
end;
{ TFRE_DB_ZFS_ZDS_STATUS, TODO Should be kind of volatile }
TFRE_DB_ZFS_ZDS_STATUS=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_DS_PLUGIN }
TFRE_DB_ZFS_DS_PLUGIN=class(TFRE_DB_STATUS_PLUGIN) { PLUGIN FOR ZFS FILESYSTEMS DS, ZVOL }
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure MoveFastChangingZFSPropertiesToPlugin; { create fast changing status sub object }
function GetZDSStatus : TFRE_DB_ZFS_ZDS_STATUS;
procedure ClearZDSStatus ;
end;
{ TFRE_DB_ZFS_BASE base for all ZFS Datasets like objects }
TFRE_DB_ZFS_BASE=class(TFRE_DB_ObjectEx)
private
function GetPoolID: TFRE_DB_GUID;
function GetServiceParentID: TFRE_DB_GUID;
procedure SetPoolID(AValue: TFRE_DB_GUID);
procedure SetServiceParentID(AValue: TFRE_DB_GUID);
function getdsname: TFRE_DB_String;
procedure setdsname(AValue: TFRE_DB_String);
protected
procedure InternalSetup; override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure SetupPropFieldFromName(const propname,propval : string);
property ServiceParent : TFRE_DB_GUID read GetServiceParentID write SetServiceParentID;
property PoolID : TFRE_DB_GUID read GetPoolID write SetPoolID;
procedure Setup_UCT_ZDS (const machineid:TFRE_DB_GUID);
property Name : TFRE_DB_String read getdsname write setdsname; { the real zfs dataset name e.g. syspool/swap }
class function Build_UCT_TAG (const dsname:TFRE_DB_String;const machine_id : TFRE_DB_GUID):TFRE_DB_String;
end;
{ TFRE_DB_ZFS_SNAPSHOT }
TFRE_DB_ZFS_SNAPSHOT=class(TFRE_DB_ZFS_BASE)
public
procedure Setup (const snapname: TFRE_DB_String; const creationtime_utc: TFRE_DB_DateTime64; const usedamount, referedamount: Int64);
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function getFieldsIgnoredBySync : TFRE_DB_NameTypeArray;
function GetDatasetName : TFRE_DB_String;
end;
{ TFRE_DB_ZFS_BOOKMARK }
TFRE_DB_ZFS_BOOKMARK=class(TFRE_DB_ZFS_BASE)
public
procedure Setup (const snapname: TFRE_DB_String; const creationtime_utc: TFRE_DB_DateTime64; const usedamount, referedamount: Int64);
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_DATASET }
TFRE_DB_ZFS_DATASET=class(TFRE_DB_ZFS_BASE)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function getFieldsIgnoredBySync: TFRE_DB_NameTypeArray;
procedure embedZFSDatasetsRec (const conn: IFRE_DB_CONNECTION);
function GetFullDatasetname : TFRE_DB_String;
function GetOrigin : TFRE_DB_String;
procedure SetIsDomainsContainer ;
procedure SetIsDomainDataset ;
procedure SetIsZoneDataset ;
procedure SetIsTemplateContainer;
procedure SetIsTemplateDataset ;
procedure SetIsZoneCfgDataset ;
procedure SetIsZoneCfgContainer ;
function IsDomainsContainer : Boolean;
function IsDomainDataset : Boolean;
function IsZoneCfgDataset : Boolean;
function IsZoneCfgContainer : Boolean;
function IsZoneDataset : Boolean;
function IsTemplateContainer : Boolean;
function IsTemplateDataset : Boolean;
procedure CFG_SetBrowseParent (const lvl : string);
function CFG_GetLevel : string;
published
function RIF_BrowseDataset (const runnning_ctx : TObject) : TFRE_DB_RIF_RESULT;
end;
{ TFRE_DB_ZFS_DATASET_FILESYSTEM }
TFRE_DB_ZFS_DATASET_FILESYSTEM=class(TFRE_DB_ZFS_DATASET) { a ZFS Filesystem }
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_ZFS_DATASET_ZVOL }
TFRE_DB_ZFS_DATASET_ZVOL=class(TFRE_DB_ZFS_DATASET) { a ZFS Blockdevice Dataset }
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function Embed (const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASET_ZVOL;
end;
{ TFRE_DB_ZFS_ZONE_CONTAINER_DATASET }
TFRE_DB_ZFS_ZONE_CONTAINER_DATASET=class(TFRE_DB_ZFS_DATASET_FILESYSTEM) { Dataset with defined substructure for domains and zone definition }
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_NFS_FILESHARE }
TFRE_DB_NFS_FILESHARE=class(TFRE_DB_ZFS_DATASET_FILESYSTEM)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_LUN }
TFRE_DB_LUN=class(TFRE_DB_ZFS_DATASET_ZVOL)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_HDD }
TFRE_DB_HDD=class(TFRE_DB_ZFS_DATASET_ZVOL)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_VIRTUAL_FILESHARE }
TFRE_DB_VIRTUAL_FILESHARE=class(TFRE_DB_ZFS_DATASET_FILESYSTEM)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_NFS_ACCESS }
TFRE_DB_NFS_ACCESS=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_LUN_VIEW }
TFRE_DB_LUN_VIEW=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
procedure Register_DB_Extensions;
function String2DBZFSRaidLevelType(const fts: string): TFRE_DB_ZFS_RAID_LEVEL;
function ParseZpool (const pooltxt: string; out pool: TFRE_DB_ZFS_POOL): boolean;
procedure CreateZFSDataCollections (const conn: IFRE_DB_COnnection);
implementation
uses fre_hal_schemes; { dirty hack, for TFRE_DB_FS_ENTRY, do proper unit separation }
{ TFRE_DB_ZFS_ZDS_STATUS }
class procedure TFRE_DB_ZFS_ZDS_STATUS.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_ZDS_STATUS.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
{ TFRE_DB_ZFS_DS_PLUGIN }
procedure TFRE_DB_ZFS_DS_PLUGIN.MoveFastChangingZFSPropertiesToPlugin;
var zds : TFRE_DB_ZFS_BASE;
zstat : IFRE_DB_Object;
procedure MoveField(const fname : TFRE_DB_NameType);
var fld : IFRE_DB_Field;
begin
fld := zds.Field(fname);
zstat.Field(fname).CloneFromField(fld);
fld.Clear;
end;
begin
MyObj.AsClass(TFRE_DB_ZFS_BASE,zds);
zstat := TFRE_DB_ZFS_ZDS_STATUS.CreateForDB;
Field('ZDS_STATE').AsObject := zstat;
MoveField('AVAILABLE');
MoveField('USED');
MoveField('UNIQUE');
MoveField('LOGICALUSED');
MoveField('USEDBYCHILDREN');
MoveField('REFERENCED');
MoveField('USEDBYDATASET');
MoveField('WRITTEN');
MoveField('USEDBYSNAPSHOTS');
MoveField('LOGICALREFERENCED');
MoveField('USEDBYREFRESERVATION');
end;
class procedure TFRE_DB_ZFS_DS_PLUGIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_STATUS_PLUGIN.Classname);
end;
class procedure TFRE_DB_ZFS_DS_PLUGIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='0.1';
if (currentVersionId='') then begin
currentVersionId:='0.1';
end;
end;
function TFRE_DB_ZFS_DS_PLUGIN.GetZDSStatus: TFRE_DB_ZFS_ZDS_STATUS;
begin
if not FieldOnlyExistingObjAs('ZDS_STATE',TFRE_DB_ZFS_ZDS_STATUS,result) then
Result:=nil;
end;
procedure TFRE_DB_ZFS_DS_PLUGIN.ClearZDSStatus;
begin
Field('ZDS_STATE').Clear;
end;
{ TFRE_DB_ZFS_IMPORTABLE_POOLS }
class procedure TFRE_DB_ZFS_IMPORTABLE_POOLS.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
end;
class procedure TFRE_DB_ZFS_IMPORTABLE_POOLS.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
{ TFRE_DB_HDD }
class procedure TFRE_DB_HDD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group: IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
group:=scheme.ReplaceInputGroup('main').Setup(GetTranslateableTextKey('scheme_main_group'));
group.AddInput('objname',GetTranslateableTextKey('scheme_objname'));
group.AddInput('size_gb',GetTranslateableTextKey('scheme_size_gb'));
end;
class procedure TFRE_DB_HDD.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_objname','Caption');
StoreTranslateableText(conn,'scheme_size_gb','Size (GB)');
end;
end;
{ TFRE_DB_ZFSOBJSTATUS_PLUGIN }
class procedure TFRE_DB_ZFSOBJSTATUS_PLUGIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_STATUS_PLUGIN.Classname);
scheme.AddSchemeField('state',fdbft_Int32);
end;
class procedure TFRE_DB_ZFSOBJSTATUS_PLUGIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
procedure TFRE_DB_ZFSOBJSTATUS_PLUGIN.SetZFSState(const avalue: String);
begin
Field('zfs_state').AsString := avalue;
end;
procedure TFRE_DB_ZFSOBJSTATUS_PLUGIN.SetVDEVStatus(const vdev: TFRE_DB_ZFS_VDEV_POOL_STATUS);
var fld : IFRE_DB_Field;
begin
Field('VDEV_POOL_STATE').AsObject := vdev; { get set by feeder }
setStable; { it has to be stable }
if vdev.FieldOnlyExisting('STATE',fld) then
SetZFSState(fld.AsString);
end;
function TFRE_DB_ZFSOBJSTATUS_PLUGIN.GetVDEVStatus: TFRE_DB_ZFS_VDEV_POOL_STATUS;
begin
if not FieldOnlyExistingObjAs('VDEV_POOL_STATE',TFRE_DB_ZFS_VDEV_POOL_STATUS,result) then
Result:=nil;
end;
procedure TFRE_DB_ZFSOBJSTATUS_PLUGIN.ClearVDEVStatus;
begin
Field('VDEV_POOL_STATE').Clear;
end;
{ TFRE_DB_POOLSTATUS_PLUGIN }
procedure TFRE_DB_POOLSTATUS_PLUGIN.InternalSetup;
begin
inherited InternalSetup;
setScrubStatus(false);
end;
class procedure TFRE_DB_POOLSTATUS_PLUGIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ZFSOBJSTATUS_PLUGIN.Classname);
end;
class procedure TFRE_DB_POOLSTATUS_PLUGIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
procedure TFRE_DB_POOLSTATUS_PLUGIN.setScrubStatus(const scrubbing: boolean);
begin
Field('scrubbing').AsBoolean:=scrubbing;
end;
function TFRE_DB_POOLSTATUS_PLUGIN.isScrubInProgress: Boolean;
begin
Result:=Field('scrubbing').AsBoolean;
end;
procedure TFRE_DB_POOLSTATUS_PLUGIN.SetVDEVStatus(const vdev: TFRE_DB_ZFS_VDEV_POOL_STATUS);
begin
inherited SetVDEVStatus(vdev);
if vdev.FieldOnlyExistingString('PSS_STATE')='DSS_SCANNING' then
setScrubStatus(true)
else
setScrubStatus(false);
vdev.Field('UCT').AsString := 'ZPPVDS_'+GFRE_BT.HashFast32_Hex(MyObj.Field('UCT').AsString);
end;
{ TFRE_DB_ZFS_ZONE_CONTAINER_DATASET }
class procedure TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_DATASET_FILESYSTEM.Classname);
end;
class procedure TFRE_DB_ZFS_ZONE_CONTAINER_DATASET.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
inherited InstallDBObjects(conn,currentVersionId,newVersionId);
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
{ TFRE_DB_ZFS_DS_BASE }
function TFRE_DB_ZFS_BASE.getdsname: TFRE_DB_String;
begin
result := Field('name').AsString;
end;
procedure TFRE_DB_ZFS_BASE.setdsname(AValue: TFRE_DB_String);
begin
field('name').AsString := AValue;
end;
function TFRE_DB_ZFS_BASE.GetPoolID: TFRE_DB_GUID;
begin
result := Field('poolid').AsObjectLink;
end;
function TFRE_DB_ZFS_BASE.GetServiceParentID: TFRE_DB_GUID;
begin
result := Field('serviceparent').AsObjectLink;
end;
procedure TFRE_DB_ZFS_BASE.SetPoolID(AValue: TFRE_DB_GUID);
begin
Field('poolid').AsObjectLink := AValue;
end;
procedure TFRE_DB_ZFS_BASE.SetServiceParentID(AValue: TFRE_DB_GUID);
begin
Field('serviceparent').AsObjectLink := AValue;
end;
procedure TFRE_DB_ZFS_BASE.InternalSetup;
begin
inherited InternalSetup;
AttachPlugin(TFRE_DB_ZFS_DS_PLUGIN.CreateForDB);
end;
class procedure TFRE_DB_ZFS_BASE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
val: IFRE_DB_ClientFieldValidator;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
if ClassName='TFRE_DB_ZFS_BASE' then begin //create validator only once
GFRE_DBI.RegisterSysClientFieldValidator(GFRE_DBI.NewClientFieldValidator('zfsname').Setup('[a-z0-9_:\\-.]+',
GFRE_DBI.CreateText('$validator_zfsname','ZFS Name Validator'),
GetTranslateableTextKey('validator_zfsname_help'),
'a-z0-9_:\-.'));
end;
scheme.AddSchemeField('name',fdbft_String);
scheme.GetSchemeField('objname').SetupFieldDef(true,false,'','zfsname');
end;
class procedure TFRE_DB_ZFS_BASE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'validator_zfsname_help','[a-z0-9_-:.]');
end;
end;
procedure TFRE_DB_ZFS_BASE.SetupPropFieldFromName(const propname, propval: string);
procedure Setupfield(const fname:string;const prop:string);
var val:NativeInt;
procedure SetDateUTC;
begin
Field(fname).AsDateTimeUTC:=StrToInt64(prop)*1000;
end;
procedure SetInteger;
begin
if prop='-' then
begin
Field(fname).AsInt64:=-1;
exit;
end;
Field(fname).AsInt64:=StrToInt64(prop);
end;
begin
case fname of
'creation' :
begin
SetDateUTC;
exit;
end;
'filesystem_count',
'filesystem_limit',
'snapshot_count',
'snapshot_limit':
begin
if (prop='18446744073709551615') or (prop='-') then
begin
Field(fname).AsInt64 := 0;
exit;
end;
SetInteger;
exit;
end;
'mounted':
begin
if prop='yes' then
Field(fname).AsBoolean:=true
else
Field(fname).AsBoolean:=false;
exit;
end;
'used','available','logicalused','quota','referenced','copies',
'logicalreferenced','reservation','usedbydataset','recordsize','written','refquota','usedbysnapshots','refreservation','usedbychildren','usedbyrefreservation' :
begin
SetInteger;
exit;
end;
end;
if prop='on' then
begin
field(fname).AsBoolean:=true;
exit;
end;
if prop='off' then
begin
field(fname).AsBoolean:=false;
exit;
end;
Field(fname).AsString:=prop; { fallback }
end;
begin
Setupfield(lowercase(propname),propval);
end;
procedure TFRE_DB_ZFS_BASE.Setup_UCT_ZDS(const machineid: TFRE_DB_GUID);
var uctval : string;
plug : TFRE_DB_ZFS_DS_PLUGIN;
begin
uctval := name+'@'+machineid.AsHexString;
field('uct').AsString := 'ZDS_'+uctval;
end;
class function TFRE_DB_ZFS_BASE.Build_UCT_TAG(const dsname: TFRE_DB_String; const machine_id: TFRE_DB_GUID): TFRE_DB_String;
begin
result := 'ZDS_'+dsname+ '@' + machine_id.AsHexString;
end;
{ TFRE_DB_ZFS_BOOKMARK }
procedure TFRE_DB_ZFS_BOOKMARK.Setup(const snapname: TFRE_DB_String; const creationtime_utc: TFRE_DB_DateTime64; const usedamount, referedamount: Int64);
begin
end;
class procedure TFRE_DB_ZFS_BOOKMARK.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
end;
class procedure TFRE_DB_ZFS_BOOKMARK.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
{ TFRE_DB_ZFS_REPLACEDISK }
class procedure TFRE_DB_ZFS_REPLACEDISK.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_REPLACEDISK.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
function TFRE_DB_ZFS_REPLACEDISK.mayHaveZFSChildren: Boolean;
begin
Result:=true;
end;
function TFRE_DB_ZFS_REPLACEDISK.acceptsNewZFSChildren(const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=false;
end;
{ TFRE_DB_ZFS_VDEV_STATUS }
class procedure TFRE_DB_ZFS_VDEV_POOL_STATUS.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
//scheme.AddSchemeField('IOPS_R',fdbft_String);
//scheme.AddSchemeField('IOPS_W',fdbft_String);
//scheme.AddSchemeField('TRANSFER_R',fdbft_String);
//scheme.AddSchemeField('TRANSFER_W',fdbft_String);
//
//group:=scheme.AddInputGroup('zpool_iostat_common').Setup('$scheme_TFRE_DB_ZPOOL_IOSTAT_common');
//group.AddInput('IOPS_R',GetTranslateableTextKey('$scheme_TFRE_DB_ZPOOL_IOSTAT_IOPS_R'),true);
//group.AddInput('IOPS_W',GetTranslateableTextKey('$scheme_TFRE_DB_ZPOOL_IOSTAT_IOPS_W'),true);
//group.AddInput('TRANSFER_R',GetTranslateableTextKey('$scheme_TFRE_DB_ZPOOL_IOSTAT_TRANSFER_R'),true);
//group.AddInput('TRANSFER_W',GetTranslateableTextKey('$scheme_TFRE_DB_ZPOOL_IOSTAT_TRANSFER_W'),true);
//
end;
class procedure TFRE_DB_ZFS_VDEV_POOL_STATUS.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
class procedure TFRE_DB_IOSTAT.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_IOSTAT.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
procedure TFRE_DB_IOSTAT.SetBlockdevice(const blockdevice: TFRE_DB_GUID);
begin
field('blockdeviceid').AsObjectLink := blockdevice;
end;
function TFRE_DB_IOSTAT.GetBlockdevice: TFRE_DB_GUID;
begin
result := field('blockdeviceid').AsObjectLink;
end;
{ TFRE_DB_ZFS_DISKCONTAINER }
function TFRE_DB_ZFS_DISKCONTAINER.GetRaidLevel: TFRE_DB_ZFS_RAID_LEVEL;
begin
if FieldExists('raidLevel') then begin
Result:=String2DBZFSRaidLevelType(Field('raidLevel').AsString);
end else begin
Result:=zfs_rl_stripe;
end;
end;
procedure TFRE_DB_ZFS_DISKCONTAINER.SetRaidLevel(AValue: TFRE_DB_ZFS_RAID_LEVEL);
begin
Field('raidLevel').AsString:=CFRE_DB_ZFS_RAID_LEVEL[AValue];
end;
procedure TFRE_DB_ZFS_DISKCONTAINER.SetupNameUCTTagsPlugins(const objname: TFRE_DB_NameType; const zfsguid: TFRE_DB_String);
var plugin : TFRE_DB_ZFSOBJSTATUS_PLUGIN;
uname : TFRE_DB_NameType;
begin
uname := uppercase(objname);
setZFSGuid(uname+zfsguid);
setname(objname);
Field('UCT').AsString:=uname+'_'+zfsguid;
{
FIXXME : REMOVE Subtags should be set generic
}
GetPlugin(TFRE_DB_ZFSOBJSTATUS_PLUGIN,plugin);
//SetPluginContainerTag('PLG_CT_'+uname+zfsguid);
//plugin.Field('UCT').AsString:='PLG_'+uname+'_'+zfsguid;
plugin.setStable;
end;
class procedure TFRE_DB_ZFS_DISKCONTAINER.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
function TFRE_DB_ZFS_DISKCONTAINER.addBlockdevice(const blockdevice: TFRE_DB_ZFS_BLOCKDEVICE): TFRE_DB_ZFS_BLOCKDEVICE;
begin
blockdevice.SetZFSPARENTID(UID);
blockdevice.poolId:=poolId;
blockdevice.IsUnassigned:=false;
Result:=blockdevice;
end;
function TFRE_DB_ZFS_DISKCONTAINER.addBlockdeviceEmbedded(const blockdevice: TFRE_DB_ZFS_BLOCKDEVICE): TFRE_DB_ZFS_BLOCKDEVICE;
begin
//blockdevice.SetZFSPARENT(UID);
//blockdevice.poolId:=poolId;
Field(blockdevice.getZFSGuid).asobject := blockdevice;
end;
function TFRE_DB_ZFS_DISKCONTAINER.createBlockdeviceEmbedded(const devicename: TFRE_DB_String): TFRE_DB_ZFS_BLOCKDEVICE;
begin
Result:=TFRE_DB_ZFS_BLOCKDEVICE.CreateForDB;
//Result.SetZFSPARENT(UID);
//Result.poolId:=poolId;
Field(devicename).AsObject := Result;
end;
function TFRE_DB_ZFS_DISKCONTAINER.createDiskReplaceContainerEmbedded(const devicename: TFRE_DB_String): TFRE_DB_ZFS_REPLACEDISK;
begin
Result:=TFRE_DB_ZFS_REPLACEDISK.CreateForDB;
//Result.parentInZFSId:=UID;
//Result.poolId:=poolId;
Field(devicename).AsObject := Result;
end;
function TFRE_DB_ZFS_DISKCONTAINER.createDiskSpareContainerEmbedded(const devicename: TFRE_DB_String): TFRE_DB_ZFS_SPARE;
begin
Result:=TFRE_DB_ZFS_SPARE.CreateForDB;
//Result.parentInZFSId:=UID;
//Result.poolId:=poolId;
Field(devicename).AsObject := Result;
end;
function TFRE_DB_ZFS_DISKCONTAINER.mayHaveZFSChildren: Boolean;
begin
Result:=true;
end;
function TFRE_DB_ZFS_DISKCONTAINER.acceptsNewZFSChildren(const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=true;
end;
{ TFRE_DB_ZFS_RAIDCONTAINER }
function TFRE_DB_ZFS_CONTAINER.GetRaidLevel: TFRE_DB_ZFS_RAID_LEVEL;
begin
Result:=zfs_rl_undefined;
end;
procedure TFRE_DB_ZFS_CONTAINER.SetRaidLevel(AValue: TFRE_DB_ZFS_RAID_LEVEL);
begin
if AValue<>zfs_rl_stripe then raise EFOS_ZFS_Exception.Create('A Vdev container has to be striped.');
inherited SetRaidLevel(AValue);
end;
class procedure TFRE_DB_ZFS_CONTAINER.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_CONTAINER.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
function TFRE_DB_ZFS_CONTAINER.createVdev: TFRE_DB_ZFS_VDEV_RAIDMIRROR;
begin
Result:=TFRE_DB_ZFS_VDEV_RAIDMIRROR.CreateForDB;
Result.SetZFSPARENTID(UID);
Result.poolId:=poolId;
end;
function TFRE_DB_ZFS_CONTAINER.createVdevEmbedded(const devicename: TFRE_DB_String): TFRE_DB_ZFS_VDEV_RAIDMIRROR;
begin
Result:=TFRE_DB_ZFS_VDEV_RAIDMIRROR.CreateForDB;
//Result.SetZFSPARENTID(UID);
//Result.poolId:=poolId;
Field(devicename).asObject:=Result;
end;
{ TFRE_DB_ZFS_DATASTORAGE }
class procedure TFRE_DB_ZFS_DATASTORAGE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_DATASTORAGE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
class procedure TFRE_DB_ZFS_DATASTORAGE.STAT_TRANSFORM(const transformed_output: IFRE_DB_Object; const stat_data: IFRE_DB_Object; const statfieldname: TFRE_DB_Nametype);
var s,d,a : double;
r,c,w : UInt64;
begin
if assigned(stat_data) then
begin
s := stat_data.Field('SPACE').AsUInt64 / (1024*1024*1024*1024);
d := stat_data.Field('DSPACE').AsUInt64 / (1024*1024*1024*1024);
a := stat_data.Field('ALLOC').AsUInt64/(1024*1024*1024*1024);
r := stat_data.Field('R_ERRORS').AsUInt64;
w := stat_data.Field('W_ERRORS').AsUInt64;
c := stat_data.Field('C_ERRORS').AsUInt64;
transformed_output.Field(statfieldname).AsString := stat_data.Field('STATE').AsString+' '+format('S/D/A %f TB %f TB %f TB R/W/C Errors(%d/%d/%d)',[s,d,a,r,w,c]);
end;
end;
{ TFRE_DB_ZFS_OBJ }
function TFRE_DB_ZFS_OBJ.getZFSGuid: string;
begin
Result:=Field('zfs_guid').AsString;
end;
function TFRE_DB_ZFS_OBJ.hasParentInZFS: boolean;
begin
result := (FieldExists('ZFSPARENT')) and (not Field('ZFSPARENT').IsEmptyArray);
end;
function TFRE_DB_ZFS_OBJ.GetZFSPARENTID: TFRE_DB_GUID;
begin
Result:=Field('ZFSPARENT').AsObjectLink;
end;
procedure TFRE_DB_ZFS_OBJ.SetSvcPARENTID(AValue: TFRE_DB_GUID);
begin
Field('SERVICEPARENT').AsObjectLink := AValue;
end;
function TFRE_DB_ZFS_OBJ.GetPoolId: TFRE_DB_GUID;
begin
if FieldExists('pool_uid') then
Result:=Field('pool_uid').AsObjectLink
else
Result:=CFRE_DB_NullGUID;
end;
function TFRE_DB_ZFS_OBJ.GetSvcPARENTID: TFRE_DB_GUID;
begin
end;
function TFRE_DB_ZFS_OBJ.GetTransferRead: TFRE_DB_String;
begin
abort; //wrong
//if FieldExists('zpooliostat') then
// result:=Field('zpooliostat').AsObject.Field('transfer_r').AsString
//else
// result:='';
end;
function TFRE_DB_ZFS_OBJ.GetTransferWrite: TFRE_DB_String;
begin
abort;
//if FieldExists('zpooliostat') then
// result:=Field('zpooliostat').AsObject.Field('transfer_w').AsString
//else
// result:='';
end;
function TFRE_DB_ZFS_OBJ.GetIopsRead: TFRE_DB_String;
begin
aborT;
//if FieldExists('zpooliostat') then
// result:=Field('zpooliostat').AsObject.Field('iops_r').AsString
//else
// result:='';
end;
function TFRE_DB_ZFS_OBJ.GetIopsWrite: TFRE_DB_String;
begin
abort;
//if FieldExists('zpooliostat') then
// result:=Field('zpooliostat').AsObject.Field('iops_w').AsString
//else
// result:='';
end;
class procedure TFRE_DB_ZFS_OBJ.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.AddSchemeField('status_mos',fdbft_String);
scheme.AddSchemeField('state',fdbft_String);
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main'));
group.AddInput('objname',GetTranslateableTextKey('scheme_objname'));
end;
class procedure TFRE_DB_ZFS_OBJ.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_objname','Name');
end;
end;
procedure TFRE_DB_ZFS_OBJ.InternalSetup;
begin
inherited InternalSetup;
AttachPlugin(TFRE_DB_ZFSOBJSTATUS_PLUGIN.CreateForDB);
end;
procedure TFRE_DB_ZFS_OBJ.removeFromPool;
begin
DeleteField('ZFSPARENT');
DeleteField('pool_uid');
end;
function TFRE_DB_ZFS_OBJ.hasPool: Boolean;
begin
Result:=GetPoolId<>CFRE_DB_NullGUID;
end;
function TFRE_DB_ZFS_OBJ.getPool(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_POOL;
begin
if hasPool then begin
CheckDbResult(conn.FetchAs(poolId,TFRE_DB_ZFS_POOL,Result),'TFRE_DB_ZFS_OBJ.getPool');
end else begin
Result:=Nil;
end;
end;
function TFRE_DB_ZFS_OBJ.getZFSParent(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_OBJ;
var
zfsParent: IFRE_DB_Object;
begin
conn.Fetch(GetZFSPARENTID,zfsParent);
if Assigned(zfsParent) then begin
Result:=zfsParent.Implementor_HC as TFRE_DB_ZFS_OBJ;
end else begin
Result:=Nil;
end;
end;
function TFRE_DB_ZFS_OBJ.getCaption: TFRE_DB_String;
begin
Result:=Field('objname').AsString;
end;
procedure TFRE_DB_ZFS_OBJ.SetZFSPARENTID(AValue: TFRE_DB_GUID);
begin
Field('ZFSPARENT').AsObjectLink:=AValue;
end;
procedure TFRE_DB_ZFS_OBJ.SetPoolId(AValue: TFRE_DB_GUID);
begin
Field('pool_uid').AsObjectLink:=AValue;
end;
procedure TFRE_DB_ZFS_OBJ.SetMachineID(AValue: TFRE_DB_GUID);
begin
Field('machineid').AsObjectLink := AValue;
end;
function TFRE_DB_ZFS_OBJ.getIOStat: TFRE_DB_IOSTAT;
begin
if FieldExists('iostat') then
result := (Field('iostat').AsObject.Implementor_HC as TFRE_DB_IOSTAT)
else
result := nil;
end;
procedure TFRE_DB_ZFS_OBJ.setIOStat(const Avalue: TFRE_DB_IOSTAT);
begin
Field('iostat').AsObject:=AValue;
end;
function TFRE_DB_ZFS_OBJ.getMachineID: TFRE_DB_GUID;
begin
if (FieldExists('machineid')) and (not Field('machineid').IsEmptyArray) then
result := Field('machineid').AsObjectLink
else
result := CFRE_DB_NullGUID;
end;
function TFRE_DB_ZFS_OBJ.getId: TFRE_DB_String;
begin
Result:=UID_String;
end;
function TFRE_DB_ZFS_OBJ.getZFSChildren(const conn: IFRE_DB_CONNECTION): IFRE_DB_ObjectArray;
var
refs: TFRE_DB_GUIDArray;
obj : IFRE_DB_Object;
i : Integer;
begin
refs:=conn.GetReferences(Self.UID,false,'','ZFSPARENT');
SetLength(Result,Length(refs));
for i := 0 to Length(refs) - 1 do begin
CheckDbResult(conn.Fetch(refs[i],obj),'TFRE_DB_ZFS_OBJ.getChildren');
Result[i]:=obj;
end;
end;
function TFRE_DB_ZFS_OBJ.mayHaveZFSChildren: Boolean;
begin
Result:=false;
end;
function TFRE_DB_ZFS_OBJ.acceptsNewZFSChildren(const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=false;
end;
procedure TFRE_DB_ZFS_OBJ.setZFSGuid(const avalue: String);
begin
Field('zfs_guid').AsString:=avalue;
end;
function TFRE_DB_ZFS_OBJ.canIdentify: Boolean;
begin
Result:=false;
end;
procedure TFRE_DB_ZFS_OBJ.embedChildrenRecursive(const conn: IFRE_DB_CONNECTION; const include_os_blockdevices: boolean);
var
children : IFRE_DB_ObjectArray;
i : NativeInt;
ds_obj : TFRE_DB_ZFS_DATASTORAGE;
s_obj : TFRE_DB_ZFS_SPARE;
l_obj : TFRE_DB_ZFS_LOG;
c_obj : TFRE_DB_ZFS_CACHE;
zfs_obj : TFRE_DB_ZFS_OBJ;
zio_obj : TFRE_DB_ZFS_VDEV_POOL_STATUS;
os_obj : TFRE_DB_ZFS_BLOCKDEVICE;
begin
children := getZFSChildren(conn);
for i:= 0 to high(children) do
begin
// writeln('SWL EMBED :',children[i].SchemeClass);
if children[i].IsA(TFRE_DB_ZFS_DATASTORAGE,ds_obj) then
begin
(self.Implementor_HC as TFRE_DB_ZFS_POOL).addDatastorageEmbedded(ds_obj);
ds_obj.embedChildrenRecursive(conn,include_os_blockdevices);
continue;
end;
if children[i].IsA(TFRE_DB_ZFS_SPARE,s_obj) then
begin
(self.Implementor_HC as TFRE_DB_ZFS_POOL).addSpareEmbedded(s_obj);
s_obj.embedChildrenRecursive(conn,include_os_blockdevices);
continue;
end;
if children[i].IsA(TFRE_DB_ZFS_LOG,l_obj) then
begin
(self.Implementor_HC as TFRE_DB_ZFS_POOL).addLogEmbedded(l_obj);
l_obj.embedChildrenRecursive(conn,include_os_blockdevices);
continue;
end;
if children[i].IsA(TFRE_DB_ZFS_CACHE,c_obj) then
begin
(self.Implementor_HC as TFRE_DB_ZFS_POOL).addCacheEmbedded(c_obj);
c_obj.embedChildrenRecursive(conn,include_os_blockdevices);
continue;
end;
if children[i].IsA(TFRE_DB_ZFS_BLOCKDEVICE,os_obj) then
begin
if include_os_blockdevices then
begin
addChildEmbedded(os_obj);
end
else
begin
// writeln('SWL SKIP :',children[i].SchemeClass);
// do not embed for feeder
end;
continue;
end;
if children[i].IsA(TFRE_DB_ZFS_OBJ,zfs_obj) then
begin
addChildEmbedded(zfs_obj);
zfs_obj.embedChildrenRecursive(conn,include_os_blockdevices);
continue;
end;
raise EFRE_DB_Exception('unhandled class in TFRE_DB_ZFS_OBJ.embedChildrenRecursive '+ children[i].SchemeClass);
end;
//embedZpoolIostat(conn);
end;
procedure TFRE_DB_ZFS_OBJ.addChildEmbedded(const child: TFRE_DB_ZFS_OBJ);
var
fieldname : TFRE_DB_String;
status : TFRE_DB_ZFSOBJSTATUS_PLUGIN;
begin
//child.parentInZFSId:=UID;
//child.poolId:=poolId;
GetPlugin(TFRE_DB_ZFSOBJSTATUS_PLUGIN,status);
if status.isPlanned then
fieldname := child.UID_String { planned pools have no zfs guid, they get fully replaced on creation }
else
fieldname := child.Field('zfs_guid').asstring;
Field(fieldname).AsObject := child;
end;
//procedure TFRE_DB_ZFS_OBJ.embedIostat(const conn: IFRE_DB_Connection);
//var mo : IFRE_DB_Object;
// refs : TFRE_DB_ObjectReferences;
// i : NativeInt;
// obj : IFRE_DB_Object;
// liostat: TFRE_DB_IOSTAT;
//
//begin
// refs := conn.GetReferencesDetailed(UID,false);
// for i:=0 to high(refs) do
// begin
// CheckDbResult(conn.Fetch(refs[i].linked_uid,obj),' could not fetch referencing object '+FREDB_G2H(refs[i].linked_uid));
// if obj.IsA(TFRE_DB_IOSTAT,liostat) then
// begin
// setIOStat(liostat);
// end
// else
// obj.Finalize;
// end;
//end;
//procedure TFRE_DB_ZFS_OBJ.embedZpoolIostat(const conn: IFRE_DB_Connection);
//var refs : TFRE_DB_ObjectReferences;
// i : NativeInt;
// obj : IFRE_DB_Object;
// liostat: TFRE_DB_ZFS_VDEV_STATUS;
//
//begin
// refs := conn.GetReferencesDetailed(UID,false,uppercase(TFRE_DB_ZFS_VDEV_STATUS.ClassName));
// for i:=0 to high(refs) do
// begin
// CheckDbResult(conn.Fetch(refs[i].linked_uid,obj),' could not fetch referencing object '+FREDB_G2H(refs[i].linked_uid));
// if obj.IsA(TFRE_DB_ZFS_VDEV_STATUS,liostat) then
// begin
// setZpoolIoStatEmbedded(liostat);
// end
// else
// obj.Finalize;
// end;
//end;
procedure TFRE_DB_ZFS_OBJ.SetMOSStatus(const status: TFRE_DB_MOS_STATUS_TYPE; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION);
begin
GFRE_MOS_SetMOSStatusandUpdate(self,status,input,ses,app,conn);
end;
function TFRE_DB_ZFS_OBJ.GetMOSStatus: TFRE_DB_MOS_STATUS_TYPE;
begin
Result:=String2DBMOSStatus(Field('status_mos').AsString);
end;
procedure TFRE_DB_ZFS_OBJ.SetName(const avalue: TFRE_DB_String);
begin
field('objname').asstring := avalue;
end;
function TFRE_DB_ZFS_OBJ.WEB_MOSChildStatusChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
SetMOSStatus(GFRE_MOS_MOSChildStatusChanged(UID,input,ses,app,conn),input,ses,app,conn);
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_DB_ZFS_OBJ.WEB_MOSStatus(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=GFRE_DBI.NewObject;
Result.Field('status_mos').AsString:=Field('status_mos').AsString;
end;
{ TFRE_DB_ZFS_CACHE }
function TFRE_DB_ZFS_CACHE.GetRaidLevel: TFRE_DB_ZFS_RAID_LEVEL;
begin
Result:=zfs_rl_stripe;
end;
procedure TFRE_DB_ZFS_CACHE.SetRaidLevel(AValue: TFRE_DB_ZFS_RAID_LEVEL);
begin
if AValue<>zfs_rl_stripe then raise EFOS_ZFS_Exception.Create('A cache container has to be striped.');
inherited SetRaidLevel(AValue);
end;
class procedure TFRE_DB_ZFS_CACHE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_CACHE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
{ TFRE_DB_ZFS_LOG }
class procedure TFRE_DB_ZFS_LOG.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_LOG.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
{ TFRE_DB_ZFS_SPARE }
function TFRE_DB_ZFS_SPARE.GetRaidLevel: TFRE_DB_ZFS_RAID_LEVEL;
begin
Result:=zfs_rl_undefined;
end;
procedure TFRE_DB_ZFS_SPARE.SetRaidLevel(AValue: TFRE_DB_ZFS_RAID_LEVEL);
begin
if AValue<>zfs_rl_undefined then raise EFOS_ZFS_Exception.Create('A spare container does not support a raid level.');
inherited SetRaidLevel(AValue);
end;
class procedure TFRE_DB_ZFS_SPARE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_SPARE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
{ TFRE_DB_ZFS_VDEV_RAIDMIRROR }
function TFRE_DB_ZFS_VDEV_RAIDMIRROR.GetRaidLevel: TFRE_DB_ZFS_RAID_LEVEL;
begin
if FieldExists('raidLevel') then begin
Result:=String2DBZFSRaidLevelType(Field('raidLevel').AsString);
end else begin
Result:=zfs_rl_undefined;
end;
end;
procedure TFRE_DB_ZFS_VDEV_RAIDMIRROR.SetRaidLevel(AValue: TFRE_DB_ZFS_RAID_LEVEL);
begin
if AValue=zfs_rl_stripe then raise EFOS_ZFS_Exception.Create('Raid level stripe is not allowd for a Vdev.');
inherited SetRaidLevel(AValue);
end;
class procedure TFRE_DB_ZFS_VDEV_RAIDMIRROR.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_ZFS_VDEV_RAIDMIRROR.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
function TFRE_DB_ZFS_VDEV_RAIDMIRROR.acceptsNewZFSChildren(const conn: IFRE_DB_CONNECTION): Boolean;
var
zfsParent: TFRE_DB_ZFS_OBJ;
status : TFRE_DB_ZFSOBJSTATUS_PLUGIN;
begin
zfsParent:=getZFSParent(conn);
GetPlugin(TFRE_DB_ZFSOBJSTATUS_PLUGIN,status);
if status.isPlanned or (Assigned(zfsParent) and (zfsParent.Implementor_HC is TFRE_DB_ZFS_LOG)) then begin
Result:=true;
end else begin
Result:=false;
end;
end;
class procedure TFRE_DB_ZFS_VDEV_RAIDMIRROR.STAT_TRANSFORM(const transformed_output: IFRE_DB_Object; const stat_data: IFRE_DB_Object; const statfieldname: TFRE_DB_Nametype);
begin
if assigned(stat_data) then
transformed_output.Field(statfieldname).AsString := stat_data.Field('STATE').AsString;
end;
{ TFRE_DB_ZFS_BLOCKDEVICE }
function TFRE_DB_ZFS_BLOCKDEVICE.getDeviceName: TFRE_DB_String;
begin
result := Field('devicename').AsString;
end;
function TFRE_DB_ZFS_BLOCKDEVICE.getIsOffline: Boolean;
begin
Result:=(FieldExists('isOffline') and Field('isOffline').AsBoolean);
end;
function TFRE_DB_ZFS_BLOCKDEVICE.getisUnassigned: Boolean;
begin
result:=(FieldExists('isUnassigned') and Field('isUnassigned').AsBoolean);
end;
procedure TFRE_DB_ZFS_BLOCKDEVICE.setDeviceName(AValue: TFRE_DB_String);
begin
Field('devicename').AsString := AValue;
end;
function TFRE_DB_ZFS_BLOCKDEVICE.getDeviceIdentifier: TFRE_DB_String;
begin
result := Field('deviceIdentifier').AsString;
end;
procedure TFRE_DB_ZFS_BLOCKDEVICE.setIsOffline(AValue: Boolean);
begin
Field('isOffline').AsBoolean:=AValue;
end;
procedure TFRE_DB_ZFS_BLOCKDEVICE.setIsUnassgined(AValue: Boolean);
begin
Field('isUnassigned').AsBoolean:=AValue;
end;
function TFRE_DB_ZFS_BLOCKDEVICE.getCaption: TFRE_DB_String;
begin
Result:=Field('devicename').asstring;
end;
procedure TFRE_DB_ZFS_BLOCKDEVICE.setDeviceIdentifier(AValue: TFRE_DB_String);
begin
Field('deviceIdentifier').AsString := AValue;
end;
class procedure TFRE_DB_ZFS_BLOCKDEVICE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName('TFRE_DB_ZFS_OBJ');
scheme.AddSchemeField('machineid',fdbft_String).SetupFieldDef(true);
scheme.AddSchemeField('deviceidentifier',fdbft_String).SetupFieldDef(true);
scheme.AddSchemeField('devicename',fdbft_String).SetupFieldDef(true);
end;
class procedure TFRE_DB_ZFS_BLOCKDEVICE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_state','State');
end;
end;
class function TFRE_DB_ZFS_BLOCKDEVICE.GetMachineDeviceIdentifier(const vmachine_uid: TFRE_DB_GUID; const vdeviceIdentifier: TFRE_DB_String): TFRE_DB_String;
begin
result := FREDB_G2H(vmachine_uid)+'_'+uppercase(vDeviceIdentifier);
end;
class function TFRE_DB_ZFS_BLOCKDEVICE.GetMachineDeviceName(const vmachine_uid: TFRE_DB_GUID; const vdeviceName: TFRE_DB_String): TFRE_DB_String;
begin
result := FREDB_G2H(vmachine_uid)+'_'+uppercase(vdeviceName);
end;
function TFRE_DB_ZFS_BLOCKDEVICE.mayHaveZFSChildren: Boolean;
begin
//Result:=false;
Result:=true;
end;
function TFRE_DB_ZFS_BLOCKDEVICE.canIdentify: Boolean;
begin
Result:=true;
end;
class procedure TFRE_DB_ZFS_BLOCKDEVICE.STAT_TRANSFORM(const transformed_output: IFRE_DB_Object; const stat_data: IFRE_DB_Object; const statfieldname: TFRE_DB_Nametype);
begin
if assigned(stat_data) then
transformed_output.Field(statfieldname).AsString := stat_data.Field('STATE').AsString;
end;
{ TFRE_DB_ZFS_POOL }
function TFRE_DB_ZFS_POOL.GetDatastorage(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASTORAGE;
var
i : Integer;
children: IFRE_DB_ObjectArray;
begin
Result:=nil;
children:=getZFSChildren(conn);
for i := 0 to High(children) do begin
if children[i].Implementor_HC is TFRE_DB_ZFS_DATASTORAGE then begin
Result:=children[i].Implementor_HC as TFRE_DB_ZFS_DATASTORAGE;
break;
end;
end;
end;
function TFRE_DB_ZFS_POOL.GetDatastorageEmbedded: TFRE_DB_ZFS_DATASTORAGE;
begin
if FieldExists('datastorage') then begin
result := Field('datastorage').asObject.Implementor_HC as TFRE_DB_ZFS_DATASTORAGE;
end else begin
Result := Nil;
end;
end;
function TFRE_DB_ZFS_POOL.GetSpare(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_SPARE;
var
i : Integer;
children: IFRE_DB_ObjectArray;
begin
Result:=nil;
children:=getZFSChildren(conn);
for i := 0 to High(children) do begin
if children[i].Implementor_HC is TFRE_DB_ZFS_SPARE then begin
Result:=children[i].Implementor_HC as TFRE_DB_ZFS_SPARE;
break;
end;
end;
end;
function TFRE_DB_ZFS_POOL.GetSpareEmbedded(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_SPARE;
begin
if FieldExists('spares') then begin
result := Field('spares').asObject.Implementor_HC as TFRE_DB_ZFS_SPARE;
end else begin
Result := Nil;
end;
end;
function TFRE_DB_ZFS_POOL.GetCache(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_CACHE;
var
i : Integer;
children: IFRE_DB_ObjectArray;
begin
Result:=nil;
children:=getZFSChildren(conn);
for i := 0 to High(children) do begin
if children[i].Implementor_HC is TFRE_DB_ZFS_CACHE then begin
Result:=children[i].Implementor_HC as TFRE_DB_ZFS_CACHE;
break;
end;
end;
end;
function TFRE_DB_ZFS_POOL.GetCacheEmbedded(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_CACHE;
begin
if FieldExists('cache') then begin
result := Field('cache').asObject.Implementor_HC as TFRE_DB_ZFS_CACHE;
end else begin
Result := Nil;
end;
end;
function TFRE_DB_ZFS_POOL.GetLog(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_LOG;
var
i : Integer;
children: IFRE_DB_ObjectArray;
begin
Result:=nil;
children:=getZFSChildren(conn);
for i := 0 to High(children) do begin
if children[i].Implementor_HC is TFRE_DB_ZFS_LOG then begin
Result:=children[i].Implementor_HC as TFRE_DB_ZFS_LOG;
break;
end;
end;
end;
function TFRE_DB_ZFS_POOL.GetLogEmbedded(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_LOG;
begin
if FieldExists('logs') then begin
result := Field('logs').asObject.Implementor_HC as TFRE_DB_ZFS_LOG;
end else begin
Result := Nil;
end;
end;
function TFRE_DB_ZFS_POOL.GetPoolId: TFRE_DB_GUID;
begin
Result:=UID;
end;
procedure TFRE_DB_ZFS_POOL.SetPoolId(AValue: TFRE_DB_GUID);
begin
//dont change UID of Pool
end;
class procedure TFRE_DB_ZFS_POOL.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_OBJ.ClassName);
scheme.AddSchemeField('scan',fdbft_String);
scheme.AddSchemeField('errors',fdbft_String);
GFRE_DBI.RegisterSysClientFieldValidator(GFRE_DBI.NewClientFieldValidator('poolname').Setup('[a-z][a-z0-9_:\\-.]*',
GFRE_DBI.CreateText('$validator_poolname','ZFS Pool Validator'),
GetTranslateableTextKey('validator_poolname_help'),
'a-z0-9_:\-.'));
scheme.GetSchemeField('objname').SetupFieldDef(true,false,'','poolname');
group:=scheme.AddInputGroup('zpool').Setup(GetTranslateableTextKey('scheme_zpool'));
group.AddInput('objname',GetTranslateableTextKey('scheme_pool'));
group.AddInput('scan',GetTranslateableTextKey('scheme_scan'));
group.AddInput('errors',GetTranslateableTextKey('scheme_errors'));
end;
class procedure TFRE_DB_ZFS_POOL.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','General Information');
StoreTranslateableText(conn,'scheme_objname','Pool name');
StoreTranslateableText(conn,'scheme_zpool','General Information');
StoreTranslateableText(conn,'scheme_pool','Pool name');
StoreTranslateableText(conn,'scheme_scan','Scan');
StoreTranslateableText(conn,'scheme_errors','Errors');
StoreTranslateableText(conn,'pool_content_header','Pool Information');
StoreTranslateableText(conn,'validator_poolname_help','[a-z0-9_-:.] starting with a letter');
end;
end;
class function TFRE_DB_ZFS_POOL.getFieldsIgnoredBySync: TFRE_DB_NameTypeArray;
begin
Result:=TFRE_DB_NameTypeArray.create('POOL_UID','ZFSPARENT','VDEV_POOL_STATE','SERVICEPARENT');
end;
//procedure TFRE_DB_ZFS_POOL._getMOSCaption(const calcfieldsetter: IFRE_DB_CALCFIELD_SETTER);
//begin
// calcfieldsetter.SetAsString('Zpool '+caption+' '+Field('state').asstring);
//end;
class function TFRE_DB_ZFS_POOL.CreateEmbeddedPoolObjectfromDB(const conn: IFRE_DB_CONNECTION; const db_zfs_pool_id: TFRE_DB_GUID; const include_os_blockdevices: boolean): TFRE_DB_ZFS_POOL;
var
obj : IFRE_DB_Object;
pool : TFRE_DB_ZFS_POOL;
begin
CheckDbResult(conn.Fetch(db_zfs_pool_id,obj),'Could not find pool for CreateEmbeddedPoolObjectfromDB');
pool := (obj.Implementor_HC as TFRE_DB_ZFS_POOL);
pool.embedChildrenRecursive(conn,include_os_blockdevices);
result := pool;
end;
class function TFRE_DB_ZFS_POOL.CreateEmbeddedZFSDatasets(const conn: IFRE_DB_CONNECTION; const db_zfs_pool_id: TFRE_DB_GUID): TFRE_DB_ZFS_POOL;
var
obj : IFRE_DB_Object;
pool : TFRE_DB_ZFS_POOL;
begin
CheckDbResult(conn.Fetch(db_zfs_pool_id,obj),'Could not find pool for CreateEmbeddedPoolObjectfromDB');
obj.AsClass(TFRE_DB_ZFS_POOL,pool);
pool.ClearAllFieldsExcept(['UCT','OBJNAME',cFRE_DB_SYS_PLUGIN_CONTAINER]); { needed to match new datasets into the pool }
pool.embedZFSDatasetsRec(conn);
result := pool;
end;
procedure TFRE_DB_ZFS_POOL.InternalSetup;
begin
AttachPlugin(TFRE_DB_POOLSTATUS_PLUGIN.CreateForDB);
end;
function TFRE_DB_ZFS_POOL.mayHaveZFSChildren: Boolean;
begin
Result:=true;
end;
function TFRE_DB_ZFS_POOL.acceptsNewZFSChildren(const conn: IFRE_DB_CONNECTION): Boolean;
begin
Result:=true;
end;
function TFRE_DB_ZFS_POOL.getPool(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_POOL;
begin
Result:=Self;
end;
function TFRE_DB_ZFS_POOL.getPoolName: TFRE_DB_String;
begin
Result:=getCaption;
end;
function TFRE_DB_ZFS_POOL.createDatastorage: TFRE_DB_ZFS_DATASTORAGE;
begin
Result:=TFRE_DB_ZFS_DATASTORAGE.CreateForDB;
Result.poolId:=UID;
Result.SetZFSPARENTID(UID);
end;
function TFRE_DB_ZFS_POOL.createDatastorageEmbedded: TFRE_DB_ZFS_DATASTORAGE;
begin
Result:=TFRE_DB_ZFS_DATASTORAGE.CreateForDB;
Field('datastorage').asObject := Result;
end;
procedure TFRE_DB_ZFS_POOL.addDataStorageEmbedded(const ds: TFRE_DB_ZFS_DATASTORAGE);
begin
Field('datastorage').asObject := ds;
end;
function TFRE_DB_ZFS_POOL.createCache: TFRE_DB_ZFS_CACHE;
begin
Result:=TFRE_DB_ZFS_CACHE.CreateForDB;
Result.poolId:=UID;
Result.SetZFSPARENTID(UID);
end;
function TFRE_DB_ZFS_POOL.createCacheEmbedded: TFRE_DB_ZFS_CACHE;
begin
Result:=TFRE_DB_ZFS_CACHE.CreateForDB;
Field('cache').asObject := Result;
Result.SetupNameUCTTagsPlugins('cache',getZFSGuid);
end;
procedure TFRE_DB_ZFS_POOL.addCacheEmbedded(const ds: TFRE_DB_ZFS_CACHE);
begin
//ds.poolId:=UID;
//ds.parentInZFSId:=UID;
Field('cache').asObject := ds;
end;
function TFRE_DB_ZFS_POOL.createLog: TFRE_DB_ZFS_LOG;
begin
Result:=TFRE_DB_ZFS_LOG.CreateForDB;
Result.poolId:=UID;
Result.SetZFSPARENTID(UID);
end;
function TFRE_DB_ZFS_POOL.createLogEmbedded: TFRE_DB_ZFS_LOG;
var plugin : TFRE_DB_ZFSOBJSTATUS_PLUGIN;
begin
Result:=TFRE_DB_ZFS_LOG.CreateForDB;
//Result.parentInZFSId:=UID;
result.SetupNameUCTTagsPlugins('logs',getZFSGuid);
//result.setZFSGuid('LOG'+getZFSGuid);
//result.setname('logs');
//result.Field('UCT').AsString:='LOG_'+getZFSGuid;
//result.GetPlugin(TFRE_DB_ZFSOBJSTATUS_PLUGIN,plugin);
//Result.SetPluginContainerTag('PLG_CT_LOG'+getZFSGuid);
//plugin.Field('UCT').AsString:='PLOG_'+getZFSGuid;
//plugin.SetNew(false);
//plugin.SetModified(false);
Field('logs').asObject := Result;
end;
procedure TFRE_DB_ZFS_POOL.addLogEmbedded(const ds: TFRE_DB_ZFS_LOG);
begin
//ds.poolId:=UID;
//ds.parentInZFSId:=UID;
Field('logs').asObject := ds;
end;
function TFRE_DB_ZFS_POOL.createSpare: TFRE_DB_ZFS_SPARE;
var
coll: IFRE_DB_COLLECTION;
begin
Result:=TFRE_DB_ZFS_SPARE.CreateForDB;
Result.poolId:=UID;
Result.SetZFSPARENTID(UID);
end;
function TFRE_DB_ZFS_POOL.createSpareEmbedded: TFRE_DB_ZFS_SPARE;
begin
Result:=TFRE_DB_ZFS_SPARE.CreateForDB;
//Result.poolId:=UID;
//Result.parentInZFSId:=UID;
Field('spares').asobject := Result;
Result.SetupNameUCTTagsPlugins('spares',getZFSGuid);
end;
procedure TFRE_DB_ZFS_POOL.addSpareEmbedded(const ds: TFRE_DB_ZFS_SPARE);
begin
//ds.poolId:=UID;
//ds.parentInZFSId:=UID;
Field('spares').asObject := ds;
end;
procedure TFRE_DB_ZFS_POOL.SetForceMode(const force: boolean);
begin
Field('FORCE').AsBoolean:=force;
end;
function TFRE_DB_ZFS_POOL.CheckPoolConfigStatus(out error: string): Boolean;
begin
error := ''; { FIXXME Check Pool validity }
result := true;
end;
procedure TFRE_DB_ZFS_POOL.CreatePhysicalPool;
var
zfs : TFRE_DB_ZFS;
os,es,zfscmd : string;
res : integer;
begin
{$IFDEF SOLARIS}
res := zfs.CreateDiskPool(self,os,es,zfscmd);
if res<>0 then
raise EFRE_DB_Exception.Create(edb_ERROR,'zpool create failed: '+es);
{$ENDIF}
end;
function TFRE_DB_ZFS_POOL.getRootDataset(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASET;
var
refs: IFRE_DB_ObjectArray;
begin
Result:=nil;
conn.FetchExpandReferences([Self.UID],['TFRE_DB_ZFS_DATASET<SERVICEPARENT'],refs);
if Length(refs)>0 then begin
refs[0].AsClass(TFRE_DB_ZFS_DATASET,Result);
end;
end;
procedure TFRE_DB_ZFS_POOL.embedZFSDatasetsRec(const conn: IFRE_DB_CONNECTION);
var
refs : IFRE_DB_ObjectArray;
i : Integer;
ds : TFRE_DB_ZFS_DATASET;
uctfld : IFRE_DB_Field;
begin
conn.FetchExpandReferences([Self.UID],['<SERVICEPARENT'],refs);
for i := 0 to Length(refs) - 1 do begin
if refs[i].IsA(TFRE_DB_ZFS_DATASET,ds) then
begin
Field(ds.GetUCTHashed).AsObject := ds;
ds.embedZFSDatasetsRec(conn);
end
else
begin
writeln('Not a Dataset obj : ',refs[i].DumpToString());
refs[i].Finalize;
refs[i]:=Nil;
end;
end;
end;
procedure TFRE_DB_ZFS_POOL.SetPoolUCTTags(out status: TFRE_DB_POOLSTATUS_PLUGIN);
var uctval : shortstring;
begin
uctval := 'P_'+Field('objname').AsString+'@'+MachineID.AsHexString;
Field('UCT').AsString := uctval;
uctval := GFRE_BT.HashFast32_Hex(uctval);
{
FIXXME : REMOVE Subtags should be set generic
}
GetPlugin(TFRE_DB_POOLSTATUS_PLUGIN,status);
//SetPluginContainerTag('PLG_CT_P_'+uctval);
//status.Field('UCT').AsString := 'ZPP_'+uctval;
end;
class function TFRE_DB_ZFS_POOL.Build_UCT_TAG(const name: TFRE_DB_String; const machine_id: TFRE_DB_GUID): TFRE_DB_String;
begin
result := 'P_'+name + '@' + machine_id.AsHexString;
end;
procedure TFRE_DB_ZFS_POOL.SetSystemSoftwareVersion(const version: string);
begin
Field('ecf_sys_soft').AsString:=version;
end;
function TFRE_DB_ZFS_POOL.WEB_MOSContent(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
panel : TFRE_DB_FORM_PANEL_DESC;
scheme : IFRE_DB_SchemeObject;
begin
GFRE_DBI.GetSystemSchemeByName(SchemeClass,scheme);
panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(GetTranslateableTextShort(conn,'pool_content_header'),true,false);
panel.AddSchemeFormGroup(scheme.GetInputGroup('zpool'),ses);
panel.FillWithObjectValues(self,ses);
Result:=panel;
end;
function TFRE_DB_ZFS_POOL.WEB_ZFSContent(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=TFRE_DB_HTML_DESC.create.Describe('I am a Pool');//FIXXME: deliver real content here
end;
class procedure TFRE_DB_ZFS_POOL.STAT_TRANSFORM(const transformed_output: IFRE_DB_Object; const stat_data: IFRE_DB_Object; const statfieldname: TFRE_DB_Nametype);
var s : string;
diff : NativeInt;
begin
if assigned(stat_data) then
begin
s := stat_data.Field('STATE').AsString;
if stat_data.Field('PSS_FUNC').asstring='POOL_SCAN_SCRUB' then
begin
stat_data.Field('PSS_SCRUBPERCENT').asreal32 := stat_data.Field('PSS_EXAMINED').AsUInt64/stat_data.Field('PSS_TO_EXAMINE').AsUInt64*100;
diff:=(GFRE_DT.Now_UTC-stat_data.field('PSS_START_TIME').AsDateTimeUTC) div 1000;
writeln('SWL TIMEDIFF',diff);
stat_data.Field('PSS_SCRUBRATE').asUint64 := stat_data.Field('PSS_EXAMINED').AsUInt64 div diff;
stat_data.Field('PSS_SCRUBTOGO').asUint64 := (stat_data.Field('PSS_TO_EXAMINE').AsUInt64-stat_data.Field('PSS_EXAMINED').AsUInt64) div stat_data.Field('PSS_SCRUBRATE').asUint64;
if stat_data.Field('PSS_STATE').AsString = 'DSS_FINISHED' then
begin
s:=s+', last scrub of '+GFRE_BT.ByteToString(stat_data.Field('PSS_TO_EXAMINE').AsUInt64)+' finished on '+stat_data.Field('PSS_END_TIME').AsString;
end
else
begin
s:=s+', scrubbing '+GFRE_BT.ByteToString(stat_data.Field('PSS_EXAMINED').AsUInt64)+ ' of '+GFRE_BT.ByteToString(stat_data.Field('PSS_TO_EXAMINE').AsUInt64)+' scanned, '+FloatToStrF(stat_data.Field('PSS_SCRUBPERCENT').asreal32,ffFixed,5,3)+'% done. Rate '+GFRE_BT.ByteToString(stat_data.Field('PSS_SCRUBRATE').AsUInt64)+'/s';
end;
end;
// 518G scanned out of 9,75T at 561M/s, 4h47m to go
// 0 repaired, 5,19% done
//stat_data.Field('PSS_STATETEXT').asstring := s;
//writeln('SENDSTAT zpool iostat for id:',new_obj.UID_String,' ',zpool_iostat.DumpToString());
transformed_output.Field(statfieldname).AsString := s;
end;
end;
function TFRE_DB_ZFS_POOL.RIF_CreatePool(const runnning_ctx: TObject): TFRE_DB_RIF_RESULT;
var
zfs: TFRE_DB_ZFS;
begin
{$IFDEF SOLARIS}
abort;
//result := TFRE_DB_RIF_RESULT.CreateForDB;
//writeln('RIF_Create Pool : EMBEDDED POOL DEFINITION--');
//writeln(DumpToString());
//result.Field('RES').AsString:='SENT';
//zfs := TFRE_DB_ZFS.create;
//try
// writeln('RUNNING CTX ',runnning_ctx.ClassName);
// zfs.CreateDiskPool(self,result);
//finally
// zfs.Free;
//end;
{$ENDIF}
//
end;
function TFRE_DB_ZFS_POOL.RIF_CreatePoolInstall(const runnning_ctx: TObject): IFRE_DB_Object;
begin
end;
function TFRE_DB_ZFS_POOL.RIF_DestroyPool(const runnning_ctx: TObject): IFRE_DB_Object;
begin
end;
function TFRE_DB_ZFS_POOL.RIF_ExportPool(const runnning_ctx: TObject): IFRE_DB_Object;
begin
end;
function TFRE_DB_ZFS_POOL.RIF_ExtendPool(const runnning_ctx: TObject): IFRE_DB_Object;
begin
end;
{ TFRE_DB_ZFSJob }
procedure TFRE_DB_ZFSJob._SSHSnapShotReplicate(const do_replicate: boolean);
var res : integer;
error : string;
exists : boolean;
snapshotname : string;
snapshotkey : string;
incrementalsnapshotname : string;
source_ts : TFRE_DB_DateTime64;
destination_ts : TFRE_DB_DateTime64;
function SourceZFS : TFRE_DB_ZFS;
begin
result := TFRE_DB_ZFS.Create;
if Field('remotehost').AsString<>'' then begin
result.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
end;
end;
function DestinationZFS : TFRE_DB_ZFS;
begin
result := TFRE_DB_ZFS.Create;
result.SetRemoteSSH(JobConfig.Field('destinationuser').AsString,JobConfig.Field('destinationhost').AsString, JobConfig.Field('destinationkeyfilename').AsString, JobConfig.Field('destinationport').AsInt32);
end;
function ResultCheck(const msg: string):boolean;
begin
result := false;
if res<>0 then begin
SetStatus(statusFailure,msg+':'+error);
result := true;
end;
end;
begin
snapshotkey := JobConfig.Field('snapshotkey').AsString;
res := SourceZFS.GetLastSnapShot(JobConfig.Field('sourcedataset').AsString, snapshotkey, snapshotname,source_ts,error);
if res = 0 then begin
snapshotname := GFRE_BT.SepRight(snapshotname,'-');
snapshotname := snapshotkey+'-'+inttostr(strtoint(snapshotname)+1);
end else begin
snapshotname := snapshotkey+'-'+'1';
end;
res := SourceZFS.CreateSnapShot(JobConfig.Field('sourcedataset').AsString,snapshotname,error);
if ResultCheck('CAN NOT CREATE SOURCE SNAPSHOT') then exit;
res := SourceZFS.SnapShotExists(JobConfig.Field('sourcedataset').AsString,snapshotname,source_ts,error,exists); // Check if source snapshot exists, get source_ts
if ResultCheck('CAN NOT GET SOURCE SNAPSHOT CREATION TIME') then exit;
if do_replicate then begin
res := DestinationZFS.DataSetExists(JobConfig.Field('destinationdataset').AsString,error,exists,true); // Check if destination dataset exists
if ResultCheck('CAN NOT CHECK IF DESTINATION DATASET EXISTS') then exit;
if not exists then begin
incrementalsnapshotname := '';
end else begin
// ICECREMENTAL :-)
writeln('NOW INCREMENTAL');
res := DestinationZFS.GetLastSnapShot(JobConfig.Field('destinationdataset').AsString,'',incrementalsnapshotname,destination_ts,error,true);
if ResultCheck('CAN NOT GET LAST SNAPSHOT FOR DESTINATION DATASET') then exit;
writeln(incrementalsnapshotname);
end;
res := SourceZFS.SendSnapshot(JobConfig.Field('sourcedataset').AsString,snapshotname,JobConfig.Field('destinationhost').AsString,JobConfig.Field('destinationuser').AsString,JobConfig.Field('destinationdataset').AsString,JobConfig.Field('replicationkeyfilename').AsString, error, incrementalsnapshotname, zfsSendReplicated,true,JobConfig.Field('replicationport').asint32,true); // Send Snapshotname to Destination
if ResultCheck('ERROR ON SENDING SNAPSHOT') then exit;
writeln(error);
if error<>'' then begin // Result was OK, write Warning
SetStatus(statusWarning,'WARNING ON ZFS SEND/RECEIVE');
GetReport.Field('STATUSDETAIL').asstring := error;
end;
res := DestinationZFS.SnapShotExists(JobConfig.Field('destinationdataset').AsString,snapshotname,destination_ts,error,exists,true); // Check if destination snapshot exists
if ResultCheck('CAN NOT CHECK IF DESTINATION SNAPSHOT EXISTS AFTER RECEIVE') then exit;
if exists then begin
if source_ts=destination_ts then begin // Check matching timestamp
SetStatus(statusOK, 'REPLICATION OF SNAPSHOT '+snapshotname+ ' SUCCESSFUL');
end else begin
SetStatus(statusFailure, 'CREATION TIME OF SNAPSHOTS '+snapshotname+' NOT IDENTICAL SOURCE:'+ GFRE_DT.ToStrFOS(source_ts)+' DESTINATION:'+GFRE_DT.ToStrFOS(destination_ts));
end;
end;
end else begin
SetStatus(statusOK, 'CREATION OF SNAPSHOT '+snapshotname+ ' SUCCESSFUL');
end;
end;
procedure TFRE_DB_ZFSJob._TCPSnapShotReplicate(const do_replicate: boolean);
var res : integer;
error : string;
exists : boolean;
snapshotname : string;
snapshotkey : string;
incrementalsnapshotname : string;
source_ts : TFRE_DB_DateTime64;
destination_ts : TFRE_DB_DateTime64;
function SourceZFS : TFRE_DB_ZFS;
begin
result := TFRE_DB_ZFS.Create;
if Field('remotehost').AsString<>'' then begin
result.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
end;
end;
function DestinationZFS : TFRE_DB_ZFS;
begin
result := TFRE_DB_ZFS.Create;
end;
function ResultCheck(const msg: string):boolean;
begin
result := false;
if res<>0 then begin
// SetStatus(statusFailure,msg+':'+error);
AddProgressLog('FAIL',msg+' '+error);
result := true;
end;
end;
begin
snapshotkey := JobConfig.Field('snapshotkey').AsString;
res := SourceZFS.GetLastSnapShot(JobConfig.Field('sourcedataset').AsString, snapshotkey, snapshotname,source_ts,error);
if res = 0 then begin
snapshotname := GFRE_BT.SepRight(snapshotname,'-');
snapshotname := snapshotkey+'-'+inttostr(strtoint(snapshotname)+1);
end else begin
snapshotname := snapshotkey+'-'+'1';
end;
res := SourceZFS.CreateSnapShot(JobConfig.Field('sourcedataset').AsString,snapshotname,error);
if ResultCheck('CAN NOT CREATE SOURCE SNAPSHOT') then exit;
res := SourceZFS.SnapShotExists(JobConfig.Field('sourcedataset').AsString,snapshotname,source_ts,error,exists); // Check if source snapshot exists, get source_ts
if ResultCheck('CAN NOT GET SOURCE SNAPSHOT CREATION TIME') then exit;
if do_replicate then begin
res := DestinationZFS.TCPDataSetExists(JobConfig.Field('destinationdataset').AsString,error,exists,JobConfig.Field('destinationhost').AsString,JobConfig.Field('destinationport').AsInt32); // Check if destination dataset exists
if ResultCheck('CAN NOT CHECK IF DESTINATION DATASET EXISTS') then exit;
if not exists then begin
incrementalsnapshotname := '';
end else begin
// ICECREMENTAL :-)
res := DestinationZFS.TCPGetLastSnapShot(JobConfig.Field('destinationdataset').AsString,'',incrementalsnapshotname,destination_ts,error,JobConfig.Field('destinationhost').AsString,JobConfig.Field('destinationport').AsInt32);
if ResultCheck('CAN NOT GET LAST SNAPSHOT FOR DESTINATION DATASET') then exit;
writeln(incrementalsnapshotname);
end;
res := SourceZFS.TCPSendSnapshot(JobConfig.Field('sourcedataset').AsString,snapshotname,JobConfig.Field('destinationhost').AsString,JobConfig.Field('destinationport').AsInt32,JobConfig.Field('destinationdataset').AsString, error, incrementalsnapshotname, zfsSendReplicated,false,JobConfig.Field('jobid').asstring); // Send Snapshotname to Destination
if ResultCheck('ERROR ON SENDING SNAPSHOT') then exit;
writeln(error);
if error<>'' then begin // Result was OK, write Warning
SetStatus(statusWarning,'WARNING ON ZFS SEND/RECEIVE');
getreport.Field('STATUSDETAIL').asstring := error;
end;
res := DestinationZFS.TCPSnapShotExists(JobConfig.Field('destinationdataset').AsString,snapshotname,destination_ts,error,exists,JobConfig.Field('destinationhost').AsString,JobConfig.Field('destinationport').AsInt32); // Check if destination snapshot exists
if ResultCheck('CAN NOT CHECK IF DESTINATION SNAPSHOT EXISTS AFTER RECEIVE') then exit;
if exists then begin
if source_ts=destination_ts then begin // Check matching timestamp
SetStatus(statusOK, 'REPLICATION OF SNAPSHOT '+snapshotname+ ' SUCCESSFUL');
end else begin
SetStatus(statusFailure, 'CREATION TIME OF SNAPSHOTS '+snapshotname+' NOT IDENTICAL SOURCE:'+ GFRE_DT.ToStrFOS(source_ts)+' DESTINATION:'+GFRE_DT.ToStrFOS(destination_ts));
end;
end;
end else begin
SetStatus(statusOK, 'CREATION OF SNAPSHOT '+snapshotname+ ' SUCCESSFUL');
end;
end;
procedure TFRE_DB_ZFSJob._SnapShotCheck;
var
zfs : TFRE_DB_ZFS;
res : integer;
snapshotname : string;
creation_ts : TFRE_DB_DateTime64;
error : string;
dt : TFRE_DB_DateTime64;
diffs : integer;
begin
zfs := TFRE_DB_ZFS.CreateForDB;
zfs.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
res := zfs.GetLastSnapShot(JobConfig.Field('dataset').AsString,JobConfig.Field('snapshotkey').AsString,snapshotname,creation_ts,error);
if res<>0 then begin
SetStatus(statusFailure,'NO SNAPSHOT FOUND FOR DATASET '+JobConfig.Field('dataset').AsString);
getreport.Field('STATUSDETAIL').asstring := error;
end else begin
getreport.Field('SNAPSHOT').asstring := snapshotname;
getreport.Field('CREATION').AsDateTimeUTC := creation_ts;
dt := GFRE_DT.Now_UTC;
diffs := (dt - creation_ts) div 1000;
if diffs < JobConfig.Field('warning_seconds').AsInt32 then begin
SetStatus(statusOK,'SNAPSHOT CHECK OK SECONDS:'+inttostr(diffs));
end else begin
if diffs < JobConfig.Field('error_seconds').AsInt32 then begin
SetStatus(statusWarning,'SNAPSHOT TOO OLD SECONDS:'+inttostr(diffs));
end else begin
SetStatus(statusFailure,'SNAPSHOT TOO OLD SECONDS:'+inttostr(diffs));
end;
end;
end;
end;
procedure TFRE_DB_ZFSJob._PoolStatus;
var zfs : TFRE_DB_ZFS;
res : integer;
error : string;
pool : IFRE_DB_Object;
begin
abort; //rework
//zfs := TFRE_DB_ZFS.CreateForDB;
//zfs.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
//res := zfs.GetPoolStatus(JobConfig.Field('poolname').AsString,error,pool);
//if res<>0 then begin
// SetStatus(statusFailure,'FAILURE ON CHECKING POOL '+JobConfig.Field('poolname').AsString);
// report.Field('STATUSDETAIL').asstring := error;
//end else begin
// _AnalyzePool(zfs.GetProcess(0));
//end;
// writeln(report.DumpToString());
end;
procedure TFRE_DB_ZFSJob._DataSetSpace;
var zfs : TFRE_DB_ZFS;
res : integer;
error : string;
datasetobject : IFRE_DB_Object;
total : UInt64;
percent : double;
percent_b : byte;
begin
zfs := TFRE_DB_ZFS.CreateForDB;
zfs.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
res := zfs.GetDataset(JobConfig.Field('dataset').AsString,error,datasetobject);
// writeln(datasetobject.DumpToString());
if res<>0 then begin
SetStatus(statusFailure,'FAILURE ON GETTING DATASET SPACE '+JobConfig.Field('dataset').AsString);
getreport.Field('STATUSDETAIL').asstring := error;
end else begin
total := datasetobject.Field('avail').AsUInt64+datasetobject.Field('used').AsUInt64;
percent := (datasetobject.Field('used').AsUInt64 / total);
percent_b := round(percent*100);
writeln(percent_b);
if percent_b>JobConfig.Field('error_percent').AsByte then begin
SetStatus(statusFailure,'DATASET SPACE LIMIT '+inttostr(JobConfig.Field('error_percent').AsByte)+'% EXCEEDED :'+inttostr(percent_b)+'%');
end else if percent_b>JobConfig.Field('warning_percent').AsByte then begin
SetStatus(statusWarning,'DATASET SPACE LIMIT '+inttostr(JobConfig.Field('warning_percent').AsByte)+'% WARNING :'+inttostr(percent_b)+'%');
end else begin
SetStatus(statusOK,'DATASET SPACE LIMIT OK :'+inttostr(percent_b)+'%');
end;
getreport.Field('STATUSDETAIL').asstring := 'TOTAL:'+inttostr((total div (1024*1024*1024)))+'GB AVAIL:'+inttostr((datasetobject.Field('avail').AsUInt64 div (1024*1024*1024)))+'GB USED:'+inttostr((datasetobject.Field('used').AsUInt64 div (1024*1024*1024)))+'GB';
end;
end;
procedure TFRE_DB_ZFSJob._AnalyzePool(const proc: IFRE_DB_Object);
var dates : string;
scans : string;
ts : TFRE_DB_DateTime64;
nowt : int64;
daydiff : int64;
i : integer;
pool : IFRE_DB_Object;
report : TFRE_DB_STATUS_PLUGIN;
begin
report := GetReport;
report.CopyField(proc,'exitstatus');
report.CopyField(proc,'errorstring');
pool := proc.Field('pool').asobject;
report.Field('pool').asobject := pool;
report.Field('poolname').asstring := pool.Field('pool').asstring;
if pool.Field('state').asstring<>'ONLINE' then begin
SetStatus(statusFailure, 'POOL '+report.Field('poolname').asstring+' IN STATE '+pool.Field('state').asstring);
end;
if pool.FieldExists('scan') then begin
scans := pool.Field('scan').AsString;
if pos(' on ',scans)>0 then begin
dates := Copy(scans,Pos(' on ',scans)+4,maxint);
// writeln('DATES:',dates);
try
ts := GFRE_DT.FromHttp(dates);
except
ts := 0;
end;
report.Field('scan_ts').AsDateTimeUTC := ts;
nowt := GFRE_DT.Now_UTC;
daydiff:= (((nowt-ts) div 1000) div 86400);
if daydiff < JobConfig.Field('scrub_warning_days').AsInt32 then begin
SetStatus(statusOK, 'LAST SCAN FOR POOL '+report.Field('poolname').asstring+' '+inttostr(daydiff)+' DAYS AGO.');
end else begin
if daydiff < JobConfig.Field('scrub_error_days').AsInt32 then begin
SetStatus(statusWarning, 'LAST SCAN FOR POOL '+report.Field('poolname').asstring+' '+inttostr(daydiff)+' DAYS AGO.');
end else begin
SetStatus(statusFailure, 'LAST SCAN FOR POOL '+report.Field('poolname').asstring+' '+inttostr(daydiff)+' DAYS AGO.');
end;
end;
end else begin
if Pos(' in progress ',scans)>0 then begin
dates := Copy(scans,Pos('since',scans)+6,24);
// writeln('DATES:',dates,'-');
try
ts := GFRE_DT.FromHttp(dates);
except
ts := 0;
end;
report.Field('scan_ts').AsDateTimeUTC := ts;
SetStatus(statusOK, 'SCAN FOR POOL '+report.Field('poolname').asstring+' IN PROGRESS.');
end else begin
SetStatus(statusFailure, 'UNKNOWN SCAN INFORMATION FOR POOL '+report.Field('poolname').asstring);
end;
end;
end else begin
SetStatus(statusFailure, 'NO SCAN INFORMATION FOR POOL '+report.Field('poolname').asstring);
end;
end;
class procedure TFRE_DB_ZFSJob.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
// scheme.SetParentSchemeByName ('TFRE_DB_TESTCASE');
end;
class procedure TFRE_DB_ZFSJob.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
inherited InstallDBObjects(conn, currentVersionId, newVersionId);
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
procedure TFRE_DB_ZFSJob.InternalSetup;
begin
inherited InternalSetup;
Field('MAX_ALLOWED_TIME').AsInt32 := 86400;
end;
procedure TFRE_DB_ZFSJob.ExecuteJob;
var
cmd : string;
zfs : TFRE_DB_ZFS;
errors : string;
procedure SetupZFS;
begin
zfs := TFRE_DB_ZFS.CreateForDB;
zfs.SetRemoteSSH (Field('remoteuser').asstring, Field('remotehost').asstring, Field('remotekeyfilename').asstring);
end;
begin
cmd := JobConfig.Field('cmd').asstring;
case cmd of
'scrub' : begin
SetupZFS;
Field('exitstatus').asint32 := zfs.Scrub(JobConfig.Field('poolname').asstring,errors);
Field('errorstring').asstring := errors;
end;
'sshreplicate': begin
_SSHSnapShotReplicate(true);
end;
'tcpreplicate': begin
_TCPSnapShotReplicate(true);
end;
'snapshot': begin
_SSHSnapShotReplicate(false);
end;
'snapshotcheck': begin
_Snapshotcheck;
end;
'poolstatus': begin
_PoolStatus;
end;
'datasetspace': begin
_DataSetspace;
end
else
raise EFRE_DB_Exception.Create('UNKNOWN ZFS CMD '+cmd);
end;
end;
{ TFRE_DB_ZFS }
procedure TFRE_DB_ZFS.AddParameter(const parameter: string; var params: TFRE_DB_StringArray);
begin
SetLength(params,Length(params)+1);
params[high(params)] := parameter;
end;
procedure TFRE_DB_ZFS.AnalyzeSnapshotsLegacy(const proc_OutputToString: string);
var
slist : TStringList;
props : TFRE_DB_StringArray;
snapo : IFRE_DB_Object;
i : integer;
snapname : string;
begin
slist := TStringList.Create;
try
slist.text := proc_OutputToString;
for i := 0 to slist.count -1 do begin
GFRE_BT.SeperateString(slist[i],#9,props);
snapo := GFRE_DBI.NewObject;
snapname := GFRE_BT.SepRight(props[0],'@');
snapo.Field('name').AsString := snapname;
snapo.Field('creation').AsDateTimeUTC := StrToInt64(props[1])*1000;
snapo.Field('used').AsInt64 := StrToInt64(props[2]);
Field('snapshots').AddObject(snapo);
end;
finally
slist.Free;
end;
end;
//procedure TFRE_DB_ZFS.BuildEmbeddedSnapshotList(const proc_OutputToString: string);
//var
// slist : TStringList;
// props : TFRE_DB_StringArray;
// snapo : TFRE_DB_ZFS_SNAPSHOT;
// i : integer;
// snapname : string;
// creation : TFRE_DB_DateTime64;
// used : Int64;
// referd : Int64;
//begin
// slist := TStringList.Create;
// try
// slist.text := proc_OutputToString;
// for i := 0 to slist.count -1 do begin
// GFRE_BT.SeperateString(slist[i],#9,props);
// snapo := TFRE_DB_ZFS_SNAPSHOT.CreateForDB;
// snapname := GFRE_BT.SepRight(props[0],'@');
// creation := StrToInt64(props[1])*1000;
// used := StrToInt64(props[2]);
// referd := StrToInt64(props[3]);
// snapo.Setup(snapname,creation,used,referd);
// Field('embedded_snapshots').AddObject(snapo);
// end;
// finally
// slist.Free;
// end;
//end;
//procedure TFRE_DB_ZFS.AnalyzeDataSetSpace(const proc: TFRE_DB_Process);
//var slist : TStringList;
// llist : TStringList;
// datasetobject : TFRE_DB_ZFS_DATASET;
//// NAME USED AVAIL REFER
//// zones 3741499296256 178121831936 4795709424
//
//
//begin
// slist := TStringList.Create;
// llist := TStringList.Create;
// try
// slist.text := TFRE_DB_Process (proc.Implementor_HC).OutputToString;
// llist.CommaText:= slist[1];
// datasetobject := TFRE_DB_ZFS_DATASET.Create;
// datasetobject.Field('used').AsUInt64 := StrToInt64(trim(llist[1]));
// datasetobject.Field('avail').AsUInt64:= StrToInt64(trim(llist[2]));
// datasetobject.Field('refer').AsUInt64:= StrToInt64(trim(llist[3]));
// proc.Field('datasetobject').asobject := datasetobject;
// finally
// llist.free;
// slist.Free;
// end;
//end;
//
//procedure TFRE_DB_ZFS.AnalyzePoolList(const proc: TFRE_DB_Process);
//var slist : TStringList;
// llist : TStringList;
// pool : IFRE_DB_Object;
// i : NativeInt;
//begin
// abort;
// slist := TStringList.Create;
// llist := TStringList.Create;
// try
// slist.text := TFRE_DB_Process (proc.Implementor_HC).OutputToString;
// for i:= 1 to slist.count-1 do
// begin
// llist.CommaText:= slist[i];
// pool := GFRE_DBI.NewObject;
// pool.Field('name').AsString := trim(llist[0]);
// pool.Field('zpool_guid').AsString := trim(llist[1]);
// proc.Field('pools').addobject(pool);
// end;
// finally
// llist.free;
// slist.Free;
// end;
//end;
procedure TFRE_DB_ZFS.SetRemoteSSH(const user: string; const host: string; const keyfilename: string; const port: integer);
begin
abort; // rework
end;
function TFRE_DB_ZFS.CreateSnapShot(const dataset: string; const snapshotname: string; out error: string): integer;
//var
// proc : TFRE_DB_Process;
begin
abort;// rework;
//ClearProcess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zfs',TFRE_DB_StringArray.Create('snapshot','-r',dataset+'@'+snapshotname));
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.DataSetExists(const dataset: string; out error: string; out exists: boolean; const foscmdmode: boolean): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//ClearProcess;
//exists := false;
//proc := TFRE_DB_Process.create;
//if foscmdmode=false then begin
// proc.SetupInput('zfs',TFRE_DB_StringArray.Create('list','-H','-o','name',dataset));
//end else begin
// proc.SetupInput('foscmd',TFRE_DB_StringArray.Create('DSEXISTS',dataset));
//end;
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//if result = 0 then begin
// if Pos(dataset,proc.OutputToString)=1 then begin
// exists := true;
// end;
//end else begin
// if Pos('does not exist',proc.ErrorToString)>0 then begin
// result := 0;
// end;
//end;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.TCPDataSetExists(const dataset: string; out error: string; out exists: boolean; const destinationhost: string; const destinationport: integer): integer;
//var
// proc : TFRE_DB_Process;
// ststream : TFRE_DB_Stream;
begin
abort;// rework;
// ClearProcess;
// exists := false;
// ststream := TFRE_DB_Stream.Create;
// ststream.SetFromRawByteString('DSEXISTS%'+dataset+'%0%0'+LineEnding);
// ststream.Position:=0;
// ststream.SaveToFile('teststream');
// proc := TFRE_DB_Process.create;
// try
// proc.SetupInput('nc',TFRE_DB_StringArray.Create(destinationhost,inttostr(destinationport)),ststream);
//// proc.SetupInput('nc',TFRE_DB_StringArray.Create('test'));
// AddProcess(proc);
// ExecuteMulti;
// result := proc.Field('exitstatus').AsInt32;
// if result = 0 then begin
// if Pos(dataset,proc.OutputToString)=1 then begin
// exists := true;
// end;
// end else begin
// exists := false;
// end;
// error := proc.Field('errorstring').AsString;
// finally
// proc.Free;
// end;
end;
function TFRE_DB_ZFS.TCPSendSnapshot(const dataset: string; const snapshotname: string; const destinationhost: string; const destinationport: integer; const destinationdataset: string; out error: string; const incrementalsnapshot: string; const sendmode: TFRE_DB_ZFS_Sendmode; const compressed: boolean;const jobid:string): integer;
//var
// proc : TFRE_DB_Process;
// zcommand : string;
// zparameter : string;
// totalsize : int64;
// sl : TStringList;
// s : string;
begin
abort; // REWORK THIS
//totalsize:=0;
//ClearProcess;
//proc := TFRE_DB_Process.create;
//
//case sendmode of
// zfsSend : ; // no additional options
// zfsSendReplicated : zparameter := '-R ';
// zfsSendRecursive : zparameter := '-r ';
// zfsSendRecursiveProperties : zparameter := '-r -p ';
// else
// raise EFOS_ZFS_Exception.Create('INVALID ZFS SEND MODE');
//end;
//if length(incrementalsnapshot)>0 then begin
// zparameter := zparameter+'-I '+dataset+'@'+incrementalsnapshot+' ';
//end;
//zparameter := zparameter +dataset+'@'+snapshotname;
//
//// get totalsize
//zcommand := 'zfs send -n -P '+zparameter;
//proc.SetupInput(zcommand,nil);
//writeln('SWL:',zcommand);
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//if result<>0 then
// begin
// error := proc.ErrorToString;
// halt(result);
// end
//else
// begin
// sl:=TstringList.Create;
// try
// sl.Text:=proc.ErrorToString; //output is in error
// s:=sl[sl.count-1];
// if Pos('size',s)=1 then
// begin
// s:=trim(GFRE_BT.SepRight(s,#9));
// totalsize:=strtointdef(s,-1);
// writeln('SWL: TOTAL',totalsize);
// end;
// finally
// sl.free;
// end;
// end;
//
//ClearProcess;
//proc := TFRE_DB_Process.create;
//
//zcommand := cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'bin'+DirectorySeparator+CFRE_FOSCMD;
//if compressed then
// zcommand := zcommand +' SENDBZ '
//else
// zcommand := zcommand +' SEND ';
//if Field ('remotehost').AsString<>'' then
// zcommand := zcommand +'"'''+destinationhost+'*'+inttostr(destinationport)+'*'+zparameter+'*'+destinationdataset+''' '+jobid+' '+inttostr(totalsize)+'"'
//else
// zcommand := zcommand +'"'+destinationhost+'*'+inttostr(destinationport)+'*'+zparameter+'*'+destinationdataset+'" '+jobid+' '+inttostr(totalsize);
//
//writeln('SWL:',zcommand);
//proc.SetupInput(zcommand,nil);
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.OutputToString;
end;
function TFRE_DB_ZFS.SnapShotExists(const dataset: string; const snapshotname: string; out creation_ts: TFRE_DB_DateTime64; out error: string; out exists: boolean; const foscmdmode: boolean): integer;
//var
// isnap : integer;
// proc : TFRE_DB_Process;
// snapo : IFRE_DB_Object;
begin
abort; // REWORK THIS
// exists := false;
// creation_ts := 0;
// GetSnapshots(dataset,foscmdmode);
// proc := GetProcess(0);
// if FieldExists('snapshots') then begin
// for isnap := 0 to Field('snapshots').ValueCount-1 do begin
// snapo := Field('snapshots').AsObjectItem[isnap];
// if snapo.Field('name').asstring = snapshotname then begin
// creation_ts := snapo.Field('creation').AsDateTimeUTC;
// exists := true;
// break;
// end;
// end;
// end;
//// writeln('Exitstatus:',proc.ExitStatus);
// result := proc.ExitStatus;
// error := proc.ErrorToString;
end;
function TFRE_DB_ZFS.TCPSnapShotExists(const dataset: string; const snapshotname: string; out creation_ts: TFRE_DB_DateTime64; out error: string; out exists: boolean; const destinationhost: string; const destinationport: integer): integer;
//var
// isnap : integer;
// proc : TFRE_DB_Process;
// snapo : IFRE_DB_Object;
begin
abort; // REWORK THIS
// exists := false;
// creation_ts := 0;
// TCPGetSnapshots(dataset,destinationhost,destinationport);
// proc := GetProcess(0);
// if FieldExists('snapshots') then begin
// for isnap := 0 to Field('snapshots').ValueCount-1 do begin
// snapo := Field('snapshots').AsObjectItem[isnap];
// if snapo.Field('name').asstring = snapshotname then begin
// creation_ts := snapo.Field('creation').AsDateTimeUTC;
// exists := true;
// break;
// end;
// end;
// end;
//// writeln('Exitstatus:',proc.ExitStatus);
// result := proc.ExitStatus;
// error := proc.ErrorToString;
end;
function TFRE_DB_ZFS.GetLastSnapShot(const dataset: string; const snapshotkey: string; out snapshotname: string; out creation_ts: TFRE_DB_DateTime64; out error: string; const foscmdmode: boolean): integer;
//var
// isnap : integer;
// proc : TFRE_DB_Process;
// snapo : IFRE_DB_Object;
begin
abort; // REWORK THIS
//GetSnapshots(dataset,foscmdmode);
//creation_ts := 0;
//snapshotname := '';
//proc := GetProcess(0);
//result := proc.ExitStatus;
//error := proc.ErrorToString;
//if FieldExists('snapshots') then begin
// for isnap := Field('snapshots').ValueCount-1 downto 0 do begin
// snapo := Field('snapshots').AsObjectItem[isnap];
// if (snapshotkey='') or (Pos(snapshotkey,snapo.Field('name').asstring)=1) then begin
// snapshotname := snapo.Field('name').asstring;
// creation_ts := snapo.Field('creation').AsDateTimeUTC;
// exit;
// end;
// end;
//end;
//// not found
//result := -1;
end;
function TFRE_DB_ZFS.TCPGetLastSnapShot(const dataset: string; const snapshotkey: string; out snapshotname: string; out creation_ts: TFRE_DB_DateTime64; out error: string; const destinationhost: string; const destinationport: integer): integer;
//var
// isnap : integer;
// proc : TFRE_DB_Process;
// snapo : IFRE_DB_Object;
begin
abort; // REWORK THIS
//TCPGetSnapshots(dataset,destinationhost,destinationport);
//creation_ts := 0;
//snapshotname := '';
//proc := GetProcess(0);
//result := proc.ExitStatus;
//error := proc.ErrorToString;
//if FieldExists('snapshots') then begin
// for isnap := Field('snapshots').ValueCount-1 downto 0 do begin
// snapo := Field('snapshots').AsObjectItem[isnap];
// if (snapshotkey='') or (Pos(snapshotkey,snapo.Field('name').asstring)=1) then begin
// snapshotname := snapo.Field('name').asstring;
// creation_ts := snapo.Field('creation').AsDateTimeUTC;
// exit;
// end;
// end;
//end;
//// not found
//result := -1;
end;
function TFRE_DB_ZFS.CreateDataset(const dataset: string; out error: string): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//ClearProcess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zfs',TFRE_DB_StringArray.Create('create',dataset));
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.DestroyDataset(const dataset: string; out error: string; const recursive: boolean; const dependents: boolean; const force: boolean): integer;
//var
// proc : TFRE_DB_Process;
// params : TFRE_DB_StringArray;
// pcount : integer;
begin
abort; // REWORK THIS
//ClearProcess;
//proc := TFRE_DB_Process.create;
//SetLength(params,1);
//params[0] := 'destroy';
//if recursive then AddParameter('-r',params);
//if dependents then AddParameter('-R',params);
//if force then AddParameter('-f',params);
//AddParameter('-p',params);
//AddParameter(dataset,params);
//proc.SetupInput('zfs',params);
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
// writeln(proc.DumpToString);
// writeln('OUT:',proc.OutputToString);
end;
{ dataset='' delivers all snapshots }
procedure TFRE_DB_ZFS.GetSnapshots(const dataset: string; const foscmdmode: boolean);
//var
// proc : TFRE_DB_Process; { zfs list -t snapshot -o name,creation,used,referenced,logicalreferenced,logicalused,userrefs }
// test : string;
begin
abort; // REWORK THIS
//ClearProcess;
//proc := TFRE_DB_Process.create;
//if foscmdmode=false then begin
// proc.SetupInput('zfs',TFRE_DB_StringArray.Create('list','-r','-H','-p','-t','snapshot','-o','name,creation,used,referenced,logicalreferenced,logicalused,userrefs',dataset));
//end else begin
// proc.SetupInput('foscmd',TFRE_DB_StringArray.Create('GETSNAPSHOTS',dataset));
//end;
//proc.Field('dataset').AsString:=dataset;
//AddProcess(proc);
//ExecuteMulti;
//if (proc.ExitStatus=0) then
// AnalyzeSnapshotsLegacy(proc.OutputToString);
end;
procedure TFRE_DB_ZFS.TCPGetSnapshots(const dataset: string; const destinationhost: string; const destinationport: integer);
//var
// proc : TFRE_DB_Process;
// ststream : TFRE_DB_Stream;
begin
abort; // REWORK THIS
//ClearProcess;
//ststream := TFRE_DB_Stream.Create;
//ststream.SetFromRawByteString('GETSNAPSHOTS%'+dataset+'%0%0'+LineEnding);
//ststream.Position:=0;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('nc',TFRE_DB_StringArray.Create(destinationhost,inttostr(destinationport)),ststream);
//proc.Field('dataset').AsString:=dataset;
//AddProcess(proc);
//ExecuteMulti;
//if proc.ExitStatus=0 then
// AnalyzeSnapshotsLegacy(proc.OutputToString);
end;
function TFRE_DB_ZFS.DestroySnapshot(const dataset: string; const snapshotname: string; out error: string): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//ClearProcess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zfs',TFRE_DB_StringArray.Create('destroy','-r',dataset+'@'+snapshotname));
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.SendSnapshot(const dataset: string; const snapshotname: string; const destinationhost: string; const destinationuser: string; const destinationdataset: string; const destinationkeyfilename: string; out error: string; const incrementalsnapshot: string; const sendmode: TFRE_DB_ZFS_Sendmode; const compressed: boolean; const destinationport: integer; const foscmdmode: boolean): integer;
//var
// proc : TFRE_DB_Process;
// zcommand : string;
begin
abort; // REWORK THIS
// ClearProcess;
// proc := TFRE_DB_Process.create;
//// ssh -i ~/.firmos/fre/ssl/user/id_rsa root@10.1.0.116 zfs "send testpool/ds1@20121016 | ssh -i /zones/rootkey/id_rsa 10.1.0.130 zfs receive zones/testpool/ds1"
// zcommand := '"'+ 'zfs send ';
// case sendmode of
// zfsSend : ; // no additional options
// zfsSendReplicated : zcommand := zcommand + '-R ';
// zfsSendRecursive : zcommand := zcommand + '-r ';
// zfsSendRecursiveProperties : zcommand := zcommand + '-r -p ';
// else
// raise EFOS_ZFS_Exception.Create('INVALID ZFS SEND MODE');
// end;
// if length(incrementalsnapshot)>0 then begin
// zcommand := zcommand+'-I '+dataset+'@'+incrementalsnapshot+' ';
// end;
// zcommand := zcommand +dataset+'@'+snapshotname;
// if compressed then begin
// zcommand := zcommand +' | bzip2 -c';
// end;
// zcommand := zcommand +' | ssh -i '+destinationkeyfilename+' -p '+ inttostr(destinationport)+' '+destinationuser+'@'+destinationhost+' ''';
// if foscmdmode=false then begin
// if compressed then begin
// zcommand := zcommand +'bzcat | ';
// end;
// zcommand := zcommand + 'zfs receive -u -F '+ destinationdataset+''' "';
// end else begin
// if compressed then begin
// zcommand := zcommand + 'foscmd RECEIVEBZ '+ destinationdataset+''' "';
// end else begin
// zcommand := zcommand + 'foscmd RECEIVE '+ destinationdataset+''' "';
// end;
// end;
//// writeln(zcommand);
// proc.SetupInput(zcommand,nil);
// AddProcess(proc);
// ExecuteMulti;
// result := proc.Field('exitstatus').AsInt32;
// error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.Scrub(const poolname: string; out error: string): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//Clearprocess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zpool',TFRE_DB_StringArray.Create('scrub',poolname));
//AddProcess(proc);
//ExecuteMulti;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.GetPoolStatus(const poolname: string; out error: string; out pool: IFRE_DB_Object): integer;
//var
// proc : TFRE_DB_Process;
// pool_hc : TFRE_DB_ZFS_POOL;
begin
abort; // REWORK THIS
// ClearProcess;
// proc := TFRE_DB_Process.create;
// proc.SetupInput('zpool',TFRE_DB_StringArray.Create ('status',poolname));
// AddProcess(proc);
// ExecuteMulti;
// if proc.Field('exitstatus').AsInt32=0 then
// begin
//// if(GFRE_BT.StringFromFile('spare2'),pool_hc) then //DEBUG
// if ParseZpool(TFRE_DB_Process (proc.Implementor_HC).OutputToString,pool_hc) then
// begin
// pool := pool_hc;
// proc.Field('exitstatus').AsInt32 :=0;
// end
// else
// begin
// if Assigned(pool_hc) then
// pool_hc.Finalize;
// pool := nil;
// proc.Field('exitstatus').AsInt32 :=-1;
// error := proc.Field('errorstring').AsString;
// end;
// end;
// result := proc.Field('exitstatus').AsInt32;
end;
function TFRE_DB_ZFS.GetDataset(const dataset: string; out error: string; out datasetobject: IFRE_DB_Object): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//if dataset='' then
// raise EFRE_DB_Exception.Create(edb_ERROR,'you can use this function only to get one dataset');
//ClearProcess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zfs',TFRE_DB_StringArray.Create ('list','-p','-o','name,used,avail,refer',dataset));
//AddProcess(proc);
//ExecuteMulti;
//AnalyzeDataSetSpace(proc);
//datasetobject := proc.Field('datasetobject').AsObject;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
//function TFRE_DB_ZFS.EmbedDatasets: boolean;
//var
// proc : TFRE_DB_Process;
//procedure BuildEmbeddedDatasetList;
//var
// slist : TStringList;
// props : TFRE_DB_StringArray;
// ds : TFRE_DB_ZFS_DATASET;
// i : integer;
// fieldcount : NativeInt;
//begin
// slist := TStringList.Create;
// try
// slist.text := proc.OutputToString;
// fieldcount := Length(TFRE_DB_ZFS_PROPNAMES);
// for i := 0 to slist.count -1 do begin
// GFRE_BT.SeperateString(slist[i],#9,props);
// if Length(props)<>TFRE_DB_ZFS_PROPNAMES_CNT then
// raise EFRE_DB_Exception.Create(edb_ERROR,'got not enough properties for zfs dataset expected [%d] got [%d] line [%s]',[TFRE_DB_ZFS_PROPNAMES_CNT,length(props),slist[i]]);
// ds := TFRE_DB_ZFS_DATASET.CreateForDB;
// ds.SetupFromParseStrings(props);
// Field('embedded_ds').AddObject(ds);
// end;
// finally
// slist.Free;
// end;
//end;
//begin
// ClearProcess;
// proc := TFRE_DB_Process.create;
// proc.SetupInput('zfs',TFRE_DB_StringArray.Create ('list','-p','-H','-o','name,available,clones,compressratio,creation,defer_destroy,logicalreferenced,'+
// 'logicalused,mounted,origin,refcompressratio,referenced,type,used,usedbychildren,usedbydataset,'+
// 'usedbyrefreservation,usedbysnapshots,userrefs,written,aclinherit,aclmode,atime,canmount,casesensitivity,'+
// 'checksum,compression,dedup,filesystem_count,filesystem_limit,logbias,mountpoint,nbmand,primarycache,quota,'+
// 'readonly,recordsize,refquota,refreservation,reservation,secondarycache,sharenfs,sharesmb,snapdir,snapshot_count,'+
// 'snapshot_limit,sync,utf8only,version,volblocksize,volsize,vscan,xattr,zoned'));
// AddProcess(proc);
// ExecuteMulti;
// BuildEmbeddedDatasetList;
//end;
function TFRE_DB_ZFS.GetPools(out error: string; out pools: IFRE_DB_Object): integer;
//var
// proc : TFRE_DB_Process;
begin
abort; // REWORK THIS
//ClearProcess;
//proc := TFRE_DB_Process.create;
//proc.SetupInput('zpool',TFRE_DB_StringArray.Create ('list','-p','-o','name,guid'));
//AddProcess(proc);
//ExecuteMulti;
//AnalyzePoolList(proc);
//pools := proc.Field('pools').AsObject.CloneToNewObject;
//result := proc.Field('exitstatus').AsInt32;
//error := proc.Field('errorstring').AsString;
end;
function TFRE_DB_ZFS.CreateDiskPool(const pool_definition: IFRE_DB_Object; out output, errorout, zfs_cmd: string): integer;
var
zlog : TFRE_DB_ZFS_LOG;
spare : TFRE_DB_ZFS_SPARE;
cache : TFRE_DB_ZFS_CACHE;
procedure _parseVdevs(const obj:IFRE_DB_Object);
var ds : TFRE_DB_ZFS_DATASTORAGE;
vdevcont : TFRE_DB_ZFS_CONTAINER;
vdev : TFRE_DB_ZFS_VDEV_RAIDMIRROR;
bd : TFRE_DB_ZFS_BLOCKDEVICE;
begin
if obj.IsA(TFRE_DB_ZFS_DATASTORAGE,ds) then
begin
ds.ForAllObjects(@_parseVdevs);
exit;
end;
if obj.isA(TFRE_DB_ZFS_LOG,zlog) then
begin
; // zlog is assigned now ;
//zfs_cmd:=zfs_cmd+' log';
//zlog.ForAllObjects(@_parseVdevs);
//exit;
end;
if obj.isA(TFRE_DB_ZFS_CONTAINER,vdevcont) then
begin
if vdevcont.IsA(TFRE_DB_ZFS_LOG) then
exit;
if vdevcont.IsA(TFRE_DB_ZFS_CACHE) then
exit;
vdevcont.ForAllObjects(@_parseVdevs);
exit;
end;
if obj.IsA(TFRE_DB_ZFS_VDEV_RAIDMIRROR,vdev) then
begin
case (vdev.Implementor_HC as TFRE_DB_ZFS_VDEV_RAIDMIRROR).GetRaidLevel of
zfs_rl_mirror: zfs_cmd:=zfs_cmd+' mirror';
zfs_rl_z1 : zfs_cmd:=zfs_cmd+' raidz1';
zfs_rl_z2 : zfs_cmd:=zfs_cmd+' raidz2';
zfs_rl_z3 : zfs_cmd:=zfs_cmd+' raidz3';
else
raise EFRE_DB_Exception.Create('unsupported raiadlevel in CreateDiskpool for datastorage'+CFRE_DB_ZFS_RAID_LEVEL[(vdev.Implementor_HC as TFRE_DB_ZFS_VDEV_RAIDMIRROR).GetRaidLevel]);
end;
vdev.ForAllObjects(@_parseVdevs);
exit;
end;
if obj.IsA(TFRE_DB_ZFS_CACHE,cache) then
begin
; // cache is assigned now
//zfs_cmd:=zfs_cmd+' cache';
//cache.ForAllObjects(@_parseVdevs);
//exit;
end;
if obj.IsA(TFRE_DB_ZFS_SPARE,spare) then
begin
; // spare is assigned now ;
//zfs_cmd:=zfs_cmd+' spare';
//spare.ForAllObjects(@_parseVdevs);
//exit;
end;
if obj.IsA(TFRE_DB_ZFS_BLOCKDEVICE,bd) then
begin
zfs_cmd:=zfs_cmd+' '+bd.DeviceName;
exit;
end;
end;
begin
if pool_definition.Field('FORCE').AsBoolean=true then
zfs_cmd := 'zpool create -f '+pool_definition.Field('objname').asstring
else
zfs_cmd := 'zpool create '+pool_definition.Field('objname').asstring;
zlog := nil;
cache := nil;
spare := nil;
pool_definition.ForAllObjects(@_parseVdevs);
if assigned(spare) then
begin
zfs_cmd := zfs_cmd+' spare';
spare.ForAllObjects(@_parseVdevs);
end;
if assigned(zlog) then
begin
zfs_cmd := zfs_cmd+' log';
zlog.ForAllObjects(@_parseVdevs);
end;
if assigned(cache) then
begin
zfs_cmd := zfs_cmd+' cache';
cache.ForAllObjects(@_parseVdevs);
end;
GFRE_LOG.Log('ZFS POOL : '+zfs_cmd,'ZPOOL',fll_Info);
result := FRE_ProcessCMD(zfs_cmd,output,errorout,cFRE_REMOTE_SSL_PORT,cFRE_REMOTE_HOST,cFRE_REMOTE_USER,cFRE_REMOTE_SSL_ID_FILE);
GFRE_LOG.Log('ZFS POOL : OUTPUT '+output+' ERROROUT '+errorout,'ZPOOL',fll_Info);
end;
procedure TFRE_DB_ZFSJob.SetScrub(const poolname: string);
begin
JobConfig.Field('cmd').AsString :='scrub';
JobConfig.Field('poolname').AsString :=poolname;
end;
procedure TFRE_DB_ZFSJob.SetPoolStatus(const poolname: string; const scrub_warning_days: integer; const scrub_error_days: integer);
begin
JobConfig.Field('cmd').AsString :='poolstatus';
JobConfig.Field('poolname').AsString := poolname;
JobConfig.Field('scrub_warning_days').AsInt32 := scrub_warning_days;
JobConfig.Field('scrub_error_days').AsInt32 := scrub_error_days;
end;
procedure TFRE_DB_ZFSJob.SetDatasetspace(const dataset: string; const warning_percent: integer; const error_percent: integer);
begin
JobConfig.Field('cmd').AsString :='datasetspace';
JobConfig.Field('dataset').AsString := dataset;
JobConfig.Field('warning_percent').AsByte := warning_percent;
JobConfig.Field('error_percent').AsByte := error_percent;
end;
procedure TFRE_DB_ZFSJob.SetSSHReplicate(const sourcedataset: string; const destinationdataset: string; const snapshotkey: string; const destinationhost: string; const destinationuser: string; const destinationkeyfilename: string; const replicationkeyfilename: string; const destinationport: integer; const replicationport: integer);
begin
Field('MAX_ALLOWED_TIME').AsInt32 := 86400*14;
JobConfig.Field('cmd').AsString :='sshreplicate';
JobConfig.Field('sourcedataset').AsString :=sourcedataset;
JobConfig.Field('destinationdataset').AsString :=destinationdataset;
JobConfig.Field('snapshotkey').AsString :=snapshotkey;
JobConfig.Field('destinationhost').AsString :=destinationhost;
JobConfig.Field('destinationuser').AsString :=destinationuser;
JobConfig.Field('destinationkeyfilename').AsString :=destinationkeyfilename;
JobConfig.Field('replicationkeyfilename').AsString :=replicationkeyfilename;
JobConfig.Field('destinationport').AsInt32 :=destinationport;
JobConfig.Field('replicationport').AsInt32 :=replicationport;
end;
procedure TFRE_DB_ZFSJob.SetTCPReplicate(const sourcedataset: string; const destinationdataset: string; const snapshotkey: string; const destinationhost: string; const destinationport: integer);
begin
Field('MAX_ALLOWED_TIME').AsInt32 := 86400*14;
JobConfig.Field('cmd').AsString :='tcpreplicate';
JobConfig.Field('sourcedataset').AsString :=sourcedataset;
JobConfig.Field('destinationdataset').AsString :=destinationdataset;
JobConfig.Field('snapshotkey').AsString :=snapshotkey;
JobConfig.Field('destinationhost').AsString :=destinationhost;
JobConfig.Field('destinationport').AsInt32 :=destinationport;
JobConfig.Field('jobid').AsString :=JobKey;
end;
procedure TFRE_DB_ZFSJob.SetSnapshot(const dataset: string; const snapshotkey: string);
begin
JobConfig.Field('cmd').AsString := 'snapshot';
JobConfig.Field('sourcedataset').AsString := dataset;
JobConfig.Field('snapshotkey').AsString := snapshotkey;
end;
procedure TFRE_DB_ZFSJob.SetSnapshotCheck(const dataset: string; const snapshotkey: string; const warning_seconds: integer; const error_seconds: integer);
begin
JobConfig.Field('cmd').AsString := 'snapshotcheck';
JobConfig.Field('dataset').AsString := dataset;
JobConfig.Field('snapshotkey').AsString := snapshotkey;
JobConfig.Field('warning_seconds').AsInt32 := warning_seconds;
JobConfig.Field('error_seconds').AsInt32 := error_seconds;
end;
{ TFRE_DB_ZFS_SNAPSHOT }
procedure TFRE_DB_ZFS_SNAPSHOT.Setup(const snapname: TFRE_DB_String; const creationtime_utc: TFRE_DB_DateTime64; const usedamount, referedamount: Int64);
begin
Field('objname').AsString := snapname;
//Field('parentid',fdbft_ObjLink); //parent id e.g. fileshare,lun
Field('creation').AsDateTimeUTC := creationtime_utc;
Field('used_mb').AsInt64 := usedamount;
Field('refer_mb').AsInt64 := referedamount;
end;
class procedure TFRE_DB_ZFS_SNAPSHOT.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_BASE.Classname);
scheme.GetSchemeField('objname').required:=true; // zfs snapshot
scheme.AddSchemeField('parentid',fdbft_ObjLink); // parent id e.g. fileshare,lun
scheme.AddSchemeField('creation',fdbft_DateTimeUTC);
scheme.AddSchemeField('used_mb',fdbft_UInt32);
scheme.AddSchemeField('refer_mb',fdbft_UInt32);
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main_group'));
group.AddInput('objname',GetTranslateableTextKey('scheme_objname'));
group.AddInput('desc.txt',GetTranslateableTextKey('scheme_description'));
//group.AddInput('creation',GetTranslateableTextKey('scheme_creation'),true);
//group.AddInput('used_mb',GetTranslateableTextKey('scheme_used'),true);
//group.AddInput('refer_mb',GetTranslateableTextKey('scheme_refer'),true);
end;
class procedure TFRE_DB_ZFS_SNAPSHOT.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_objname','Name');
StoreTranslateableText(conn,'scheme_description','Description');
StoreTranslateableText(conn,'scheme_creation','Creation Timestamp');
StoreTranslateableText(conn,'scheme_used','Used [MB]');
StoreTranslateableText(conn,'scheme_refer','Refer [MB]');
end;
end;
class function TFRE_DB_ZFS_SNAPSHOT.getFieldsIgnoredBySync: TFRE_DB_NameTypeArray;
begin
Result:=TFRE_DB_NameTypeArray.create('SERVICEPARENT','OBJNAME');
end;
function TFRE_DB_ZFS_SNAPSHOT.GetDatasetName: TFRE_DB_String;
begin
result := GFRE_BT.SepLeft(Name,'@');
end;
{ TFRE_DB_LUN_VIEW }
class procedure TFRE_DB_LUN_VIEW.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.AddSchemeField('fileshare',fdbft_ObjLink).required:=true;
scheme.AddSchemeField('initiatorgroup',fdbft_String);
scheme.AddSchemeField('targetgroup',fdbft_String);
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main'));
group.AddInput('initiatorgroup',GetTranslateableTextKey('scheme_initiatorgroup'));
group.AddInput('targetgroup',GetTranslateableTextKey('scheme_targetgroup'));
end;
class procedure TFRE_DB_LUN_VIEW.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','View Parameter');
StoreTranslateableText(conn,'scheme_initiatorgroup','Initiator Group');
StoreTranslateableText(conn,'scheme_targetgroup','Target Group');
end;
end;
{ TFRE_DB_ZFS_DATASET_ZVOL }
class procedure TFRE_DB_ZFS_DATASET_ZVOL.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group : IFRE_DB_InputGroupSchemeDefinition;
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('cache').Setup(GFRE_DBI.CreateText('$enum_cache','Cache'));
enum.addEntry('NONE',GetTranslateableTextKey('enum_cache_none'));
enum.addEntry('ALL',GetTranslateableTextKey('enum_cache_all'));
enum.addEntry('METADATA',GetTranslateableTextKey('enum_cache_metadata'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_DATASET.Classname);
scheme.AddSchemeField('size_gb',fdbft_UInt32).SetupFieldDefNumMin(true,1);
scheme.AddSchemeField('primarycache',fdbft_String).SetupFieldDef(true,false,'cache');
scheme.AddSchemeField('secondarycache',fdbft_String).SetupFieldDef(true,false,'cache');
group:=scheme.AddInputGroup('volume').Setup(GetTranslateableTextKey('scheme_volume_group'));
group.AddInput('size_gb',GetTranslateableTextKey('scheme_size'));
group.AddInput('primarycache',GetTranslateableTextKey('scheme_primarycache'),false,false,'','',false,dh_chooser_radio);
group.AddInput('secondarycache',GetTranslateableTextKey('scheme_secondarycache'),false,false,'','',false,dh_chooser_radio);
end;
class procedure TFRE_DB_ZFS_DATASET_ZVOL.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_volume_group','Volume Properties');
StoreTranslateableText(conn,'scheme_primarycache','Primary Cache');
StoreTranslateableText(conn,'scheme_secondarycache','Secondary Cache');
StoreTranslateableText(conn,'scheme_size','Size [MB]');
StoreTranslateableText(conn,'enum_cache_none','None');
StoreTranslateableText(conn,'enum_cache_all','All');
StoreTranslateableText(conn,'enum_cache_metadata','Metadata');
end;
end;
function TFRE_DB_ZFS_DATASET_ZVOL.Embed(const conn: IFRE_DB_CONNECTION): TFRE_DB_ZFS_DATASET_ZVOL;
begin
self.CloneToNewObject(true).AsClass(TFRE_DB_ZFS_DATASET_ZVOL,Result);
Result.DeleteField('poolid');
Result.Field('FULLDATASETNAME').AsString:=GetFullDatasetname;
end;
{ TFRE_DB_ZFS_DATASET_FILESYSTEM }
class procedure TFRE_DB_ZFS_DATASET_FILESYSTEM.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group : IFRE_DB_InputGroupSchemeDefinition;
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('aclinheritance').Setup(GFRE_DBI.CreateText('$enum_aclinheritance','ACL Inheritance'));
enum.addEntry('DISCARD',GetTranslateableTextKey('enum_aclinheritance_discard'));
enum.addEntry('NOALLOW',GetTranslateableTextKey('enum_aclinheritance_noallow'));
enum.addEntry('RESTRICTED',GetTranslateableTextKey('enum_aclinheritance_restricted'));
enum.addEntry('PASSTHROUGH',GetTranslateableTextKey('enum_aclinheritance_passthrough'));
enum.addEntry('PASSTHROUGH-X',GetTranslateableTextKey('enum_aclinheritance_passthroughx'));
GFRE_DBI.RegisterSysEnum(enum);
enum:=GFRE_DBI.NewEnum('aclmode').Setup(GFRE_DBI.CreateText('$enum_aclmode','ACL Mode'));
enum.addEntry('DISCARD',GetTranslateableTextKey('enum_aclmode_discard'));
enum.addEntry('GROUPMASK',GetTranslateableTextKey('enum_aclmode_groupmask'));
enum.addEntry('PASSTHROUGH',GetTranslateableTextKey('enum_aclmode_passthrough'));
GFRE_DBI.RegisterSysEnum(enum);
enum:=GFRE_DBI.NewEnum('canmount').Setup(GFRE_DBI.CreateText('$enum_canmount','Can Mount'));
enum.addEntry('OFF',GetTranslateableTextKey('enum_canmount_off'));
enum.addEntry('ON',GetTranslateableTextKey('enum_canmount_on'));
enum.addEntry('NOAUTO',GetTranslateableTextKey('enum_canmount_noauto'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_DATASET.Classname);
scheme.AddSchemeField('referenced_mb',fdbft_UInt32); //FIXXME
scheme.AddSchemeField('refer_mb',fdbft_UInt32); //FIXXME
scheme.AddSchemeField('used_mb',fdbft_UInt32); //FIXXME
scheme.AddSchemeField('quota',fdbft_UInt32);
scheme.AddSchemeField('atime',fdbft_Boolean);
scheme.AddSchemeField('devices',fdbft_Boolean);
scheme.AddSchemeField('exec',fdbft_Boolean);
scheme.AddSchemeField('setuid',fdbft_Boolean);
scheme.AddSchemeField('aclinherit',fdbft_String).SetupFieldDef(true,false,'aclinheritance');
scheme.AddSchemeField('aclmode',fdbft_String).SetupFieldDef(true,false,'aclmode');
scheme.AddSchemeField('canmount',fdbft_String).SetupFieldDef(true,false,'canmount');
scheme.AddSchemeField('xattr',fdbft_Boolean);
scheme.AddSchemeField('mountpoint',fdbft_String);
group:=scheme.AddInputGroup('properties').Setup(GetTranslateableTextKey('scheme_properties_group'));
group.AddInput('quota',GetTranslateableTextKey('scheme_quota'));
//group.AddInput('referenced_mb',GetTranslateableTextKey('scheme_referenced')); //FIXXME
group.AddInput('atime',GetTranslateableTextKey('scheme_atime'));
group.AddInput('devices',GetTranslateableTextKey('scheme_devices'));
group.AddInput('exec',GetTranslateableTextKey('scheme_exec'));
group.AddInput('setuid',GetTranslateableTextKey('scheme_setuid'));
group.AddInput('snapshots',GetTranslateableTextKey('scheme_snapshots')); //FIXXME
group.AddInput('aclinherit',GetTranslateableTextKey('scheme_aclinherit'),false,false,'','',false,dh_chooser_radio);
group.AddInput('aclmode',GetTranslateableTextKey('scheme_aclmode'),false,false,'','',false,dh_chooser_radio);
group.AddInput('canmount',GetTranslateableTextKey('scheme_canmount'),false,false,'','',false,dh_chooser_radio);
group.AddInput('xattr',GetTranslateableTextKey('scheme_xattr'));
end;
class procedure TFRE_DB_ZFS_DATASET_FILESYSTEM.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_objname','Dataset Name');
StoreTranslateableText(conn,'scheme_properties_group','Properties');
StoreTranslateableText(conn,'scheme_quota','Quota [MB]');
StoreTranslateableText(conn,'scheme_atime','Access Time');
StoreTranslateableText(conn,'scheme_devices','Allow Devices');
StoreTranslateableText(conn,'scheme_exec','Allow Execution');
StoreTranslateableText(conn,'scheme_setuid','Allow Set UID');
StoreTranslateableText(conn,'scheme_snapshots','Show Snapshots');
StoreTranslateableText(conn,'scheme_aclinherit','ACL Inheritance');
StoreTranslateableText(conn,'scheme_aclmode','ACL Mode');
StoreTranslateableText(conn,'scheme_canmount','Can Mount');
StoreTranslateableText(conn,'scheme_xattr','Extended Attributes');
StoreTranslateableText(conn,'scheme_refer','Refer [MB]');
StoreTranslateableText(conn,'scheme_used','Used [MB]');
StoreTranslateableText(conn,'scheme_referenced','Referenced Quota [MB]');
StoreTranslateableText(conn,'enum_aclinheritance_discard','Discard');
StoreTranslateableText(conn,'enum_aclinheritance_noallow','NoAllow');
StoreTranslateableText(conn,'enum_aclinheritance_restricted','Restricted');
StoreTranslateableText(conn,'enum_aclinheritance_passthrough','Passthrough');
StoreTranslateableText(conn,'enum_aclinheritance_passthroughx','Passthrough-X');
StoreTranslateableText(conn,'enum_aclmode_discard','Discard');
StoreTranslateableText(conn,'enum_aclmode_groupmask','Groupmask');
StoreTranslateableText(conn,'enum_aclmode_passthrough','Passthrough');
StoreTranslateableText(conn,'enum_canmount_off','Off');
StoreTranslateableText(conn,'enum_canmount_on','On');
StoreTranslateableText(conn,'enum_canmount_noauto','NoAuto');
end;
end;
procedure TFRE_DB_ZFS_DATASET.SetIsDomainsContainer;
begin
field('ecf_dst').AsString:='DD';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsDomainDataset;
begin
field('ecf_dst').AsString:='D';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsZoneDataset;
begin
field('ecf_dst').AsString:='Z';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsTemplateContainer;
begin
field('ecf_dst').AsString:='TC';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsTemplateDataset;
begin
field('ecf_dst').AsString:='T';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsZoneCfgDataset;
begin
field('ecf_dst').AsString:='ZC';
end;
procedure TFRE_DB_ZFS_DATASET.SetIsZoneCfgContainer;
begin
field('ecf_dst').AsString:='ZZ';
end;
function TFRE_DB_ZFS_DATASET.IsDomainsContainer: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='DD';
end;
function TFRE_DB_ZFS_DATASET.IsDomainDataset: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='D';
end;
function TFRE_DB_ZFS_DATASET.IsZoneCfgDataset: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='ZC';
end;
function TFRE_DB_ZFS_DATASET.IsZoneCfgContainer: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='ZZ';
end;
function TFRE_DB_ZFS_DATASET.IsZoneDataset: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='Z';
end;
function TFRE_DB_ZFS_DATASET.IsTemplateContainer: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='TC';
end;
function TFRE_DB_ZFS_DATASET.IsTemplateDataset: Boolean;
begin
result := FieldOnlyExistingString('ecf_dst')='T';
end;
procedure TFRE_DB_ZFS_DATASET.CFG_SetBrowseParent(const lvl: string);
begin
Field('cfg_lvl').AsString := lvl;
end;
function TFRE_DB_ZFS_DATASET.CFG_GetLevel: string;
var lvl,mp : string;
begin
mp := field('mountpoint').AsString;
lvl := Field('cfg_lvl').AsString;
result := mp+'/'+lvl;
end;
function TFRE_DB_ZFS_DATASET.RIF_BrowseDataset(const runnning_ctx: TObject): TFRE_DB_RIF_RESULT;
var reply_data : IFRE_DB_Object;
level : string;
procedure ListDirLevel(const basepath: string);
var Info : TSearchRec;
entry : TFRE_DB_FS_ENTRY;
count : NativeInt;
dir : IFRE_DB_Object;
isfile : boolean;
hasChilds : boolean;
function CheckChilds(const path:string):boolean;
var sub : TSearchRec;
bp : string;
fnd : boolean;
begin
bp := basepath+path+'/*';
fnd := FindFirst (bp,faAnyFile and faDirectory,sub)=0;
result := false;
if fnd then
repeat
With sub do
begin
if (name='.') or (name='..') then
Continue;
result := true;
break;
end;
until FindNext(sub)<>0;
FindClose(sub);
end;
begin
dir := result.field('dir').AsObject;
count := 0;
If FindFirst (basepath+'*',faAnyFile and faDirectory,Info)=0 then
Repeat
With Info do
begin
if (name='.') or (name='..') then
Continue;
entry := TFRE_DB_FS_ENTRY.CreateForDB;
isfile := (Attr and faDirectory) <> faDirectory;
if not isfile then
hasChilds := CheckChilds(name)
else
hasChilds := false;
entry.SetProperties(name,isfile,Size,mode,Time,hasChilds);
dir.Field(inttostr(count)).AsObject := entry;
inc(count);
end;
Until FindNext(info)<>0;
FindClose(Info);
end;
begin
{$IFDEF SOLARIS }
level := CFG_GetLevel;
result := TFRE_DB_RIF_RESULT.CreateForDB;
ListDirLevel(level);
result.ErrorCode:=0;
writeln('::: BROWSE - LEVEL ',level,' ',Result.DumpToString());
{$ENDIF}
end;
{ TFRE_DB_LUN }
class procedure TFRE_DB_LUN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.AddSchemeField('writeback',fdbft_Boolean);
scheme.AddSchemeField('writeprotect',fdbft_Boolean);
group:=scheme.AddInputGroup('lun').Setup(GetTranslateableTextKey('scheme_lun_group'));
group.AddInput('writeback',GetTranslateableTextKey('scheme_writeback'));
group.AddInput('writeprotect',GetTranslateableTextKey('scheme_writeprotect'));
end;
class procedure TFRE_DB_LUN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_lun_group','LUN Parameter');
StoreTranslateableText(conn,'scheme_writeback','Writeback');
StoreTranslateableText(conn,'scheme_writeprotect','Writeprotect');
end;
end;
{ TFRE_DB_NFS_ACCESS }
class procedure TFRE_DB_NFS_ACCESS.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group : IFRE_DB_InputGroupSchemeDefinition;
enum : IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('nfs_access').Setup(GFRE_DBI.CreateText('$enum_nfs_access','NFS Access'));
enum.addEntry('RW',GetTranslateableTextKey('enum_nfs_access_rw'));
enum.addEntry('RO',GetTranslateableTextKey('enum_nfs_access_ro'));
enum.addEntry('ROOT',GetTranslateableTextKey('enum_nfs_access_root'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.AddSchemeField('fileshare',fdbft_ObjLink).required:=true;
scheme.AddSchemeField('accesstype',fdbft_String).SetupFieldDef(true,false,'nfs_access');
scheme.AddSchemeField('subnet',fdbft_String).SetupFieldDef(true);
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main'));
group.AddInput('accesstype',GetTranslateableTextKey('scheme_accesstype'),false,false,'','',false,dh_chooser_radio);
group.AddInput('subnet',GetTranslateableTextKey('scheme_subnet'));
end;
class procedure TFRE_DB_NFS_ACCESS.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main','Access Parameter');
StoreTranslateableText(conn,'scheme_accesstype','Access Type');
StoreTranslateableText(conn,'scheme_subnet','Subnet/Host');
StoreTranslateableText(conn,'enum_nfs_access','NFS Access');
StoreTranslateableText(conn,'enum_nfs_access_rw','Read-Write');
StoreTranslateableText(conn,'enum_nfs_access_ro','Read-Only');
StoreTranslateableText(conn,'enum_nfs_access_root','Root');
end;
end;
{ TFRE_DB_VIRTUAL_FILESHARE }
class procedure TFRE_DB_VIRTUAL_FILESHARE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName);
scheme.AddSchemeField('fileserver',fdbft_ObjLink).required:=true;
scheme.AddSchemeField('group',fdbft_ObjLink).required:=true;
group:=scheme.ReplaceInputGroup('main');
group.AddInput('objname',GetTranslateableTextKey('scheme_sharename'));
group.AddInput('desc.txt',GetTranslateableTextKey('scheme_description'));
group.AddInput('quota',GetTranslateableTextKey('scheme_quota'));
group.AddInput('referenced_mb',GetTranslateableTextKey('scheme_referenced'));
end;
class procedure TFRE_DB_VIRTUAL_FILESHARE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_sharename','Share Name');
StoreTranslateableText(conn,'scheme_description','Description');
StoreTranslateableText(conn,'scheme_quota','Quota [MB]');
StoreTranslateableText(conn,'scheme_referenced','Referenced Quota [MB]');
end;
end;
{ TFRE_DB_NFS_FILESHARE }
class procedure TFRE_DB_NFS_FILESHARE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group : IFRE_DB_InputGroupSchemeDefinition;
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('nfs_auth').Setup(GFRE_DBI.CreateText('$enum_nfs_auth','NFS Auth'));
enum.addEntry('SYS',GetTranslateableTextKey('enum_nfs_auth_sys'));
enum.addEntry('NONE',GetTranslateableTextKey('enum_nfs_auth_none'));
enum.addEntry('DES',GetTranslateableTextKey('enum_nfs_auth_des'));
enum.addEntry('K5',GetTranslateableTextKey('enum_nfs_auth_k5'));
enum.addEntry('K5C',GetTranslateableTextKey('enum_nfs_auth_k5c'));
enum.addEntry('K5CE',GetTranslateableTextKey('enum_nfs_auth_k5ce'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ZFS_DATASET_FILESYSTEM.ClassName);
scheme.AddSchemeField('anonymous',fdbft_Boolean);
scheme.AddSchemeField('anonymousrw',fdbft_Boolean);
scheme.AddSchemeField('auth',fdbft_String).SetupFieldDef(true,false,'nfs_auth');
group:=scheme.AddInputGroup('nfs').Setup(GetTranslateableTextKey('scheme_NFS_group'));
group.AddInput('objname',GetTranslateableTextKey('scheme_export'));
group.AddInput('anonymous',GetTranslateableTextKey('scheme_anonymous'));
group.AddInput('anonymousrw',GetTranslateableTextKey('scheme_anonymousrw'));
group.AddInput('auth',GetTranslateableTextKey('scheme_auth'),false,false,'','',false,dh_chooser_radio);
end;
class procedure TFRE_DB_NFS_FILESHARE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_NFS_group','NFS Properties');
StoreTranslateableText(conn,'scheme_export','Export name');
StoreTranslateableText(conn,'scheme_anonymous','Anonymous access');
StoreTranslateableText(conn,'scheme_anonymousrw','Anonymous RW access');
StoreTranslateableText(conn,'scheme_auth','Authentication');
StoreTranslateableText(conn,'enum_nfs_auth_sys','System users AUTH_SYS');
StoreTranslateableText(conn,'enum_nfs_auth_none','Nobody AUTH_NONE');
StoreTranslateableText(conn,'enum_nfs_auth_des','Public key AUTH_DES');
StoreTranslateableText(conn,'enum_nfs_auth_k5','Kerberos V5');
StoreTranslateableText(conn,'enum_nfs_auth_k5c','Kerberos V5 with checksums');
StoreTranslateableText(conn,'enum_nfs_auth_k5ce','Kerberos V5 with checksums and encryption');
end;
end;
{ TFRE_DB_ZFS_DATASET }
class procedure TFRE_DB_ZFS_DATASET.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group : IFRE_DB_InputGroupSchemeDefinition;
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('logbias').Setup(GFRE_DBI.CreateText('$enum_logbias','Log Bias'));
enum.addEntry('LATENCY',GetTranslateableTextKey('enum_logbias_latency'));
enum.addEntry('THROUGHPUT',GetTranslateableTextKey('enum_logbias_throughput'));
GFRE_DBI.RegisterSysEnum(enum);
enum:=GFRE_DBI.NewEnum('compression').Setup(GFRE_DBI.CreateText('$enum_compression','Compression'));
enum.addEntry('OFF',GetTranslateableTextKey('enum_compression_off'));
enum.addEntry('ON',GetTranslateableTextKey('enum_compression_on'));
enum.addEntry('GZIP',GetTranslateableTextKey('enum_compression_gzip'));
enum.addEntry('GZIP-1',GetTranslateableTextKey('enum_compression_gzip-1'));
enum.addEntry('GZIP-2',GetTranslateableTextKey('enum_compression_gzip-2'));
enum.addEntry('GZIP-3',GetTranslateableTextKey('enum_compression_gzip-3'));
enum.addEntry('GZIP-4',GetTranslateableTextKey('enum_compression_gzip-4'));
enum.addEntry('GZIP-5',GetTranslateableTextKey('enum_compression_gzip-5'));
enum.addEntry('GZIP-6',GetTranslateableTextKey('enum_compression_gzip-6'));
enum.addEntry('GZIP-7',GetTranslateableTextKey('enum_compression_gzip-7'));
enum.addEntry('GZIP-8',GetTranslateableTextKey('enum_compression_gzip-8'));
enum.addEntry('GZIP-9',GetTranslateableTextKey('enum_compression_gzip-9'));
GFRE_DBI.RegisterSysEnum(enum);
enum:=GFRE_DBI.NewEnum('copies').Setup(GFRE_DBI.CreateText('$enum_copies','Copies'));
enum.addEntry('1',GetTranslateableTextKey('enum_copies_1'));
enum.addEntry('2',GetTranslateableTextKey('enum_copies_2'));
enum.addEntry('3',GetTranslateableTextKey('enum_copies_3'));
GFRE_DBI.RegisterSysEnum(enum);
enum:=GFRE_DBI.NewEnum('sync').Setup(GFRE_DBI.CreateText('$enum_sync','Sync Mode'));
enum.addEntry('STANDARD',GetTranslateableTextKey('enum_sync_standard'));
enum.addEntry('ALWAYS',GetTranslateableTextKey('enum_sync_always'));
enum.addEntry('DISABLED',GetTranslateableTextKey('enum_sync_disabled'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
scheme.GetSchemeField('objname').required:=true;
scheme.AddSchemeField('poolid',fdbft_ObjLink);
scheme.AddSchemeField('reservation_mb',fdbft_UInt32);
scheme.AddSchemeField('refres_mb',fdbft_UInt32);
scheme.AddSchemeField('recordsize_kb',fdbft_UInt16);
scheme.AddSchemeField('readonly',fdbft_Boolean);
scheme.AddSchemeField('logbias',fdbft_String).SetupFieldDef(true,false,'logbias');
scheme.AddSchemeField('deduplication',fdbft_Boolean);
scheme.AddSchemeField('checksum',fdbft_Boolean);
scheme.AddSchemeField('compression',fdbft_String).SetupFieldDef(true,false,'compression');
scheme.AddSchemeField('snapshots',fdbft_Boolean);
scheme.AddSchemeField('copies',fdbft_String).SetupFieldDef(true,false,'copies');
scheme.AddSchemeField('sync',fdbft_String).SetupFieldDef(true,false,'sync');
scheme.AddSchemeField('fileservername',fdbft_String);
scheme.AddSchemeField('snapshot_jobs',fdbft_ObjLink).MultiValues:=true;
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main_group'));
group.AddInput('objname',GetTranslateableTextKey('scheme_objname'));
group:=scheme.AddInputGroup('advanced').Setup(GetTranslateableTextKey('scheme_advanced_group'));
group.AddInput('reservation_mb',GetTranslateableTextKey('scheme_reservation'));
group.AddInput('refres_mb',GetTranslateableTextKey('scheme_refres'));
group.AddInput('recordsize_kb',GetTranslateableTextKey('scheme_recordsize'));
group.AddInput('logbias',GetTranslateableTextKey('scheme_logbias'),false,false,'','',false,dh_chooser_radio);
group.AddInput('deduplication',GetTranslateableTextKey('scheme_deduplication'));
group.AddInput('checksum',GetTranslateableTextKey('scheme_checksum'));
group.AddInput('compression',GetTranslateableTextKey('scheme_compression'),false,false,'','',false,dh_chooser_radio);
group.AddInput('readonly',GetTranslateableTextKey('scheme_readonly'));
group.AddInput('copies',GetTranslateableTextKey('scheme_copies'),false,false,'','',false,dh_chooser_radio);
group.AddInput('sync',GetTranslateableTextKey('scheme_sync'),false,false,'','',false,dh_chooser_radio);
end;
class procedure TFRE_DB_ZFS_DATASET.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_pool','Diskpool');
StoreTranslateableText(conn,'scheme_description','Description');
StoreTranslateableText(conn,'scheme_advanced_group','Advanced Properties');
StoreTranslateableText(conn,'scheme_reservation','Reservation [MB]');
StoreTranslateableText(conn,'scheme_refres','Ref. Reservation [MB]');
StoreTranslateableText(conn,'scheme_recordsize','Recordsize [kB]');
StoreTranslateableText(conn,'scheme_logbias','Log Bias');
StoreTranslateableText(conn,'scheme_deduplication','Deduplication');
StoreTranslateableText(conn,'scheme_checksum','Checksum');
StoreTranslateableText(conn,'scheme_compression','Compression');
StoreTranslateableText(conn,'scheme_readonly','Read-Only');
StoreTranslateableText(conn,'scheme_copies','Copies');
StoreTranslateableText(conn,'scheme_sync','Sync');
StoreTranslateableText(conn,'enum_logbias_latency','Latency');
StoreTranslateableText(conn,'enum_logbias_throughput','Throughput');
StoreTranslateableText(conn,'enum_compression_off','Off');
StoreTranslateableText(conn,'enum_compression_on','On');
StoreTranslateableText(conn,'enum_compression_gzip','Gzip');
StoreTranslateableText(conn,'enum_compression_gzip-1','Gzip-1');
StoreTranslateableText(conn,'enum_compression_gzip-2','Gzip-2');
StoreTranslateableText(conn,'enum_compression_gzip-3','Gzip-3');
StoreTranslateableText(conn,'enum_compression_gzip-4','Gzip-4');
StoreTranslateableText(conn,'enum_compression_gzip-5','Gzip-5');
StoreTranslateableText(conn,'enum_compression_gzip-6','Gzip-6');
StoreTranslateableText(conn,'enum_compression_gzip-7','Gzip-7');
StoreTranslateableText(conn,'enum_compression_gzip-8','Gzip-8');
StoreTranslateableText(conn,'enum_compression_gzip-9','Gzip-9');
StoreTranslateableText(conn,'enum_copies_1','1');
StoreTranslateableText(conn,'enum_copies_2','2');
StoreTranslateableText(conn,'enum_copies_3','3');
StoreTranslateableText(conn,'enum_sync_standard','Standard');
StoreTranslateableText(conn,'enum_sync_always','Always');
StoreTranslateableText(conn,'enum_sync_disabled','Disabled');
end;
end;
class function TFRE_DB_ZFS_DATASET.getFieldsIgnoredBySync: TFRE_DB_NameTypeArray;
begin
Result:=TFRE_DB_NameTypeArray.create('SERVICEPARENT','ZDS_STATE','POOLID');
end;
procedure TFRE_DB_ZFS_DATASET.embedZFSDatasetsRec(const conn: IFRE_DB_CONNECTION);
var
refs : IFRE_DB_ObjectArray;
i : Integer;
ds : TFRE_DB_ZFS_DATASET;
uctfld : IFRE_DB_Field;
begin
conn.FetchExpandReferences([Self.UID],['<SERVICEPARENT'],refs);
for i := 0 to Length(refs) - 1 do begin
if refs[i].IsA(TFRE_DB_ZFS_DATASET,ds) then
begin
Field(ds.GetUCTHashed).AsObject := ds;
ds.embedZFSDatasetsRec(conn);
end
else
begin
//writeln('Not a Dataset obj : ',refs[i].DumpToString());
refs[i].Finalize;
refs[i]:=Nil;
end;
end;
end;
function TFRE_DB_ZFS_DATASET.GetFullDatasetname: TFRE_DB_String;
//var sp_id : TFRE_DB_GUID;
// obj : IFRE_DB_Object;
// dataset: TFRE_DB_ZFS_DATASET;
begin
result := Field('name').AsString;
//result := ObjectName;
//if FieldExists('serviceparent') then
// begin
// sp_id := Field('serviceparent').AsGUID;
// repeat
// CheckDbResult(conn.Fetch(sp_id,obj),'could not fetch serviceparent '+Field('serviceparent').AsGUID.AsHexString);
// if obj.FieldExists('serviceparent') then
// sp_id := obj.Field('serviceparent').AsGUID
// else
// break;
// if obj.IsA(TFRE_DB_ZFS_DATASET,dataset) then
// result := dataset.ObjectName+'/'+result;
// obj.Finalize;
// until false;
// end;
end;
function TFRE_DB_ZFS_DATASET.GetOrigin: TFRE_DB_String;
begin
result := Field('origin').AsString;
end;
procedure Register_DB_Extensions;
begin
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFSJob);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFSOBJSTATUS_PLUGIN);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_POOLSTATUS_PLUGIN);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DS_PLUGIN);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_ZDS_STATUS);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_BASE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_OBJ);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_POOL);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_IMPORTABLE_POOLS);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DATASTORAGE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_VDEV_RAIDMIRROR);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_BLOCKDEVICE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_IOSTAT);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_VDEV_POOL_STATUS);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DISKCONTAINER);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_CONTAINER);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_SPARE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_LOG);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_CACHE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_REPLACEDISK);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DATASET);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DATASET_FILESYSTEM);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_ZONE_CONTAINER_DATASET);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_DATASET_ZVOL);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_SNAPSHOT);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFSJob);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_ZFS_BOOKMARK);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_NFS_ACCESS);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_NFS_FILESHARE);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_LUN_VIEW);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_LUN);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_HDD);
GFRE_DBI.RegisterObjectClassEx(TFRE_DB_VIRTUAL_FILESHARE);
//GFRE_DBI.Initialize_Extension_Objects;
end;
function String2DBZFSRaidLevelType(const fts: string): TFRE_DB_ZFS_RAID_LEVEL;
begin
for result in TFRE_DB_ZFS_RAID_LEVEL do begin
if CFRE_DB_ZFS_RAID_LEVEL[result]=fts then exit;
end;
raise Exception.Create('invalid short DBZFSRaidLevel specifier : ['+fts+']');
end;
function ParseZpool(const pooltxt: string; out pool: TFRE_DB_ZFS_POOL): boolean;
begin
writeln('CODE DELETETED ? OBSOLETE USE NEW METHOD');
abort;
end;
procedure CreateZFSDataCollections(const conn: IFRE_DB_COnnection);
var
collection : IFRE_DB_COLLECTION;
begin
if not conn.CollectionExists(CFRE_DB_ZFS_POOL_COLLECTION) then
begin
collection := conn.CreateCollection(CFRE_DB_ZFS_POOL_COLLECTION);
collection.DefineIndexOnField('zfs_guid',fdbft_String,true,true);
end else begin
collection := conn.GetCollection(CFRE_DB_ZFS_POOL_COLLECTION);
end;
if not collection.IndexExists('upid') then begin
collection.DefineIndexOnField('uct',fdbft_String,true,true,'upid',false);
end;
if not conn.CollectionExists(CFRE_DB_ZFS_DATASET_COLLECTION) then
begin
collection := conn.CreateCollection(CFRE_DB_ZFS_DATASET_COLLECTION);
end else begin
collection := conn.GetCollection(CFRE_DB_ZFS_DATASET_COLLECTION);
end;
if not collection.IndexExists('upid') then begin
collection.DefineIndexOnField('uct',fdbft_String,true,true,'upid',false);
end;
if not conn.CollectionExists(CFRE_DB_ZFS_SNAPSHOT_COLLECTION) then
begin
collection := conn.CreateCollection(CFRE_DB_ZFS_SNAPSHOT_COLLECTION);
end;
if not conn.CollectionExists(CFRE_DB_ZFS_VDEV_COLLECTION) then
begin
collection := conn.CreateCollection(CFRE_DB_ZFS_VDEV_COLLECTION);
collection.DefineIndexOnField('zfs_guid',fdbft_String,true,true);
end;
if not conn.CollectionExists(CFRE_DB_ZFS_BLOCKDEVICE_COLLECTION) then
begin
collection := conn.CreateCollection(CFRE_DB_ZFS_BLOCKDEVICE_COLLECTION);
collection.DefineIndexOnField('zfs_guid',fdbft_String,true,true);
end;
end;
initialization
end.
|
{: Solar system planetary elements and positions utility unit.<p>
Based on document by Paul Schlyter (Stockholm, Sweden)<br>
http://www.stjarnhimlen.se/comp/ppcomp.html<p>
Coordinates system takes Z as "up", ie. normal to the ecliptic plane,
"axis" around which the planets turn.<p>
Eric Grange<br>
http://glscene.org}
{ RCDType,RCDCount :Integer;
RCDXYSize, RCDZSize, RCDPosition : Double;}
(*
Spec,{Tag: 1 Sun,2 Planet,3 Ast,4 Com,5 Deb,6 Ring,7 Moon, 8 3ds
19 CometSprite
20 Sun Flare, 21 Ring Proxy, 22 FFDebris Proxy}
Species,{Hint Parent# ,sub#}
SubSpecies{Object#}
for Proxyi:=1 to trunc(DebrisDataTmpArray[i].Density) do
begin
DCSolarSystem.children[LevelCount].children[0].Children[Level2Count].children[Proxyi].
DCSolarSystem.children[LevelCount].children[0].Children[Level2Count].AddChild(FFDebris);
proxy:=TGLProxyObject(DCSolarSystem.children[LevelCount].children[0].Children[Level2Count].AddNewChild(TGLProxyObject));
DCSolarSystem.children[LevelCount].children[0].Children[Level2Count].children[Proxyi].Translate(x,y,z);
TGLLensFlare = class(TGLBaseSceneObject)
TGLSprite = class (TGLSceneObject)
TGLPoints = class (TGLImmaterialSceneObject)
TGLLinesNode = class(TGLNode)
TGLLinesNodes = class(TGLNodes)
TGLPoints = class (TGLImmaterialSceneObject)
TGLLineBase = class(TGLImmaterialSceneObject)
TGLNodedLines = class(TGLLineBase)
TGLLines = class(TGLNodedLines)
TGLQuadricObject = class(TGLSceneObject)
TGLSphere = class (TGLQuadricObject)
*)
(*
TSystemData = record
NbSun : byte; //ONLY 1 allowed so far
NbPlanet : byte;
NbAsteroid : Byte;
NbComet : Byte;
NbDebris : Byte;
end;
TSunData = record // Also Equal to material texture
{NOT 8.3 NAME only Extension ADDED ..ONLY .jpg Expected: .bmp .tif .tga .png ignored}
SunName : String[255] ;
Radius : Double;
ObjectRotation : Double;
AxisTilt : Double;
nbS3ds : Byte;
DocIndex : Byte;
SystemObjectScale : Double; {Sun ONLY}
SystemDistanceScale : Double; {Sun ONLY}
end;
TPlanetData = record
Name : String[255]; {Planet.jpg .. Planet_Bump.jpg}
Radius : Double;
ObjectRotation : Double;
AxisTilt : Double;
nbRings : Byte;
nbMoons : Byte;
nbS3ds : Byte;
DocIndex : Byte;
Albedo, OrbitRotation : Double;
aDistance,aDistanceVar : Double; //aConstEdit aVarEdit
Inclination,InclinationVar : Double; //iConstEdit iVarEdit
Eccentricity , EVar, EMax : Double; //eConstEdit eVarEdit EMaxEdit
nLongitude, nLongitudeVar : Double; //NConstEdit NVarEdit
wPerihelion,wPerihelionVar : Double; //wConstEdit wVarEdit
mAnomaly, mAnomalyVar : Double; //MConstEdit MVarEdit
Mass, Density : Double;
Atmosphere, VelocityType : Byte;
Velocity, VelocityDir : Double;
{Which way does the wind blow Given a direction
0 to 100 or 1 to 100 is that 100 or 101}
end;
TMoonRingData = record //3ds files and DebrisAsteroid too
Name : String[255];{Planet_Moon.jpg}
Radius : Double;
ObjectRotation : Double;
AxisTilt : Double;
S3dsTex :Boolean;
DocIndex : Byte;
Mass, Density : Double;
RCDType,RCDCount:Integer;
RCDXYSize, RCDZSize, RCDPosition : Double;
Albedo, OrbitRotation : Double;
aDistance,aDistanceVar : Double;
Inclination,InclinationVar : Double;
Eccentricity , EVar, EMax : Double;
nLongitude, nLongitudeVar : Double;
wPerihelion,wPerihelionVar : Double;
mAnomaly, mAnomalyVar : Double;
Atmosphere, VelocityType : Byte;
Velocity, VelocityDir : Double;
end;
TACDData = record //Asteroid Comet Debris sphere..NOT DebrisAsteroid
Name : String[255];
Radius : Double;
ObjectRotation : Double;
AxisTilt : Double;
nbS3ds : Byte;
DocIndex : Byte;
RCDType,RCDCount :Integer;
RCDXYSize, RCDZSize, RCDPosition : Double;
Albedo, OrbitRotation : Double;
aDistance,aDistanceVar : Double;
Inclination,InclinationVar : Double;
Eccentricity , EVar, EMax : Double;
nLongitude, nLongitudeVar : Double;
wPerihelion,wPerihelionVar : Double;
mAnomaly, mAnomalyVar : Double;
Mass, Density : Double;
Atmosphere, VelocityType : Byte;
Velocity, VelocityDir : Double;
end;
*)
unit USolarSystem;
interface
uses
System.SysUtils,
System.Math,
GLVectorGeometry;
type
TOrbitalElements = record
N : Double; // longitude of the ascending node
i : Double; // inclination to the ecliptic (plane of the Earth's orbit)
w : Double; // argument of perihelion
a : Double; // semi-major axis, or mean distance from Sun
e : Double; // eccentricity (0=circle, 0-1=ellipse, 1=parabola)
M : Double; // mean anomaly (0 at perihelion; increases uniformly with time)
end;
{The whole point is these are used to compute the ABOVE.. Depending on the CURRENT TIME}
TOrbitalElementsData = record
NConst, NVar : Double; // longitude of the ascending node
iConst, iVar : Double; // inclination to the ecliptic (plane of the Earth's orbit)
wConst, wVar : Double; // argument of perihelion
aConst, aVar : Double; // semi-major axis, or mean distance from Sun
eConst, eVar : Double; // eccentricity (0=circle, 0-1=ellipse, 1=parabola)
MConst, MVar : Double; // mean anomaly (0 at perihelion; increases uniformly with time)
end;
const
// geocentric sun elements (?)
cSunOrbitalElements : TOrbitalElementsData = (
NConst : 0.0; NVar : 0.0;
iConst : 0.0; iVar : 0.0;
wConst : 282.9404; wVar : 4.70935E-5;
aConst : 1.000000; aVar : 0.0; // (AU)
eConst : 0.016709; eVar : -1.151E-9;
MConst : 356.0470; MVar : 0.9856002585 );
// geocentric moon elements
cMoonOrbitalElements : TOrbitalElementsData = (
NConst : 125.1228; NVar : -0.0529538083;
iConst : 5.1454; iVar : 0.0;
wConst : 318.0634; wVar : 0.1643573223;
aConst : 60.2666; aVar : 0.0; // (Earth radii)
eConst : 0.054900; eVar : 0.0;
MConst : 115.3654; MVar : 13.0649929509 );
// heliocentric mercury elements
cMercuryOrbitalElements : TOrbitalElementsData = (
NConst : 48.3313; NVar : 3.24587E-5;
iConst : 7.0047; iVar : 5.00E-8;
wConst : 29.1241; wVar : 1.01444E-5;
aConst : 0.387098; aVar : 0.0; // (AU)
eConst : 0.205635; eVar : 5.59E-10;
MConst : 168.6562; MVar : 4.0923344368 );
// heliocentric venus elements
cVenusOrbitalElements : TOrbitalElementsData = (
NConst : 76.6799; NVar : 2.46590E-5;
iConst : 3.3946; iVar : 2.75E-8;
wConst : 54.8910; wVar : 1.38374E-5;
aConst : 0.723330; aVar : 0.0; // (AU)
eConst : 0.006773; eVar : -1.302E-9;
MConst : 48.0052; MVar : 1.6021302244 );
// heliocentric mars elements
cMarsOrbitalElements : TOrbitalElementsData = (
NConst : 49.5574; NVar : 2.11081E-5;
iConst : 1.8497; iVar : -1.78E-8;
wConst : 286.5016; wVar : 2.92961E-5;
aConst : 1.523688; aVar : 0.0; // (AU)
eConst : 0.093405; eVar : 2.516E-9;
MConst : 18.6021; MVar : 0.5240207766 );
// heliocentric jupiter elements
cJupiterOrbitalElements : TOrbitalElementsData = (
NConst : 100.4542; NVar : 2.76854E-5;
iConst : 1.3030; iVar : -1.557E-7;
wConst : 273.8777; wVar : 1.64505E-5;
aConst : 5.20256; aVar : 0.0; // (AU)
eConst : 0.048498; eVar : 4.469E-9;
MConst : 19.8950; MVar : 0.0830853001 );
// heliocentric saturn elements
cSaturnOrbitalElements : TOrbitalElementsData = (
NConst : 113.6634; NVar : 2.38980E-5;
iConst : 2.4886; iVar : -1.081E-7;
wConst : 339.3939; wVar : 2.97661E-5;
aConst : 9.55475; aVar : 0.0; // (AU)
eConst : 0.055546; eVar : -9.499E-9;
MConst : 316.9670; MVar : 0.0334442282 );
// heliocentric uranus elements
cUranusOrbitalElements : TOrbitalElementsData = (
NConst : 74.0005; NVar : 1.3978E-5;
iConst : 0.7733; iVar : 1.9E-8;
wConst : 96.6612; wVar : 3.0565E-5;
aConst : 19.18171; aVar : -1.55E-8; // (AU)
eConst : 0.047318; eVar : 7.45E-9;
MConst : 142.5905; MVar : 0.011725806 );
// heliocentric neptune elements
cNeptuneOrbitalElements : TOrbitalElementsData = (
NConst : 131.7806; NVar : 3.0173E-5;
iConst : 1.7700; iVar : -2.55E-7;
wConst : 272.8461; wVar : -6.027E-6;
aConst : 30.05826; aVar : 3.313E-8; // (AU)
eConst : 0.008606; eVar : 2.15E-9;
MConst : 260.2471; MVar : 0.005995147 );
cAUToKilometers = 149.6e6; // astronomical units to kilometers
cEarthRadius = 6400; // earth radius in kilometers
{: Converts a TDateTime (GMT+0) into the julian day used for computations. }
function GMTDateTimeToJulianDay(const dt : TDateTime) : Double;
{: Compute orbital elements for given julian day. }
function ComputeOrbitalElements(const oeData : TOrbitalElementsData;
const d : Double) : TOrbitalElements;
{: Compute the planet position for given julian day (in AU). }
function ComputePlanetPosition(const orbitalElements : TOrbitalElements) : TAffineVector; overload;
function ComputePlanetPosition(const orbitalElementsData : TOrbitalElementsData;
const d : Double) : TAffineVector; overload;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// GMTDateTimeToJulianDay
//
function GMTDateTimeToJulianDay(const dt : TDateTime) : Double;
begin
Result:=dt-EncodeDate(2000, 1, 1);
end;
// ComputeOrbitalElements
//
function ComputeOrbitalElements(const oeData : TOrbitalElementsData;
const d : Double) : TOrbitalElements;
begin
with Result, oeData do begin
N:=NConst+NVar*d;
i:=iConst+iVar*d;
w:=wConst+wVar*d;
a:=aConst+aVar*d;
e:=eConst+eVar*d;
M:=MConst+MVar*d;
end;
end;
// ComputeSunPosition (prepared elements)
//
function ComputePlanetPosition(const orbitalElements : TOrbitalElements) : TAffineVector;
var
eccentricAnomaly, eA0 : Double;
sm, cm, se, ce, si, ci, cn, sn, cvw, svw : Double;
xv, yv, v, r : Double;
nn : Integer; // numerical instability bailout
begin
with orbitalElements do begin
// E = M + e*(180/pi) * sin(M) * ( 1.0 + e * cos(M) )
SinCosine(M*cPIdiv180, sm, cm);
eccentricAnomaly:=M+e*c180divPI*sm*(1.0+e*cm);
nn:=0;
repeat
eA0:=eccentricAnomaly;
// E1 = E0 - ( E0 - e*(180/pi) * sin(E0) - M ) / ( 1 - e * cos(E0) )
SinCosine(eA0*cPIdiv180, se, ce);
eccentricAnomaly:=eA0-(eA0-e*c180divPI*se-M)/(1-e*ce);
Inc(nn);
until (nn>10) or (Abs(eccentricAnomaly-eA0)<1e-4);
SinCosine(eccentricAnomaly*cPIdiv180, se, ce);
xv:=a*(ce-e);
yv:=a*(Sqrt(1.0-e*e)*se);
v:=ArcTan2(yv, xv)*c180divPI;
r:=Sqrt(xv*xv+yv*yv);
SinCosine(i*cPIdiv180, si, ci);
SinCosine(N*cPIdiv180, sn, cn);
SinCosine((v+w)*cPIdiv180, svw, cvw);
end;
// xh = r * ( cos(N) * cos(v+w) - sin(N) * sin(v+w) * cos(i) )
Result.X:=r*(cn*cvw-sn*svw*ci);
// yh = r * ( sin(N) * cos(v+w) + cos(N) * sin(v+w) * cos(i) )
Result.Y:=r*(sn*cvw+cn*svw*ci);
// zh = r * ( sin(v+w) * sin(i) )
Result.Z:=r*(svw*si);
end;
// ComputePlanetPosition (data)
//
function ComputePlanetPosition(const orbitalElementsData : TOrbitalElementsData;
const d : Double) : TAffineVector;
var
oe : TOrbitalElements;
begin
oe:=ComputeOrbitalElements(orbitalElementsData, d);
Result:=ComputePlanetPosition(oe);
end;
end.
|
unit globConfig;
{
Global configuration of SW.
}
interface
uses IniFiles, SysUtils, Types, Generics.Collections, Classes;
type
TServerConfig = record
host:string;
port:Word;
end;
TGlobConfigData = record
server:TServerConfig;
seconds:boolean;
end;
TGlobConfig = class
public const
_DEFAULT_FN = 'config.ini';
private
filename:string;
public
data:TGlobConfigData;
procedure LoadFile(const filename:string = _DEFAULT_FN);
procedure SaveFile(const filename:string); overload;
procedure SaveFile(); overload;
property fn:string read filename;
end;
var
config:TGlobConfig;
implementation
uses tcpClient;
////////////////////////////////////////////////////////////////////////////////
procedure TGlobConfig.LoadFile(const filename:string = _DEFAULT_FN);
var ini:TMemIniFile;
begin
ini := TMemIniFile.Create(filename, TEncoding.UTF8);
try
Self.filename := filename;
Self.data.server.host := ini.ReadString('server', 'host', 'localhost');
Self.data.server.port := ini.ReadInteger('server', 'port', _DEFAULT_PORT);
Self.data.seconds := ini.ReadBool('time', 'seconds', true);
finally
ini.Free();
end;
end;
procedure TGlobConfig.SaveFile(const filename:string);
var ini:TMemIniFile;
begin
ini := TMemIniFile.Create(filename, TEncoding.UTF8);
try
ini.WriteString('server', 'host', Self.data.server.host);
ini.WriteInteger('server', 'port', Self.data.server.port);
ini.WriteBool('time', 'seconds', Self.data.seconds);
ini.UpdateFile();
finally
ini.Free();
end;
end;
procedure TGlobConfig.SaveFile();
begin
Self.SaveFile(Self.filename);
end;
////////////////////////////////////////////////////////////////////////////////
initialization
config := TGlobConfig.Create();
finalization
FreeAndNil(config);
end.//unit
|
unit System_Rtc;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls;
type
{ TSystemRtc }
TSystemRtc = class
private // Attribute
type
TBitReg8 = bitpacked record
case byte of
0: (Value: byte); // 8Bit Register Value
2: (bit: bitpacked array[0..7] of boolean); // Bit Data
end;
var
clkUpdateTimer: TTimer;
clkDateTime, almDateTime, corrDateTime: TDateTime;
rtcRam: array[0..127] of byte;
dataAddr: byte;
ctrlA, ctrlB, ctrlC, ctrlD: TBitReg8;
const
// Bitkonstanten für Control Register A
UIP = $07; // Update in Progress
DV = $70; // Oszillator Control
RS = $0F; // Rate Selector
// Bitkonstanten für Control Register B
SB = $07; // Set Bit
PIE = $06; // Periodic Interrupt Enable
AIE = $05; // Alarm Interrupt Enable
UIE = $04; // Update-Ended Interrupt Enable
SQWE = $03; // Square-Wave Enable
DM = $02; // Data Mode: 0 = BCD-Mode , 1 = Binary-Mode
CM24 = $01; // Clock Mode: 0 = 12-Hour Mode , 1 = 24-Hour Mode
DSE = $00; // Daylight Saving Enable
// Bitkonstanten für Control Register C
IRQF = $07; // Interrupt Request Flag
PF = $06; // Periodic Interrupt Flag
AF = $05; // Alarm Interrupt Flag
UF = $04; // Update-Ended Interrupt Flag
// Bitkonstanten für Control Register D
VRT = $07; // Valid RAM and Time
protected // Attribute
public // Attribute
public // Konstruktor/Destruktor
constructor Create; overload;
destructor Destroy; override;
private // Methoden
procedure checkUpdateTimer;
function BcdToInteger(Value: byte): byte;
function IntegerToBcd(Value: byte): byte;
function getActualYear: byte;
function getActualCentury: byte;
procedure saveRtcData;
procedure readRtcData;
protected // Methoden
procedure doClock(Sender: TObject);
public // Methoden
procedure setAddress(addr: byte);
procedure Write(Data: byte);
function Read: byte;
procedure reset;
end;
var
SystemRtc: TSystemRtc;
implementation
{ TSystemRtc }
uses DateUtils, StrUtils, System_Settings;
// --------------------------------------------------------------------------------
constructor TSystemRtc.Create;
begin
inherited Create;
clkUpdateTimer := TTimer.Create(nil);
clkUpdateTimer.Enabled := False;
clkUpdateTimer.Interval := 100;
clkUpdateTimer.OnTimer := @doClock;
clkDateTime := now;
corrDateTime := clkDateTime;
readRtcData;
ctrlD.bit[VRT] := True;
checkUpdateTimer;
end;
// --------------------------------------------------------------------------------
destructor TSystemRtc.Destroy;
begin
if Assigned(clkUpdateTimer) then begin
clkUpdateTimer.Enabled := False;
clkUpdateTimer.OnTimer := nil;
clkUpdateTimer.Destroy;
end;
saveRtcData;
inherited Destroy;
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.checkUpdateTimer;
begin
if ((ctrlA.Value and DV) = %00100000) then begin
clkUpdateTimer.Enabled := True;
end
else begin
clkUpdateTimer.Enabled := False;
end;
end;
// --------------------------------------------------------------------------------
function TSystemRtc.BcdToInteger(Value: byte): byte;
begin
Result := (Value and $0F);
Result := Result + (((Value shr 4) and $0F) * 10);
end;
// --------------------------------------------------------------------------------
function TSystemRtc.IntegerToBcd(Value: byte): byte;
begin
Result := Value div 10 mod 10;
Result := (Result shl 4) or Value mod 10;
end;
// --------------------------------------------------------------------------------
function TSystemRtc.getActualYear: byte;
begin
Result := (FormatDateTime('yy', clkDateTime).ToInteger and $7F);
end;
// --------------------------------------------------------------------------------
function TSystemRtc.getActualCentury: byte;
begin
Result := ((((FormatDateTime('yyyy', clkDateTime).ToInteger) - getActualYear) div 100) and $7F);
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.saveRtcData;
var
Data: string;
addr: byte;
begin
Data := IntToHex(ctrlA.Value, 2);
Data := Data + IntToHex(ctrlB.Value, 2);
Data := Data + IntToHex(ctrlC.Value, 2);
Data := Data + IntToHex(ctrlD.Value, 2);
for addr := $0E to $31 do begin
Data := Data + IntToHex(rtcRam[addr], 2);
end;
for addr := $33 to $7F do begin
Data := Data + IntToHex(rtcRam[addr], 2);
end;
SystemSettings.WriteString('RTC', 'Data', Data);
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.readRtcData;
var
Data: string;
addr, index: byte;
begin
Data := SystemSettings.ReadString('RTC', 'Data', '');
if (Data.IsEmpty) then
exit;
ctrlA.Value := Hex2Dec(Data.Substring(0, 2));
ctrlB.Value := Hex2Dec(Data.Substring(2, 2));
ctrlC.Value := Hex2Dec(Data.Substring(4, 2));
ctrlD.Value := Hex2Dec(Data.Substring(6, 2));
index := 8;
for addr := $0E to $31 do begin
rtcRam[addr] := Hex2Dec(Data.Substring(index, 2));
Inc(index, 2);
end;
for addr := $33 to $7F do begin
rtcRam[addr] := Hex2Dec(Data.Substring(index, 2));
Inc(index, 2);
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.doClock(Sender: TObject);
begin
if (not ctrlB.bit[SB]) then begin
ctrlA.bit[UIP] := True;
clkDateTime := IncMilliSecond(clkDateTime, Round(MilliSecondSpan(corrDateTime, now)));
corrDateTime := now;
ctrlA.bit[UIP] := False;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.setAddress(addr: byte);
begin
dataAddr := (addr and $7F);
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.Write(Data: byte);
begin
case (dataAddr) of
$00: begin // write Clock Seconds
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $3F);
end
else begin // bcd
Data := BcdToInteger(Data and $7F);
end;
clkDateTime := RecodeSecond(clkDateTime, Data);
end;
$01: begin // write Alarm Seconds
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $3F);
end
else begin // bcd
Data := BcdToInteger(Data and $7F);
end;
almDateTime := RecodeSecond(almDateTime, Data);
end;
$02: begin // write Clock Minutes
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $3F);
end
else begin // bcd
Data := BcdToInteger(Data and $7F);
end;
clkDateTime := RecodeMinute(clkDateTime, Data);
end;
$03: begin // write Alarm Minutes
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $3F);
end
else begin // bcd
Data := BcdToInteger(Data and $7F);
end;
almDateTime := RecodeMinute(almDateTime, Data);
end;
$04: begin // write Clock Hours
if (ctrlB.bit[DM]) then begin // binär
if (ctrlB.bit[CM24]) then begin // binär 24Std
Data := (Data and $1F);
end
else begin // binär 12Std
Data := (Data and $8F);
if ((Data and $80) <> 0) then begin
//Data := ((Data + 12) - 128);
Data := ((Data and $1F) + 12);
end;
end;
end
else begin // bcd
if (ctrlB.bit[CM24]) then begin // bcd 24Std
Data := BcdToInteger(Data and $3F);
end
else begin // bcd 12Std
Data := (Data and $9F);
if ((Data and $80) <> 0) then begin
Data := (BcdToInteger((Data and $3F)) + 12);
end;
end;
end;
clkDateTime := RecodeHour(clkDateTime, Data);
end;
$05: begin // write Alarm Hours
if (ctrlB.bit[DM]) then begin // binär
if (ctrlB.bit[CM24]) then begin // binär 24Std
Data := (Data and $1F);
end
else begin // binär 12Std
Data := (Data and $8F);
if ((Data and $80) <> 0) then begin
//Data := ((Data + 12) - 128);
Data := ((Data and $1F) + 12);
end;
end;
end
else begin // bcd
if (ctrlB.bit[CM24]) then begin // bcd 24Std
Data := BcdToInteger(Data and $3F);
end
else begin // bcd 12Std
Data := (Data and $9F);
if ((Data and $80) <> 0) then begin
Data := (BcdToInteger((Data and $3F)) + 12);
end;
end;
end;
almDateTime := RecodeHour(almDateTime, Data);
end;
$06: begin // write Clock Day
//clkDay := ((clkDay and not $07) or (Data and $07));
end;
$07: begin // write Clock Date
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $1F);
end
else begin // bcd
Data := BcdToInteger(Data and $3F);
end;
clkDateTime := RecodeDay(clkDateTime, Data);
end;
$08: begin // write Clock Month
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $0F);
end
else begin // bcd
Data := BcdToInteger(Data and $1F);
end;
clkDateTime := RecodeMonth(clkDateTime, Data);
end;
$09: begin // write Clock Year
if (ctrlB.bit[DM]) then begin // binär
Data := (Data and $7F);
end
else begin // bcd
Data := BcdToInteger(Data and $FF);
end;
clkDateTime := RecodeYear(clkDateTime, ((getActualCentury * 100) + Data));
end;
$0A: begin // write Control Register A
ctrlA.Value := ((ctrlA.Value and not $7F) or (Data and $7F));
checkUpdateTimer;
end;
$0B: begin // write Control Register B
ctrlB.Value := ((ctrlB.Value and not $FF) or (Data and $FF));
end;
$0C: begin // write Control Register C
ctrlC.Value := ((ctrlC.Value and not $00) or (Data and $00));
end;
$0D: begin // write Control Register D
ctrlD.Value := ((ctrlD.Value and not $00) or (Data and $00));
end;
$0E..$31: begin
rtcRam[dataAddr] := Data;
end;
$32: begin // write Clock Century
if (not ctrlB.bit[DM]) then begin // bcd only
Data := BcdToInteger(Data and $FF);
clkDateTime := RecodeYear(clkDateTime, ((Data * 100) + getActualYear));
end;
end;
$33..$7F: begin
rtcRam[dataAddr] := Data;
end;
end;
end;
// --------------------------------------------------------------------------------
function TSystemRtc.Read: byte;
begin
case (dataAddr) of
$00: begin // read Clock Seconds
Result := (FormatDateTime('ss', clkDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $3F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $7F);
end;
end;
$01: begin // read Alarm Seconds
Result := (FormatDateTime('ss', almDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $3F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $7F);
end;
end;
$02: begin // read Clock Minutes
Result := (FormatDateTime('nn', clkDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $3F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $7F);
end;
end;
$03: begin // read Alarm Minutes
Result := (FormatDateTime('nn', almDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $3F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $7F);
end;
end;
$04: begin // read Clock Hours
Result := (FormatDateTime('hh', clkDateTime).ToInteger and $1F);
if (ctrlB.bit[DM]) then begin // binär
if (not ctrlB.bit[CM24]) then begin // binär 12Std
if (IsPM(clkDateTime)) then begin
Result := (((Result - 12) + 128) and $8F);
end;
end;
end
else begin // bcd
if (ctrlB.bit[CM24]) then begin // bcd 24Std
Result := (IntegerToBcd(Result) and $3F);
end
else begin // bcd 12Std
if (IsPM(clkDateTime)) then begin
Result := (IntegerToBcd(Result - 12) and $1F);
Result := ((Result + 128) and $9F);
end;
end;
end;
end;
$05: begin // read Alarm Hours
Result := (FormatDateTime('hh', almDateTime).ToInteger and $1F);
if (ctrlB.bit[DM]) then begin // binär
if (not ctrlB.bit[CM24]) then begin // binär 12Std
if (IsPM(clkDateTime)) then begin
Result := (((Result - 12) + 128) and $8F);
end;
end;
end
else begin // bcd
if (ctrlB.bit[CM24]) then begin // bcd 24Std
Result := (IntegerToBcd(Result) and $3F);
end
else begin // bcd 12Std
if (IsPM(almDateTime)) then begin
Result := (IntegerToBcd(Result - 12) and $1F);
Result := ((Result + 128) and $9F);
end;
end;
end;
end;
$06: begin // read Clock Day
Result := (DayOfTheWeek(clkDateTime) and $07);
end;
$07: begin // read Clock Date
Result := (FormatDateTime('dd', clkDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $1F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $3F);
end;
end;
$08: begin // read Clock Month
Result := (FormatDateTime('mm', clkDateTime).ToInteger);
if (ctrlB.bit[DM]) then begin // binär
Result := (Result and $0F);
end
else begin // bcd
Result := (IntegerToBcd(Result) and $1F);
end;
end;
$09: begin // read Clock Year
if (ctrlB.bit[DM]) then begin // binär
Result := (getActualYear and $7F);
end
else begin // bcd
Result := (IntegerToBcd(getActualYear) and $FF);
end;
end;
$0A: begin // read Control Register A
Result := (ctrlA.Value and $FF);
end;
$0B: begin // read Control Register B
Result := (ctrlB.Value and $FF);
end;
$0C: begin // read Control Register C
Result := (ctrlC.Value and $F0);
ctrlC.Value := 0;
end;
$0D: begin // read Control Register D
Result := (ctrlD.Value and $80);
end;
$0E..$31: begin
Result := rtcRam[dataAddr];
end;
$32: begin // read Clock Century
if (not ctrlB.bit[DM]) then begin // bcd only
Result := (IntegerToBcd(getActualCentury) and $FF);
end;
end;
$33..$7F: begin
Result := rtcRam[dataAddr];
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemRtc.reset;
begin
ctrlB.bit[PIE] := False;
ctrlB.bit[AIE] := False;
ctrlB.bit[UIE] := False;
ctrlB.bit[SQWE] := False;
ctrlC.bit[IRQF] := False;
ctrlC.bit[PF] := False;
ctrlC.bit[AF] := False;
ctrlC.bit[UF] := False;
end;
// --------------------------------------------------------------------------------
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clTlsSocket;
interface
{$I clVer.inc}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
Windows, Classes, clSocket, clSspi, clCert;
type
TclOnVerifyPeerEvent = procedure (Sender: TObject; ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean) of object;
TclTlsNetworkStream = class(TclNetworkStream)
private
FReadData: TStream;
FWriteData: TStream;
FSSPIBuffer: TStream;
FSSPI: TclTlsSspi;
FSSPIResult: TclSspiReturnCode;
FPacketSize: Integer;
FNeedAuthenticate: Boolean;
FWriteSize: Int64;
FOnGetCertificate: TclOnGetCertificateEvent;
FOnVerifyPeer: TclOnVerifyPeerEvent;
FCertificateFlags: TclCertificateFlags;
FTargetName: string;
FTLSFlags: TclTlsFlags;
FPeerVerified: Boolean;
FRequireClientCertificate: Boolean;
procedure Authenticate(ADestination: TStream);
procedure AfterRead(ABuffer, ADestination: TStream);
function WriteBuffer(ABuffer: TStream; ABufferSize: Int64): Boolean;
procedure TlsUpdateProgress(ABytesProceed: Int64);
procedure TlsStreamReady;
function GetSSPI: TclTlsSspi;
procedure FreeSSPI;
procedure VerifyPeer;
procedure SetCertificateFlags(const Value: TclCertificateFlags);
procedure SetTLSFlags(const Value: TclTlsFlags);
protected
procedure UpdateProgress(ABytesProceed: Int64); override;
procedure StreamReady; override;
property SSPI: TclTlsSspi read GetSSPI;
public
constructor Create;
destructor Destroy; override;
procedure Assign(ASource: TclNetworkStream); override;
function Connect(const AIP: string; APort: Integer): Boolean; override;
procedure Accept; override;
procedure Close(ANotifyPeer: Boolean); override;
function Read(AData: TStream): Boolean; override;
function Write(AData: TStream): Boolean; override;
function GetBatchSize: Integer; override;
procedure OpenClientSession; override;
procedure OpenServerSession; override;
property TargetName: string read FTargetName write FTargetName;
property CertificateFlags: TclCertificateFlags read FCertificateFlags write SetCertificateFlags;
property TLSFlags: TclTlsFlags read FTLSFlags write SetTLSFlags;
property RequireClientCertificate: Boolean read FRequireClientCertificate write FRequireClientCertificate;
property OnGetCertificate: TclOnGetCertificateEvent read FOnGetCertificate write FOnGetCertificate;
property OnVerifyPeer: TclOnVerifyPeerEvent read FOnVerifyPeer write FOnVerifyPeer;
end;
resourcestring
cReAuthNeeded = 'The connection must be re-negotiated';
implementation
uses
SysUtils, clSspiUtils{$IFDEF LOGGER}, clLogger{$ENDIF};
{ TclTlsNetworkStream }
procedure TclTlsNetworkStream.Accept;
begin
ClearNextAction();
inherited Accept();
OpenServerSession();
end;
procedure TclTlsNetworkStream.Close(ANotifyPeer: Boolean);
begin
ClearNextAction();
FSSPIResult := rcOK;
FSSPIBuffer.Size := 0;
try
FSSPIResult := SSPI.EndSession(FSSPIBuffer);
except
on EclSSPIError do ;
end;
try
if ANotifyPeer and (FSSPIResult = rcCompleteNeeded) then
begin
if not WriteBuffer(nil, 0) then
begin
SetNextAction(saWrite);
end;
end;
except
on E: EclSocketError do
begin
if (E.ErrorCode <> 10053) then raise;
end;
end;
FNeedAuthenticate := False;
FSSPIResult := rcReAuthNeeded;
end;
constructor TclTlsNetworkStream.Create;
begin
inherited Create();
FReadData := TMemoryStream.Create();
FWriteData := TMemoryStream.Create();
FSSPIBuffer := TMemoryStream.Create();
TLSFlags := [tfUseTLS];
end;
destructor TclTlsNetworkStream.Destroy;
begin
FWriteData.Free();
FReadData.Free();
FSSPIBuffer.Free();
FreeSSPI();
inherited Destroy();
end;
procedure TclTlsNetworkStream.FreeSSPI;
begin
FSSPI.Free();
FSSPI := nil;
FPeerVerified := False;
end;
function TclTlsNetworkStream.GetBatchSize: Integer;
begin
if (FPacketSize = 0) and (FSSPIResult = rcOK) then
begin
try
FPacketSize := Integer(SSPI.StreamSizes.cbHeader + SSPI.StreamSizes.cbTrailer);
except
on EclSSPIError do ;
end;
end;
Result := inherited GetBatchSize() + FPacketSize;
end;
function TclTlsNetworkStream.Connect(const AIP: string; APort: Integer): Boolean;
begin
ClearNextAction();
Result := inherited Connect(AIP, APort);
OpenClientSession();
end;
function TclTlsNetworkStream.Read(AData: TStream): Boolean;
var
oldPos: Int64;
stream: TMemoryStream;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Read');{$ENDIF}
oldPos := -1;
if (AData <> nil) then
begin
oldPos := AData.Position;
end;
try
ClearNextAction();
Result := True;
if (FReadData.Size > 0) and (AData <> nil) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read: if (FSSPIResult = rcOK)');{$ENDIF}
AData.CopyFrom(FReadData, 0);
FReadData.Size := 0;
end else
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read: else of if (FSSPIResult = rcOK)');{$ENDIF}
if (AData = nil) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read: else of if (FSSPIResult = rcOK), (AData = nil)');{$ENDIF}
AData := FReadData;
end;
stream := TMemoryStream.Create();
try
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read: before inherited Read, %d', nil, [stream.Size]);{$ENDIF}
Result := inherited Read(stream);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read: after inherited Read', stream, 0);{$ENDIF}
if (stream.Size > 0) then
begin
stream.Position := 0;
AfterRead(stream, AData);
end;
finally
stream.Free();
end;
end;
HasReadData := (FReadData.Size > 0);
if (FSSPIResult = rcReAuthNeeded) then
begin
SetNextAction(saWrite);
end else
if not (FSSPIResult in [rcOK, rcError, rcClosingNeeded]) then
begin
SetNextAction(saRead);
end;
finally
if (oldPos > -1) then
begin
TlsUpdateProgress(AData.Size - oldPos);
end;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Read'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Read', E); raise; end; end;{$ENDIF}
end;
function TclTlsNetworkStream.Write(AData: TStream): Boolean;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Write');{$ENDIF}
ClearNextAction();
Result := True;
if FNeedAuthenticate then
begin
FNeedAuthenticate := False;
Authenticate(nil);
end else
if (AData <> nil) then
begin
while Result and (AData.Position < AData.Size) do
begin
if (FWriteData.Size = 0) then
begin
FWriteSize := AData.Size - AData.Position;
if (FWriteSize > Connection.BatchSize) then
begin
FWriteSize := Connection.BatchSize;
end;
Result := WriteBuffer(AData, FWriteSize);
if Result then
begin
TlsUpdateProgress(FWriteSize);
AData.Position := AData.Position + FWriteSize;
end;
end else
begin
Result := WriteBuffer(nil, 0);
if Result then
begin
TlsUpdateProgress(FWriteSize);
AData.Position := AData.Position + FWriteSize;
end;
end;
end;
end else
begin
Result := WriteBuffer(nil, 0);
if not Result then
begin
SetNextAction(saWrite);
end;
end;
if (FSSPIResult <> rcOK) then
begin
SetNextAction(saRead);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Write'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Write', E); raise; end; end;{$ENDIF}
end;
procedure TclTlsNetworkStream.Authenticate(ADestination: TStream);
var
cert: TclCertificate;
certHandled: Boolean;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Authenticate');{$ENDIF}
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'Authenticate, FSSPIBuffer.Position = %d, FSSPIBuffer.Size = %d', nil, [FSSPIBuffer.Position, FSSPIBuffer.Size]);
{$ENDIF}
try
FPacketSize := 0;
FSSPIResult := SSPI.GenContext(FSSPIBuffer, nil, False);
if (FSSPIResult = rcCredentialNeeded) then
begin
cert := nil;
certHandled := False;
if Assigned(OnGetCertificate) then
begin
OnGetCertificate(Self, cert, certHandled);
end;
FSSPIResult := SSPI.GenContext(FSSPIBuffer, cert, certHandled);
end;
if (FSSPIResult = rcCredentialNeeded) then
begin
raise EclSSPIError.Create(SSPIErrorQueryLocalCertificate, -1);
end;
if (FSSPIResult in [rcOK, rcEncodeNeeded]) then
begin
VerifyPeer();
end;
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'Authenticate, before case FSSPIResult of, FSSPIBuffer.Position = %d, FSSPIBuffer.Size = %d', nil, [FSSPIBuffer.Position, FSSPIBuffer.Size]);
clPutLogMessage(Self, edInside, 'Authenticate, before case FSSPIResult of, FSSPIResult = %s', nil, [clSspiReturnCodes[FSSPIResult]]);
{$ENDIF}
case FSSPIResult of
rcAuthContinueNeeded:
begin
if not WriteBuffer(nil, 0) then
begin
SetNextAction(saWrite);
end;
FSSPIResult := rcAuthDataNeeded;
end;
rcEncodeNeeded:
begin
AfterRead(FSSPIBuffer, ADestination);
FSSPIResult := rcOk;
end;
rcOK:
begin
if (SSPI is TclTlsServerSspi) then
begin
FSSPIResult := rcAuthContinueNeeded;
if not WriteBuffer(nil, 0) then
begin
SetNextAction(saWrite);
end;
FSSPIResult := rcOk;
end;
end;
end;
finally
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'Authenticate, inside finally, FSSPIBuffer.Position = %d, FSSPIBuffer.Size = %d', nil, [FSSPIBuffer.Position, FSSPIBuffer.Size]);
{$ENDIF}
if not (FSSPIResult in [rcOK, rcAuthContinueNeeded, rcAuthMoreDataNeeded]) then
begin
FSSPIBuffer.Size := 0;
end;
end;
if (FSSPIResult = rcOK) then
begin
TlsStreamReady();
end;
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'Authenticate, before end, FSSPIBuffer.Position = %d, FSSPIBuffer.Size = %d', nil, [FSSPIBuffer.Position, FSSPIBuffer.Size]);
{$ENDIF}
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Authenticate'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Authenticate', E); raise; end; end;{$ENDIF}
end;
procedure TclTlsNetworkStream.AfterRead(ABuffer, ADestination: TStream);
var
oldPos: Int64;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'AfterRead, ABuffer.Position = %d, ABuffer.Size = %d, FSSPIResult = %s', nil, [ABuffer.Position, ABuffer.Size, clSspiReturnCodes[FSSPIResult]]);{$ENDIF}
case FSSPIResult of
rcOk,
rcAuthDataNeeded:
begin
FSSPIBuffer.Size := 0;
FSSPIBuffer.CopyFrom(ABuffer, ABuffer.Size);
FSSPIBuffer.Position := 0;
if (FSSPIResult = rcAuthDataNeeded) then
begin
Authenticate(ADestination);
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'AfterRead, %d, Authenticate exit', nil, [FSSPIBuffer.Size]);{$ENDIF}
Exit;
end;
end;
rcAuthMoreDataNeeded,
rcMoreDataNeeded:
begin
oldPos := FSSPIBuffer.Position;
FSSPIBuffer.Position := FSSPIBuffer.Size;
FSSPIBuffer.CopyFrom(ABuffer, ABuffer.Size);
FSSPIBuffer.Position := oldPos;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AfterRead, oldPos = %d', nil, [oldPos]);{$ENDIF}
if (FSSPIResult = rcAuthMoreDataNeeded) then
begin
Authenticate(ADestination);
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'AfterRead, %d, Authenticate exit', nil, [FSSPIBuffer.Size]);{$ENDIF}
Exit;
end;
end;
end;
Assert(ADestination <> nil);
FSSPIResult := SSPI.Decrypt(FSSPIBuffer, ADestination, FSSPIBuffer);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AfterRead, FSSPI.Decrypt %s', nil, [clSspiReturnCodes[FSSPIResult]]);{$ENDIF}
case FSSPIResult of
rcOk: FSSPIBuffer.Size := 0;
rcReAuthNeeded:
begin
FSSPIBuffer.Size := 0;
FNeedAuthenticate := True;
end;
rcContinueAndMoreDataNeeded: FSSPIResult := rcMoreDataNeeded;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AfterRead, %d', nil, [ADestination.Size]);{$ENDIF}
{$IFDEF LOGGER}
clPutLogMessage(Self, edLeave, 'AfterRead, %d', nil, [FSSPIBuffer.Size]);
except on E: Exception do begin clPutLogMessage(Self, edLeave, 'AfterRead, %d', E, [FSSPIBuffer.Size]); raise; end; end;
{$ENDIF}
end;
function TclTlsNetworkStream.WriteBuffer(ABuffer: TStream; ABufferSize: Int64): Boolean;
begin
if (FWriteData.Size = 0) then
begin
if not (FSSPIResult in [rcCompleteNeeded, rcAuthContinueNeeded]) then
begin
Assert(ABuffer <> nil);
FSSPIBuffer.Size := 0;
SSPI.Encrypt(ABuffer, FSSPIBuffer, ABufferSize); //TODO use FWriteData instead
FWriteData.CopyFrom(FSSPIBuffer, FSSPIBuffer.Size);
FSSPIBuffer.Position := 0;
end else
begin
Assert(ABuffer = nil);
FWriteData.CopyFrom(FSSPIBuffer, FSSPIBuffer.Size);
FSSPIBuffer.Size := 0;
end;
FWriteData.Position := 0;
end;
Result := inherited Write(FWriteData);
if Result then
begin
FWriteData.Size := 0;
end;
end;
procedure TclTlsNetworkStream.UpdateProgress(ABytesProceed: Int64);
begin
end;
procedure TclTlsNetworkStream.TlsUpdateProgress(ABytesProceed: Int64);
begin
inherited UpdateProgress(ABytesProceed);
end;
function TclTlsNetworkStream.GetSSPI: TclTlsSspi;
begin
Result := FSSPI;
Assert(Result <> nil);
end;
procedure TclTlsNetworkStream.StreamReady;
begin
end;
procedure TclTlsNetworkStream.TlsStreamReady;
begin
inherited StreamReady();
end;
procedure TclTlsNetworkStream.VerifyPeer;
var
statusText: string;
begin
if FPeerVerified then Exit;
FPeerVerified := SSPI.Certified;
statusText := GetSSPIErrorMessage(SSPI.StatusCode);
if Assigned(OnVerifyPeer) then
begin
OnVerifyPeer(Self, SSPI.PeerCertificate, statusText, SSPI.StatusCode, FPeerVerified);
end;
if not FPeerVerified then
begin
raise EclSSPIError.Create(statusText, SSPI.StatusCode);
end;
end;
procedure TclTlsNetworkStream.OpenClientSession;
begin
FreeSSPI();
FSSPI := TclTlsClientSspi.Create(TargetName);
FSSPI.CertificateFlags := CertificateFlags;
FSSPI.TLSFlags := TLSFlags;
FSSPIBuffer.Size := 0;
FNeedAuthenticate := True;
SetNextAction(saWrite);
end;
procedure TclTlsNetworkStream.OpenServerSession;
begin
FreeSSPI();
FSSPI := TclTlsServerSspi.Create(RequireClientCertificate);
FSSPI.CertificateFlags := CertificateFlags;
FSSPI.TLSFlags := TLSFlags;
FSSPIBuffer.Size := 0;
FSSPIResult := rcAuthDataNeeded;
FNeedAuthenticate := False;
SetNextAction(saRead);
end;
procedure TclTlsNetworkStream.SetCertificateFlags(const Value: TclCertificateFlags);
begin
FCertificateFlags := Value;
if (FSSPI <> nil) then
begin
FSSPI.CertificateFlags := FCertificateFlags;
end;
end;
procedure TclTlsNetworkStream.SetTLSFlags(const Value: TclTlsFlags);
begin
FTLSFlags := Value;
if (FSSPI <> nil) then
begin
FSSPI.TLSFlags := FTLSFlags;
end;
end;
procedure TclTlsNetworkStream.Assign(ASource: TclNetworkStream);
var
src: TclTlsNetworkStream;
begin
inherited Assign(ASource);
if (ASource is TclTlsNetworkStream) then
begin
src := ASource as TclTlsNetworkStream;
FTargetName := src.TargetName;
FCertificateFlags := src.CertificateFlags;
FTLSFlags := src.TLSFlags;
FRequireClientCertificate := src.RequireClientCertificate;
end;
end;
end.
|
unit MT5.Deal;
{$SCOPEDENUMS ON}
interface
uses
System.SysUtils, System.JSON, REST.JSON, System.Generics.Collections,
MT5.Connect, MT5.RetCode;
type
TMTDealProtocol = class;
TMTDeal = class;
TMTDealTotalAnswer = class;
TMTDealPageAnswer = class;
TMTDealAnswer = class;
TMTDealJson = class;
TMTDealProtocol = class
private
{ private declarations }
FMTConnect: TMTConnect;
function ParseDeal(ACommand: string; AAnswer: string; out ADealAnswer: TMTDealAnswer): TMTRetCodeType;
function ParseDealPage(AAnswer: string; out ADealPageAnswer: TMTDealPageAnswer): TMTRetCodeType;
function ParseDealTotal(AAnswer: string; out ADealTotalAnswer: TMTDealTotalAnswer): TMTRetCodeType;
protected
{ protected declarations }
public
{ public declarations }
constructor Create(AConnect: TMTConnect);
function DealGet(ATicket: string; out ADeal: TMTDeal): TMTRetCodeType;
function DealGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out ADealsCollection: TArray<TMTDeal>): TMTRetCodeType;
function DealGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
end;
TMTEnDealAction = (
DEAL_BUY = 0, // buy
DEAL_SELL = 1, // sell
DEAL_BALANCE = 2, // deposit operation
DEAL_CREDIT = 3, // credit operation
DEAL_CHARGE = 4, // additional charges
DEAL_CORRECTION = 5, // correction deals
DEAL_BONUS = 6, // bouns
DEAL_COMMISSION = 7, // commission
DEAL_COMMISSION_DAILY = 8, // daily commission
DEAL_COMMISSION_MONTHLY = 9, // monthly commission
DEAL_AGENT_DAILY = 10, // daily agent commission
DEAL_AGENT_MONTHLY = 11, // monthly agent commission
DEAL_INTERESTRATE = 12, // interest rate charges
DEAL_BUY_CANCELED = 13, // canceled buy deal
DEAL_SELL_CANCELED = 14, // canceled sell deal
DEAL_DIVIDEND = 15, // dividend
DEAL_DIVIDEND_FRANKED = 16, // franked dividend
DEAL_TAX = 17, // taxes
DEAL_AGENT = 18, // instant agent commission
DEAL_SO_COMPENSATION = 19, // negative balance compensation after stop-out
// --- enumeration borders
DEAL_FIRST = TMTEnDealAction.DEAL_BUY,
DEAL_LAST = TMTEnDealAction.DEAL_SO_COMPENSATION
);
TMTEnEntryFlags = (
ENTRY_IN = 0, // in market
ENTRY_OUT = 1, // out of market
ENTRY_INOUT = 2, // reverse
ENTRY_OUT_BY = 3, // closed by hedged position
ENTRY_STATE = 255, // state record
// --- enumeration borders
ENTRY_FIRST = TMTEnEntryFlags.ENTRY_IN,
ENTRY_LAST = TMTEnEntryFlags.ENTRY_STATE
);
TMTEnDealReason = (
DEAL_REASON_CLIENT = 0, // deal placed manually
DEAL_REASON_EXPERT = 1, // deal placed by expert
DEAL_REASON_DEALER = 2, // deal placed by dealer
DEAL_REASON_SL = 3, // deal placed due SL
DEAL_REASON_TP = 4, // deal placed due TP
DEAL_REASON_SO = 5, // deal placed due Stop-Out
DEAL_REASON_ROLLOVER = 6, // deal placed due rollover
DEAL_REASON_EXTERNAL_CLIENT = 7, // deal placed from the external system by client
DEAL_REASON_VMARGIN = 8, // deal placed due variation margin
DEAL_REASON_GATEWAY = 9, // deal placed by gateway
DEAL_REASON_SIGNAL = 10, // deal placed by signal service
DEAL_REASON_SETTLEMENT = 11, // deal placed due settlement
DEAL_REASON_TRANSFER = 12, // deal placed due position transfer
DEAL_REASON_SYNC = 13, // deal placed due position synchronization
DEAL_REASON_EXTERNAL_SERVICE = 14, // deal placed from the external system due service issues
DEAL_REASON_MIGRATION = 15, // deal placed due migration
DEAL_REASON_MOBILE = 16, // deal placed manually by mobile terminal
DEAL_REASON_WEB = 17, // deal placed manually by web terminal
DEAL_REASON_SPLIT = 18, // deal placed due split
// --- enumeration borders
DEAL_REASON_FIRST = TMTEnDealReason.DEAL_REASON_CLIENT,
DEAL_REASON_LAST = TMTEnDealReason.DEAL_REASON_SPLIT
);
TMTEnTradeModifyFlags = (
MODIFY_FLAGS_ADMIN = 1,
MODIFY_FLAGS_MANAGER = 2,
MODIFY_FLAGS_POSITION = 4,
MODIFY_FLAGS_RESTORE = 8,
MODIFY_FLAGS_API_ADMIN = 16,
MODIFY_FLAGS_API_MANAGER = 32,
MODIFY_FLAGS_API_SERVER = 64,
MODIFY_FLAGS_API_GATEWAY = 128,
MODIFY_FLAGS_API_SERVER_ADD = 256,
// --- enumeration borders
MODIFY_FLAGS_NONE = 0,
MODIFY_FLAGS_ALL = 511
);
TMTDeal = class
private
FSymbol: string;
FPriceGateway: Single;
FExternalID: string;
FRateMargin: Single;
FPricePosition: Single;
FComment: string;
FPrice: Single;
FExpertID: Int64;
FContractSize: Single;
FRateProfit: Single;
FDeal: Int64;
FPositionID: Int64;
FOrder: Int64;
FReason: TMTEnDealReason;
FDealer: Int64;
FDigitsCurrency: Int64;
FVolumeExt: Int64;
FDigits: Int64;
FCommission: Single;
FTime: Int64;
FModifyFlags: TMTEnEntryFlags;
FStorage: Single;
FVolumeClosedExt: Int64;
FVolume: Int64;
FEntry: TMTEnEntryFlags;
FLogin: Int64;
FAction: TMTEnDealAction;
FGateway: string;
FTimeMsc: string;
FVolumeClosed: Int64;
FProfitRaw: Single;
FTickValue: Single;
FFlags: Int64;
FTickSize: Single;
FProfit: Single;
FPriceSL: Single;
FPriceTP: Single;
FFee: Single;
FValue: Single;
FOriginalJSON: TJSONObject;
procedure SetAction(const Value: TMTEnDealAction);
procedure SetComment(const Value: string);
procedure SetCommission(const Value: Single);
procedure SetContractSize(const Value: Single);
procedure SetDeal(const Value: Int64);
procedure SetDealer(const Value: Int64);
procedure SetDigits(const Value: Int64);
procedure SetDigitsCurrency(const Value: Int64);
procedure SetEntry(const Value: TMTEnEntryFlags);
procedure SetExpertID(const Value: Int64);
procedure SetExternalID(const Value: string);
procedure SetFlags(const Value: Int64);
procedure SetGateway(const Value: string);
procedure SetLogin(const Value: Int64);
procedure SetModifyFlags(const Value: TMTEnEntryFlags);
procedure SetOrder(const Value: Int64);
procedure SetPositionID(const Value: Int64);
procedure SetPrice(const Value: Single);
procedure SetPriceGateway(const Value: Single);
procedure SetPricePosition(const Value: Single);
procedure SetProfit(const Value: Single);
procedure SetProfitRaw(const Value: Single);
procedure SetRateMargin(const Value: Single);
procedure SetRateProfit(const Value: Single);
procedure SetReason(const Value: TMTEnDealReason);
procedure SetStorage(const Value: Single);
procedure SetSymbol(const Value: string);
procedure SetTickSize(const Value: Single);
procedure SetTickValue(const Value: Single);
procedure SetTime(const Value: Int64);
procedure SetTimeMsc(const Value: string);
procedure SetVolume(const Value: Int64);
procedure SetVolumeClosed(const Value: Int64);
procedure SetVolumeClosedExt(const Value: Int64);
procedure SetVolumeExt(const Value: Int64);
procedure SetPriceSL(const Value: Single);
procedure SetPriceTP(const Value: Single);
procedure SetFee(const Value: Single);
procedure SetValue(const Value: Single);
{ private declarations }
protected
{ protected declarations }
procedure SetOriginalJSON(AValue: TJSONObject);
public
{ public declarations }
destructor Destroy; override;
property Deal: Int64 read FDeal write SetDeal;
property ExternalID: string read FExternalID write SetExternalID;
property Login: Int64 read FLogin write SetLogin;
property Dealer: Int64 read FDealer write SetDealer;
property Order: Int64 read FOrder write SetOrder;
property Action: TMTEnDealAction read FAction write SetAction;
property Entry: TMTEnEntryFlags read FEntry write SetEntry;
property Reason: TMTEnDealReason read FReason write SetReason;
property Digits: Int64 read FDigits write SetDigits;
property DigitsCurrency: Int64 read FDigitsCurrency write SetDigitsCurrency;
property ContractSize: Single read FContractSize write SetContractSize;
property Time: Int64 read FTime write SetTime;
property TimeMsc: string read FTimeMsc write SetTimeMsc;
property Symbol: string read FSymbol write SetSymbol;
property Price: Single read FPrice write SetPrice;
property Volume: Int64 read FVolume write SetVolume;
property VolumeExt: Int64 read FVolumeExt write SetVolumeExt;
property Profit: Single read FProfit write SetProfit;
property Storage: Single read FStorage write SetStorage;
property Commission: Single read FCommission write SetCommission;
property Fee: Single read FFee write SetFee;
property RateProfit: Single read FRateProfit write SetRateProfit;
property RateMargin: Single read FRateMargin write SetRateMargin;
property ExpertID: Int64 read FExpertID write SetExpertID;
property PositionID: Int64 read FPositionID write SetPositionID;
property Comment: string read FComment write SetComment;
property ProfitRaw: Single read FProfitRaw write SetProfitRaw;
property PricePosition: Single read FPricePosition write SetPricePosition;
property VolumeClosed: Int64 read FVolumeClosed write SetVolumeClosed;
property VolumeClosedExt: Int64 read FVolumeClosedExt write SetVolumeClosedExt;
property TickValue: Single read FTickValue write SetTickValue;
property TickSize: Single read FTickSize write SetTickSize;
property Flags: Int64 read FFlags write SetFlags;
property Gateway: string read FGateway write SetGateway;
property PriceGateway: Single read FPriceGateway write SetPriceGateway;
property ModifyFlags: TMTEnEntryFlags read FModifyFlags write SetModifyFlags;
property PriceSL: Single read FPriceSL write SetPriceSL;
property PriceTP: Single read FPriceTP write SetPriceTP;
property Value: Single read FValue write SetValue;
function ToOriginalJSON: TJSONObject;
end;
TMTDealTotalAnswer = class
private
FRetCode: string;
FTotal: Integer;
procedure SetRetCode(const Value: string);
procedure SetTotal(const Value: Integer);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
constructor Create; virtual;
property RetCode: string read FRetCode write SetRetCode;
property Total: Integer read FTotal write SetTotal;
end;
TMTDealPageAnswer = class
private
FConfigJson: string;
FRetCode: string;
procedure SetConfigJson(const Value: string);
procedure SetRetCode(const Value: string);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
constructor Create; virtual;
property RetCode: string read FRetCode write SetRetCode;
property ConfigJson: string read FConfigJson write SetConfigJson;
function GetArrayFromJson: TArray<TMTDeal>;
end;
TMTDealAnswer = class
private
FConfigJson: string;
FRetCode: string;
procedure SetConfigJson(const Value: string);
procedure SetRetCode(const Value: string);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
constructor Create; virtual;
property RetCode: string read FRetCode write SetRetCode;
property ConfigJson: string read FConfigJson write SetConfigJson;
function GetFromJson: TMTDeal;
end;
TMTDealJson = class
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
class function GetFromJson(AJsonObject: TJSONObject): TMTDeal;
end;
implementation
uses
MT5.Types, MT5.Protocol, MT5.Utils, MT5.BaseAnswer, MT5.ParseProtocol;
{ TMTDealProtocol }
constructor TMTDealProtocol.Create(AConnect: TMTConnect);
begin
FMTConnect := AConnect;
end;
function TMTDealProtocol.DealGet(ATicket: string; out ADeal: TMTDeal): TMTRetCodeType;
var
LData: TArray<TMTQuery>;
LAnswer: TArray<Byte>;
LAnswerString: string;
LRetCodeType: TMTRetCodeType;
LDealAnswer: TMTDealAnswer;
begin
LData := [
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_TICKET, ATicket)
];
if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_DEAL_GET, LData) then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswer := FMTConnect.Read(True);
if Length(LAnswer) = 0 then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswerString := TMTUtils.GetString(LAnswer);
LRetCodeType := ParseDeal(TMTProtocolConsts.WEB_CMD_DEAL_GET, LAnswerString, LDealAnswer);
try
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
ADeal := LDealAnswer.GetFromJson;
Exit(TMTRetCodeType.MT_RET_OK);
finally
LDealAnswer.Free;
end;
end;
function TMTDealProtocol.DealGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out ADealsCollection: TArray<TMTDeal>): TMTRetCodeType;
var
LData: TArray<TMTQuery>;
LAnswer: TArray<Byte>;
LAnswerString: string;
LRetCodeType: TMTRetCodeType;
LDealPageAnswer: TMTDealPageAnswer;
begin
LData := [
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_LOGIN, ALogin.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_FROM, AFrom.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_TO, ATo.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_OFFSET, AOffset.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_TOTAL, ATotal.ToString)
];
if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_DEAL_GET_PAGE, LData) then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswer := FMTConnect.Read(True);
if Length(LAnswer) = 0 then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswerString := TMTUtils.GetString(LAnswer);
LRetCodeType := ParseDealPage(LAnswerString, LDealPageAnswer);
try
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
ADealsCollection := LDealPageAnswer.GetArrayFromJson;
Exit(TMTRetCodeType.MT_RET_OK);
finally
LDealPageAnswer.Free;
end;
end;
function TMTDealProtocol.DealGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
var
LData: TArray<TMTQuery>;
LAnswer: TArray<Byte>;
LAnswerString: string;
LRetCodeType: TMTRetCodeType;
LDealTotalAnswer: TMTDealTotalAnswer;
begin
ATotal := 0;
LData := [
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_LOGIN, ALogin.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_FROM, AFrom.ToString),
TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_TO, ATo.ToString)
];
if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_DEAL_GET_TOTAL, LData) then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswer := FMTConnect.Read(True);
if Length(LAnswer) = 0 then
Exit(TMTRetCodeType.MT_RET_ERR_NETWORK);
LAnswerString := TMTUtils.GetString(LAnswer);
LRetCodeType := ParseDealTotal(LAnswerString, LDealTotalAnswer);
try
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
ATotal := LDealTotalAnswer.Total;
Exit(TMTRetCodeType.MT_RET_OK);
finally
LDealTotalAnswer.Free;
end;
end;
function TMTDealProtocol.ParseDeal(ACommand, AAnswer: string; out ADealAnswer: TMTDealAnswer): TMTRetCodeType;
var
LPos: Integer;
LPosEnd: Integer;
LCommandReal: string;
LParam: TMTAnswerParam;
LRetCodeType: TMTRetCodeType;
LJsonDataString: string;
begin
LPos := 0;
ADealAnswer := nil;
LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos);
if (LCommandReal <> ACommand) then
Exit(TMTRetCodeType.MT_RET_ERR_DATA);
ADealAnswer := TMTDealAnswer.Create;
LPosEnd := -1;
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
try
while LParam <> nil do
begin
if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then
begin
ADealAnswer.RetCode := LParam.Value;
Break;
end;
FreeAndNil(LParam);
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
end;
finally
LParam.Free;
end;
LRetCodeType := TMTParseProtocol.GetRetCode(ADealAnswer.RetCode);
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
LJsonDataString := TMTParseProtocol.GetJson(AAnswer, LPosEnd);
if LJsonDataString = EmptyStr then
Exit(TMTRetCodeType.MT_RET_REPORT_NODATA);
ADealAnswer.ConfigJson := LJsonDataString;
Exit(TMTRetCodeType.MT_RET_OK);
end;
function TMTDealProtocol.ParseDealPage(AAnswer: string; out ADealPageAnswer: TMTDealPageAnswer): TMTRetCodeType;
var
LPos: Integer;
LPosEnd: Integer;
LCommandReal: string;
LParam: TMTAnswerParam;
LRetCodeType: TMTRetCodeType;
LJsonDataString: string;
begin
LPos := 0;
ADealPageAnswer := nil;
LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos);
if (LCommandReal <> TMTProtocolConsts.WEB_CMD_DEAL_GET_PAGE) then
Exit(TMTRetCodeType.MT_RET_ERR_DATA);
ADealPageAnswer := TMTDealPageAnswer.Create;
LPosEnd := -1;
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
try
while LParam <> nil do
begin
if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then
begin
ADealPageAnswer.RetCode := LParam.Value;
Break;
end;
FreeAndNil(LParam);
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
end;
finally
LParam.Free;
end;
LRetCodeType := TMTParseProtocol.GetRetCode(ADealPageAnswer.RetCode);
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
LJsonDataString := TMTParseProtocol.GetJson(AAnswer, LPosEnd);
if LJsonDataString = EmptyStr then
Exit(TMTRetCodeType.MT_RET_REPORT_NODATA);
ADealPageAnswer.ConfigJson := LJsonDataString;
Exit(TMTRetCodeType.MT_RET_OK);
end;
function TMTDealProtocol.ParseDealTotal(AAnswer: string; out ADealTotalAnswer: TMTDealTotalAnswer): TMTRetCodeType;
var
LPos: Integer;
LPosEnd: Integer;
LCommandReal: string;
LParam: TMTAnswerParam;
LRetCodeType: TMTRetCodeType;
begin
LPos := 0;
ADealTotalAnswer := nil;
LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos);
if (LCommandReal <> TMTProtocolConsts.WEB_CMD_DEAL_GET_TOTAL) then
Exit(TMTRetCodeType.MT_RET_ERR_DATA);
ADealTotalAnswer := TMTDealTotalAnswer.Create;
LPosEnd := -1;
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
try
while LParam <> nil do
begin
if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then
ADealTotalAnswer.RetCode := LParam.Value;
if LParam.Name = TMTProtocolConsts.WEB_PARAM_TOTAL then
ADealTotalAnswer.Total := LParam.Value.ToInteger;
FreeAndNil(LParam);
LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd);
end;
finally
LParam.Free;
end;
LRetCodeType := TMTParseProtocol.GetRetCode(ADealTotalAnswer.RetCode);
if LRetCodeType <> TMTRetCodeType.MT_RET_OK then
Exit(LRetCodeType);
Exit(TMTRetCodeType.MT_RET_OK);
end;
{ TMTDeal }
destructor TMTDeal.Destroy;
begin
FOriginalJSON.Free;
inherited;
end;
procedure TMTDeal.SetAction(const Value: TMTEnDealAction);
begin
FAction := Value;
end;
procedure TMTDeal.SetComment(const Value: string);
begin
FComment := Value;
end;
procedure TMTDeal.SetCommission(const Value: Single);
begin
FCommission := Value;
end;
procedure TMTDeal.SetContractSize(const Value: Single);
begin
FContractSize := Value;
end;
procedure TMTDeal.SetDeal(const Value: Int64);
begin
FDeal := Value;
end;
procedure TMTDeal.SetDealer(const Value: Int64);
begin
FDealer := Value;
end;
procedure TMTDeal.SetDigits(const Value: Int64);
begin
FDigits := Value;
end;
procedure TMTDeal.SetDigitsCurrency(const Value: Int64);
begin
FDigitsCurrency := Value;
end;
procedure TMTDeal.SetEntry(const Value: TMTEnEntryFlags);
begin
FEntry := Value;
end;
procedure TMTDeal.SetExpertID(const Value: Int64);
begin
FExpertID := Value;
end;
procedure TMTDeal.SetExternalID(const Value: string);
begin
FExternalID := Value;
end;
procedure TMTDeal.SetFee(const Value: Single);
begin
FFee := Value;
end;
procedure TMTDeal.SetFlags(const Value: Int64);
begin
FFlags := Value;
end;
procedure TMTDeal.SetGateway(const Value: string);
begin
FGateway := Value;
end;
procedure TMTDeal.SetLogin(const Value: Int64);
begin
FLogin := Value;
end;
procedure TMTDeal.SetModifyFlags(const Value: TMTEnEntryFlags);
begin
FModifyFlags := Value;
end;
procedure TMTDeal.SetOrder(const Value: Int64);
begin
FOrder := Value;
end;
procedure TMTDeal.SetOriginalJSON(AValue: TJSONObject);
begin
FOriginalJSON := AValue;
end;
procedure TMTDeal.SetPositionID(const Value: Int64);
begin
FPositionID := Value;
end;
procedure TMTDeal.SetPrice(const Value: Single);
begin
FPrice := Value;
end;
procedure TMTDeal.SetPriceGateway(const Value: Single);
begin
FPriceGateway := Value;
end;
procedure TMTDeal.SetPricePosition(const Value: Single);
begin
FPricePosition := Value;
end;
procedure TMTDeal.SetPriceSL(const Value: Single);
begin
FPriceSL := Value;
end;
procedure TMTDeal.SetPriceTP(const Value: Single);
begin
FPriceTP := Value;
end;
procedure TMTDeal.SetProfit(const Value: Single);
begin
FProfit := Value;
end;
procedure TMTDeal.SetProfitRaw(const Value: Single);
begin
FProfitRaw := Value;
end;
procedure TMTDeal.SetRateMargin(const Value: Single);
begin
FRateMargin := Value;
end;
procedure TMTDeal.SetRateProfit(const Value: Single);
begin
FRateProfit := Value;
end;
procedure TMTDeal.SetReason(const Value: TMTEnDealReason);
begin
FReason := Value;
end;
procedure TMTDeal.SetStorage(const Value: Single);
begin
FStorage := Value;
end;
procedure TMTDeal.SetSymbol(const Value: string);
begin
FSymbol := Value;
end;
procedure TMTDeal.SetTickSize(const Value: Single);
begin
FTickSize := Value;
end;
procedure TMTDeal.SetTickValue(const Value: Single);
begin
FTickValue := Value;
end;
procedure TMTDeal.SetTime(const Value: Int64);
begin
FTime := Value;
end;
procedure TMTDeal.SetTimeMsc(const Value: string);
begin
FTimeMsc := Value;
end;
procedure TMTDeal.SetValue(const Value: Single);
begin
FValue := Value;
end;
procedure TMTDeal.SetVolume(const Value: Int64);
begin
FVolume := Value;
end;
procedure TMTDeal.SetVolumeClosed(const Value: Int64);
begin
FVolumeClosed := Value;
end;
procedure TMTDeal.SetVolumeClosedExt(const Value: Int64);
begin
FVolumeClosedExt := Value;
end;
procedure TMTDeal.SetVolumeExt(const Value: Int64);
begin
FVolumeExt := Value;
end;
function TMTDeal.ToOriginalJSON: TJSONObject;
begin
Result := FOriginalJSON;
end;
{ TMTDealTotalAnswer }
constructor TMTDealTotalAnswer.Create;
begin
FRetCode := '-1';
FTotal := 0;
end;
procedure TMTDealTotalAnswer.SetRetCode(const Value: string);
begin
FRetCode := Value;
end;
procedure TMTDealTotalAnswer.SetTotal(const Value: Integer);
begin
FTotal := Value;
end;
{ TMTDealPageAnswer }
constructor TMTDealPageAnswer.Create;
begin
FConfigJson := '';
FRetCode := '-1';
end;
function TMTDealPageAnswer.GetArrayFromJson: TArray<TMTDeal>;
var
LDealsJsonArray: TJsonArray;
I: Integer;
begin
LDealsJsonArray := TJSONObject.ParseJSONValue(ConfigJson) as TJsonArray;
try
for I := 0 to LDealsJsonArray.Count - 1 do
Result := Result + [TMTDealJson.GetFromJson(TJSONObject(LDealsJsonArray.Items[I]))];
finally
LDealsJsonArray.Free;
end;
end;
procedure TMTDealPageAnswer.SetConfigJson(const Value: string);
begin
FConfigJson := Value;
end;
procedure TMTDealPageAnswer.SetRetCode(const Value: string);
begin
FRetCode := Value;
end;
{ TMTDealAnswer }
constructor TMTDealAnswer.Create;
begin
FConfigJson := '';
FRetCode := '-1';
end;
function TMTDealAnswer.GetFromJson: TMTDeal;
begin
Result := TMTDealJson.GetFromJson(TJSONObject.ParseJSONValue(ConfigJson) as TJSONObject);
end;
procedure TMTDealAnswer.SetConfigJson(const Value: string);
begin
FConfigJson := Value;
end;
procedure TMTDealAnswer.SetRetCode(const Value: string);
begin
FRetCode := Value;
end;
{ TMTDealJson }
class function TMTDealJson.GetFromJson(AJsonObject: TJSONObject): TMTDeal;
var
LDeal: TMTDeal;
LVolumeExt: Int64;
LVolumeClosedExt: Int64;
LPriceSL: Single;
LPriceTP: Single;
begin
LDeal := TMTDeal.Create;
Result := LDeal;
LDeal.Symbol := AJsonObject.GetValue<string>('Symbol');
LDeal.PriceGateway := AJsonObject.GetValue<Single>('PriceGateway');
LDeal.ExternalID := AJsonObject.GetValue<string>('ExternalID');
LDeal.RateMargin := AJsonObject.GetValue<Single>('RateMargin');
LDeal.PricePosition := AJsonObject.GetValue<Single>('PricePosition');
LDeal.Comment := AJsonObject.GetValue<string>('Comment');
LDeal.Price := AJsonObject.GetValue<Single>('Price');
LDeal.ExpertID := AJsonObject.GetValue<Int64>('ExpertID');
LDeal.ContractSize := AJsonObject.GetValue<Single>('ContractSize');
LDeal.RateProfit := AJsonObject.GetValue<Single>('RateProfit');
LDeal.Deal := AJsonObject.GetValue<Int64>('Deal');
LDeal.PositionID := AJsonObject.GetValue<Int64>('PositionID');
LDeal.Order := AJsonObject.GetValue<Int64>('Order');
LDeal.Reason := TMTEnDealReason(AJsonObject.GetValue<Integer>('Reason'));
LDeal.Dealer := AJsonObject.GetValue<Int64>('Dealer');
LDeal.DigitsCurrency := AJsonObject.GetValue<Int64>('DigitsCurrency');
if AJsonObject.TryGetValue<Int64>('VolumeExt', LVolumeExt) then
LDeal.VolumeExt := AJsonObject.GetValue<Int64>('VolumeExt')
else
LDeal.VolumeExt := TMTUtils.ToNewVolume(LDeal.Volume);
LDeal.Digits := AJsonObject.GetValue<Int64>('Digits');
LDeal.Commission := AJsonObject.GetValue<Single>('Commission');
LDeal.Value := AJsonObject.GetValue<Single>('Value');
LDeal.Time := AJsonObject.GetValue<Int64>('Time');
LDeal.ModifyFlags := TMTEnEntryFlags(AJsonObject.GetValue<Integer>('ModifyFlags'));
LDeal.Storage := AJsonObject.GetValue<Single>('Storage');
if AJsonObject.TryGetValue<Int64>('VolumeClosedExt', LVolumeClosedExt) then
LDeal.VolumeClosedExt := AJsonObject.GetValue<Int64>('VolumeClosedExt')
else
LDeal.VolumeClosedExt := TMTUtils.ToNewVolume(LDeal.VolumeClosed);
if AJsonObject.TryGetValue<Single>('PriceSL', LPriceSL) then
LDeal.PriceSL := LPriceSL;
if AJsonObject.TryGetValue<Single>('PriceTP', LPriceTP) then
LDeal.PriceTP := LPriceTP;
LDeal.Volume := AJsonObject.GetValue<Int64>('Volume');
LDeal.Entry := TMTEnEntryFlags(AJsonObject.GetValue<Integer>('Entry'));
LDeal.Login := AJsonObject.GetValue<Int64>('Login');
LDeal.Action := TMTEnDealAction(AJsonObject.GetValue<Integer>('Action'));
LDeal.Gateway := AJsonObject.GetValue<string>('Gateway');
LDeal.TimeMsc := AJsonObject.GetValue<string>('TimeMsc');
LDeal.VolumeClosed := AJsonObject.GetValue<Int64>('VolumeClosed');
LDeal.ProfitRaw := AJsonObject.GetValue<Single>('ProfitRaw');
LDeal.TickValue := AJsonObject.GetValue<Single>('TickValue');
LDeal.Flags := AJsonObject.GetValue<Int64>('Flags');
LDeal.TickSize := AJsonObject.GetValue<Single>('TickSize');
LDeal.Profit := AJsonObject.GetValue<Single>('Profit');
LDeal.Fee := AJsonObject.GetValue<Single>('Fee');
LDeal.SetOriginalJSON(AJsonObject.Clone as TJSONObject);
end;
end.
|
unit ibSHSQLMonitorEditors;
interface
uses
SysUtils, Classes, DesignIntf, TypInfo, StrUtils,
SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors;
type
TibSHSQLMonitorPropEditor = class(TibBTPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(AValues: TStrings); override;
procedure SetValue(const Value: string); override;
procedure Edit; override;
end;
IibSHSQLMonitorFilterPropEditor = interface
['{B9B660B1-9DFE-4546-A796-94F71CE90F6B}']
end;
TibSHSQLMonitorFilterPropEditor = class(TibSHSQLMonitorPropEditor, IibSHSQLMonitorFilterPropEditor);
implementation
uses
ibSHConsts, ibSHValues;
{ TibSHSQLMonitorPropEditor }
function TibSHSQLMonitorPropEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
end;
function TibSHSQLMonitorPropEditor.GetValue: string;
var
SQLMonitor: IibSHSQLMonitor;
begin
Result := inherited GetValue;
if Supports(Self, IibSHSQLMonitorFilterPropEditor) and Supports(Component, IibSHSQLMonitor, SQLMonitor) then
begin
Result := Trim(SQLMonitor.Filter.CommaText);
Result := AnsiReplaceStr(Result, '"', '');
Result := AnsiReplaceStr(Result, ',', ', ');
end;
end;
procedure TibSHSQLMonitorPropEditor.GetValues(AValues: TStrings);
begin
inherited GetValues(AValues);
end;
procedure TibSHSQLMonitorPropEditor.SetValue(const Value: string);
begin
inherited SetValue(Value);
end;
procedure TibSHSQLMonitorPropEditor.Edit;
begin
inherited Edit;
end;
end.
|
unit BasicRenderingTypes;
interface
type
PVertexItem = ^TVertexItem;
TVertexItem = record
ID: integer;
x,y,z: single;
Next: PVertexItem;
end;
PTriangleItem = ^TTriangleItem;
TTriangleItem = record
v1, v2, v3: integer;
Color: cardinal;
Next: PTriangleItem;
end;
PQuadItem = ^TQuadItem;
TQuadItem = record
v1, v2, v3, v4: integer;
Color: cardinal;
Next: PQuadItem;
end;
TTriangleNeighbourItem = record
ID: integer;
V1,V2: integer;
end;
PTriangleNeighbourItem = ^TTriangleNeighbourItem;
TSurfaceDescriptiorItem = record
Triangles: array [0..5] of PTriangleItem;
Quads: array [0..5] of PQuadItem;
end;
TDescriptor = record
Start,Size: integer;
end;
TADescriptor = array of TDescriptor;
TNeighborDetectorSaveData = record
cID, nID : integer;
end;
TScreenshotType = (stNone,stBmp,stTga,stJpg,stGif,stPng,stDDS,stPS,stPDF,stEPS,stSVG);
TRenderProc = procedure of object;
implementation
end.
|
unit frmFNEditCarNo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, Buttons, ExtCtrls, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, DBClient, StdCtrls, StrUtils, frmBase,
Grids, DBGrids;
type
TFNEditCarNoForm = class(TBaseForm)
cxTVEditCarNO: TcxGridDBTableView;
cxLEditCarNO: TcxGridLevel;
cxGEditCarNO: TcxGrid;
Panel1: TPanel;
Panel2: TPanel;
SBtnExit: TSpeedButton;
CDSEditCarNO: TClientDataSet;
DSEditCarNOData: TDataSource;
SBtnRefresh: TSpeedButton;
chkLocalQuery: TCheckBox;
Label1: TLabel;
EdtNewLocation: TEdit;
BtnEdit: TButton;
Label2: TLabel;
EctCarNo: TEdit;
SBtnSave: TSpeedButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure SBtnExitClick(Sender: TObject);
procedure chkLocalQueryClick(Sender: TObject);
procedure SBtnRefreshClick(Sender: TObject);
procedure SBtnSaveClick(Sender: TObject);
procedure BtnEditClick(Sender: TObject);
procedure CDSEditCarNOAfterScroll(DataSet: TDataSet);
procedure EdtNewLocationKeyPress(Sender: TObject; var Key: Char);
procedure cxTVEditCarNODataControllerFilterBeforeChange(
Sender: TcxDBDataFilterCriteria; ADataSet: TDataSet;
const AFilterText: String);
procedure cxTVEditCarNOEditValueChanged(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem);
private
{ Private declarations }
procedure init; //初始化方法
function GetEditCarNoData(aDepartment : string) : Boolean; //获取要修改车位满车记录数据
function GetSaveString(aCDS : TClientDataSet; aCarNo : string) : String; overload;//获取本地修改过的布号列表
function GetSaveString(var returnCarNo : string; aCDS : TClientDataSet) : String; overload;
procedure Query; //查询方法
procedure FillStrings(aCDS : TClientDataSet; aFieldName : string; aList : TStrings); //根据指定字段填充TStrings
procedure Save;
procedure SaveByCarNo; //根据车号保存方法
procedure SaveByFnCard; //根据后整卡号保存方法
procedure EditNewLocation(aCDS: TClientDataSet; aCarNo, src_Dep, aNewLocation : String); overload;
function EditNewLocation(aCDS: TClientDataSet; filterField, filterValue : array of String; aLocateField, aEditField, aEditValue : String) : Boolean; overload;
//function CheckIsSample(aFnCard : String) : Boolean; //2015-03-04 APJ zhaogang Edit
function CheckIsSampleORIsDisposal(aFabricNO : String) : Boolean; //根据后整卡号,检查是否为样布或处理布
public
{ Public declarations }
OldCar_No : String // Added by WuDev 2016/9/8 11:21:38 增加车牌号修改
end;
var
FNEditCarNoForm: TFNEditCarNoForm;
implementation
uses uFNMResource, ServerDllPub, uShowMessage, uGridDecorator, uLogin;
{$R *.dfm}
{ TFNEditCarNoForm }
procedure TFNEditCarNoForm.init;
begin
SBtnRefresh.Glyph.LoadFromResourceName(HInstance, RES_REFRESH);
SBtnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE);
SBtnExit.Glyph.LoadFromResourceName(HInstance, RES_EXIT);
end;
procedure TFNEditCarNoForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFNEditCarNoForm.FormDestroy(Sender: TObject);
begin
FNEditCarNoForm := nil;
end;
procedure TFNEditCarNoForm.SBtnExitClick(Sender: TObject);
begin
Close;
end;
procedure TFNEditCarNoForm.chkLocalQueryClick(Sender: TObject);
begin
cxTVEditCarNO.OptionsView.GroupByBox := chkLocalQuery.Checked;
end;
{
function TFNEditCarNoForm.GetgiFullCarFabricsFramework : Boolean;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
Result := False;
sql := QuotedStr('GetgiFullCarFabricsFramework') + ',' + QuotedStr('');
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.Data := vData;
Result := True;
end;
}
function TFNEditCarNoForm.GetEditCarNoData(aDepartment: string): Boolean;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
Result := False;
try
ShowMsg('正在获取数据稍等!', crHourGlass);
sql := QuotedStr('GetEditCarNOData') + ',' + QuotedStr(aDepartment);
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.Data := vData;
Result := ((CDSEditCarNO.Active) and (CDSEditCarNO.RecordCount > 0));
finally
ShowMsg('', crDefault);
end;//finally
end;
procedure TFNEditCarNoForm.Query;
var
i : Integer;
begin
if not GetEditCarNoData(Login.CurrentDepartment) then
begin
SBtnSave.Enabled := False;
BtnEdit.Enabled := False;
TMsgDialog.ShowMsgDialog('没有待修改车位的坯布数据', 2);
Exit;
end;//if
//绑定cxGrid
GridDecorator.BindCxViewWithDataSource(cxTVEditCarNO, DSEditCarNOData);
for i := 0 to cxTVEditCarNO.ColumnCount - 1 do
cxTVEditCarNO.Columns[i].Options.Editing := False;
//序号列可修改
cxTVEditCarNO.GetColumnByFieldName('Sequence').Options.Editing := True;
//cxTVEditCarNO.GetColumnByFieldName('NewLocation').Options.Editing := True;
if CDSEditCarNO.RecordCount > 0 then
begin
SBtnSave.Enabled := True;
CDSEditCarNO.IndexFieldNames := 'Car_No;FN_Card';
//FillStrings(CDSEditCarNO, 'Car_No', CBBCarNo.Items);
CDSEditCarNO.First;
EctCarNo.Text := CDSEditCarNO.FieldByName('Car_No').AsString;
end;//if
end;
procedure TFNEditCarNoForm.SBtnRefreshClick(Sender: TObject);
begin
Query;
end;
procedure TFNEditCarNoForm.SaveByCarNo;
var
updateList, carNo : string;
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
if (Trim(EctCarNo.Text) <> '') or (CDSEditCarNO.Active) then
begin
if CDSEditCarNO.State in [dsEdit, dsInsert] then
CDSEditCarNO.Post;
if CDSEditCarNO.RecordCount > 0 then
begin
try
ShowMsg('正在保存数据稍等!', crHourGlass);
{
updateList := GetSaveString(CDSEditCarNO, EctCarNo.text); //组织数据
//后整卡号列表 | 新车号列表 | 各卡号总码长 | 全部卡号总码长 | 当前部门 | 操作人ID
sql := updateList + '|' + login.CurrentDepartment + '|' + login.LoginID;
sql := QuotedStr('SaveEditCarNOData') + ',' + QuotedStr(sql);}
//车号| 新车位| 源部门 | 当前部门 | 操作人ID | 车号
updateList := GetSaveString(carNo, CDSEditCarNO); //组织数据
if updateList = '' then
Exit;
if MessageDlg('是否对车号[' + carNo + ']执行运输下机操作?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then
Exit;
sql := updateList + '|' + login.CurrentDepartment + '|' + login.LoginID + '|' +oldCar_No;
sql := QuotedStr('SaveEditCarNODataByCarNo') + ',' + QuotedStr(sql);
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.MergeChangeLog;
if GetEditCarNoData(Login.CurrentDepartment) then
TMsgDialog.ShowMsgDialog('数据保存成功', mtInformation);
finally
ShowMsg('', crDefault);
end;//finally
end;//if
end;//if
end;
function TFNEditCarNoForm.GetSaveString(aCDS : TClientDataSet; aCarNo : string) : String;
var
fnCardList, quantityList, newLocationList : string;
fnCard, newLocation : String;
quantity, total : Real;
i : Integer;
begin
Result := '';
if (aCDS.Active) and (aCDS.RecordCount > 0) and (Trim(aCarNo) <> '') then
begin
try
total := 0;
quantity := -1;
aCDS.DisableControls;
aCDS.Filter := 'Car_No = ' + QuotedStr(aCarNo);
aCDS.Filtered := True;
aCDS.First;
while not aCDS.Eof do
begin
if fnCard <> aCDS.FieldByName('FN_Card').AsString then
begin
quantity := 0;
//卡号
fnCard := aCDS.FieldByName('FN_Card').AsString;
fnCardList := fnCardList + fnCard + ','; //累加卡号
//新车位
//如果新车位(后整车位就是车号)为空,则用原车号
newLocation := aCDS.FieldByName('NewLocation').AsString;
if Trim(newLocation) = '' then
newLocation := EdtNewLocation.Text;
if Trim(newLocation) = '' then
newLocation := aCDS.FieldByName('Car_No').AsString;
newLocationList := newLocationList + newLocation + ',';//累加记录车位
end;
quantity := quantity + aCDS.FieldByName('Quantity').AsFloat;//卡号总码长
//总码长
total := total + aCDS.FieldByName('Quantity').AsFloat; //累加计算全部卡号总码长
aCDS.Next;
if (fnCard <> aCDS.FieldByName('FN_Card').AsString) or (aCDS.Eof) then
quantityList := quantityList + FloatToStr(quantity)+ ',';//aCDS.FieldByName('Quantity').AsString + ',';//每张卡码长}
end;//while
{
//累加个卡号的总码长
for i := 0 to fncList.Count - 1 do
begin
aCDS.Filter := 'FN_Card = ' + QuotedStr(fncList.Strings[i]);
aCDS.Filtered := True;
aCDS.First;
while not aCDS.Eof do
begin
quantity := quantity + aCDS.FieldByName('Quantity').AsFloat;
aCDS.Next;
end;//while
quantityList := quantityList + FloatToStr(quantity) + ',';
total := total + quantity; //累加计算全部卡号总码长
quantity := 0;
end;//for
}
Result := fnCardList + '|' + NewLocationList + '|' + quantityList + '|' + FloatToStr(total);
finally
aCDS.Filtered := False;
aCDS.Filter := '';
aCDS.IndexFieldNames := 'Car_No';
aCDS.EnableControls;
end;//finally
end;//if
end;
procedure TFNEditCarNoForm.FillStrings(aCDS: TClientDataSet; aFieldName : string; aList: TStrings);
var
aField : string;
begin
aCDS.First;
aList.Clear;
while not aCDS.Eof do
begin
if aField <> aCDS.FieldByName(aFieldName).AsString then
begin
aField := aCDS.FieldByName(aFieldName).AsString;
aList.Add(aField);
end;//if
aCDS.Next;
end;//while
end;
procedure TFNEditCarNoForm.SBtnSaveClick(Sender: TObject);
begin
inherited;
Save;
end;
procedure TFNEditCarNoForm.EditNewLocation(aCDS: TClientDataSet; aCarNo, src_Dep, aNewLocation : String);
var
oldFilter, carNo : string;
begin
if (EdtNewLocation.Text <> '') and (aCDS.Active) and (aCDS.RecordCount > 0) then
begin
carNo := aCDS.FieldByName('Car_No').AsString;
oldFilter := aCDS.Filter; //记录原过滤条件
try
aCDS.MergeChangeLog;//清空之前的修改记录
aCDS.DisableControls;
aCDS.Filter := 'Car_No = ' + QuotedStr(aCarNo) + ' and Src_Department = ' + QuotedStr(src_Dep);
aCDS.Filtered := True;
if aCDS.RecordCount > 0 then
begin
aCDS.First;
while not aCDS.Eof do
begin
aCDS.Edit;
aCDS.FieldByName('NewLocation').AsString := aNewLocation;
aCDS.Post;
aCDS.Next;
end;//while
end;//if
finally
aCDS.Filtered := False;
aCDS.Filter := '';
if oldFilter <> '' then
begin
aCDS.Filter := oldFilter;
aCDS.Filtered := True;
end;//if
aCDS.Locate('Car_No', carNo, []);
aCDS.EnableControls;
end;//finally
end;//if
end;
procedure TFNEditCarNoForm.BtnEditClick(Sender: TObject);
begin
inherited;
{EditNewLocation(CDSEditCarNO,
CDSEditCarNO.FieldByName('Car_No').AsString,
CDSEditCarNO.FieldByName('Src_Department').AsString,
EdtNewLocation.Text); }
// Added by WuDev 2016/9/7 11:03:47 增加车牌号修改
OldCar_No:= CDSEditCarNO.FieldByName('Car_No').AsString;
EditNewLocation(CDSEditCarNO,
['FN_Card','Src_Department'],
[CDSEditCarNO.fieldByName('FN_Card').AsString, CDSEditCarNO.FieldByName('Src_Department').AsString],
'Fabric_NO', 'Car_No', EctCarNo.Text);
// end
EditNewLocation(CDSEditCarNO,
['Car_No','Src_Department'],
[CDSEditCarNO.FieldByName('Car_No').AsString, CDSEditCarNO.FieldByName('Src_Department').AsString],
'Fabric_NO', 'NewLocation', EdtNewLocation.Text);
end;
procedure TFNEditCarNoForm.CDSEditCarNOAfterScroll(DataSet: TDataSet);
begin
inherited;
EctCarNo.Text := TClientDataSet(DataSet).FieldByName('Car_No').AsString;
end;
procedure TFNEditCarNoForm.EdtNewLocationKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
TEdit(Sender).CharCase := ecUpperCase;
end;
procedure TFNEditCarNoForm.cxTVEditCarNODataControllerFilterBeforeChange(
Sender: TcxDBDataFilterCriteria; ADataSet: TDataSet;
const AFilterText: String);
begin
inherited;
if AFilterText <> '' then
begin
if Pos('= TRUE', UpperCase(AFilterText)) > 0 then
ADataSet.Filter := Stringreplace(UpperCase(AFilterText), '= TRUE', '<> FALSE', [rfReplaceAll])
else
ADataSet.Filter := AFilterText;
ADataSet.Filtered := True;
ADataSet.First;
end
else
begin
ADataSet.Filtered := False;
ADataSet.Filter := '';
end;//else}
end;
function TFNEditCarNoForm.GetSaveString(var returnCarNo : string; aCDS: TClientDataSet): String;
var
carNo, newLocation, srcDep, Sequence : String;
cds : TClientDataSet;
begin
Result := '';
if aCDS.Active then
begin
if aCDS.ChangeCount < 1 then
begin
TMsgDialog.ShowMsgDialog('请修改车位后再执行保存', mtWarning);
Exit;
end;//if
cds := TClientDataSet.Create(nil);
try
cds.Data := aCDS.Delta;
//防止同车中有试样布和处理布
cds.First;
while not cds.Eof do
begin
if cds.FieldByName('Car_No').AsString <> '' then
if (cds.FieldByName('Is_Sample').AsBoolean) or (cds.FieldByName('Is_Disposal').AsBoolean) then
begin
TMsgDialog.ShowMsgDialog('同车中有非正常布,请先让试样布或处理布执行运输下机操作', mtWarning);
Exit;
end;//if
cds.Next;
end;//while
cds.Data := aCDS.Data; // Added by WuDev 2016/9/8 14:48:31
cds.First;
while not cds.Eof do
begin
if cds.FieldByName('Car_No').AsString <> '' then
begin
carNo := cds.FieldByName('Car_No').AsString;
srcDep := cds.FieldByName('Src_Department').AsString;
newLocation := cds.FieldByName('NewLocation').AsString; // Added by WuDev 2016/9/8 11:50:20 增加地位号的修改
end
else
begin
Sequence := cds.FieldByName('Sequence').AsString;
newLocation := cds.FieldByName('NewLocation').AsString;
Break;
end;//else
cds.Next;
end;//while
returnCarNo := carNo;
Result := carNo + '|' + newLocation + '|' + srcDep + '|' + Sequence;
finally
if Assigned(cds) then
begin
cds.Close;
FreeAndNil(cds);
end;//if
end;//finally
end;//if
end;
function TFNEditCarNoForm.EditNewLocation(aCDS: TClientDataSet;
filterField, filterValue: array of String; aLocateField, aEditField,
aEditValue: String): Boolean;
var
locateValue, value, oldFilterStr, filterStr,oldIndex : String;
i : Integer;
begin
Result := False;
//carNo := aCDS.FieldByName('Car_No').AsString;
locateValue := aCDS.FieldByName(aLocateField).AsString;
oldFilterStr := aCDS.Filter;
// Added by WuDev 2016/9/7 17:58:51 去掉排序功能
oldIndex:= aCDS.IndexFieldNames;
aCDS.IndexFieldNames:= '';
try
aCDS.DisableControls;
for i := 0 to Length(filterField) - 1 do
begin
if (filterStr <> '') then
filterStr := filterStr + ' and ' + filterField[i] + ' = ' + QuotedStr(filterValue[i])
else
filterStr := filterField[i] + ' = ' + QuotedStr(filterValue[i]);
end;
aCDS.Filter := filterStr;
aCDS.Filtered := True;
if aCDS.RecordCount > 0 then
begin
aCDS.First;
while not aCDS.Eof do
begin
value := aCDS.FieldByName(aEditField).AsString;
if value <> aEditValue then
begin
aCDS.Edit;
aCDS.FieldByName(aEditField).AsString := aEditValue;
aCDS.Post;
Result := True;
end;//if
aCDS.Next;
end;//while
end;//if
finally
aCDS.Filtered := False;
aCDS.Filter := '';
aCDS.IndexFieldNames:= oldIndex;
if oldFilterStr <> '' then
begin
aCDS.Filter := oldFilterStr;
aCDS.Filtered := True;
end;//if
aCDS.Locate(aLocateField, locateValue, []);
aCDS.EnableControls;
end;//finally
end;
procedure TFNEditCarNoForm.cxTVEditCarNOEditValueChanged(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
var
value : String;
begin
inherited;
if cxTVEditCarNO.GetColumnByFieldName('Sequence').Editing then
begin
value := VarToStr(cxTVEditCarNO.Controller.EditingController.Edit.EditValue);
EditNewLocation(CDSEditCarNO,
['Car_No','Src_Department'],
[EctCarNo.Text, CDSEditCarNO.FieldByName('Src_Department').AsString],
'Fabric_NO', 'Sequence', value);
end;//if
end;
function TFNEditCarNoForm.CheckIsSampleORIsDisposal(aFabricNO: String): Boolean;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
cds : TClientDataSet;
begin
Result := False;
cds := TClientDataSet.Create(nil);
try
sql := QuotedStr('CheckIsSampleORIsDisposal') + ',' + QuotedStr(aFabricNO);
FNMServerObj.GetQueryData(vData, 'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
cds.Data := vData;
if(cds.Active) and (not cds.IsEmpty) then
begin
if (cds.FieldByName('Is_Sample').AsBoolean)
or (cds.FieldByName('Is_Disposal').AsBoolean) then
Result := True
end;
finally
if Assigned(cds) then
FreeAndNil(cds);
end;//finally
end;
procedure TFNEditCarNoForm.Save;
begin
if (not CDSEditCarNO.Active) and (CDSEditCarNO.RecordCount = 0) then
Exit;
try
cxGEditCarNO.Enabled := False;
//检查是否为样布或处理布
if CheckIsSampleORIsDisposal(CDSEditCarNO.FieldByName('Fabric_NO').AsString) then
SaveByFnCard //如果是样布或处理布,则以卡号为单位进行下机
else
SaveByCarNo; //如果是正常布,则以车号为单位进行下机
finally
cxGEditCarNO.Enabled := True;
end;//finally
end;
procedure TFNEditCarNoForm.SaveByFnCard;
var
newLocation,newCarNo : String;
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
try
newLocation := CDSEditCarNO.FieldByName('NewLocation').AsString;
newCarNo:= CDSEditCarNO.fieldByName('Car_No').AsString; // Added by WuDev 2016/9/7 15:52:51 增加车牌号修改
if newLocation = '' then
newLocation := CDSEditCarNO.FieldByName('Location').AsString;
sql := CDSEditCarNO.FieldByName('FN_Card').AsString + '|' + newLocation + '|' + login.LoginID + '|' +newCarNo; // Modified by WuDev 2016/9/7 15:53:11 增加车牌号修改
sql := QuotedStr('UpdateEditCarNODataByFnCard') + ',' + QuotedStr(sql);
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSEditCarNO.MergeChangeLog;
if GetEditCarNoData(Login.CurrentDepartment) then
TMsgDialog.ShowMsgDialog('数据保存成功', mtInformation);
finally
ShowMsg('', crDefault);
end;//finally
end;
end.
|
// Wheberson Hudson Migueletti, em Brasília, 11 de dezembro de 1998.
unit DelphiBitmap;
interface
uses Windows, SysUtils, Classes, Graphics, DelphiImage;
type
TBitmap= class (DelphiImage.TImage)
protected
Bitmap: Graphics.TBitmap;
Stream: TStream;
public
constructor Create; override;
destructor Destroy; override;
procedure Clear;
procedure AssignTo (Dest: TPersistent); override;
function IsValid (const FileName: String): Boolean; override;
procedure LoadFromFile (const FileName: String); override;
end;
implementation
const
cBMP= $4D42;
constructor TBitmap.Create;
begin
inherited Create;
Stream:= TMemoryStream.Create;
Bitmap:= Graphics.TBitmap.Create;
end;
destructor TBitmap.Destroy;
begin
Stream.Free;
Bitmap.Free;
inherited Destroy;
end;
procedure TBitmap.Clear;
begin
TMemoryStream (Stream).Clear;
Bitmap.Free;
Bitmap:= Graphics.TBitmap.Create;
end;
procedure TBitmap.AssignTo (Dest: TPersistent);
begin
if Dest is Graphics.TBitmap then begin
//TBitmap (Dest).Assign (Bitmap)
Stream.Seek (0, soFromBeginning);
Graphics.TBitmap (Dest).LoadFromStream (Stream);
end
else
inherited AssignTo (Dest);
end;
function TBitmap.IsValid (const FileName: String): Boolean;
var
Local : TStream;
Header: TBitmapFileHeader;
begin
Result:= False;
if FileExists (FileName) then begin
Local:= TFileStream.Create (FileName, fmOpenRead);
try
Result:= (Local.Read (Header, cSizeOfBitmapFileHeader) = cSizeOfBitmapFileHeader) and (Header.bfType = cBMP);
finally
Local.Free;
end;
end;
end;
procedure TBitmap.LoadFromFile (const FileName: String);
var
FileHeader: TBitmapFileHeader;
InfoHeader: TBitmapInfoHeader;
begin
Clear;
TMemoryStream (Stream).LoadFromFile (FileName);
Stream.Seek (0, soFromBeginning);
if (Stream.Read (FileHeader, cSizeOfBitmapFileHeader) = cSizeOfBitmapFileHeader) and (FileHeader.bfType = cBMP) then begin
Stream.Read (InfoHeader, cSizeOfBitmapInfoHeader);
Stream.Seek (0, soFromBeginning);
Bitmap.LoadFromStream (Stream);
Width := Bitmap.Width;
Height := Bitmap.Height;
BitsPerPixel:= InfoHeader.biBitCount;
end;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls;
const
DEMO_TITLE = 'FNC Core Utils - Base64 encoding and decoding';
DEMO_BUTTON = 'Execute';
type
TFrmMain = class(TForm)
btnExecute: TButton;
txtLog: TAdvMemo;
procedure btnExecuteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses TMSFNCUtils;
procedure TFrmMain.btnExecuteClick(Sender: TObject);
var
LURL: String;
begin
LURL := 'https://www.tmssoftware.com/';
txtLog.Lines.Add( TTMSFNCUtils.Encode64(LURL, True ) );
txtLog.Lines.Add( TTMSFNCUtils.Encode64(LURL, False ) );
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
btnExecute.Caption := DEMO_BUTTON;
self.Caption := DEMO_TITLE;
txtLog.Lines.Clear;
end;
end.
|
unit Pospolite.View.DOM.Screen;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, SysUtils, Forms, LCLType, LCLIntf, Pospolite.View.Basics;
type
{ TPLDOMScreen }
TPLDOMScreen = record
public
function height: TPLInt; inline;
function width: TPLInt; inline;
function availHeight: TPLInt; inline;
function availWidth: TPLInt; inline;
function colorDepth: TPLShortInt;
function pixelDepth: TPLShortInt; inline;
function deviceScaleFactor: TPLFloat; inline;
function devicePPI: TPLInt; inline;
end;
implementation
{ TPLDOMScreen }
function TPLDOMScreen.height: TPLInt;
begin
Result := Screen.Height;
end;
function TPLDOMScreen.width: TPLInt;
begin
Result := Screen.Width;
end;
function TPLDOMScreen.availHeight: TPLInt;
begin
Result := Screen.WorkAreaHeight;
end;
function TPLDOMScreen.availWidth: TPLInt;
begin
Result := Screen.WorkAreaWidth;
end;
function TPLDOMScreen.colorDepth: TPLShortInt;
var
dc: HDC;
begin
dc := GetDC(0);
Result := GetDeviceCaps(dc, BITSPIXEL);
ReleaseDC(0, dc);
end;
function TPLDOMScreen.pixelDepth: TPLShortInt;
begin
Result := colorDepth;
end;
function TPLDOMScreen.deviceScaleFactor: TPLFloat;
begin
Result := Screen.PixelsPerInch / 96;
end;
function TPLDOMScreen.devicePPI: TPLInt;
begin
Result := Screen.PixelsPerInch;
end;
end.
|
unit FreeOTFEfmeOptions_Hotkeys;
interface
uses
Classes, ComCtrls, fmeBaseOptions,
Controls, Dialogs, Forms,
fmeLcOptions, MainSettings,
Graphics, Messages, SDUStdCtrls, StdCtrls, SysUtils, Variants, Windows;
type
TfmeHotKeysOptions = class (TfmeLcOptions)
gbHotkeys: TGroupBox;
Label1: TLabel;
Label2: TLabel;
hkDismount: THotKey;
ckHotkeyDismount: TSDUCheckBox;
ckHotkeyDismountEmerg: TSDUCheckBox;
hkDismountEmerg: THotKey;
procedure ckCheckBoxClick(Sender: TObject);
PROTECTED
procedure _ReadSettings(config: TMainSettings); OVERRIDE;
procedure _WriteSettings(config: TMainSettings); OVERRIDE;
PUBLIC
procedure Initialize(); OVERRIDE;
procedure EnableDisableControls(); OVERRIDE;
end;
implementation
{$R *.dfm}
uses
Math,
SDUGeneral;
procedure TfmeHotKeysOptions.ckCheckBoxClick(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeHotKeysOptions.Initialize();
var
maxCkBoxWidth: Integer;
begin
// ckHotkeyDismount and ckHotkeyDismountEmerg have AutoSize := TRUE
// Use the autosized controls to determine how big the groupbox needs to be
maxCkBoxWidth := max(ckHotkeyDismount.Width, ckHotkeyDismountEmerg.Width);
gbHotkeys.Width := max(((ckHotkeyDismount.left * 2) + maxCkBoxWidth), max(
(hkDismount.left + hkDismount.Width + ckHotkeyDismount.left),
(hkDismountEmerg.left + hkDismountEmerg.Width + ckHotkeyDismount.left)));
SDUCenterControl(gbHotkeys, ccHorizontal);
SDUCenterControl(gbHotkeys, ccVertical, 25);
end;
procedure TfmeHotKeysOptions.EnableDisableControls();
begin
inherited;
SDUEnableControl(hkDismount, ckHotkeyDismount.Checked);
SDUEnableControl(hkDismountEmerg, ckHotkeyDismountEmerg.Checked);
end;
procedure TfmeHotKeysOptions._ReadSettings(config: TMainSettings);
begin
// Hotkeys...
ckHotkeyDismount.Checked := config.OptHKeyEnableDismount;
hkDismount.HotKey := config.OptHKeyKeyDismount;
ckHotkeyDismountEmerg.Checked := config.OptHKeyEnableDismountEmerg;
hkDismountEmerg.HotKey := config.OptHKeyKeyDismountEmerg;
end;
procedure TfmeHotKeysOptions._WriteSettings(config: TMainSettings);
begin
// Hotkeys...
config.OptHKeyEnableDismount := ckHotkeyDismount.Checked;
config.OptHKeyKeyDismount := hkDismount.HotKey;
config.OptHKeyEnableDismountEmerg := ckHotkeyDismountEmerg.Checked;
config.OptHKeyKeyDismountEmerg := hkDismountEmerg.HotKey;
end;
end.
|
unit FormCustom360DegAnimation;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TFrmCustom360DegAnimation = class(TForm)
LbNumFrames: TLabel;
EdNumFrames: TEdit;
Bevel1: TBevel;
BtOK: TButton;
BtCancel: TButton;
LbFrameDelay: TLabel;
EdFrameDelay: TEdit;
procedure BtOKClick(Sender: TObject);
procedure BtCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
OK: boolean;
NumFrames: longword;
FrameDelay: longword;
end;
implementation
{$R *.dfm}
procedure TFrmCustom360DegAnimation.BtCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFrmCustom360DegAnimation.BtOKClick(Sender: TObject);
begin
NumFrames := StrToIntDef(EdNumFrames.Text, 0);
if NumFrames > 0 then
begin
FrameDelay := StrToIntDef(EdFrameDelay.Text, 0);
if FrameDelay > 0 then
begin
OK := true;
close;
end
else
begin
ShowMessage('Warning: Insert a valid time in millisseconds of frame delay for an animation. It must be a positive non-zero value.');
end;
end
else
begin
ShowMessage('Warning: Insert a valid amount of frames for an animation. It must be a positive non-zero value.');
end;
end;
procedure TFrmCustom360DegAnimation.FormCreate(Sender: TObject);
begin
OK := false;
end;
end.
|
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2019, Michael R. . All rights reserved.
// ####
// #### 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.
// ###################################################################
// fido2 dll import file for fido2.dll V 1.12.0 and higher
// the file is basically a conversion of the imported header files of the fido2.dll
// based on the sources in: https://github.com/Yubico/libfido2
// check out: https://developers.yubico.com/libfido2/
// for more information
unit Fido2dll;
interface
const libFido = 'fido2.dll';
{$MinEnumSize 4} // C headers seem to have 4 bytes minimum enum size
type
size_t = NativeUInt;
fido_sigset_t = Integer;
Pfido_sigset_t = ^fido_sigset_t;
PPAnsiChar = ^PAnsiChar;
// ###########################################
// #### from types.h
// ###########################################
type
fido_log_handler_t = procedure(msg : PAnsiChar); cdecl;
type
fido_opt_t = ( FIDO_OPT_OMIT, // use authenticator's default
FIDO_OPT_FALSE, // explicitly set option to false
FIDO_OPT_TRUE ); // explicitly set option to true
Pfido_dev = Pointer;
fido_dev_rx_t = function( dev : Pfido_dev; flag : Byte; buf : PByte; n : size_t; count : integer) : integer; cdecl;
fido_dev_transport_t = packed record
rx : fido_dev_rx_t;
tx : fido_dev_rx_t;
end;
Pfido_dev_transport_t = ^fido_dev_transport_t;
TFidoHandle = Pointer;
fido_dev_io_open_t = function ( inp : PAnsiChar ) : TFidoHandle; cdecl;
fido_dev_io_close_t = procedure( fidoHdl : TFidoHandle); cdecl;
fido_dev_io_read_t = function ( fidoHdl : TFidoHandle; buf : PByte; n : size_t; count : integer) : integer; cdecl;
fido_dev_io_write_t = function( fidoHdl : TFidoHandle; buf : PByte; n : size_t) : integer; cdecl;
fido_dev_io = packed record
open : fido_dev_io_open_t;
close : fido_dev_io_close_t;
read : fido_dev_io_read_t ;
write : fido_dev_io_write_t;
end;
fido_dev_io_t = fido_dev_io;
Pfido_dev_io_t = ^fido_dev_io_t;
fido_dev_info = packed record
path : PAnsiChar; // device path
vendor_id : Int16; // 2-byte vendor id
product_id : Int16; // 2-byte product id
manufacturer : PAnsiChar; // manufacturer string
product : PAnsiChar; // product string
io : fido_dev_io_t; // io functions
transport : fido_dev_transport_t; // transport functions
end;
fido_dev_info_t = fido_dev_info;
fido_ctap_info = packed record
nonce : UInt64; // echoed nonce
cid : UInt32; // channel id
protocol : UInt8; // ctaphid protocol id
major : UInt8; // major version number
minor : UInt8; // minor version number
build : UInt8; // build version number
flags : Uint8; // capabilities flags; see FIDO_CAP_*
end;
fido_ctap_info_t = fido_ctap_info;
fido_dev = packed record
nonce : UInt64; // issued nonce
attr : fido_ctap_info_t; // device attributes
cid : UInt32; // assigned channel id
path : PAnsiChar; // device Path
io_handle : Pointer; // abstract i/o handle
io : fido_dev_io_t; // i/o functions & data
io_own : boolean; // device has own io/transport
rx_len : size_t; // length of HID input reports
tx_len : size_t; // length of HID output reports
flags : integer; // internal flags; see FIDO_DEV_*
transport : fido_dev_transport_t; // transport functions
maxmsgsize : UINT64; // max message size
timeout_ms : Integer; // read timeout in ms
end;
fido_dev_t = fido_dev;
// ###########################################
// #### from param.h
// ###########################################
// Authentication data flags.
const CTAP_AUTHDATA_USER_PRESENT = $01;
CTAP_AUTHDATA_USER_VERIFIED = $04;
CTAP_AUTHDATA_ATT_CRED = $40;
CTAP_AUTHDATA_EXT_DATA = $80;
// CTAPHID command opcodes.
CTAP_CMD_PING = $01;
CTAP_CMD_MSG = $03;
CTAP_CMD_LOCK = $04;
CTAP_CMD_INIT = $06;
CTAP_CMD_WINK = $08;
CTAP_CMD_CBOR = $10;
CTAP_CMD_CANCEL = $11;
CTAP_KEEPALIVE = $3b;
CTAP_FRAME_INIT = $80;
// CTAPHID CBOR command opcodes.
CTAP_CBOR_MAKECRED = $01;
CTAP_CBOR_ASSERT = $02;
CTAP_CBOR_GETINFO = $04;
CTAP_CBOR_CLIENT_PIN = $06;
CTAP_CBOR_RESET = $07;
CTAP_CBOR_NEXT_ASSERT = $08;
CTAP_CBOR_BIO_ENROLL_PRE = $40;
CTAP_CBOR_CRED_MGMT_PRE = $41;
// U2F command opcodes.
U2F_CMD_REGISTER = $01;
U2F_CMD_AUTH = $02;
// U2F command flags.
U2F_AUTH_SIGN = $03;
U2F_AUTH_CHECK = $07;
// ISO7816-4 status words.
SW_CONDITIONS_NOT_SATISFIED = $6985;
SW_WRONG_DATA = $6a80;
SW_NO_ERROR = $9000;
// HID Broadcast channel ID.
CTAP_CID_BROADCAST = $ffffffff;
CTAP_INIT_HEADER_LEN = 7;
CTAP_CONT_HEADER_LEN = 5;
// Expected size of a HID report in bytes.
CTAP_MAX_REPORT_LEN = 64;
CTAP_MIN_REPORT_LEN = 8;
// CTAP capability bits.
FIDO_CAP_WINK = $01; // if set, device supports CTAP_CMD_WINK
FIDO_CAP_CBOR = $04; // if set, device supports CTAP_CMD_CBOR
FIDO_CAP_NMSG = $08; // if set, device doesn't support CTAP_CMD_MSG
// Supported COSE algorithms.
COSE_UNSPEC = 0;
COSE_ES256 = -7;
COSE_EDDSA = -8;
COSE_ES384 = -35;
COSE_RS256 = -257;
COSE_RS1 = -65535;
// Supported COSE types.
COSE_KTY_OKP = 1;
COSE_KTY_EC2 = 2;
COSE_KTY_RSA = 3;
// Supported curves.
COSE_P256 = 1;
COSE_P384 = 2;
COSE_ED25519 = 6;
// Supported extensions.
FIDO_EXT_HMAC_SECRET = $01;
FIDO_EXT_CRED_PROTECT = $02;
FIDO_EXT_LARGEBLOB_KEY = $04;
FIDO_EXT_CRED_BLOB = $08;
FIDO_EXT_MINPINLEN = $10;
// supported credential protection policies
FIDO_CRED_PROT_UV_OPTIONAL = $01;
FIDO_CRED_PROT_UV_OPTIONAL_WITH_ID = $02;
FIDO_CRED_PROT_UV_REQUIRED = $03;
// maximum message size
FIDO_MAXMSG = 2048;
// Recognised UV modes.
FIDO_UV_MODE_TUP = $0001; // internal test of user presence
FIDO_UV_MODE_FP = $0002; // internal fingerprint check
FIDO_UV_MODE_PIN = $0004; // internal pin check
FIDO_UV_MODE_VOICE = $0008; //internal voice recognition
FIDO_UV_MODE_FACE = $0010; //internal face recognition
FIDO_UV_MODE_LOCATION = $0020; //internal location check
FIDO_UV_MODE_EYE = $0040; //internal eyeprint check
FIDO_UV_MODE_DRAWN = $0080; //internal drawn pattern check
FIDO_UV_MODE_HAND = $0100; //internal handprint verification
FIDO_UV_MODE_NONE = $0200; //TUP/UV not required
FIDO_UV_MODE_ALL = $0400; //all supported UV modes required
FIDO_UV_MODE_EXT_PIN = $0800; // external pin verification
FIDO_UV_MODE_EXT_DRAWN = $1000; //external drawn pattern check
// ######################################################
// #### blob.h
// ######################################################
type
fido_blob = packed record
ptr : PByte;
len : size_t;
end;
fido_blob_t = fido_blob;
Pfido_blob_t = ^fido_blob_t;
fido_blob_array = packed record
ptr : Pfido_blob_t;
len : size_t;
end;
fido_blob_array_t = fido_blob_array;
// ######################################################
// #### type.h
// ######################################################
// COSE ES256 (ECDSA over P-256 with SHA-256) public key
type
es256_pk = packed record
x : Array[0..31] of byte;
y : Array[0..31] of byte;
end;
es256_pk_t = es256_pk;
// COSE ES256 (ECDSA over P-256 with SHA-256) (secret) key
es256_sk = packed record
d : Array[0..31] of byte;
end;
es256_sk_t = es256_sk;
// COSE ES384 (ECDSA over P-384 with SHA-384) public key */
es384_pk = packed record
x : Array[0..47] of byte;
y : Array[0..47] of byte;
end;
es384_pk_t = es384_pk;
Pes384_pk_t = ^es384_pk_t;
// COSE RS256 (2048-bit RSA with PKCS1 padding and SHA-256) public key
rs256_pk = packed record
n : Array[0..255] of Byte;
e : Array[0..2] of Byte;
end;
rs256_pk_t = rs256_pk;
// COSE EDDSA (ED25519)
eddsa_pk = packed record
x : Array[0..31] of Byte;
end;
eddsa_pk_t = eddsa_pk;
// PACKED_TYPE(fido_authdata_t,
fido_authdata = packed record
rp_id_hash : Array[0..31] of Byte; // sha256 of fido_rp.id
flags : Byte; // user present/verified
sigcount : UInt32; // signature counter
// actually longer ?? what does that mean?
end;
fido_authdata_t = fido_authdata;
//PACKED_TYPE(fido_attcred_raw_t,
fido_attcred_raw = packed record
aaguid : Array[0..15] of Byte; // credential's aaguid
id_len : UInt16; // credential id length
body : PByte; // uint8_t body[]; // credential id + pubkey // todo: verify that this is translation is correct
end;
fido_attcred_raw_t = fido_attcred_raw;
fido_attcred = packed record
aaguid : Array[0..15] of Byte; // credential's aaguid
id : fido_blob_t; // credential id
case typ : integer of // credential's cose algorithm
COSE_ES256 : (es256 : es256_pk_t);
COSE_ES384 : (es384 : es384_pk_t );
COSE_RS256 : (rs256 : rs256_pk_t);
COSE_EDDSA : (eddsa : eddsa_pk_t);
end;
fido_attcred_t = fido_attcred;
fido_attstmt = packed record
certinfo : fido_blob_t; // tpm attestation TPMS_ATTEST structure
pubarea : fido_blob_t; // tpm attestation TPMT_PUBLIC structure
cbor : fido_blob_t; // cbor-encoded attestation statement
x5c : fido_blob_t; // attestation certificate
sig : fido_blob_t ; // attestation signature
alg : integer; // attestation algorithm (cose)
end;
fido_attstmt_t = fido_attstmt;
fido_rp = packed record
id : PAnsiChar; //relying party id
name : PAnsiChar; //relying party name
end;
fido_rp_t = fido_rp;
fido_user = packed record
id : fido_blob_t; // required
icon : PAnsiChar; // optional
name : PAnsiChar; // optional
display_name : PAnsiChar; // required
end;
fido_user_t = fido_user;
fido_cred_ext = packed record
mask : integer; // enabled extensions
prot : integer; // protection policy
minpinlen : size_t; // minimum pin length #
end;
fido_cred_ext_t = fido_cred_ext;
fido_cred = packed record
cd : fido_blob_t; // client data
cdh : fido_blob_t; // client data hash
rp : fido_rp_t; // relying party
user : fido_user_t; // user entity
excl : fido_blob_array_t; // list of credential ids to exclude
rk : fido_opt_t; // resident key
uv : fido_opt_t; // user verification
ext : integer; // enabled extensions
typ : integer; // cose algorithm
fmt : PAnsiChar; // credential format
authdata_ext : integer; // decoded extensions
authdata_cbor : fido_blob_t; // raw cbor payload
authdata : fido_authdata_t; // decoded authdata payload
attcred : fido_attcred_t; // returned credential (key + id)
attstmt : fido_attstmt_t; // attestation statement (x509 + sig)
largeblob_key : fido_blob_t; // decoded large blob key
blob : fido_blob_t; // CTAP 2.1 credBlob
end;
fido_cred_t = fido_cred;
fido_assert_extattr = packed record
mask : integer; // decoded extensions
hmac_secret_enc : fido_blob_t; // hmac secret, encrypted
blob : fido_blob_t; // decoded CTAP 2.1 credBlob
end;
fido_assert_extattr_t = fido_assert_extattr;
_fido_assert_stmt = packed record
id : fido_blob_t; // credential id
user : fido_user_t; // user attributes
hmac_secret : fido_blob_t; // hmac secret
authdata_ext : fido_assert_extattr_t; // decoded extensions
authdata_cbor : fido_blob_t; // raw cbor payload
authdata : fido_authdata_t; // decoded authdata payload
sig : fido_blob_t; // signature of cdh + authdata
largeblob_key : fido_blob_t; // decoded large blob key
end;
fido_assert_stmt = _fido_assert_stmt;
Pfido_assert_stmt = ^fido_assert_stmt;
fido_assert_ext = packed record
mask : integer; // enabled extensions
hmac_salt : fido_blob_t; // optional hmac-secret salt
end;
fido_assert_ext_t = fido_assert_ext;
fido_assert = packed record
rp_id : PAnsiChar; // relying party id
cd : fido_blob_t; // client data
cdh : fido_blob_t; // client data hash
allow_list : fido_blob_array_t; // list of allowed credentials
up : fido_opt_t; // user presence
uv : fido_opt_t; // user verification
ext : fido_assert_ext_t; // enabled extensions
stmp : Pfido_assert_stmt; // array of expected assertions
stmt_cnt : size_t; // number of allocated assertions
stmt_len : size_t; // number of received assertions
end;
fido_assert_t = fido_assert;
fido_opt_array = packed record
name : PPAnsiChar;
value : PBoolean;
len : size_t;
end;
fido_opt_array_t = fido_opt_array;
fido_str_array = packed record
ptr : PPAnsichar;
len : size_t;
end;
fido_str_array_t = fido_str_array;
fido_byte_array = packed record
ptr : PByte;
len : size_t;
end;
fido_byte_array_t = fido_byte_array;
fido_algo = packed record
typ : PAnsiChar;
cose : integer;
end;
fido_algo_t = fido_algo;
Pfido_algo_t = ^fido_algo_t;
fido_algo_array = packed record
ptr : Pfido_algo_t;
len : size_t;
end;
fido_algo_array_t = fido_algo_array;
fido_cert_array = packed record
name : PPAnsichar;
value : PUInt64;
len : size_t;
end;
fido_cert_array_t = fido_cert_array;
fido_cbor_info = packed record
versions : fido_str_array_t; // supported versions: fido2|u2f
extensions : fido_str_array_t; // list of supported extensions
transports : fido_str_array_t; // list of supported transports
aaguid : Array[0..15] of Byte; // aaguid
options : fido_opt_array_t; // list of supported options
maxmsgsiz : UInt64; // maximum message size
protocols : fido_byte_array_t; // supported pin protocols
algorithms : fido_algo_array_t;// list of supported algorithms
maxcredcntlst : Uint64; // max of credentials in list
maxcredidlen : Uint64; // max credential ID length
fwversion : UINT64; // firmware version
maxcredbloblen : UINT64; // max credBlob length
maxlargeblob : UINT64; // max largeBlob array length
maxrpid_minlen : UINT64; // max rpid in set_pin_minlen_rpid
minpinlen : UINT64; // min pin len enforced
uv_attempts : UINT64; // platform uv attempts
uv_modality : UINT64; // bitmask of supported uv types
rk_remaining : Int64; // remaining resident credentials
new_pin_reqd : Boolean; // new pin required
certs : fido_cert_array_t; // associated certifications
end;
fido_cbor_info_t = fido_cbor_info;
//PACKED_TYPE(fido_ctap_info_t,
// defined in section 8.1.9.1.3 (CTAPHID_INIT) of the fido2 ctap spec
// ###########################################
// #### fido.h
// ###########################################
// fido internal:
type
Pfido_assert_t = ^fido_assert_t;
PPfido_assert_t = ^Pfido_assert_t;
Pfido_cbor_info_t = ^fido_cbor_info_t;
PPfido_cbor_info_t = ^Pfido_cbor_info_t;
Pfido_cred_t = ^fido_cred_t;
PPfido_cred_t = ^Pfido_cred_t;
Pfido_dev_t = ^fido_dev_t;
PPfido_dev_t = ^Pfido_dev_t;
Pfido_dev_info_t = ^fido_dev_info_t;
PPfido_dev_info_t = ^Pfido_dev_info_t;
Pes256_pk_t = ^es256_pk_t;
PPes256_pk_t = ^Pes256_pk_t;
Pes256_sk_t = ^es256_sk_t;
PPes256_sk_t = ^Pes256_sk_t;
Prs256_pk_t = ^rs256_pk_t;
PPrs256_pk_t = ^Prs256_pk_t;
Peddsa_pk_t = ^eddsa_pk_t;
PPeddsa_pk_t = ^Peddsa_pk_t;
// opensl
EVP_PKEY = packed record end;
PEVP_PKEY = ^EVP_PKEY;
PPEVP_PKEY = ^PEVP_PKEY;
EC_KEY = packed record end;
PEC_KEY = ^EC_KEY;
RSA = packed record end;
PRSA = ^RSA;
// credman.h
fido_credman_metadata = packed record
rk_existing : UInt64;
rk_remaining : UInt64;
end;
fido_credman_metadata_t = fido_credman_metadata;
Pfido_credman_metadata_t = ^fido_credman_metadata_t;
fido_credman_single_rp = packed record
rp_entity : fido_rp_t;
rp_id_hash : fido_blob_t;
end;
Pfido_credman_single_rp = ^fido_credman_single_rp;
fido_credman_rp = packed record
ptr : Pfido_credman_single_rp;
n_alloc : size_t; // number of allocated entries
n_rx : size_t; // number of populated entries
end;
fido_credman_rp_t = fido_credman_rp;
Pfido_credman_rp_t = ^fido_credman_rp_t;
_fido_credman_rk = packed record
ptr : Pfido_cred_t;
n_alloc : size_t; // number of allocated entries
n_rx : size_t; // number of populated entries
end;
fido_credman_rk_t = _fido_credman_rk;
Pfido_credman_rk_t = ^fido_credman_rk_t;
// ###########################################
// #### fido\err.h
// ###########################################
const FIDO_ERR_SUCCESS = $00;
FIDO_ERR_INVALID_COMMAND = $01;
FIDO_ERR_INVALID_PARAMETER = $02;
FIDO_ERR_INVALID_LENGTH = $03;
FIDO_ERR_INVALID_SEQ = $04;
FIDO_ERR_TIMEOUT = $05;
FIDO_ERR_CHANNEL_BUSY = $06;
FIDO_ERR_LOCK_REQUIRED = $0a;
FIDO_ERR_INVALID_CHANNEL = $0b;
FIDO_ERR_CBOR_UNEXPECTED_TYPE = $11;
FIDO_ERR_INVALID_CBOR = $12;
FIDO_ERR_MISSING_PARAMETER = $14;
FIDO_ERR_LIMIT_EXCEEDED = $15;
FIDO_ERR_UNSUPPORTED_EXTENSION = $16;
FIDO_ERR_FP_DATABASE_FULL = $17;
FIDO_ERR_LARGEBLOB_STORAGE_FULL = $18;
FIDO_ERR_CREDENTIAL_EXCLUDED = $19;
FIDO_ERR_PROCESSING = $21;
FIDO_ERR_INVALID_CREDENTIAL = $22;
FIDO_ERR_USER_ACTION_PENDING = $23;
FIDO_ERR_OPERATION_PENDING = $24;
FIDO_ERR_NO_OPERATIONS = $25;
FIDO_ERR_UNSUPPORTED_ALGORITHM = $26;
FIDO_ERR_OPERATION_DENIED = $27;
FIDO_ERR_KEY_STORE_FULL = $28;
FIDO_ERR_NOT_BUSY = $29;
FIDO_ERR_NO_OPERATION_PENDING = $2a;
FIDO_ERR_UNSUPPORTED_OPTION = $2b;
FIDO_ERR_INVALID_OPTION = $2c;
FIDO_ERR_KEEPALIVE_CANCEL = $2d;
FIDO_ERR_NO_CREDENTIALS = $2e;
FIDO_ERR_USER_ACTION_TIMEOUT = $2f;
FIDO_ERR_NOT_ALLOWED = $30;
FIDO_ERR_PIN_INVALID = $31;
FIDO_ERR_PIN_BLOCKED = $32;
FIDO_ERR_PIN_AUTH_INVALID = $33;
FIDO_ERR_PIN_AUTH_BLOCKED = $34;
FIDO_ERR_PIN_NOT_SET = $35;
FIDO_ERR_PIN_REQUIRED = $36;
FIDO_ERR_PIN_POLICY_VIOLATION = $37;
FIDO_ERR_PIN_TOKEN_EXPIRED = $38;
FIDO_ERR_REQUEST_TOO_LARGE = $39;
FIDO_ERR_ACTION_TIMEOUT = $3a;
FIDO_ERR_UP_REQUIRED = $3b;
FIDO_ERR_UV_BLOCKED = $3c;
FIDO_ERR_UV_INVALID = $3f;
FIDO_ERR_UNAUTHORIZED_PERM = $40;
FIDO_ERR_ERR_OTHER = $7f;
FIDO_ERR_SPEC_LAST = $df;
// defined internally
FIDO_OK = FIDO_ERR_SUCCESS;
FIDO_ERR_TX = -1;
FIDO_ERR_RX = -2;
FIDO_ERR_RX_NOT_CBOR = -3;
FIDO_ERR_RX_INVALID_CBOR = -4;
FIDO_ERR_INVALID_PARAM = -5;
FIDO_ERR_INVALID_SIG = -6;
FIDO_ERR_INVALID_ARGUMENT = -7;
FIDO_ERR_USER_PRESENCE_REQUIRED = -8;
FIDO_ERR_INTERNAL = -9;
FIDO_ERR_NOTFOUND = -10;
FIDO_ERR_COMPRESS = -11;
// const char *fido_strerr(int);
function fido_strerr( errCode : integer ) : PAnsiChar; cdecl; external libFido;
// from eddsa.h
function eddsa_pk_new : Peddsa_pk_t; cdecl; external libFido;
procedure eddsa_pk_free( var pkp : Peddsa_pk_t ); cdecl; external libFido;
function eddsa_pk_to_EVP_PKEY( pk : Peddsa_pk_t ) : PEVP_PKEY; cdecl; external libFido;
function eddsa_pk_from_EVP_PKEY( pk : Peddsa_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function eddsa_pk_from_ptr(pk : Peddsa_pk_t; ptr : Pointer; len : size_t) : integer; cdecl; external libFido;
// from es256.h
function es256_pk_new : Pes256_pk_t; cdecl; external libFido;
procedure es256_pk_free( var pkp : Pes256_pk_t ); cdecl; external libFido;
function es256_pk_to_EVP_PKEY( pk : Pes256_pk_t) : PEVP_PKEY; cdecl; external libFido;
function es256_pk_from_EC_KEY( pk : Pes256_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function es256_pk_from_EVP_PKEY(pk : Pes256_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function es256_pk_from_ptr(pk : Pes256_pk_t; ptr : Pointer; len : size_t) : integer; cdecl; external libFido;
// from es384.h
function es384_pk_new : Pes384_pk_t; cdecl; external libFido;
procedure es384_pk_free(var pk : Pes384_pk_t); cdecl; external libFido;
function es384_pk_to_EVP_PKEY(pk : Pes384_pk_t) : PEVP_PKEY; cdecl; external libFido;
function es384_pk_from_EC_KEY(pk : Pes384_pk_t; pkey : PEC_KEY) : integer; cdecl; external libFido;
function es384_pk_from_EVP_PKEY(pk : Pes384_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function es384_pk_from_ptr(pk : Pes384_pk_t; ptr : Pointer; len : size_t) : integer; cdecl; external libFido;
// from rs256.h
function rs256_pk_new : Prs256_pk_t; cdecl; external libFido;
procedure rs256_pk_free( var pkp : Prs256_pk_t ); cdecl; external libFido;
function rs256_pk_to_EVP_PKEY( pk : Prs256_pk_t ) : PEVP_PKEY; cdecl; external libFido;
function rs256_pk_from_EVP_PKEY(pk : Prs256_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function rs256_pk_from_RSA( pk : Prs256_pk_t; pkey : PEVP_PKEY) : integer; cdecl; external libFido;
function rs256_pk_from_ptr(pk : Prs256_pk_t; ptr : Pointer; len : size_t) : integer; cdecl; external libFido;
// ###########################################
// #### from fido.h
// ###########################################
function fido_assert_new : Pfido_assert_t; cdecl; external libFido;
function fido_cred_new : Pfido_cred_t; cdecl; external libFido;
function fido_dev_new : Pfido_dev_t; cdecl; external libFido;
function fido_dev_new_with_info( dev : Pfido_dev_info_t) : Pfido_dev_t; cdecl; external libFido;
function fido_dev_info_new(n : size_t) : Pfido_dev_info_t; cdecl; external libFido;
function fido_cbor_info_new : Pfido_cbor_info_t; cdecl; external libFido;
function fido_dev_io_handle( dev : Pfido_dev ) : Pointer; cdecl; external libFido;
procedure fido_assert_free( var assert_p : Pfido_assert_t); cdecl; external libFido;
procedure fido_cbor_info_free(var ci_p : Pfido_cbor_info_t); cdecl; external libFido;
procedure fido_cred_free(var cred_p : Pfido_cred_t); cdecl; external libFido;
procedure fido_dev_force_fido2(dev : Pfido_dev_t); cdecl; external libFido;
procedure fido_dev_force_u2f(dev : Pfido_dev_t); cdecl; external libFido;
procedure fido_dev_free(var dev_p : Pfido_dev_t); cdecl; external libFido;
procedure fido_dev_info_free(devlist_p : PPfido_dev_info_t; n : size_t); cdecl; external libFido;
const cFidoInitDefault = 0;
cFidoInitDebug = 1;
procedure fido_init(flags : integer); cdecl; external libFido;
procedure fido_set_log_handler(log_handler : fido_log_handler_t); cdecl; external libFido;
function fido_assert_authdata_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_clientdata_hash_ptr(assert : Pfido_assert_t) : PByte; cdecl; external libFido;
function fido_assert_hmac_secret_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_id_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_largeblob_key_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_sig_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_user_id_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_assert_blob_ptr(assert : Pfido_assert_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_cbor_info_certs_name_ptr( ci : Pfido_cbor_info_t ) : PPAnsiChar; cdecl; external libFido;
function fido_cbor_info_extensions_ptr(ci : Pfido_cbor_info_t) : PPAnsiChar; cdecl; external libFido;
function fido_cbor_info_options_name_ptr(ci : Pfido_cbor_info_t) : PPAnsiChar; cdecl; external libFido;
function fido_cbor_info_transports_ptr(ci : Pfido_cbor_info_t) : PPAnsiChar; cdecl; external libFido;
function fido_cbor_info_versions_ptr(ci : Pfido_cbor_info_t) : PPAnsiChar; cdecl; external libFido;
function fido_cbor_info_options_value_ptr(ci : Pfido_cbor_info_t) : PBoolean; cdecl; external libFido;
function fido_assert_rp_id(assert : Pfido_assert_t) : PAnsiChar; cdecl; external libFido;
function fido_assert_user_display_name(assert : Pfido_assert_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_assert_user_icon(assert : Pfido_assert_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_assert_user_name(assert : Pfido_assert_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_cbor_info_algorithm_type(ci : Pfido_cbor_info_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_display_name(cred_p : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_fmt(cred_p : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_rp_id(cred_p : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_rp_name(cred_p : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_user_name(cred_p : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_dev_info_manufacturer_string(devlist : Pfido_dev_info_t) : PAnsiChar; cdecl; external libFido;
function fido_dev_info_path(devlist : Pfido_dev_info_t) : PAnsiChar; cdecl; external libFido;
function fido_dev_info_product_string(devList : Pfido_dev_info_t) : PAnsiChar; cdecl; external libFido;
function fido_dev_info_ptr(devList : Pfido_dev_info_t; n : size_t) : Pfido_dev_info_t; cdecl; external libFido;
function fido_cbor_info_protocols_ptr(ci : Pfido_cbor_info_t) : PByte; cdecl; external libFido;
function fido_cbor_info_certs_value_ptr(ci : Pfido_cbor_info_t) : PUInt64; cdecl; external libFido;
function fido_cbor_info_aaguid_ptr(ci : Pfido_cbor_info_t) : PByte; cdecl; external libFido;
function fido_cred_aaguid_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_attstmt_ptr(cred_p : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_authdata_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_authdata_raw_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_clientdata_hash_ptr(ci : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_id_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_aaguid_len(ci : Pfido_cred_t) : size_t; cdecl; external libFido;
function fido_cred_user_id_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_pubkey_ptr(ci : Pfido_cred_t) : PAnsiChar; cdecl; external libFido;
function fido_cred_sig_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_x5c_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_largeblob_key_ptr(ci : Pfido_cred_t) : PByte; cdecl; external libFido;
function fido_cred_pin_minlen(cred : Pfido_cred_t) : size_t; cdecl; external libFido;
function fido_assert_allow_cred(assert : Pfido_assert_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_set_authdata(assert : Pfido_assert_t; idx : size_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_set_clientdata_hash(assert : Pfido_assert_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_set_count(assert : Pfido_assert_t; n : size_t) : integer; cdecl; external libFido;
function fido_assert_set_extensions(assert : Pfido_assert_t; flags : integer) : integer; cdecl; external libFido;
function fido_assert_set_hmac_salt(assert : Pfido_assert_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_set_hmac_secret(assert : Pfido_assert_t; idx : size_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
//function fido_assert_set_options(assert : Pfido_assert_t; bool, bool) __attribute__((__deprecated__)) : integer;
function fido_assert_set_rp(assert : Pfido_assert_t; id : PAnsiChar) : integer; cdecl; external libFido;
function fido_assert_set_up(assert : Pfido_assert_t; up : fido_opt_t) : integer; cdecl; external libFido;
function fido_assert_set_uv(assert : Pfido_assert_t; uv : fido_opt_t) : integer; cdecl; external libFido;
function fido_assert_set_sig(assert : Pfido_assert_t; idx : size_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_verify(assert : Pfido_assert_t; idx : size_t; cose_alg : integer; pk : Pointer) : integer; cdecl; external libFido;
function fido_cbor_info_algorithm_cose(ci : Pfido_cbor_info_t; idx : size_t) : integer; cdecl; external libFido;
function fido_assert_set_authdata_raw(assert : Pfido_assert_t; idx : size_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_assert_set_clientdata(assert : Pfido_assert_t; ptr : PAnsiChar; len : size_t): integer; cdecl; external libFido;
function fido_assert_sigcount(assert : Pfido_assert_t; idx : size_t): UInt32; cdecl; external libFido;
function fido_cred_exclude(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_prot(cred : Pfido_cred_t) : integer; cdecl; external libFido;
function fido_cred_set_attstmt(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_authdata(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_clientdata_hash(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_extensions(cred : Pfido_cred_t; flags : integer) : integer; cdecl; external libFido;
function fido_cred_set_fmt(cred : Pfido_cred_t; ptr : PAnsiChar) : integer; cdecl; external libFido;
function fido_cred_set_id(cred : Pfido_cred_t; ptr : PAnsiChar; len : size_t) : integer; cdecl; external libFido;
// function fido_cred_set_options(cred : Pfido_cred_t; bool, bool) __attribute__((__deprecated__)) : integer;
function fido_cred_set_pin_minlen(ci : Pfido_cred_t; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_prot( cred : Pfido_cred_t; prot : integer) : integer; cdecl; external libFido;
function fido_cred_set_rk(cred : Pfido_cred_t; rk : fido_opt_t) : integer; cdecl; external libFido;
function fido_cred_set_rp(cred : Pfido_cred_t; rp : PAnsiChar; name : PAnsiChar) : integer; cdecl; external libFido;
function fido_cred_set_sig(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_type(cred : Pfido_cred_t; cose_alg : integer) : integer; cdecl; external libFido;
function fido_cred_set_uv(cred : Pfido_cred_t; uv : fido_opt_t) : integer; cdecl; external libFido;
function fido_cred_type(cred : Pfido_cred_t) : integer; cdecl; external libFido;
function fido_cred_set_user(cred : Pfido_cred_t; user_id : PByte; user_id_len : size_t; name : PAnsiChar; display_name : PAnsiChar; icon : PAnsiChar ) : integer; cdecl; external libFido;
function fido_cred_set_x509(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_authdata_raw(cred : Pfido_cred_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_blob(cred : Pfido_cred_t; data : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_cred_set_clientdata(cred : Pfido_cred_t; ptr : PAnsiChar; len : size_t) : integer; cdecl; external libFido;
function fido_cred_verify(cred : Pfido_cred_t) : integer; cdecl; external libFido;
function fido_cred_verify_self( cred : Pfido_cred_t) : integer; cdecl; external libFido;
function fido_dev_close(dev : Pfido_dev_t) : integer; cdecl; external libFido;
function fido_dev_get_assert(dev : Pfido_dev_t; assert : Pfido_assert_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_get_cbor_info(dev : Pfido_dev_t; ci : Pfido_cbor_info_t) : integer; cdecl; external libFido;
function fido_dev_get_retry_count(dev : Pfido_dev_t; var retries : Integer) : integer; cdecl; external libFido;
function fido_dev_get_uv_retry_count(dev : Pfido_dev_t; var retries : integer) : integer; cdecl; external libFido;
function fido_dev_get_touch_begin(dev : Pfido_dev_t) : integer; cdecl; external libFido;
function fido_dev_get_touch_status(dev : Pfido_dev_t; var touched : integer; waitMs : integer) : integer; cdecl; external libFido;
function fido_dev_info_manifest(devlist : Pfido_dev_info_t; ilen : size_t; var olen : Integer) : integer; cdecl; external libFido;
function fido_dev_info_set(devlist : Pfido_dev_info_t; i : size_t; path : PAnsiChar;
manufacturer : PAnsiChar; product : PAnsiChar; io : Pfido_dev_io_t; transport : Pfido_dev_transport_t ) : integer; cdecl; external libFido;
function fido_dev_make_cred(dev : Pfido_dev_t; cred : Pfido_cred_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_open_with_info(dev : Pfido_dev_t ) : integer; cdecl; external libFido;
function fido_dev_open(dev : Pfido_dev_t; path : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_reset(dev : Pfido_dev_t) : integer; cdecl; external libFido;
function fido_dev_set_io_functions(dev : Pfido_dev_t; io : Pfido_dev_io_t) : integer; cdecl; external libFido;
function fido_dev_set_pin(dev : Pfido_dev_t; pin : PAnsiChar; oldPin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_set_transport_functions(dev : Pfido_dev_t; transFun : Pfido_dev_transport_t) : integer; cdecl; external libFido;
function fido_dev_set_timeout(dev : Pfido_dev_t; ms : integer) : integer; cdecl; external libFido;
function fido_dev_set_sigmask(dev : Pfido_dev_t; sigmask : Pfido_sigset_t) : integer; cdecl; external libFido;
function fido_dev_cancel(dev : Pfido_dev_t) : integer; cdecl; external libFido;
function fido_dev_has_pin(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_has_uv(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_is_fido2(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_is_winhello(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_supports_pin(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_supports_cred_prot(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_supports_permissions(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_supports_credman(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_supports_uv(dev : Pfido_dev_t) : boolean; cdecl; external libFido;
function fido_dev_largeblob_get(dev : Pfido_dev_t; key_ptr : PByte; keyLen : size_t;
var blob_ptr : Pbyte; var blob_len : size_t) : integer; cdecl; external libFido;
function fido_dev_largeblob_set(dev : Pfido_dev_t; key_ptr : PByte; key_len : integer;
blob : PByte; blob_len : size_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_largeblob_remove(dev : Pfido_dev_t; key_ptr : PByte; key_len : size_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_largeblob_get_array(dev : Pfido_dev_t; var cbor_ptr : PByte; var cbor_len : size_t) : integer; cdecl; external libFido;
function fido_dev_largeblob_set_array(dev : Pfido_dev_t; cbor_ptr : PByte; cbor_len : size_t; pin : PAnsiChar) : Integer; cdecl; external libFido;
function fido_assert_authdata_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_cred_authdata_raw_len(cred : Pfido_cred_t) : size_t; cdecl; external libFido;
function fido_assert_clientdata_hash_len(assert : Pfido_assert_t) : size_t; cdecl; external libFido;
function fido_assert_count(assert : Pfido_assert_t) : size_t; cdecl; external libFido;
function fido_assert_hmac_secret_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_assert_id_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl;external libFido;
function fido_assert_largeblob_key_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libfido;
function fido_assert_sig_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_assert_user_id_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_assert_blob_len(assert : Pfido_assert_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_cbor_info_aaguid_len(ci : Pfido_cbor_info_t) : size_t; cdecl; external libFido;
function fido_cbor_info_algorithm_count(ci : Pfido_cbor_info_t) : size_t; cdecl; external libFido;
function fido_cbor_info_certs_len(ci : Pfido_cbor_info_t) : size_t; cdecl; external libFido;
function fido_cbor_info_extensions_len(ci : Pfido_cbor_info_t) : size_t;cdecl; external libFido;
function fido_cbor_info_options_len(ci : Pfido_cbor_info_t) : size_t;cdecl; external libFido;
function fido_cbor_info_protocols_len(ci : Pfido_cbor_info_t) : size_t;cdecl; external libFido;
function fido_cbor_info_transports_len(ci : Pfido_cbor_info_t) : size_t;cdecl; external libFido;
function fido_cbor_info_versions_len(ci : Pfido_cbor_info_t) : size_t;cdecl; external libFido;
function fido_cred_attstmt_len(ci : Pfido_cred_t) : size_t; cdecl; external libFido;
function fido_cred_authdata_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_clientdata_hash_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_id_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_user_id_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_pubkey_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_sig_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_x5c_len(cred : Pfido_cred_t) : size_t;cdecl; external libFido;
function fido_cred_largeblob_key_len(cred : Pfido_cred_t) : size_t; cdecl; external libFido;
function fido_assert_flags(assert : Pfido_assert_t; flags : size_t) : Byte; cdecl; external libFido;
function fido_cred_flags(cred : Pfido_cred_t) : Byte; cdecl; external libFido;
function fido_cred_sigcount(cred : Pfido_cred_t) : Longword; cdecl; external libFido;
function fido_dev_protocol(dev : Pfido_dev_t) : Byte; cdecl; external libFido;
function fido_dev_major(dev : Pfido_dev_t) : Byte; cdecl; external libFido;
function fido_dev_minor(dev : Pfido_dev_t) : Byte; cdecl; external libFido;
function fido_dev_build(dev : Pfido_dev_t) : Byte; cdecl; external libFido;
function fido_dev_flags(dev : Pfido_dev_t) : Byte; cdecl; external libFido;
function fido_dev_info_vendor(di : Pfido_dev_info_t) : smallInt; cdecl; external libFido;
function fido_dev_info_product(di : Pfido_dev_info_t) : smallInt; cdecl; external libFido;
function fido_cbor_info_maxmsgsiz(ci : Pfido_cbor_info_t) : UInt64; cdecl; external libFido;
function fido_cbor_info_maxlargeblob(ci : Pfido_cbor_info_t) : UInt64; cdecl; external libFido;
function fido_cbor_info_fwversion(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_maxcredcntlst(ci : Pfido_cbor_info_t) : UInt64; cdecl; external libFido;
function fido_cbor_info_maxcredidlen(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_minpinlen(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_maxcredbloblen(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_maxrpid_minpinlen(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_uv_attempts(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_uv_modality(ci : Pfido_cbor_info_t) : UINT64; cdecl; external libFido;
function fido_cbor_info_rk_remaining(ci : Pfido_cbor_info_t) : INT64; cdecl; external libFido;
function fido_cbor_info_new_pin_required(ci : Pfido_cbor_info_t) : Boolean; cdecl; external libFido;
// ###########################################
// #### from config.h
// ###########################################
function fido_dev_enable_entattest(dev : Pfido_dev_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_force_pin_change(dev : Pfido_dev_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_toggle_always_uv(dev : Pfido_dev_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_set_pin_minlen(dev : Pfido_dev_t; len : size_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_dev_set_pin_minlen_rpid(dev : Pfido_dev_t; rpid : PAnsiChar; n : size_t; pin : PAnsiChar) : integer; cdecl; external libFido;
// ###########################################
// #### from bio.h
// ###########################################
type
fido_bio_template_t = packed record
id : fido_blob_t;
name : PAnsiChar;
end;
Pfido_bio_template_t = ^fido_bio_template_t;
fido_bio_template_array = packed record
ptr : Pfido_bio_template_t;
n_alloc : size_t; // number of allocated entries
n_rx : size_t; // number of populated entries
end;
fido_bio_template_array_t = fido_bio_template_array;
fido_bio_enroll = packed record
remaining_samples : UInt8;
last_status : UInt8;
token : Pfido_blob_t;
end;
fido_bio_enroll_t = fido_bio_enroll;
fido_bio_info = packed record
typ : UInt8;
max_samples : UInt8;
end;
fido_bio_info_t = fido_bio_info;
Pfido_bio_info_t = ^fido_bio_info_t;
Pfido_bio_template_array_t = pointer;
Pfido_bio_enroll_t = Pointer;
const FIDO_BIO_ENROLL_FP_GOOD = $00;
FIDO_BIO_ENROLL_FP_TOO_HIGH = $01;
FIDO_BIO_ENROLL_FP_TOO_LOW = $02;
FIDO_BIO_ENROLL_FP_TOO_LEFT = $03;
FIDO_BIO_ENROLL_FP_TOO_RIGHT = $04;
FIDO_BIO_ENROLL_FP_TOO_FAST = $05;
FIDO_BIO_ENROLL_FP_TOO_SLOW = $06;
FIDO_BIO_ENROLL_FP_POOR_QUALITY = $07;
FIDO_BIO_ENROLL_FP_TOO_SKEWED = $08;
FIDO_BIO_ENROLL_FP_TOO_SHORT = $09;
FIDO_BIO_ENROLL_FP_MERGE_FAILURE = $0a;
FIDO_BIO_ENROLL_FP_EXISTS = $0b;
FIDO_BIO_ENROLL_FP_DATABASE_FULL = $0c;
FIDO_BIO_ENROLL_NO_USER_ACTIVITY = $0d;
FIDO_BIO_ENROLL_NO_USER_PRESENCE_TRANSITION = $0e;
function fido_bio_template_name(template : Pfido_bio_template_t) : PAnsiChar; cdecl; external libFido;
function fido_bio_template(templateArray : Pfido_bio_template_array_t; idx : size_t ): Pfido_bio_template_t; cdecl; external libFido;
function fido_bio_template_id_ptr(template : Pfido_bio_template_t) : PByte; cdecl; external libFido;
function fido_bio_enroll_new : Pfido_bio_enroll_t; cdecl; external libFido;
function fido_bio_info_new : Pfido_bio_info_t; cdecl; external libFido;
function fido_bio_template_array_new : Pfido_bio_template_array_t; cdecl; external libFido;
function fido_bio_template_new : Pfido_bio_template_t; cdecl; external libFido;
function fido_bio_dev_enroll_begin(dev : Pfido_dev_t; template : Pfido_bio_template_t;
endroll : Pfido_bio_enroll_t; timeout : UInt32; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_bio_dev_enroll_cancel(dev : Pfido_dev_t) : integer; cdecl; external libFido;
function fido_bio_dev_enroll_continue(dev : Pfido_dev_t; template : Pfido_bio_template_t;
enroll : Pfido_bio_enroll_t; timeout : uint32) : integer; cdecl; external libFido;
function fido_bio_dev_enroll_remove(dev : Pfido_dev_t; template : Pfido_bio_template_t;
pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_bio_dev_get_info(dev : Pfido_dev_t; info : Pfido_bio_info_t) : integer; cdecl; external libFido;
function fido_bio_dev_get_template_array(dev : Pfido_dev_t; templateArray : Pfido_bio_template_array_t;
pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_bio_dev_set_template_name(dev : Pfido_dev_t; template : Pfido_bio_template_t;
pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_bio_template_set_id(template : Pfido_bio_template_t; ptr : PByte; len : size_t) : integer; cdecl; external libFido;
function fido_bio_template_set_name(template : Pfido_bio_template_t; name : PAnsiChar) : integer; cdecl; external libFido;
function fido_bio_template_array_count(template_array : Pfido_bio_template_array_t) : size_t; cdecl; external libFido;
function fido_bio_template_id_len(template : Pfido_bio_template_t) : size_t; cdecl; external libFido;
function fido_bio_enroll_last_status(enroll : Pfido_bio_enroll_t) : byte; cdecl; external libFido;
function fido_bio_enroll_remaining_samples(enroll : Pfido_bio_enroll_t) : byte; cdecl; external libFido;
function fido_bio_info_max_samples(info : Pfido_bio_info_t) : Byte; cdecl; external libFido;
function fido_bio_info_type(info : Pfido_bio_info_t) : Byte; cdecl; external libFido;
procedure fido_bio_enroll_free(var enroll : Pfido_bio_enroll_t); cdecl; external libFido;
procedure fido_bio_info_free(var info : Pfido_bio_info_t); cdecl; external libFido;
procedure fido_bio_template_array_free(var template_array : Pfido_bio_template_array_t); cdecl; external libFido;
procedure fido_bio_template_free(var template : Pfido_bio_template_t); cdecl; external libFido;
// ###########################################
// #### from credman.h
// ###########################################
function fido_credman_rp_id(rp : Pfido_credman_rp_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_credman_rp_name(rp : Pfido_credman_rp_t; idx : size_t) : PAnsiChar; cdecl; external libFido;
function fido_credman_rk(rk : Pfido_credman_rk_t; idx : size_t) : Pfido_cred_t; cdecl; external libFido;
function fido_credman_metadata_new : Pfido_credman_metadata_t; cdecl; external libFido;
function fido_credman_rk_new : Pfido_credman_rk_t; cdecl; external libFido;
function fido_credman_rp_new : Pfido_credman_rp_t; cdecl; external libFido;
function fido_credman_del_dev_rk(dev : Pfido_dev_t; cred_id : PByte; cred_id_len : size_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_credman_get_dev_metadata(dev : Pfido_dev_t; metaData : Pfido_credman_metadata_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_credman_get_dev_rk(dev : Pfido_dev_t; rp_id : PAnsiChar; rk : Pfido_credman_rk_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_credman_set_dev_rk(dev : Pfido_dev_t; cred : Pfido_cred_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_credman_get_dev_rp(dev : Pfido_dev_t; rp : Pfido_credman_rp_t; pin : PAnsiChar) : integer; cdecl; external libFido;
function fido_credman_rk_count(rk : Pfido_credman_rk_t) : size_t; cdecl; external libFido;
function fido_credman_rp_count(rp : Pfido_credman_rp_t) : size_t; cdecl; external libFido;
function fido_credman_rp_id_hash_len(rp : Pfido_credman_rp_t; idx : size_t) : size_t; cdecl; external libFido;
function fido_credman_rp_id_hash_ptr(rp : Pfido_credman_rp_t; idx : size_t) : PByte; cdecl; external libFido;
function fido_credman_rk_existing(metadata : Pfido_credman_metadata_t) : UINT64; cdecl; external libFido;
function fido_credman_rk_remaining(metadata : Pfido_credman_metadata_t) : UINT64; cdecl; external libFido;
procedure fido_credman_metadata_free(var metadata_p : Pfido_credman_metadata_t); cdecl; external libFido;
procedure fido_credman_rk_free(var rk_p : Pfido_credman_rk_t); cdecl; external libFido;
procedure fido_credman_rp_free(var rp_p : Pfido_credman_rp_t); cdecl; external libFido;
implementation
end.
|
unit uLineProps;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls,
iexColorButton, imageenview, iexLayers, ieview, hyiedefs, ExtCtrls, Buttons;
type
TLineProps = class(TForm)
lblHeading: TLabel;
btnOK: TButton;
btnCancel: TButton;
lblRotate: TLabel;
btnBorderColor: TIEColorButton;
lblBorderWidth: TLabel;
edtBorderWidth: TEdit;
updBorderWidth: TUpDown;
lblStartShape: TLabel;
cmbStartShape: TComboBox;
lblEndShape: TLabel;
cmbEndShape: TComboBox;
lblShapeSize: TLabel;
edtShapeSize: TEdit;
updShapeSize: TUpDown;
btnShapeColor: TIEColorButton;
lblShapeColor: TLabel;
procedure FormCreate(Sender: TObject);
procedure cmbEndShapeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure ControlChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer);
end;
implementation
{$R *.dfm}
uses
iexCanvasUtils, hyieutils;
const
Default_Combo_Draw_Shape_Color = $003539E5;
Shape_ComboBox_Show_Text = True;
procedure TLineProps.FormCreate(Sender: TObject);
begin
btnBorderColor.SelectedColor := clBlack;
updBorderWidth.Position := 1;
cmbStartShape.ItemIndex := 0;
cmbEndShape.ItemIndex := 1;
updShapeSize.Position := 20;
btnShapeColor.SelectedColor := clRed;
end;
procedure TLineProps.ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer);
begin
if EditingLayer.Kind <> ielkLine then
exit;
ImageEnView.LockUpdate();
with TIELineLayer( EditingLayer ) do
try
LineColor := btnBorderColor.SelectedColor;
LineWidth := updBorderWidth.Position;
FillColor := btnShapeColor.SelectedColor;
LabelPosition := ielpHide;
// Note: Reverse StartShape and EndShape to look more natural when dragging
EndShape := TIELineEndShape( cmbStartShape.ItemIndex );
StartShape := TIELineEndShape( cmbEndShape.ItemIndex );
ShapeSize := updShapeSize.Position;
LabelAlignment := iejCenter;
finally
ImageEnView.UnlockUpdate();
end;
end;
procedure TLineProps.cmbEndShapeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
IEDrawLineEndShapeToComboListBoxItem( TComboBox( Control ).Canvas,
Rect,
Control.Enabled,
TIELineEndShape( Index ),
clBlack,
Default_Combo_Draw_Shape_Color,
Shape_ComboBox_Show_Text,
Control = cmbEndShape );
end;
procedure TLineProps.ControlChange(Sender: TObject);
var
haveShape: Boolean;
begin
haveShape := ( cmbStartShape.ItemIndex > 0 ) or ( cmbEndShape.ItemIndex > 0 );
lblShapeSize .Enabled := haveShape;
edtShapeSize .Enabled := haveShape;
updShapeSize .Enabled := haveShape;
btnShapeColor.Enabled := haveShape;
lblShapeColor.Enabled := haveShape;
end;
procedure TLineProps.FormShow(Sender: TObject);
begin
IEInitializeComboBox( cmbEndShape );
IEInitializeComboBox( cmbStartShape );
ControlChange(nil);
end;
end.
|
unit PrefConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin,IniFiles;
type
TfrmPrefConfig = class(TForm)
GroupBoxServer: TGroupBox;
EditServerCheckTimeOut: TSpinEdit;
LabelCheckTimeOut: TLabel;
Label1: TLabel;
GroupBox1: TGroupBox;
LabelSendBlockSize: TLabel;
Label3: TLabel;
EditSendBlockSize: TSpinEdit;
ButtonOK: TButton;
procedure EditServerCheckTimeOutChange(Sender: TObject);
procedure EditSendBlockSizeChange(Sender: TObject);
procedure ButtonOKClick(Sender: TObject);
private
{ Private declarations }
public
boShowOK:Boolean;//在设置显示数据前,不触发事件
{ Public declarations }
end;
var
frmPrefConfig: TfrmPrefConfig;
implementation
uses GateShare;
{$R *.dfm}
procedure TfrmPrefConfig.EditServerCheckTimeOutChange(Sender: TObject);
begin
if boShowOK then
dwCheckServerTimeOutTime:=EditServerCheckTimeOut.Value * 1000;
end;
procedure TfrmPrefConfig.EditSendBlockSizeChange(Sender: TObject);
begin
if boShowOK then
nClientSendBlockSize:=EditSendBlockSize.Value;
end;
procedure TfrmPrefConfig.ButtonOKClick(Sender: TObject);
begin
Conf.WriteInteger(GateClass,'ServerCheckTimeOut',dwCheckServerTimeOutTime);
Conf.WriteInteger(GateClass,'ClientSendBlockSize',nClientSendBlockSize);
Close;
end;
end.
|
unit Server.Controller.Game;
interface
uses Server.Entities.Game,
Common.Entities.Card,
Common.Entities.Round,
Common.Entities.Bet, Common.Entities.Player;
type
TGameController=class
private
FGame:TGame;
function DetermineWinner(ACards: TCardsThrown): String;
function CheckBetTerminated:Boolean;
procedure CheckGameTerminated;
procedure TerminateGame(const AWinner:TTeam);
function NextPlayer(const APlayerName: String): String;
function PreviousPlayer(const APlayerName: String): String;
function CountTricks(const ARounds:TGameRounds; const AGamer:String): Integer;
procedure CalcResults(AWinner: TTeam);
procedure CalcSingleResults;
procedure ShowResults;
procedure UpdateScore;
procedure CalcPoints(AGame: TGame);
procedure DistributeTalon(AGame: TGame);
function TrickBy(const ACard: TCardKey; const ALastRound: Integer;
var AWinsByTeam: TTeam): Boolean;
public
constructor Create(AGame:TGame);
procedure Shuffle;
procedure SetKing(const ACard:TCardKey);
procedure ChangeCards(const ACards:TCards);
function NewBet(ABet:TBet):String;
function FinalBet(const ABet: TBet): String;
procedure GiveUp;
function NewRound(const AIsFirst:Boolean=False): String;
function Turn(APlayer:String; ACard:TCardKey):String;
function NextTurn(const ARound:TGameRound):String;
procedure CloseRound;
end;
implementation
uses System.SysUtils, System.Generics.Collections,Common.Entities.GameType,
Common.Entities.GameSituation, dialogs,
System.Classes, System.Math;
const EPS=1E-04;
POINTSTOWIN=35.666-EPS;
constructor TGameController.Create(AGame: TGame);
begin
inherited Create;
FGame:=AGame;
FGame.Situation.GameInfo.Clear;
FGame.Situation.GameInfo.Add('Neues Spiel gestartet');
FGame.Situation.GameInfo.Add(FGame.Situation.Beginner+' hat die Vorhand');
if FGame.Doubles.Count>0 then begin
FGame.Situation.Doubles:=FGame.Doubles[0];
FGame.Doubles.Delete(0);
end
else
FGame.Situation.Doubles:=0;
if FGame.Situation.Doubles>1 then
FGame.Situation.GameInfo.Add(Format('Es gelten %d Räder',[FGame.Situation.Doubles]))
else if FGame.Situation.Doubles=1 then
FGame.Situation.GameInfo.Add('Es gilt ein Rad');
end;
function TGameController.NewBet(ABet: TBet):String;
procedure InsertBet(const ABet:TBet);
var newBet:TBet;
begin
newBet:=TBet.Create;
newBet.Assign(ABet);
FGame.Bets.Add(newBet);
if ABet.GameTypeID='PASS' then
FGame.Situation.GameInfo.Add(Format('%s hat gepasst',[ABet.Player]))
else if ABet.GameTypeID='HOLD' then
FGame.Situation.GameInfo.Add(Format('%s hat das Spiel aufgenommen',[ABet.Player]))
else
FGame.Situation.GameInfo.Add(Format('%s lizitiert %s',[ABet.Player,ALLGAMES.Find(ABet.GameTypeID).Name]))
end;
var value:Integer;
player:TPlayerCards;
i: Integer;
game:TGameType;
actPlayer:String;
begin
if (ABet.GameTypeID='HOLD') or (ABet.GameTypeid='PASS') then
value:=0
else begin
game:=ALLGAMES.Find(ABet.GameTypeID);
if Assigned(game) then
value:=game.Value
else
raise Exception.Create('Unknown Game '+ABet.GameTypeID);
end;
player:=FGame.FindPlayer(ABet.Player);
if not assigned(player) then
raise Exception.Create('Unknown Player '+ABet.Player);
if FGame.Bets.Count>0 then begin
if FGame.Situation.TurnOn<>ABet.Player then
raise Exception.Create('Is not your turn')
else if ABet.GameTypeID='HOLD' then
raise Exception.Create('Just first bet can be a HOLD')
else if player.BetState=btPass then
raise Exception.Create('You cannot bet anymore')
else if ABet.GameTypeID='PASS' then
InsertBet(ABet)
else begin
if (value>FGame.Situation.BestBet) or ((ABet.Player=FGame.Situation.Beginner) and (ABet.GameTypeID=FGame.Bets.WinningGame)) then begin
InsertBet(ABet);
FGame.Situation.BestBet:=value;
player.BetState:=btBet;
end
else
raise Exception.Create('Your bet must be higher than actual one')
end;
end
else if ABet.Player<>FGame.Situation.Beginner then
raise Exception.Create('Is not your turn')
else begin
InsertBet(ABet);
FGame.Situation.BestBet:=value;
if ABet.GameTypeID='HOLD' then
player.BetState:=btHold
else
player.BetState:=btBet;
end;
if ABet.GameTypeID='PASS' then
player.BetState:=btPass;
if not CheckBetTerminated then begin
actPlayer:=ABet.Player;
for i := 1 to 4 do begin
FGame.Situation.TurnOn:=NextPlayer(actPlayer);
if FGame.FindPlayer(FGame.Situation.TurnOn).BetState<>btPass then
Break
else
actPlayer:=FGame.Situation.TurnOn;
end;
end;
Result:=FGame.Situation.TurnOn;
end;
function TGameController.FinalBet(const ABet:TBet):String;
function MergeBets(var ASource:TAddBets; ADest:TAddBets; const ASourceTeam:TTeam):TAddBets;
procedure Merge(var ASourceBet:TAddBet; var ADestBet:TAddBet);
begin
if (Ord(ASourceBet.BetType)>0) and (ASourceBet.BetType>ADestBet.BetType) and (ADestBet.BetType<abtRe) then begin
Inc(ADestBet.BetType);
ADestBet.Team:=ASourceTeam;
end
else
ASourceBet.BetType:=abtNone;
end;
begin
Merge(ASource.Minus10,ADest.Minus10);
Merge(ASource.ContraGame,ADest.ContraGame);
Merge(ASource.AllKings,ADest.AllKings);
Merge(ASource.KingUlt,ADest.KingUlt);
Merge(ASource.PagatUlt,ADest.PagatUlt);
Merge(ASource.VogelII,ADest.VogelII);
Merge(ASource.VogelIII,ADest.VogelIII);
Merge(ASource.VogelIV,ADest.VogelIV);
Merge(ASource.Valat,ADest.Valat);
Merge(ASource.Trull,ADest.Trull);
Merge(ASource.CatchKing,ADest.CatchKing);
Merge(ASource.CatchPagat,ADest.CatchPagat);
Merge(ASource.CatchXXI,ADest.CatchXXI);
Result:=ADest;
end;
function AddInfo(const ASL:TStringList;const AMessage:String;const APlayer:String; const ABet:TAddBet):String;
var s:String;
begin
if ABet.BetType=abtBet then
s:=APlayer+' sagt '+AMessage+' an'
else if ABet.BetType=abtContra then
s:=APlayer+' sagt contra '+AMessage
else if ABet.BetType=abtRe then
s:=APlayer+' sagt re '+AMessage else
Exit;
ASL.Add(s);
end;
var player:TPlayerCards;
sl:TStringList;
addBets:TAddBets;
begin
if FGame.LastFinalBidder='' then
FGame.LastFinalBidder:=PreviousPlayer(FGame.Situation.Gamer);
player:=FGame.FindPlayer(ABet.Player);
if not assigned(player) then
raise Exception.Create('Unknown Player '+ABet.Player);
if FGame.Situation.TurnOn<>ABet.Player then
raise Exception.Create('Is not your turn');
addBets:=ABet.AddBets;
FGame.Situation.AddBets:=MergeBets(addBets,FGame.Situation.AddBets,player.Team);
sl:=TStringList.Create;
try
if addBets.ContraGame.BetType >abtBet then
AddInfo(sl,'Spiel',ABet.Player,addBets.ContraGame);
AddInfo(sl,'Sack',ABet.Player,addBets.Minus10);
AddInfo(sl,'König ult',ABet.Player,addBets.KingUlt);
AddInfo(sl,'Pagat ult',ABet.Player,addBets.PagatUlt);
AddInfo(sl,'Vogel II',ABet.Player,addBets.VogelII);
AddInfo(sl,'Vogel III',ABet.Player,addBets.VogelIII);
AddInfo(sl,'Vogel IV',ABet.Player,addBets.VogelIV);
AddInfo(sl,'alle 4 Könige',ABet.Player,addBets.AllKings);
AddInfo(sl,'Trull',ABet.Player,addBets.Trull);
AddInfo(sl,'König Fang',ABet.Player,addBets.CatchKing);
AddInfo(sl,'Pagat Fang',ABet.Player,addBets.CatchPagat);
AddInfo(sl,'XXI Fang',ABet.Player,addBets.CatchXXI);
AddInfo(sl,'Valat',ABet.Player,addBets.Valat);
if sl.Count>0 then begin
FGame.LastFinalBidder:=PreviousPlayer(ABet.Player);
FGame.Situation.GameInfo.AddStrings(sl);
end
else if ABet.Player=FGame.Situation.Gamer then
FGame.Situation.GameInfo.Add(ABet.Player+' liegt')
else
FGame.Situation.GameInfo.Add(ABet.Player+' sagt weiter');
finally
sl.Free;
end;
if ABet.Player=FGame.LastFinalBidder then begin
FGame.Situation.State:=gsPlaying;
if not FGame.ActGame.Positive then
FGame.Situation.TurnOn:=FGame.Situation.Gamer
else
FGame.Situation.TurnOn:=FGame.Situation.Beginner;
FGame.Situation.GameInfo.Add(' ');
FGame.Situation.GameInfo.Add(FGame.Situation.TurnOn+' kommt raus');
NewRound(True);
end
else
FGame.Situation.TurnOn:=NextPlayer(ABet.Player);
Result:=FGame.Situation.TurnOn;
end;
procedure TGameController.GiveUp;
begin
if FGame.ActGame.TeamKind=tkPair then begin
if FGame.Rounds.Count=0 then begin
FGame.Active:=False;
TerminateGame(ttTeam2);
end
else
raise Exception.Create('Games with Called Kings can folded just at the beginning')
end
else
raise Exception.Create('Just Games with Called Kings can folded at the beginning')
end;
function TGameController.NewRound(const AIsFirst:Boolean):String;
var r:TGameRound;
i: Integer;
begin
r:=FGame.ActRound;
if Assigned(r) and not r.Done then
raise Exception.Create('Prior Round not closed yet')
else begin
if AIsFirst then
FGame.TalonRounds:=FGame.Rounds.Count; // rounds used by save cards of talon layeddown
r:=TGameRound.Create;
if AIsFirst or not Assigned(FGame.ActRound) then
r.TurnOn:=FGame.Situation.TurnOn
else
r.TurnOn:=FGame.ActRound.Winner;
FGame.Situation.TurnOn:=r.TurnOn;
FGame.Situation.RoundNo:=FGame.Situation.RoundNo+1;
// reihenfolge der Spieler definieren
for i := FGame.FindPlayer(r.TurnOn).Index to 3 do
r.CardsThrown.Add(TCardThrown.Create(FGame.Players[i].Name));
for i := 0 to FGame.FindPlayer(r.TurnOn).Index-1 do
r.CardsThrown.Add(TCardThrown.Create(FGame.Players[i].Name));
FGame.Rounds.Add(r);
end;
Result:=r.TurnOn;
end;
function TGameController.NextPlayer(const APlayerName:String):String;
var player:TPlayerCards;
begin
player:=FGame.FindPlayer(APlayerName);
if Assigned(player) then
Result:=FGame.Players[(player.Index+1) mod 4].Name
else
raise Exception.Create('Unknown Player '+APlayerName);
end;
function TGameController.NextTurn(const ARound: TGameRound): String;
begin
ARound.TurnOn:=NextPlayer(ARound.TurnOn);
FGame.Situation.TurnOn:=ARound.TurnOn;
Result:=ARound.TurnOn;
end;
function TGameController.PreviousPlayer(const APlayerName: String): String;
var player:TPlayerCards;
begin
player:=FGame.FindPlayer(APlayerName);
if Assigned(player) then
Result:=FGame.Players[(player.Index+3) mod 4].Name
else
raise Exception.Create('Unknown Player '+APlayerName);
end;
procedure TGameController.SetKing(const ACard: TCardKey);
function KingName(const ACard:TCardKey):String;
begin
case ACard of
HK:Result:='Herz-König';
CK:Result:='Kreuz-König';
SK:Result:='Pik-König';
DK:Result:='Karo-König';
end;
end;
var player:TPlayerCards;
begin
if FGame.Situation.State=gsCallKing then begin
if ACard in [HK,CK,SK,DK] then begin
FGame.Situation.KingSelected:=ACard;
FGame.Situation.GameInfo.Add(FGame.Situation.Gamer+' hat den '+KingName(ACard)+' gerufen');
// Get Teams
for player in FGame.Players do begin
if player.Name=FGame.Situation.Gamer then
player.Team:=ttTeam1
else if player.Cards.Exists(FGame.Situation.KingSelected) then
player.Team:=ttTeam1
else
player.Team:=ttTeam2;
end;
if FGame.ActGame.Talon<>tkNoTalon then
FGame.Situation.State:=gsGetTalon
else begin
DistributeTalon(FGame);
FGame.Situation.State:=gsFinalBet;
end
end
else
raise Exception.Create('It is not a king-card');
end
else
raise Exception.Create('you cannot choice a king now');
end;
procedure TGameController.Shuffle;
procedure IntShuffle(var ACards: TCards; const APlayerCards:TPlayerCards; const ACount: Integer; ASort:Boolean);
var i,r:Integer;
itm:TCard;
begin
APlayerCards.Cards.Clear;
for i:=1 to ACount do begin
r:=Random(ACards.Count);
itm:=ACards.Extract(ACards.Items[r]);
APlayerCards.Cards.Add(itm);
end;
if ASort then
APlayerCards.Cards.Sort;
end;
var cards:TCards;
i:Integer;
begin
cards:=ALLCARDS.Clone;
try
for I := 0 to FGame.Players.Count-1 do
IntShuffle(cards,FGame.Players[i],12,True);
IntShuffle(cards,FGame.Talon,6,False);
// FGame.Talon.Cards[2]:=Allcards[0];
finally
cards.Free
end;
end;
function TGameController.Turn(APlayer: String; ACard: TCardKey):String;
var player:TPlayerCards;
begin
player:=FGame.FindPlayer(APlayer);
if not Assigned(player) then
raise Exception.Create('Player ' +APlayer +' not known');
if FGame.ActRound.TurnOn<>APlayer then
raise Exception.Create('Turn is not on ' +APlayer);
if FGame.ActRound.Done then
raise Exception.Create('Turn is just complete');
FGame.ActRound.ThrowCard(APlayer,ACard);
FGame.Players.Find(APlayer).Cards.Find(ACard).Fold:=True;
if FGame.ActRound.Done then begin
CloseRound;
if Assigned(FGame.ActRound) then
Result:='The Winner is '+FGame.ActRound.Winner
end
else
Result:='Next Player is '+NextTurn(FGame.ActRound);
end;
procedure TGameController.CloseRound;
var
c: TCardThrown;
begin
FGame.ActRound.Winner:=DetermineWinner(FGame.ActRound.CardsThrown);
FGame.Situation.GameInfo.Add(FGame.ActRound.Winner+' sticht');
FGame.Situation.TurnOn:=FGame.ActRound.Winner;
// on Trischaken distribute talon to first 6 tricks
if (FGame.ActGame.GameTypeid='TRISCH') and (FGame.Rounds.Count<=FGame.Talon.Cards.Count) then begin
c:=TCardThrown.Create('TALON');
c.Card:=FGame.Talon.Cards[FGame.Rounds.Count-1].ID;
FGame.ActRound.CardsThrown.Add(c);
end;
CheckGameTerminated;
end;
function TGameController.DetermineWinner(ACards: TCardsThrown):String;
function ActCardWins(const AActCard:TCard; const AFormerCard:TCard):Boolean;
begin
if not Assigned(AFormerCard) then
Result:=True
else
Result:=AActCard.IsStronger(AFormerCard,FGame.ActGame.JustColors);
end;
var c:TCardThrown;
strongestCard,actCard:TCard;
begin
if ACards.Exists(T1) and ACards.Exists(T21) and ACards.Exists(T22) then // whole Trull present
Result:=ACards.Find(T1).PlayerName // Pagat wins
else begin
strongestCard:=nil;
for c in ACards do begin
actCard:=ALLCARDS.Find(c.Card);
if ActCardWins(actCard,strongestCard) then begin
Result:=c.PlayerName;
strongestCard:=actCard;
end
end;
end;
end;
procedure TGameController.ChangeCards(const ACards: TCards);
var player:TPlayerCards;
otherplayer:String;
card: TCard;
cthrown: TCardThrown;
layDown:TCard;
forOtherTeam,forMyTeam:TGameRound;
begin
try
if FGame.Situation.State=gsGetTalon then begin
otherPlayer:='';
for player in FGame.Players do begin
if player.Team=ttTeam2 then begin
otherPlayer:=player.Name;
Break;
end;
end;
player:=FGame.Players.Find(FGame.Situation.Gamer);
if not Assigned(player) then
raise Exception.Create('Actual gamer '+FGame.Situation.Gamer+' not found');
for card in ACards do begin
if not Card.Fold then begin
if card.ID in [HK,CK,DK,SK] then
raise Exception.Create('Kings cannot be layed away')
else if card.ID in [T1,T21,T22] then
raise Exception.Create('Trull cannot be layed away');
end;
end;
for card in FGame.Talon.Cards do
player.Cards.AddItem(card.ID,card.CType,card.Value,card.Points,card.ImageIndex);
forMyTeam:=TGameRound.Create;
forMyTeam.Winner:=FGame.Situation.Gamer;
if FGame.ActGame.Talon=tk3Talon then begin
forOtherTeam:=TGameRound.Create;
forOtherTeam.Winner:=otherPlayer;
end
else
forOtherTeam:=Nil;
for card in ACards do begin
laydown:=player.Cards.Find(card.ID);
if Assigned(layDown) then begin
layDown:=player.Cards.Extract(layDown);
cthrown:= TCardThrown.Create('');
cthrown.Card:=laydown.ID;
if card.Fold and (FGame.ActGame.Talon=tk3Talon)then begin // cards belongs to other team
cthrown.PlayerName:=otherplayer;
forOtherTeam.CardsThrown.Add(cthrown);
FGame.Talon.Cards.Find(card.ID).Fold:=True; // sign that belongs to other team
end
else begin // cards belongs to my team
cthrown.PlayerName:=FGame.Situation.Gamer;
forMyTeam.CardsThrown.Add(cthrown);
if (not FGame.ActGame.JustColors and (laydown.CType=ctTarock)) or
(FGame.ActGame.JustColors and (laydown.CType<>ctTarock)) then begin
FGame.Situation.CardsLayedDown.AddItem(laydown.ID,laydown.CType,laydown.Value,laydown.Points,laydown.ImageIndex);
end;
end;
laydown.Free;
end;
end;
player.Cards.Sort;
FGame.Rounds.Add(forMyTeam);
if Assigned(forOtherTeam) then
FGame.Rounds.Add(forOtherTeam);
FGame.Situation.State:=gsFinalBet;
end
else
raise Exception.Create('you cannot can cards with talon now');
finally
// ACards.Free;
end;
end;
function TGameController.CheckBetTerminated: Boolean;
var passed:Smallint;
player:TPlayerCards;
begin
Result:=False;
passed:=0;
for player in FGame.Players do begin
if player.BetState=btPass then
Inc(passed);
end;
FGame.Situation.Gamer:='';
if passed=3 then begin
for player in FGame.Players do begin
if player.BetState=btBet then begin
FGame.Situation.Gamer:=player.Name;
Result:=True;
Break;
end;
end;
end;
if Result then begin
FGame.ActGame:=ALLGames.Find(FGame.Bets.WinningGame);
FGame.Situation.GameType:=FGame.ActGame.GameTypeid;
FGame.Situation.TurnOn:=FGame.Situation.Gamer;
FGame.Situation.GameInfo.Clear;
FGame.Situation.GameInfo.Add(FGame.Situation.Gamer+' spielt '+FGame.ActGame.Name);
if FGame.ActGame.Positive then
FGame.Situation.GameInfo.Add(FGame.Situation.Beginner+' hat die Vorhand');
if FGame.ActGame.Positive and (FGame.ActGame.TeamKind=tkPair) then
FGame.Situation.State:=gsCallKing // teams will be build later
else begin
// Get Teams
for player in FGame.Players do begin
if player.Name=FGame.Situation.Gamer then
player.Team:=ttTeam1
else
player.Team:=ttTeam2;
end;
if not FGame.ActGame.Positive then begin
FGame.Situation.State:=gsFinalBet;
FGame.Situation.TurnOn:=NextPlayer(FGame.Situation.Gamer);
end
else if FGame.ActGame.Talon<>tkNoTalon then
FGame.Situation.State:=gsGetTalon
else begin
DistributeTalon(FGame);
FGame.Situation.State:=gsFinalBet
end;
end;
end;
end;
procedure TGameController.DistributeTalon(AGame:TGame);
type TKingFound=(kfNone,kfFirst,kfSecond);
procedure AssignCards(const APlayerName:String;const AFrom, ATo:Integer);
var
cthrown: TCardThrown;
i: Integer;
round: TGameRound;
begin
round:=TGameRound.Create;
round.Winner:=APlayerName;
for i:=AFrom to ATo do begin
cthrown:= TCardThrown.Create('');
cthrown.Card:=FGame.Talon.Cards[i].ID;
cthrown.PlayerName:=APlayerName;
round.CardsThrown.Add(cthrown);
end;
FGame.Rounds.Add(round);
end;
var otherplayer:String;
i: Integer;
player:TPlayerCards;
kingFound:TKingFound;
begin
if not AGame.ActGame.Positive or (AGame.ActGame.Talon<>tkNoTalon) then Exit;
otherPlayer:='';
for player in FGame.Players do begin
if player.Team=ttTeam2 then begin
otherPlayer:=player.Name;
Break;
end;
end;
kingfound:=kfNone;
if (AGame.ActGame.TeamKind=tkPair) then begin
for i:=0 to FGAme.Talon.Cards.Count-1 do begin
if FGame.Talon.Cards[i].ID=AGame.Situation.KingSelected then begin
if i<3 then
kingFound:=kfFirst
else
kingFound:=kfSecond;
Break;
end;
end;
end;
if kingFound=kfNone then //whole talon belongs to enemy
AssignCards(otherplayer,0,FGame.Talon.Cards.Count-1)
// if called king stays in Talon half of them belongs to gamer
else if kingFound=kfFirst then begin
AssignCards(FGame.Situation.Gamer,0,2);
AssignCards(otherplayer,3,5);
end
else begin
AssignCards(otherplayer,0,2);
AssignCards(FGame.Situation.Gamer,3,5);
end;
end;
procedure TGameController.CheckGameTerminated;
var winner:TTeam;
allRoundsPlayed:Boolean;
i,k: Integer;
begin
if not FGame.Active then Exit;
allRoundsPlayed:=((FGame.Rounds.Count-FGame.TalonRounds)>=12);
winner:=ttTeam1;
case FGame.ActGame.WinCondition of
wc12Rounds,
wcT1Trick,
wcT2Trick,
wcT3Trick,
wcT4Trick:begin
FGame.Active:=not allRoundsPlayed;
(* if FGame.ActRound.CardsThrown.Exists(HK) then
FGame.Active:=False;*)
if not FGame.Active then begin
CalcPoints(FGame);
if FGame.ActGame.GameTypeid='TRISCH' then begin
winner:=ttTeam2;
k:= FGame.Doubles.Count;
for i:=0 to k-1 do // add 4 doubles to next games
FGame.Doubles[i]:=FGame.Doubles[i]+1;
for i:=1 to 4-k do
FGame.Doubles.Add(1);
end
// player whos says contra must get at least 35 + 2 cards to win even is not the gamer itself
else if (FGame.Situation.AddBets.ContraGame.BetType>abtNone) and (FGame.Situation.AddBets.ContraGame.Team=ttTeam2) then begin
if FGame.Situation.Team2Results.Points>=POINTSTOWIN then
winner:=ttTeam2
else
winner:=ttTeam1;
end
else if FGame.Situation.Team1Results.Points>=POINTSTOWIN then
winner:=ttTeam1
else
winner:=ttTeam2;
// vogel-game must also be tricked
if (winner=ttTeam1) and ( FGame.ActGame.WinCondition<>wc12Rounds) then begin
if (FGame.ActGame.WinCondition=wcT1Trick) and TrickBy(T1,FGame.Rounds.Count-1,winner) then
else if (FGame.ActGame.WinCondition=wcT2Trick) and TrickBy(T2,FGame.Rounds.Count-2,winner)then
else if (FGame.ActGame.WinCondition=wcT3Trick) and TrickBy(T3,FGame.Rounds.Count-3,winner)then
else if (FGame.ActGame.WinCondition=wcT4Trick) and TrickBy(T4,FGame.Rounds.Count-4,winner)then
else
winner:=ttTeam2;
end;
end;
end;
wc0Trick: begin
if FGame.ActRound.Winner=FGame.Situation.Gamer then begin
FGame.Active:=False;
winner:=ttTeam2;
end
else if allRoundsPlayed then begin
FGame.Active:=False;
winner:=ttTeam1;
end;
end;
wc1Trick: begin
if (FGame.ActRound.Winner=FGame.Situation.Gamer) and
(CountTricks(FGame.Rounds,FGame.Situation.Gamer)>1) then begin
FGame.Active:=False;
winner:=ttTeam2;
end
else if allRoundsPlayed then begin
FGame.Active:=False;
if CountTricks(FGame.Rounds,FGame.Situation.Gamer)=1 then
winner:=ttTeam1
else
winner:=ttTeam2;
end;
end;
wc2Trick: begin
if (FGame.ActRound.Winner=FGame.Situation.Gamer) and
(CountTricks(FGame.Rounds,FGame.Situation.Gamer)>2) then begin
FGame.Active:=False;
winner:=ttTeam2;
end
else if allRoundsPlayed then begin
FGame.Active:=False;
if CountTricks(FGame.Rounds,FGame.Situation.Gamer)=2 then
winner:=ttTeam1
else
winner:=ttTeam2;
end;
end;
wc3Trick: begin
if (FGame.ActRound.Winner=FGame.Situation.Gamer) and
(CountTricks(FGame.Rounds,FGame.Situation.Gamer)>3) then begin
FGame.Active:=False;
winner:=ttTeam2;
end
else if allRoundsPlayed then begin
FGame.Active:=False;
if CountTricks(FGame.Rounds,FGame.Situation.Gamer)=3 then
winner:=ttTeam1
else
winner:=ttTeam2;
end;
end;
end;
TerminateGame(winner);
end;
procedure TGameController.CalcPoints(AGame:TGame);
var
round: TGameRound;
team1Points,team2Points:Double;
player:TPlayerCards;
existsVirgin:Boolean;
begin
team1Points:=0;
team2Points:=0;
if AGame.ActGame.TeamKind=tkSinglePlayer then begin
for player in AGame.Situation.Players do begin
player.Team:=ttNone;
player.Points:=0;
player.Results:=0;
end;
for round in AGame.Rounds do
AGame.Situation.Players.Find(round.Winner).Points:=AGame.Situation.Players.Find(round.Winner).Points+round.CardsThrown.TotalValue;
if AGame.ActGame.GameTypeid='TRISCH' then begin
existsVirgin:=False;
for player in AGame.Situation.Players do begin
if player.Points>team1Points then
team1Points:=player.Points
else if player.Points=0 then
existsVirgin:=True;
end;
for player in AGame.Situation.Players do begin
if Abs(player.Points-team1Points)<EPS then
player.Team:=ttTeam1 // team1=looser
else if existsVirgin and (player.Points=0) then // if exists virgin(s) they take it all
player.Team:=ttTeam2
else if not existsVirgin then
player.Team:=ttTeam2;
end;
end;
end
else begin
for round in AGame.Rounds do begin
AGame.Situation.Players.Find(round.Winner).Points:=AGame.Situation.Players.Find(round.Winner).Points+round.CardsThrown.TotalValue;
if AGame.TeamOf(round.Winner)=ttTeam1 then
team1Points:=team1Points+round.CardsThrown.TotalValue
else
team2Points:=team2Points+round.CardsThrown.TotalValue
end;
end;
AGame.Situation.Team1Results.SetPoints(team1Points);
AGame.Situation.Team2Results.SetPoints(team2Points);
end;
procedure TGameController.UpdateScore;
var player:TPlayerCards;
begin
if FGame.ActGame.TeamKind=tkSinglePlayer then begin
for player in FGame.Situation.Players do begin
if FGame.Situation.Doubles>0 then
player.Score:=player.Score+(player.Results*Trunc(Power(2,FGame.Situation.Doubles)))
else
player.Score:=player.Score+player.Results;
player.Results:=0;
end;
end
else begin
for player in FGame.Situation.Players do begin
if FGame.TeamOf(player.Name)=ttTeam1 then
player.Score:=player.Score+FGame.Situation.Team1Results.GrandTotal
else
player.Score:=player.Score+FGame.Situation.Team2Results.GrandTotal
end;
end;
end;
procedure TGameController.ShowResults;
procedure ShowResult(ABet:String;const ATeam1,ATeam2:Integer;AShowAlways:Boolean=False);overload;
begin
if not AShowAlways and (ATeam1=0) then Exit;
if Length(ABet)<12 then
ABet:=ABet+StringOfChar(' ',12-Length(ABet));
FGame.Situation.GameInfo.Add(Format(ABet+' %4d %4d',[ATeam1,ATeam2]));
end;
procedure ShowResult(ABet:String;const ATeam1,ATeam2:Integer;const AAddBet:TAddBet);overload;
begin
if ATeam1=0 then Exit;
if AAddBet.BetType=abtBet then
ABet:=ABet+'(B)'
else if AAddBet.BetType=abtContra then
ABet:=ABet+'(C)'
else if AAddBet.BetType=abtRe then
ABet:=ABet+'(R)';
ShowResult(ABet,ATeam1,ATeam2);
end;
var player:TPlayerCards;
addInfo: string;
begin
FGame.Situation.GameInfo.Add( '=========================');
if FGame.ActGame.TeamKind<>tkSinglePlayer then begin
FGame.Situation.GameInfo.Add( ' Team1 Team2');
ShowResult('Spiel',FGame.Situation.Team1Results.Game,FGame.Situation.Team2Results.Game);
if FGame.Situation.AddBets.ContraGame.BetType>abtBet then
ShowResult('Spiel',FGame.Situation.Team1Results.ContraGame,FGame.Situation.Team2Results.ContraGame,FGame.Situation.AddBets.ContraGame);
ShowResult('Valat',FGame.Situation.Team1Results.Valat,FGame.Situation.Team2Results.Valat,FGame.Situation.AddBets.Valat);
ShowResult(IntToStr(FGame.Situation.Team1Results.Minus10Count)+' Sack ',FGame.Situation.Team1Results.Minus10,FGame.Situation.Team2Results.Minus10,FGame.Situation.AddBets.Minus10);
ShowResult('König Ult',FGame.Situation.Team1Results.KingUlt,FGame.Situation.Team2Results.KingUlt,FGame.Situation.AddBets.KingUlt);
ShowResult('Pagat Ult',FGame.Situation.Team1Results.PagatUlt,FGame.Situation.Team2Results.PagatUlt,FGame.Situation.AddBets.PagatUlt);
ShowResult('Vogel II',FGame.Situation.Team1Results.VogelII,FGame.Situation.Team2Results.VogelII,FGame.Situation.AddBets.VogelII);
ShowResult('Vogel III',FGame.Situation.Team1Results.VogelIII,FGame.Situation.Team2Results.VogelIII,FGame.Situation.AddBets.VogelIII);
ShowResult('Vogel IV',FGame.Situation.Team1Results.VogelIV,FGame.Situation.Team2Results.VogelIV,FGame.Situation.AddBets.VogelIV);
ShowResult('Alle Könige',FGame.Situation.Team1Results.AllKings,FGame.Situation.Team2Results.AllKings,FGame.Situation.AddBets.AllKings);
ShowResult('Trull',FGame.Situation.Team1Results.Trull,FGame.Situation.Team2Results.Trull,FGame.Situation.AddBets.Trull);
ShowResult('König Fang',FGame.Situation.Team1Results.CatchKing,FGame.Situation.Team2Results.CatchKing,FGame.Situation.AddBets.CatchKing);
ShowResult('Pagat Fang',FGame.Situation.Team1Results.CatchPagat,FGame.Situation.Team2Results.CatchPagat,FGame.Situation.AddBets.CatchPagat);
ShowResult('XXI Fang',FGame.Situation.Team1Results.CatchXXI,FGame.Situation.Team2Results.CatchXXI,FGame.Situation.AddBets.CatchXXI);
FGame.Situation.GameInfo.Add( '=========================');
ShowResult('Summe',FGame.Situation.Team1Results.Total,FGame.Situation.Team2Results.Total,True);
if FGame.Situation.Doubles>0 then begin
FGame.Situation.GameInfo.Add('');
if FGame.Situation.Doubles=1 then
FGame.Situation.GameInfo.Add('Im Radl x 2')
else
FGame.Situation.GameInfo.Add(Format('Im %d-fach Radl x %d',[FGame.Situation.Doubles,Trunc(Power(2,FGame.Situation.Doubles))]));
ShowResult('Totale',FGame.Situation.Team1Results.GrandTotal,FGame.Situation.Team2Results.GrandTotal);
end;
end
else begin
for player in FGame.Players do begin
if player.Results<>0 then begin
addInfo:='';
if (FGame.ActGame.GameTypeid='TRISCH') then begin
if player.Points>=POINTSTOWIN then
addInfo:='(Bürgermeister)'
else if player.Points=0 then
addInfo:='(Jungfrau)'
else if (player.Name=FGame.Situation.Gamer) and (player.Results<0) then
addInfo:='(Vorhand)'
end;
FGame.Situation.GameInfo.Add(Format('%s %4d %s',
[player.Name+StringOfChar(' ',12-Length(player.Name)),player.Results,addInfo]));
end;
end;
FGame.Situation.GameInfo.Add( '=========================');
if FGame.Situation.Doubles>0 then begin
FGame.Situation.GameInfo.Add('');
if FGame.Situation.Doubles=1 then
FGame.Situation.GameInfo.Add(' Im Radl x 2')
else
FGame.Situation.GameInfo.Add(Format(' Im %d-fach Radl x %d',[FGame.Situation.Doubles,2*FGame.Situation.Doubles]));
end;
end;
end;
procedure TGameController.TerminateGame(const AWinner: TTeam);
begin
if not FGame.Active then begin
FGame.Situation.State:=gsTerminated;
FGame.Situation.TurnOn:=NextPlayer(FGame.Situation.Beginner);
FGame.Situation.GameInfo.Clear;
FGame.Situation.GameInfo.Add('Spiel ist beendet');
FGame.Situation.GameInfo.Add('======================');
if FGame.Rounds.Count=0 then
FGame.Situation.GameInfo.Add(FGame.Team1Names+' gibt auf und zahlt')
else if FGame.ActGame.WinCondition in [wc12Rounds,wcT1Trick,wcT2Trick,wcT3Trick,wcT4Trick] then
FGame.Situation.GameInfo.Add('Das Team1 macht '+FGame.Situation.Team1Results.PointsAsString);
if AWinner=ttTeam1 then begin
if FGame.ActGame.TeamKind in [tkSolo,tkOuvert,tkAllOuvert] then
FGame.Situation.GameInfo.Add(FGame.Situation.Gamer+' gewinnt')
else
FGame.Situation.GameInfo.Add('Das Team1 ('+FGame.Team1Names+') gewinnt')
end
else if FGame.ActGame.GameTypeid='TRISCH' then
FGame.Situation.GameInfo.Add(FGame.Team1Names+' zahlt an '+FGame.Team2Names)
else
FGame.Situation.GameInfo.Add('Das Team2 ('+FGame.Team2Names+') gewinnt');
if FGame.ActGame.TeamKind<>tkSinglePlayer then
CalcResults(AWinner)
else
CalcSingleResults;
ShowResults;
UpdateScore;
end;
end;
function TGameController.TrickBy(const ACard:TCardKey; const ALastRound:Integer; var AWinsByTeam:TTeam):Boolean;
var
card: TCardThrown;
round:TGameRound;
begin
round:=FGame.Rounds.Items[ALastRound];
AWinsByTeam:=FGame.TeamOf(round.Winner);
card:=round.CardsThrown.Find(ACard);
if Assigned(card) then begin
if (card.PlayerName=round.Winner) then // card itself tricks
Result:=true
else if FGame.TeamOf(card.PlayerName)=AWinsByTeam then // partner has destroyed the trick
result:=false
else // cath by other team
Result:=True;
end
else
Result:=false;
end;
procedure TGameController.CalcResults(AWinner:TTeam);
function AddBet(AValue:Integer; AAddBet:TAddBet;AIsValat:Boolean):Integer;
begin
case AAddBet.BetType of
abtBet: Result:=AValue*2;
abtContra: Result:=AValue*4;
abtRe: Result:=AValue*8;
else if not AIsValat then
Result:=AValue
else
Result:=0;
end;
end;
function IsValat(var AWinsByTeam:TTeam):Boolean;
var i: Integer;
begin
Result:=False;
if FGame.Rounds.Count<=FGame.TalonRounds then Exit;
AWinsByTeam:=FGame.TeamOf(FGame.Rounds[FGame.TalonRounds].Winner);
for i :=FGame.TalonRounds+1 to FGame.Rounds.Count-1 do begin
if FGame.TeamOf(FGame.Rounds[i].Winner)<>AWinsByTeam then
Exit;
end;
Result:=True;
end;
function CatchBy(const ACard:TCardKey; var AWinsByTeam:TTeam):Boolean;
var round:TGameRound;
card:TCardThrown;
begin
Result:=False;
for round in FGame.Rounds do begin
if round.CardsThrown.Exists(ACard) then begin
card:=round.CardsThrown.Find(ACard);
AWinsByTeam:=FGame.TeamOf(round.Winner);
Result:=FGame.TeamOf(card.PlayerName)<>AWinsByTeam;
Break;
end;
end;
end;
function BelongsTo(const ACard:TCardKey):TTeam;
var round:TGameRound;
begin
Result:=ttTeam1;
for round in FGame.Rounds do begin
if round.CardsThrown.Exists(ACard) then begin
Result:=FGame.TeamOf(round.Winner);
Break;
end;
end;
end;
procedure CheckBet(var AResultTeam1:Smallint; const AConditionFullFilled:Boolean;
const AWinsByTeam:TTeam;const AValue:Integer;const AAddBet:TAddBet;const AIsValat:Boolean);
begin
if AConditionFullFilled then begin
if AWinsByTeam=ttTeam1 then
AResultTeam1:=AddBet(AValue,AAddBet,AIsValat)
else
AResultTeam1:=-AddBet(AValue,AAddBet,AIsValat);
end
else if AAddBet.BetType=abtContra then begin
if AAddBet.Team=ttTeam1 then
AResultTeam1:=AddBet(AValue,AAddBet,AIsValat)
else
AResultTeam1:=-AddBet(AValue,AAddBet,AIsValat);
end
else if AAddBet.BetType<>abtNone then begin
if AAddBet.Team=ttTeam1 then
AResultTeam1:=-AddBet(AValue,AAddBet,AIsValat)
else
AResultTeam1:=AddBet(AValue,AAddBet,AIsValat);
end;
end;
var contraGame:Integer;
team1,team2:TGameResults;
winsByTeam:TTeam;
valat:Boolean;
value: Smallint;
begin
team1:=Default(TGameResults);
team2:=Default(TGameResults);
team1.Points:=FGame.Situation.Team1Results.Points;
team2.Points:=FGame.Situation.Team2Results.Points;
team1.Doubles:=FGame.Situation.Doubles;
team2.Doubles:=FGame.Situation.Doubles;
if FGame.ActGame.GameTypeid='63' then
value:=6
else
value:=FGame.ActGame.Value;
contraGame:=(AddBet(value,FGame.Situation.AddBets.ContraGame,False) div 2)-value;
case AWinner of
ttTeam1: begin
team1.Game:=value;
team1.ContraGame:=contraGame;
end;
else begin
if FGame.ActGame.GameTypeid='63' then begin
team1.Game:=-value*2;
team1.ContraGame:=-contraGame*2;
end
else begin
team1.Game:=-value;
team1.ContraGame:=-contraGame;
end;
end;
end;
if FGame.ActGame.Positive then begin
if FGame.Rounds.Count>0 then begin
valat:=IsValat(winsByTeam);
if valat then begin
if winsByTeam=ttTeam1 then
team1.Valat:=(AddBet(4,FGame.Situation.AddBets.Valat,False)-1)*team1.Game
else
team1.Valat:=-(AddBet(4,FGame.Situation.AddBets.Valat,False)-1)*team1.Game;
end
else if FGame.Situation.AddBets.Valat.BetType>abtNone then begin
if ((FGame.Situation.AddBets.Valat.Team=ttTeam1) and (FGame.Situation.AddBets.Valat.BetType in [abtBet,abtRe])) or
((FGame.Situation.AddBets.Valat.Team=ttTeam2) and (FGame.Situation.AddBets.Valat.BetType=abtContra)) then
team1.Valat:=-(AddBet(4,FGame.Situation.AddBets.Valat,False)-1)*team1.Game
else
team1.Valat:=(AddBet(4,FGame.Situation.AddBets.Valat,False)-1)*team1.Game;
end;
if not valat then begin
if FGame.Situation.Team1Results.Points>=POINTSTOWIN+20 then
team1.Minus10Count:=2
else if FGame.Situation.Team1Results.Points>=POINTSTOWIN+10 then
team1.Minus10Count:=1
else if FGame.Situation.Team1Results.Points<=POINTSTOWIN-20 then
team1.Minus10Count:=-2
else if FGame.Situation.Team1Results.Points<=POINTSTOWIN-10 then
team1.Minus10Count:=-1;
if team1.Minus10Count=0 then
CheckBet(team1.Minus10,team1.Minus10Count>0 ,ttTeam1,1,FGame.Situation.AddBets.Minus10,valat)
else if team1.Minus10Count>0 then begin
CheckBet(team1.Minus10,team1.Minus10Count>0 ,ttTeam1,1,FGame.Situation.AddBets.Minus10,valat);
if (FGame.Situation.AddBets.Minus10.Team=ttTeam2) and (FGame.Situation.AddBets.Minus10.BetType in [abtBet,abtRe]) then // Sack was done by other team whos bet it
Inc(team1.Minus10); // team2 lost his sack and get once more
end
else begin
CheckBet(team1.Minus10,team1.Minus10Count<0,ttTeam2,1,FGame.Situation.AddBets.Minus10,valat);
if (FGame.Situation.AddBets.Minus10.Team=ttTeam1) and (FGame.Situation.AddBets.Minus10.BetType in [abtBet,abtRe]) then // Sack was done by other team whos bet it
Dec(team1.Minus10) // team1 lost his sack and get once more
else if (FGame.Situation.AddBets.Minus10.Team=ttTeam2) and (FGame.Situation.AddBets.Minus10.BetType in [abtContra]) then // Sack was done by other team whos bet it
Dec(team1.Minus10); // team1 lost his sack and get once more
end;
if team1.Minus10Count>1 then
team1.Minus10:=team1.Minus10+team1.Minus10Count-1
else if team1.Minus10Count<-1 then
team1.Minus10:=team1.Minus10+team1.Minus10Count+1;
end;
if not FGame.ActGame.JustColors then begin
if FGame.ActGame.WinCondition<>wcT1Trick then
CheckBet(team1.PagatUlt,TrickBy(T1,FGame.Rounds.Count-1,winsByTeam),winsByTeam,1,FGame.Situation.AddBets.PagatUlt,valat);
if FGame.ActGame.WinCondition<>wcT2Trick then
CheckBet(team1.VogelII,TrickBy(T2, FGame.Rounds.Count-2,winsByTeam),winsByTeam,2,FGame.Situation.AddBets.VogelII,valat);
if FGame.ActGame.WinCondition<>wcT3Trick then
CheckBet(team1.VogelIII,TrickBy(T3, FGame.Rounds.Count-3,winsByTeam),winsByTeam,3,FGame.Situation.AddBets.VogelIII,valat);
if FGame.ActGame.WinCondition<>wcT4Trick then
CheckBet(team1.VogelIV,TrickBy(T4, FGame.Rounds.Count-4,winsByTeam),winsByTeam,4,FGame.Situation.AddBets.VogelIV,valat);
if (FGame.ActGame.TeamKind=tkPair) then
CheckBet(team1.KingUlt,FGame.Rounds.Last.CardsThrown.Exists(FGame.Situation.KingSelected),
FGame.TeamOf(FGame.Rounds.Last.Winner),1,FGame.Situation.AddBets.KingUlt,valat);
if not valat then begin
if FGame.ActGame.TeamKind=tkPair then
CheckBet(team1.CatchKing,CatchBy(FGame.Situation.KingSelected,winsByTeam),winsByTeam,1,FGame.Situation.AddBets.CatchKing,valat);
CheckBet(team1.CatchPagat,CatchBy(T1,winsByTeam),winsByTeam,1,FGame.Situation.AddBets.CatchPagat,valat);
CheckBet(team1.CatchXXI,CatchBy(T21,winsByTeam),winsByTeam,1,FGame.Situation.AddBets.CatchXXI,valat);
winsByTeam:=BelongsTo(T1);
CheckBet(team1.Trull,(BelongsTo(T21)=winsByTeam) and (BelongsTo(T22)=winsByTeam),winsByTeam,1,FGame.Situation.AddBets.Trull,valat);
end;
end;
if not valat then begin
winsByTeam:=BelongsTo(HK);
CheckBet(team1.AllKings,(BelongsTo(SK)=winsByTeam) and (BelongsTo(CK)=winsByTeam) and (BelongsTo(DK)=winsByTeam),winsByTeam,1,FGame.Situation.AddBets.AllKings,valat);
end;
end;
end;
team2.Game:=-team1.Game;
team2.ContraGame:=-team1.ContraGame;
team2.Minus10:=-team1.Minus10;
team2.KingUlt:=-team1.KingUlt;
team2.PagatUlt:=-team1.PagatUlt;
team2.VogelII:=-team1.VogelII;
team2.VogelIII:=-team1.VogelIII;
team2.VogelIV:=-team1.VogelIV;
team2.Trull:=-team1.Trull;
team2.AllKings:=-team1.AllKings;
team2.CatchKing:=-team1.CatchKing;
team2.CatchPagat:=-team1.CatchPagat;
team2.CatchXXI:=-team1.CatchXXI;
team2.Valat:=-team1.Valat;
if FGame.PlayersTeam2.Count>2 then begin
team1.Game:=team1.Game*3;
team1.ContraGame:=team1.ContraGame*3;
team1.Minus10:=team1.Minus10*3;
team1.KingUlt:=team1.KingUlt*3;
team1.PagatUlt:=team1.PagatUlt*3;
team1.VogelII:=team1.VogelII*3;
team1.VogelIII:=team1.VogelIII*3;
team1.VogelIV:=team1.VogelIV*3;
team1.Trull:=team1.Trull*3;
team1.AllKings:=team1.AllKings*3;
team1.CatchKing:=team1.CatchKing*3;
team1.CatchPagat:=team1.CatchPagat*3;
team1.CatchXXI:=team1.CatchXXI*3;
team1.Valat:=team1.Valat*3;
end;
FGame.Situation.Team1Results:=team1;
FGame.Situation.Team2Results:=team2;
end;
procedure TGameController.CalcSingleResults;
var loosers:TPlayers<TPlayerCards>;
winners:TPlayers<TPlayerCards>;
player:TPlayerCards;
totalvalue:Integer;
begin
if FGame.ActGame.GameTypeid='TRISCH' then begin // single player count
loosers:=FGame.PlayersTeam1; // team1=loosers
winners:=FGame.PlayersTeam2; // team2=winners
try
totalvalue:=0;
for player in loosers do begin
if player.Points>=POINTSTOWIN then // burgermaster pay twice
player.Results:=-2*(4-loosers.Count)
else
player.Results:=-1*(4-loosers.Count);
if FGame.Situation.Gamer=player.Name then //gamer pay twice
player.Results:=player.Results*2;
{ TODO : contra geht eig pro spieler }
if FGame.Situation.AddBets.ContraGame.BetType=abtBet then
player.Results:=player.Results*2;
totalvalue:=totalvalue+player.Results;
end;
for player in winners do
player.Results:=-Round(totalvalue/winners.Count);
finally
FreeAndNil(loosers);
FreeAndNil(winners);
end;
end;
end;
function TGameController.CountTricks(const ARounds:TGameRounds; const AGamer:String):Integer;
var i:Integer;
begin
Result:=0;
for i:=0 to ARounds.Count-1 do begin
if ARounds.Items[i].Winner=AGamer then
Inc(Result);
end;
end;
end.
|
{..............................................................................}
{ Summary Creating different PCB Objects }
{ }
{ CreateStrings procedure creates two different text objects on a new PCB }
{ PlacePCBObjects procedure creates different objects on a new PCB }
{ }
{ Copyright (c) 2007 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure CreateStrings;
Var
Sheet : IPCB_Sheet;
Board : IPCB_Board;
TextObj : IPCB_Text;
Begin
(*create a new pcb document *)
WorkSpace := GetWorkSpace;
If WorkSpace = Nil Then Exit;
Workspace.DM_CreateNewDocument('PCB');
// Checks if current document is a PCB kind if not, exit.
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
Sheet := Board.PCBSheet;
// Initialize PCB server.
PCBServer.PreProcess;
// Toggle Top Overlay and Bottom Overlay layers to true.
Board.LayerIsDisplayed[eTopOverLay] := True;
Board.LayerIsDisplayed[eBottomOverLay] := True;
//
//Create a first text object non True Type font.
TextObj := PCBServer.PCBObjectFactory(eTextObject, eNoDimension, eCreate_Default);
// notify that the pcb object is going to be modified
PCBServer.SendMessageToRobots(TextObj.I_ObjectAddress ,c_Broadcast, PCBM_BeginModify , c_NoEventData);
TextObj.XLocation := Sheet.SheetX + MilsToCoord(500);
TextObj.YLocation := Sheet.SheetY + MilsToCoord(500);
TextObj.Layer := eTopOverlay;
TextObj.Text := 'Traditional Protel Text';
TextObj.Size := MilsToCoord(90); // sets the height of the text.
Board.AddPCBObject(TextObj);
// notify that the pcb object has been modified
PCBServer.SendMessageToRobots(TextObj.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
PCBServer.SendMessageToRobots(Board .I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, TextObj.I_ObjectAddress);
//
// second TextObject with True Type Font enabled.
TextObj := PCBServer.PCBObjectFactory(eTextObject, eNoDimension, eCreate_Default);
// notify that the pcb object is going to be modified
PCBServer.SendMessageToRobots(TextObj.I_ObjectAddress, c_Broadcast, PCBM_BeginModify, c_NoEventData);
TextObj.XLocation := Sheet.SheetX + MilsToCoord(1000);
TextObj.YLocation := Sheet.SheetY + MilsToCoord(1000);
TextObj.Layer := eBottomOverlay;
TextObj.UseTTFonts := True;
TextObj.Italic := True;
TextObj.Bold := False;
TextObj.FontName := 'ARIAL';
// inverts the text object and a text boundary is created around the text
// The Inverted and InvertedTTTextBorder properties are useful for situations
// if text is to be placed on a copper region and create a cutout in the region.
// the color of the inverted border is the layer color and the text color itself
// is black.
TextObj.Inverted := True;
// The InvertedTTextBorder property determines the distance between the boundary of the
// the text object itself to the text border boundary.
TextObj.InvertedTTTextBorder := MilsToCoord(100);
TextObj.Text := 'Text with True Type Property enabled.';
TextObj.Size := MilsToCoord(200); // sets the height of the text.
Board.AddPCBObject(TextObj);
// notify that the pcb object has been modified
PCBServer.SendMessageToRobots(TextObj.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration,TextObj.I_ObjectAddress);
// Set LayerIsUsed property to true, since text objects now exist on these Overlay layers.
Board.LayerIsUsed[eTopOverLay] := True;
Board.LayerIsUsed[eBottomOverLay] := True;
PCBServer.PostProcess;
Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;
{..............................................................................}
{..............................................................................}
{..............................................................................}
{..............................................................................}
Var
Board : IPCB_Board;
WorkSpace : IWorkSpace;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBVia(Dummy : Integer);
Var
Via : IPCB_Via;
PadCache : TPadCache;
Begin
(* Create a Via object*)
Via := PCBServer.PCBObjectFactory(eViaObject, eNoDimension, eCreate_Default);
Via.X := MilsToCoord(2000);
Via.Y := MilsToCoord(2000);
Via.Size := MilsToCoord(50);
Via.HoleSize := MilsToCoord(20);
Via.LowLayer := eTopLayer;
Via.HighLayer := eBottomLayer;
(* Setup a pad cache *)
Padcache := Via.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
(* Assign the new pad cache to the via *)
Via.SetState_Cache := Padcache;
Board.AddPCBObject(Via);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBTrack(X1, Y1, X2, Y2, Layer, Width);
Var
Track : IPCB_Track;
Begin
(* Create a Track object*)
Track := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default);
Track.X1 := MilsToCoord(X1);
Track.Y1 := MilsToCoord(Y1);
Track.X2 := MilsToCoord(X2);
Track.Y2 := MilsToCoord(Y2);
Track.Layer := Layer;
Track.Width := MilsToCoord(Width);
Board.AddPCBObject(Track);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceASimplePad(Dummy : Integer);
Var
Pad : IPCB_Pad;
Padcache : TPadCache;
Begin
(* Create a Pad object*)
Pad := PCBServer.PCBObjectFactory(ePadObject, eNoDimension, eCreate_Default);
// Location of pad on the PCB document.
Pad.X := MilsToCoord(4000);
Pad.Y := MilsToCoord(4000);
// set up attributes of pad.
Pad.HoleSize := MilsToCoord(38);
Pad.Name := 'A new simple Pad';
Pad.Mode := ePadMode_Simple;
// For a simple pad, only need TopShape, TopXSize, TopYSize
Pad.TopShape := eRounded;
Pad.TopXSize := MilsToCoord(100);
Pad.TopYSize := MilsToCoord(100);
(* Setup a pad cache *)
Padcache := Pad.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
(* Assign the new pad cache to the pad*)
Pad.SetState_Cache := Padcache;
Board.AddPCBObject(Pad);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceATopMidBotStackPad(Dummy : Integer);
Var
Pad : IPCB_Pad;
Padcache : TPadCache;
Begin
(* Create a Pad object*)
Pad := PCBServer.PCBObjectFactory(ePadObject, eNoDimension, eCreate_Default);
// Location of pad on the PCB document.
Pad.X := MilsToCoord(3000);
Pad.Y := MilsToCoord(3000);
// set up attributes of pad.
Pad.HoleSize := MilsToCoord(38);
Pad.Name := 'A new TopMidBot Pad';
Pad.Mode := ePadMode_LocalStack;
//
Pad.TopShape := eOctagonal;
Pad.TopXSize := MilsToCoord(75);
Pad.TopYSize := MilsToCoord(75);
Pad.MidShape := eRectangular;
Pad.MidXSize := MilsToCoord(50);
Pad.MidYSize := MilsToCoord(50);
Pad.BotShape := eOctagonal;
Pad.BotXSize := MilsToCoord(100);
Pad.BotYSize := MilsToCoord(100);
(* Setup a pad cache *)
Padcache := Pad.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
(* Assign the new pad cache to the pad*)
Pad.SetState_Cache := Padcache;
Board.AddPCBObject(Pad);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAFullStackPad(0);
Var
Pad : IPCB_Pad;
Padcache : TPadCache;
Begin
(* Create a Pad object*)
Pad := PCBServer.PCBObjectFactory(ePadObject, eNoDimension, eCreate_Default);
// Location of pad on the PCB document.
Pad.X := MilsToCoord(3500);
Pad.Y := MilsToCoord(3500);
// set up attributes of pad.
Pad.HoleSize := MilsToCoord(10);
Pad.Name := 'A new fullstack Pad';
Pad.Mode := ePadMode_ExternalStack;
// Set up full stack pad
Pad.XStackSizeOnLayer(eTopLayer) := MilsToCoord(50);
Pad.YStackSizeOnLayer(eTopLayer) := MilsToCoord(50);
Pad.StackShapeOnLayer(eTopLayer) := eRounded;
Pad.XStackSizeOnLayer(eMidLayer1) := MilsToCoord(50);
Pad.YStackSizeOnLayer(eMidLayer1) := MilsToCoord(50);
Pad.StackShapeOnLayer(eMidLayer1) := eRounded;
Pad.XStackSizeOnLayer(eMidLayer2) := MilsToCoord(50);
Pad.YStackSizeOnLayer(eMidLayer2) := MilsToCoord(50);
Pad.StackShapeOnLayer(eMidLayer2) := eRounded;
Pad.XStackSizeOnLayer(eBottomLayer) := MilsToCoord(50);
Pad.YStackSizeOnLayer(eBottomLayer) := MilsToCoord(50);
Pad.StackShapeOnLayer(eBottomLayer) := eOctagonal;
(* Setup a pad cache *)
Padcache := Pad.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
(* Assign the new pad cache to the pad*)
Pad.SetState_Cache := Padcache;
Board.AddPCBObject(Pad);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBFill(Dummy : Integer);
Var
Fill : IPCB_Fill;
Begin
(* Create a Fill object*)
Fill := PCBServer.PCBObjectFactory(eFillObject, eNoDimension,eCreate_Default);
Fill.X1Location := MilsToCoord(2000);
Fill.Y1Location := MilsToCoord(2000);
Fill.X2Location := MilsToCoord(2500);
Fill.Y2Location := MilsToCoord(2500);
Fill.Layer := eBottomLayer;
Fill.Rotation := 45;
Board.AddPCBObject(Fill);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBArc(Dummy : Integer);
Var
Arc : IPCB_Arc;
Begin
Arc := PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default);
Arc.XCenter := MilsToCoord(Board.XOrigin + 1800);
Arc.YCenter := MilsToCoord(Board.YOrigin + 1800);
Arc.Radius := MilsToCoord(200);
Arc.LineWidth := MilsToCoord(50);
Arc.StartAngle := 0;
Arc.EndAngle := 270;
Arc.Layer := eBottomLayer;
Board.AddPCBObject(Arc);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBComponent(Dummy : Integer);
Begin
If IntegratedLibraryManager = Nil Then Exit;
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBText(Dummy : Integer);
Var
TextObj : IPCB_Text;
Begin
(* create a text object on a top overlay *)
Board.LayerIsDisplayed[eTopOverLay] := True;
TextObj := PCBServer.PCBObjectFactory(eTextObject, eNoDimension, eCreate_Default);
TextObj.XLocation := MilsToCoord(Board.XOrigin + 4000);
TextObj.YLocation := MilsToCoord(Board.YOrigin + 2000);
TextObj.Layer := eTopOverlay;
TextObj.Text := 'Text Object';
TextObj.Size := MilsToCoord(90); // sets the height of the text.
Board.AddPCBObject(TextObj);
End;
{..............................................................................}
{..............................................................................}
Procedure CreateANewNetClass(Dummy : Integer = 0);
Var
Board : IPCB_Board;
NetClass : IPCB_ObjectClass;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
PCBServer.PreProcess;
NetClass := PCBServer.PCBClassFactoryByClassMember(eClassMemberKind_Net);
NetClass.SuperClass := False;
NetClass.Name := 'NetGndClass';
NetClass.AddMemberByName('GND');
Board.AddPCBObject(NetClass);
PCBServer.PostProcess;
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBRegion(Dummy : Integer = 0);
Const
N = 10;
Var
I : Integer;
Region : IPCB_Region;
BaseAngle : Double;
Contour : IPCB_Contour;
Begin
Region := PCBServer.PCBObjectFactory(eRegionObject, eNoDimension,eCreate_Default);
Contour := Region.MainContour.Replicate;
Region.Layer := eBottomLayer;
BaseAngle := 2 * PI / N;
Contour.Count := N;
For I := 1 To Contour.Count Do
Begin
Contour.X[I] := MilsToCoord(200 * Sin(I * BaseAngle));
Contour.Y[I] := MilsToCoord(200 * Cos(I * BaseAngle));
End;
Contour.Translate(MilsToCoord(4500), MilsToCoord(4500));
Region.SetOutlineContour(Contour);
// Add hole to region, hole must be totally contained within MainContour
If Region.HoleCount = 0 Then
Region.GeometricPolygon.AddContourIsHole(Nil, True);
BaseAngle := 2 * PI / (N Div 2);
Region.Holes[0].Count := (N Div 2);
For I := 1 To Region.Holes[0].Count Do
Begin
Region.Holes[0].X[I] := MilsToCoord(75 * Sin(I * BaseAngle));
Region.Holes[0].Y[I] := MilsToCoord(75 * Cos(I * BaseAngle));
End;
Region.Holes[0].Translate(MilsToCoord(4500), MilsToCoord(4500));
Board.AddPCBObject(Region);
End;
{..............................................................................}
{..............................................................................}
Procedure PlacePCBObjects;
Begin
(*create a new pcb document *)
WorkSpace := GetWorkSpace;
If WorkSpace = Nil Then Exit;
Workspace.DM_CreateNewDocument('PCB');
If PCBServer = Nil Then Exit;
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil then exit;
(* Place new PCB objects*)
PlaceAPCBVia(0);
PlaceAPCBTrack(1000,1000,1500,1500,eTopLayer,50);
PlaceAPCBTrack(1500,1500,1500,1000,eTopLayer,50);
PlaceAPCBTrack(1500,1000,1000,1000,eTopLayer,50);
PlaceASimplePad(0);
PlaceATopMidBotStackPad(0);
PlaceAFullStackPad(0);
PlaceAPCBFill(0);
PlaceAPCBArc(0);
PlaceAPCBComponent(0);
PlaceAPCBText(0);
CreateANewNetClass;
PlaceAPCBRegion;
(* Refresh PCB workspace *)
ResetParameters;
AddStringParameter('Action', 'All');
RunProcess('PCB:Zoom');
End;
{..............................................................................}
{..............................................................................}
|
unit Transfer;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, IdFTP, IdComponent, IdURI, Contnrs;
type
TOnTransferStart = procedure (Sender: TObject; const AWorkCountMax: Integer)
of object;
TOnTransfer = procedure (Sender: TObject; const AWorkCount: Integer) of
object;
TOnTransferEnd = procedure (Sender: TObject) of object;
TProxySeting = record
ProxyServer: string;
ProxyPort: Integer;
ProxyUser: string;
ProxyPass: string;
end;
TTransfer = class(TPersistent)
private
FCurrentDir: string;
FFileName: string;
FHost: string;
FOnTransfer: TOnTransfer;
FOnTransferEnd: TOnTransferEnd;
FOnTransferStart: TOnTransferStart;
FPassword: string;
FPort: Integer;
FURI: TIdURI;
FURL: string;
FUser: string;
procedure SetHost(const Value: string); virtual;
protected
function GetOnStatus: TIdStatusEvent; virtual; abstract;
procedure SetOnStatus(Value: TIdStatusEvent); virtual; abstract;
procedure SetURI(Value: TIdURI); virtual;
public
procedure Abort; virtual; abstract;
procedure Connect; virtual; abstract;
procedure Get(FileName: String); overload; virtual; abstract;
procedure Get(Stream: TStream); overload; virtual; abstract;
procedure SetProxy(ProxyObj: TPersistent); overload; virtual; abstract;
procedure SetProxy(ProxyInfo: TProxySeting); overload; virtual; abstract;
procedure Work(Sender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
virtual;
procedure WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
procedure WorkStart(Sender: TObject; AWorkMode: TWorkMode; AWorkCountMax:
int64); virtual;
procedure ClearProxySeting; virtual; abstract;
property CurrentDir: string read FCurrentDir write FCurrentDir;
property FileName: string read FFileName write FFileName;
property Host: string read FHost write SetHost;
property Password: string read FPassword write FPassword;
property Port: Integer read FPort write FPort;
property URI: TIdURI read FURI write SetURI;
property User: string read FUser write FUser;
property URL: string read FURL write FURL;
published
property OnStatus: TIdStatusEvent read GetOnStatus write SetOnStatus;
property OnTransfer: TOnTransfer read FOnTransfer write FOnTransfer;
property OnTransferEnd: TOnTransferEnd read FOnTransferEnd write
FOnTransferEnd;
property OnTransferStart: TOnTransferStart read FOnTransferStart write
FOnTransferStart;
end;
TFTPTransfer = class(TTransfer)
private
FIdfTP: TIdfTP;
procedure SetHost(const Value: string); override;
protected
function GetOnStatus: TIdStatusEvent; override;
procedure SetOnStatus(Value: TIdStatusEvent); override;
procedure SetURI(Value: TIdURI); override;
public
constructor Create;
destructor Destroy; override;
procedure Abort; override;
procedure Connect; override;
procedure Get(FileName: String); overload; override;
procedure Get(Stream: TStream); overload; override;
procedure SetProxy(ProxyObj: TPersistent); overload; override;
procedure SetProxy(ProxyInfo: TProxySeting); overload; override;
procedure ClearProxySeting; override;
end;
TTransferFactory = class(TObject)
private
FIdURI: TIdURI;
FObjectList: TObjectList;
public
constructor Create;
destructor Destroy; override;
function CreateTransfer(URL: String): TTransfer; overload;
Function CreateTransfer(URL: String; ProxySeting: TProxySeting): TTransfer; overload;
end;
ExceptionNoSuport = class(Exception)
end;
implementation
uses
System.IOUtils, uHttpTransfer;
{
********************************** TTransfer ***********************************
}
procedure TTransfer.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TTransfer.SetURI(Value: TIdURI);
begin
// TODO -cMM: TTransfer.SetURI default body inserted
//if Assigned(FURI) then FURI.Free;
FURI := Value;
end;
procedure TTransfer.Work(Sender: TObject; AWorkMode: TWorkMode; AWorkCount:
Int64);
begin
if AWorkCount <> 0 then
begin
if Assigned(FOnTransfer) then
FOnTransfer(Sender, AWorkCount);
Application.ProcessMessages;
end
end;
procedure TTransfer.WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
if Assigned(FOnTransferEnd) then
FOnTransferEnd(Sender);
end;
procedure TTransfer.WorkStart(Sender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: int64);
begin
if AWorkCountMax <> 0 then
begin
if Assigned(FOnTransferStart) then
FOnTransferStart(Sender, AWorkCountMax);
end;
end;
{
********************************* TFTPTransfer *********************************
}
constructor TFTPTransfer.Create;
begin
inherited Create;
FIdFTP := TIdFTP.Create(nil);
// FIdFtp.OnWorkBegin := Self.WorkStart;
// FIdFtp.OnWork := Self.Work;
// FIdFtp.OnWorkEnd := Self.WorkEnd;
// FIdFtp.re := 8192;
//FIdFtp.TransferTimeout := 50000;
//FIdFtp.SendBufferSize := 4096;
FIdFtp.Passive := true;
self.Port := 21;
end;
destructor TFTPTransfer.Destroy;
begin
if Assigned(FIdFtp) then
begin
FIdFtp.Disconnect;
FreeAndNil(FIdFTP);
end;
inherited Destroy;
end;
procedure TFTPTransfer.Abort;
begin
FIdFtp.Abort;
end;
procedure TFTPTransfer.Connect;
begin
try
FIdFtp.Host := self.Host;
FIdFtp.Username := self.User;
FidFtp.Password := self.Password;
FIdFtp.Connect();
if (FidFtp.Username <> 'Anonymous') then
FIdFtp.Login;
except
raise;
end;
end;
procedure TFTPTransfer.Get(FileName: String);
var
temp: Int64;
begin
try
if (not FIdFTP.Connected) then
Connect();
FIdFtp.ChangeDir(self.CurrentDir);
if not DirectoryExists(ExtractFilePath(FileName)) then
TDirectory.CreateDirectory(ExtractFilePath(FileName));
temp := FIdFtp.Size(self.FileName);
if temp > 10240 then
begin
FIdFtp.OnWorkBegin := Self.WorkStart;
FIdFtp.OnWork := Self.Work;
FIdFtp.OnWorkEnd := Self.WorkEnd;
if Assigned(FIdfTP.OnWorkBegin) then
FIdfTP.OnWorkBegin(FIdfTP, wmRead, temp);
end
else
begin
FIdFtp.OnWorkBegin := nil;
FIdFtp.OnWork := nil;
FIdFtp.OnWorkEnd := nil;
end;
FIdFtp.Get(self.FileName, FileName, true);
except
raise;
end;
end;
procedure TFTPTransfer.Get(Stream: TStream);
begin
try
if (not FIdFTP.Connected) then
Connect();
FIdFtp.ChangeDir(self.CurrentDir);
FIdFtp.Get(self.FileName, Stream, true);
FIdFtp.Disconnect;
except
raise;
end;
end;
function TFTPTransfer.GetOnStatus: TIdStatusEvent;
begin
Result := FIdFtp.OnStatus
end;
procedure TFTPTransfer.SetHost(const Value: string);
begin
if (Host <> '') then
if (Host <> Value) then
FIdFtp.Disconnect;
inherited SetHost(Value);
end;
procedure TFTPTransfer.SetOnStatus(Value: TIdStatusEvent);
begin
FIdFtp.OnStatus := Value;
end;
procedure TFTPTransfer.SetProxy(ProxyObj: TPersistent);
begin
FIdFtp.ProxySettings.Assign(ProxyObj);
end;
procedure TFTPTransfer.SetProxy(ProxyInfo: TProxySeting);
begin
FIdFtp.ProxySettings.ProxyType := fpcmUserSite;
FIdFtp.ProxySettings.Host := ProxyInfo.ProxyServer;
FIdFtp.ProxySettings.UserName := ProxyInfo.ProxyUser;
FIdFtp.ProxySettings.Port := ProxyInfo.ProxyPort;
FIdFtp.ProxySettings.Password := ProxyInfo.ProxyPass;
end;
procedure TFTPTransfer.ClearProxySeting;
begin
// TODO -cMM: TFTPTransfer.ClearProxySeting default body inserted
inherited;
FIdFtp.ProxySettings.ProxyType := fpcmNone;
end;
procedure TFTPTransfer.SetURI(Value: TIdURI);
begin
// TODO -cMM: TFTPTransfer.SetURI default body inserted
//if Assigned(FURI) then FURI.Free;
inherited;
Self.URL := Value.URI;
self.Host := FURI.Host;
if trim(FURI.Username) = '' then
self.User := 'Anonymous'
else
self.User := FURI.Username;
self.Password := FURI.Password;
if trim(FURI.Path) = '' then
Self.CurrentDir := '/'
else
self.CurrentDir := FURI.Path;
self.FileName := FURI.Document;
if (FURI.Port = '') then
self.Port := 21
else
self.Port := StrToInt(FURI.Port);
end;
{
******************************* TTransferFactory *******************************
}
constructor TTransferFactory.Create;
begin
inherited Create;
FObjectList := TObjectList.Create;
FIdURI := TIdURI.Create;
end;
destructor TTransferFactory.Destroy;
begin
FreeAndNil(FObjectList);
FreeAndNil(FIdURI);
inherited Destroy;
end;
function TTransferFactory.CreateTransfer(URL: String): TTransfer;
var
Index: Integer;
begin
//测试代理的代码
//ProxyObj := TIdFtpProxySettings.Create;
//ProxyObj.Host := '192.168.168.163';
//ProxyObj.ProxyType := fpcmUserSite;
//ProxyObj.Port := 2121;
FIdURI.URI := URL;
if AnsiUpperCase(FIdURI.Protocol) = 'FTP' then
begin
Index := FObjectList.FindInstanceOf(TFTPTransfer);
if Index <> -1 then
Result := FObjectList.Items[Index] as TTransfer
else
begin
begin
Result := TFTPTransfer.Create;
FObjectList.Add(Result);
end;
end;
end
else if AnsiUpperCase(FIdURI.Protocol) = 'HTTP' then
begin
Index := FObjectList.FindInstanceOf(THTTPTransfer);
if Index <> -1 then
Result := FObjectList.Items[Index] as TTransfer
else
begin
begin
Result := THTTPTransfer.Create;
FObjectList.Add(Result);
end;
end;
end
else
raise ExceptionNoSuport.Create('不支持的网络协议!');
Result.URI := FIdURI;
end;
function TTransferFactory.CreateTransfer(URL: String;
ProxySeting: TProxySeting): TTransfer;
begin
Result := CreateTransfer(URL);
Result.SetProxy(ProxySeting);
end;
end.
|
unit uFilePersistence;
interface
uses Classes, DB, uStringFunctions, SysUtils, Variants, Math, DBClient, IniFiles, Windows;
const
FMT_DATE = 'YYYYMMDDHHNNSS';
TAM_DATE = Length(FMT_DATE);
TAM_INT = 11;
TAM_REAL = 21;
TAM_BOOLEAN = 1;
TAM_DEC = 4;
CHR_SPACE = ' ';
CHR_ZERO = '0';
STR_CRLF = #13#10;
STR_MEMO_SEP = 'G';
SUB_HIDDEN_NAME = '\security\logs\transactions.log';
type
TSaleLineType = (sltUnknow, sltOpenCash, sltOpenSale, sltAddItem,
sltAddPayment, sltCloseSale, sltCloseCash,
sltAddCustomer, sltWC, sltPC, sltCancelSale,
sltRemovedItem, sltReducaoZ, sltAbortSale, sltCancelItem,
sltAddSerialNumber, sltOBS, sltCupomVinculado, sltTotParcial);
TLastSaleItem = class
FCanceled : Boolean;
FItemLine : String;
FSerialList: TList;
private
procedure ClearSerialList;
public
constructor Create;
destructor Destroy;override;
end;
TLastSaleItemSerial = class
FItemSerialLine : String;
end;
TLastSale = class
FOpenSaleLine : String;
FCloseSaleLine : String;
FCustomerLine : String;
FSaleCode : String;
FOBS : String;
FIDCashRegister : Integer;
FIDUser : Integer;
FCanceled : Boolean;
FItemList : TStringList;
FPaymentList : TStringList;
procedure AddItem(ALine:String);
procedure AddPayment(ALine:String);
procedure AddItemSerial(ALine:String);
procedure ClearLastSale;
procedure CancelItem(APosition : Integer);
constructor Create;
destructor Destroy;override;
end;
TRegTribReducaoZ = record
Codigo: String;
ValorAcumulado: Currency;
end;
TRegReducaoZ = record
AMovDate : TDateTime;
ANumeroSerie : String;
ANumeroLoja : Integer;
ANumeroECF : Integer;
ANumReducaoZ : Integer;
ACOOInicial : Integer;
ACOOFinal : Integer;
ANumCancelamentos : Integer;
AValCancelamentos : Currency;
AValDescontos : Currency;
AGTInicial : Currency;
AGTFinal : Currency;
ASubstituicaoTrib : Currency;
AIsencao : Currency;
ANaoTributavel : Currency;
AAliquota : array of Double;
ABaseCalculo : array of Currency;
AValImposto : array of Currency;
////////////////////////////////////////////////////////////////////////////
// NOVOS CAMPOS PARA O PAF-ECF
ATipoECF : String;
AMarcaECF : String;
AModeloECF : String;
AVersaoSBECF : String;
ADataInstalacaoSBECF : TDateTime;
AMFAdicional : String;
AContadorReducaoZ : Integer;
AContadorOrdemOperacao : Integer;
AContadorReinicioOperacao : Integer;
ANumeroUsuarioECF : Integer;
AIncideISSQN : Boolean;
ADataEmissao : TDateTime;
ATribReducaoZList : array of TRegTribReducaoZ;
end;
TRegOpenCash = record
A100, A50, A20, A10, A05, A02, A01,
A0100, A050, A025, A010, A005, A001, AIDCashReg, AIDUser: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther, ATotalDebit: Currency; ADate: TDateTime;
ACOO, AGNF : Integer;
AIDCashRegMov: Integer;
end;
TRegOpenSale = record
AIDCashreg, AIDPreSale, ADeliverType, AIDCustomer, AIDMedia, AIDOtherComm,
AIDStore, AIDTourGroup: Integer;
AIsLayaway, ATaxExempt, APuppyTracker: Boolean;
AFName, ALName, AZip, AInvObs, ASaleCode, ACOO, ASerialECF: String;
APreSaleDate: TDateTime; APreSaleType: Integer; ACCF : String;
end;
TRegAddCustomer = record
AIDTipoPessoa, AIDTipoPessoaRoot: Integer;
AFirstName, ALastName, AEndereco, ACidade, ABairro, AZip, ADocumento,
ATelefone, AEstado, ATelDDD, ACelDDD, ACelelular, AEmail, AWebSite,
ACPF, AIdentidate, AOrgEmiss, ACustCard, ACMotorista,
ANomeJuridico, AInscEstadual, AInscMunicipal, AContato, AOBS: String;
AJuridico:Boolean; AExpDate, ABirthDate : TDateTime;
end;
TRegAddItem = record
AIDCustomer, AIDHold, AIDModel, AIDStore, AIDDepartment : Integer;
AQty: Double; ADiscount, ASale, ACost: Currency; AIDUser,
AIDCommis: Integer; AMovDate, ADate: TDateTime; AResetDisc,
AManager: Boolean; AIDDescriptionPrice, AIDVendorPrice: Integer;
ASuggPrice: Currency; ADocumentNumber: String; AIDDocumentType: Integer;
ATotParcial : String;
end;
TRegAddPayment = record
AIDPreSale, AIDStore, AIDUser,
AIDCustomer, AIDMeioPag, AIDCashRegMov, APayType: Integer; APreSaleDate,
AExpireDate: TDateTime; ANumParcela, AAutotize: String;
ATotalInvoice: Currency; ACheckNumber, ACustomerDocument, ACustomerName,
ACustomerPhone: String; AIDBankCheck: Integer; AOBS: String;
APaymentPlace: Integer; AIsPreDatado: Boolean;
end;
TRegAddPC = record
AIDCashRegMov, AIDUser: Integer;
ACash : Currency;
ADate : TDateTime;
AOBS: String;
ACOO, AGNF : Integer;
end;
TRegAddWC = record
AIDCashRegMov, AIDUser, A100,
A50, A20, A10, A05, A02, A01, A0100, A050, A025, A010, A005,
A001: Integer; ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther, ATotalDebit: Currency; AEnvolop: String; ADate: TDateTime;
AOBS: String; AIDReason : Integer; ACOO, AGNF : Integer;
end;
TRegCloseSale = record
AIDPreSale, AIDTourGroup, AIDOtherCommis,
AIDCashRegMov, AIDStore: Integer; ADate, APayDate: TDateTime;
ACashReceived, ASaleDiscount: Currency;
end;
TRegCloseCash = record
AIDCashRegMov, AIDUser, A100, A50,
A20, A10, A05, A02, A01, A0100, A050, A025, A010, A005, A001: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther, ATotalDebit: Currency; AEnvolop: String; ADate: TDateTime;
end;
TRegCancelSale = record
ACOO: String;
AIDUser: Integer;
// Não serão preenchido pelo getCancelSale
// Adicionados para uso exclusivo na
// classd TTXTCashInfo
ACash: Currency;
ACard: Currency;
APreCard: Currency;
ACheck: Currency;
AOther: Currency;
end;
TRegRemovedItem = record
AIDCashReg, AIDModel, AIDStore, AIDDepartment: Integer;
AQty: Double;
ADiscount, ASale, ACost: Currency;
AIDUser, AIDUserAuto, AIDCommis: Integer;
AMovDate: TDateTime;
ASaleCode, ATotParcial : String;
APosicaoItem, AIDNotasCanceladas,
AIDPreSale: Integer; AAcrescimo : Currency;
end;
TRegSerialNumber = record
APosition: Integer;
ASerialNumber: String;
AIdentificationNumber: String;
end;
TRegOBS = record
AOBS: String;
end;
TRegCupomVinculado = record
ACOOVinc,
AGNFVinc,
ACDC: Integer;
ADataHora: TDateTime
end;
TFieldValueKind = (fvkInt, fvkFloat, fvkDate, fvkBoolean, fvkString, fvkDummy, fvkMemo);
TPDVTextFile = class
private
FFileName: String;
public
protected
function HasMoreLines: Boolean;virtual;abstract;
function NextLine: String;virtual;abstract;
property FileName: String read FFileName write FFileName;
end;
TFieldToStringParser = class;
TDBExportFile = class(TPDVTextFile)
private
FSource: TDataSet;
FSaveConfig: Boolean;
FConfigFileName: String;
FFieldToStringParser: TFieldToStringParser;
function PrepareLine: String;
function PrepareField(AField: TField): String;
procedure WriteConfig;
protected
function HasMoreLines: Boolean;override;
function NextLine: String;override;
public
property SaveConfig: Boolean read FSaveConfig write FSaveConfig default True;
property ConfigFileName: String read FConfigFileName write FConfigFileName;
property Source: TDataSet read FSource write FSource;
function SaveAll: Boolean;
property FileName;
constructor Create;
destructor Destroy;override;
end;
TStringToFieldParser = class
private
FValue: String;
public
property Value: String read FValue write FValue;
function ParseInt: Variant;
function ParseFloat: Variant;
function ParseLongFloat: Variant;
function ParseDate: Variant;
function ParseBoolean: Variant;
function ParseMemo: Variant;
procedure CutBoolean(var AValue: Boolean; var ALine: String);
procedure CutDate(var AValue: TDateTime; var ALine: String);
procedure CutInteger(var AValue: Integer; var ALine: String);
procedure CutReal(var AValue: Currency; var ALine: String);
procedure CutLongReal(var AValue: Currency; var ALine: String);
procedure CutString(var AValue, ALine: String; const ASize: Integer);
procedure CutMemo(var AValue: String; var ALine: String);
procedure CutDouble(var AValue: Double; var ALine: String);
end;
TFieldToStringParser = class
private
function GetSignal(Value: Variant): Char;
public
function PrepareFieldBoolean(AValue: Variant;
AIsNull: Boolean): String;
function PrepareFieldDate(AValue: Variant; AIsNull: Boolean): String;
function PrepareFieldInt(AValue: Variant; AIsNull: Boolean): String;
function PrepareFieldReal(AValue: Variant; AIsNull: Boolean): String;
function PrepareFieldString(AValue: String; AIsNull: Boolean;
ASize: Integer): String;
function PrepareFieldMemo(AValue: Variant; AIsNull: Boolean): String;
end;
TFieldMapping = class
private
FFieldName: String;
FFieldValueKind: TFieldValueKind;
FSize: Integer;
FFound: Boolean;
function GetSize: Integer;
procedure SetSize(const Value: Integer);
procedure SetFieldValueKind(const Value: TFieldValueKind);
public
property FieldName: String read FFieldName write FFieldName;
property FieldValueKind: TFieldValueKind read FFieldValueKind write SetFieldValueKind;
property Size: Integer read GetSize write SetSize;
property Found: Boolean read FFound write FFound;
end;
TCDSImportFile = class(TPDVTextFile)
private
FClientDataSet: TClientDataSet;
FMappingList: TStringList;
FData: TStringList;
FCurrentLine: Integer;
FStringToFieldParser: TStringToFieldParser;
FIndexField: String;
function GetFieldMaps(Index: Integer): TFieldMapping;
procedure SetFieldMaps(Index: Integer; const Value: TFieldMapping);
function SaveLine(ALine: String): Boolean;
procedure TestMappings;
protected
function HasMoreLines: Boolean;override;
function NextLine: String;override;
public
property ClientDataSet: TClientDataSet read FClientDataSet write FClientDataSet;
property FieldMaps[Index: Integer]: TFieldMapping read GetFieldMaps write SetFieldMaps;
property FileName;
property IndexField: String read FIndexField write FIndexField;
constructor Create;
destructor Destroy;override;
function AddMapping(AFieldName: String; AFieldValueKind: TFieldValueKind; ASize: Integer = 0): Integer;
function MappingByName(AName: String): TFieldMapping;
function Count: Integer;
procedure Clear;
procedure Reset;
function SaveAll: Boolean;
function ReadTableConfig(AININame, ATableName: String): Boolean;
end;
TConfigWritter = class
private
FConfigFilename: String;
FDataSet: TDataSet;
FTablename: String;
function SaveFieldConfig(AIni: TIniFile; AField: TField): Boolean;
public
property ConfigFilename: String read FConfigFilename write FConfigFileName;
property DataSet: TDataSet read FDataSet write FDataSet;
property TableName: String read FTablename write FTableName;
function SaveConfig: Boolean;
end;
TSaleWritter = class
private
FFieldToStringParser: TFieldToStringParser;
FSaleLines: TStringList;
FIDCashReg: Integer;
FFileOpened: Boolean;
FLocalWorkingDir: String;
FRemoteWorkingDir: String;
FFileName: String;
FLogicalFile: TextFile;
FHiddenFile: TextFile;
function CreateNewFile: Boolean;
function WriteSaleToFile: Boolean;
procedure DeleteHiddenFileLog(iDays, iFileSizeMB : Integer);
procedure OpenHiddenFile;
function GetLinhaReducaoZ(AReducaoZ: TRegReducaoZ): String;
function GetLinhaTotParcial(AReducaoZ: TRegReducaoZ): String;
public
property IDCashReg: Integer read FIDCashReg write FIDCashReg;
property FileName: String read FFileName write FFileName;
property FileOpened: Boolean read FFileOpened write FFileOpened;
property LocalWorkingDir: String read FLocalWorkingDir write FLocalWorkingDir;
property RemoteWorkingDir: String read FRemoteWorkingDir write FRemoteWorkingDir;
constructor Create(iDays, iFileSizeMB : Integer);
destructor Destroy;override;
procedure CloseSaleFile;
function AddCustomer(AIDTipoPessoa, AIDTipoPessoaRoot: Integer;
AFirstName, ALastName, AEndereco, ACidade, ABairro, AZip, ADocumento,
ATelefone, {novos} AEstado, ATelDDD, ACelDDD, ACelelular, AEmail, AWebSite,
ACPF, AIdentidate, AOrgEmiss, ACustCard, ACMotorista,
ANomeJuridico, AInscEstadual, AInscMunicipal, AContato, AOBS: String;
AJuridico:Boolean; AExpDate, ABirthDate : TDateTime): String;
function AddHoldItem(AIDCustomer, AIDHold, AIDModel, AIDStore, AIDDepartment : Integer; AQty: Double;
ADiscount, ASale, ACost: Currency;
AIDUser, AIDCommis: Integer;
AMovDate, ADate: TDateTime;
AResetDisc, AManager: Boolean;
AIDDescriptionPrice, AIDVendorPrice: Integer;
ASuggPrice: Currency; ADocumentNumber: String;
AIDDocumentNumber: Integer; ATotParcial : String): String;
function AddRemovedItem(AIDCashReg, AIDModel, AIDStore, AIDDepartment : Integer; AQty: Double;
ADiscount, ASale, ACost: Currency;
AIDUser, AIDUserAuto, AIDCommis: Integer;
AMovDate: TDateTime; ASaleCode : String): String;
function AddPayment(AIDPreSale, AIDStore, AIDUser, AIDCustomer,
AIDMeioPag, AIDCashRegMov: Integer;
APreSaleDate, AExpireDate: TDateTime;
ANumParcela, AAutotize: String;
ATotalInvoice: Currency;
ACheckNumber, ACustomerDocument,
ACustomerName, ACustomerPhone: String;
AIDBankCheck: Integer;
AOBS: String;
APaymentPlace: Integer;
AIsPreDatado: Boolean; APayType: Integer): String;
function AddPettyCash(AIDCashRegMov, AIDUser: Integer; ACash: Currency;
ADate: TDateTime; AOBS: String; ACOO, AGNF : Integer): Boolean;
function CancelFiscalSale(ACOO: String; IDUser: Integer): Boolean;
function AbortSale(ACOO: String): String;
function SaveObs(AOBS: String): String;
function CancelItem(Position: Integer): String;
function CreateHold(ADeliverType: Integer; AIsLayaway: Boolean;
AIDStore: Integer; AFName, ALName, AZip: String;
AIDTourGroup: Integer; APreSaleDate: TDateTime; AIDCustomer,
AIDMedia, AIDOtherComm: Integer; AInvObs,
ASaleCode, ACOO: String; ATaxExempt: Boolean; AIDPreSale: Integer;
APuppyTracker: Boolean; AECFSerial, ACCF : String): String;
function GetSaleCloseLine(AIDPreSale, AIDTourGroup, AIDOtherCommis,
AIDCashRegMov, AIDStore: Integer;
ADate, APayDate: TDateTime;
ACashReceived, ASaleDiscount: Currency): String;
function PreSalePay(AIDPreSale, AIDTourGroup, AIDOtherCommis,
AIDCashRegMov, AIDStore: Integer;
ADate, APayDate: TDateTime;
ACashReceived, ASaleDiscount: Currency): String;
function OpenCashRegister(A100, A50, A20, A10, A05, A02, A01,
A0100, A050, A025, A010, A005, A001: Integer;
AIDCashReg, AIDUser: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard,
ATotalCheck, ATotalOther: Currency;
ADate: TDateTime; ATotalDebit: Currency;
ACOO, AGNF : Integer; AReducaoZ: TRegReducaoZ): Boolean;
function OpenFile(AFileName: String): Boolean;
function CloseCashRegister(AIDCashRegMov, AIDUser: Integer;
A100, A50, A20, A10, A05, A02, A01,
A0100, A050, A025, A010, A005, A001: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard,
ATotalCheck, ATotalOther: Currency;
AEnvolop: String; ADate: TDateTime; ATotalDebit: Currency;
AReducaoZ: TRegReducaoZ): Boolean;
function WithdrawCashRegister(AIDCashRegMov, AIDUser: Integer;
A100, A50, A20, A10, A05, A02, A01,
A0100, A050, A025, A010, A005, A001: Integer;
ATotalCash, ATotalCard, ATotalPreCard,
ATotalCheck, ATotalOther: Currency;
AEnvolop: String;
ADate: TDateTime;
AOBS: String; ATotalDebit: Currency;
AIDReason : Integer;
ACOO, AGNF: Integer): Boolean;
function AddSerialNumber(APosition: Integer; ASerialNumber, AIdentificationNumber: String): Boolean;
function AddVinculadoInfo(ACOOVinc, AGNFVinc, ACDC : Integer; ADataHora: TDateTime) : Boolean;
end;
TSaleLineParser = class
private
FStringToFieldParser: TStringToFieldParser;
public
constructor Create;
destructor Destroy;override;
procedure GetAddCustomer(const ALine: String;
var RAC: TRegAddCustomer);
procedure GetAddItem(const ALine: String; var RAI: TRegAddItem);
procedure GetAddPayment(const ALine: String; var RAP: TRegAddPayment);
procedure GetAddPC(const ALine: String; var RAPC: TRegAddPC);
procedure GetAddWC(const ALine: String; var RAWC: TRegAddWC);
procedure GetCloseCash(ALine: String; var RCC: TRegCloseCash);
procedure GetCloseSale(const ALine: String; var RCS: TRegCloseSale);
procedure GetOpenCash(const ALine: String; var ROC: TRegOpenCash);
procedure GetOpenSale(const ALine: String; var ROS: TRegOpenSale);
procedure GetCancelSale(const ALine: String; var RCS: TRegCancelSale);
procedure GetRemovedItem(const ALine: String; var RRI: TRegRemovedItem);
procedure GetReducaoZ(const ALine: String; var RRZ: TRegReducaoZ);
procedure GetTotParcial(const ALine: String; var RRZ: TRegReducaoZ);
procedure GetItemCanceled(const ALine: String; var Position: Integer);
procedure GetAddSerialNumber(const ALine: String; var RSN: TRegSerialNumber);
procedure GetOBS(const ALine: String; var ROBS: TRegOBS);
procedure GetCupomVinculado(const ALine: String; var RCupomVinculado : TRegCupomVinculado);
function LineType(ALine: String): TSaleLineType;
end;
procedure SetCDSIndex(AClientDataSet: TClientDataSet; AIndexField: String);
implementation
uses DateUtils;
{ TDBExportFile }
function TDBExportFile.HasMoreLines: Boolean;
begin
Result := (not (FSource.Eof or FSource.IsEmpty)) and FSource.Active;
end;
function TDBExportFile.NextLine: String;
begin
Result := PrepareLine;
FSource.Next;
end;
function TDBExportFile.PrepareLine: String;
var
I: Integer;
begin
Result := '';
for I := 0 to FSource.FieldCount - 1 do
Result := Result + PrepareField(FSource.Fields[I]);
end;
function TDBExportFile.PrepareField(AField: TField): String;
begin
case AField.DataType of
ftSmallint,
ftInteger,
ftWord,
ftLargeint,
ftAutoInc:
Result := FFieldToStringParser.PrepareFieldInt(AField.Value, AField.IsNull);
ftFloat,
ftCurrency,
ftBCD:
Result := FFieldToStringParser.PrepareFieldReal(AField.Value, AField.IsNull);
ftDate,
ftTime,
ftDateTime:
Result := FFieldToStringParser.PrepareFieldDate(AField.Value, AField.IsNull);
ftBoolean:
Result := FFieldToStringParser.PrepareFieldBoolean(AField.Value, AField.IsNull);
ftString, ftWideString:
Result := FFieldToStringParser.PrepareFieldString(AField.AsString, AField.IsNull, AField.Size);
ftMemo:
Result := FFieldToStringParser.PrepareFieldMemo(AField.AsString, AField.IsNull);
else
result := '';
end;
end;
function TDBExportFile.SaveAll: Boolean;
var
stlSave: TStringList;
begin
Result := True;
try
if FSaveConfig then
WriteConfig;
stlSave := TStringList.Create;
try
while HasMoreLines() do
stlSave.Add(NextLine);
stlSave.SaveToFile(FileName);
finally
stlSave.Free;
end;
except
Result := False;
end;
end;
procedure TDBExportFile.WriteConfig;
var
ConfW: TConfigWritter;
begin
ConfW := TConfigWritter.Create;
try
ConfW.ConfigFilename := FConfigFileName;
ConfW.TableName := UpperCase(ChangeFileExt(ExtractFileName(FileName), ''));
ConfW.DataSet := FSource;
ConfW.SaveConfig;
finally
ConfW.Free;
end;
end;
constructor TDBExportFile.Create;
begin
inherited Create;
FSaveConfig := True;
FFieldToStringParser := TFieldToStringParser.Create;
end;
destructor TDBExportFile.Destroy;
begin
FFieldToStringParser.Free;
inherited Destroy;
end;
{ TFieldMapping }
function TFieldMapping.GetSize: Integer;
begin
Result := FSize;
end;
procedure TFieldMapping.SetFieldValueKind(const Value: TFieldValueKind);
begin
FFieldValueKind := Value;
case Value of
fvkInt:
FSize := TAM_INT;
fvkFloat:
FSize := TAM_REAL;
fvkDate:
FSize := TAM_DATE;
fvkBoolean:
FSize := TAM_BOOLEAN;
fvkMemo:
FSize := 0;
end;
end;
procedure TFieldMapping.SetSize(const Value: Integer);
begin
if (FFieldValueKind in [fvkString, fvkDummy]) then
begin
if Value <= 0 then
raise Exception.Create('Size value must be greater zero for string or dummy fields.');
if (FSize <> Value) then
FSize := Value;
end
end;
{ TStringToFieldParser }
procedure TStringToFieldParser.CutInteger(var AValue: Integer; var ALine: String);
var
Result : Variant;
begin
FValue := Copy(ALine, 1, TAM_INT);
Result := ParseInt;
if Result = Null then
AValue := 0
else
AValue := ParseInt;
Delete(ALine, 1, TAM_INT);
end;
procedure TStringToFieldParser.CutDouble(var AValue: Double; var ALine: String);
var
Result : Variant;
begin
FValue := Copy(ALine, 1, TAM_REAL);
Result := ParseFloat;
if Result = Null then
AValue := 0
else
AValue := ParseFloat;
Delete(ALine, 1, TAM_REAL);
end;
procedure TStringToFieldParser.CutReal(var AValue: Currency; var ALine: String);
var
Result : Variant;
begin
FValue := Copy(ALine, 1, TAM_REAL);
Result := ParseFloat;
if Result = Null then
AValue := 0
else
AValue := ParseFloat;
Delete(ALine, 1, TAM_REAL);
end;
procedure TStringToFieldParser.CutLongReal(var AValue: Currency; var ALine: String);
var
Result : Variant;
begin
FValue := Copy(ALine, 1, TAM_REAL);
Result := ParseLongFloat;
if Result = Null then
AValue := 0
else
AValue := ParseLongFloat;
Delete(ALine, 1, TAM_REAL);
end;
procedure TStringToFieldParser.CutDate(var AValue: TDateTime; var ALine: String);
var
Result : Variant;
begin
FValue := Copy(ALine, 1, TAM_DATE);
Result := ParseDate;
if Result = Null then
AValue := 0
else
AValue := ParseDate;
Delete(ALine, 1, TAM_DATE);
end;
procedure TStringToFieldParser.CutBoolean(var AValue: Boolean; var ALine: String);
begin
FValue := Copy(ALine, 1, TAM_BOOLEAN);
AValue := ParseBoolean;
Delete(ALine, 1, TAM_BOOLEAN);
end;
procedure TStringToFieldParser.CutMemo(var AValue: String; var ALine: String);
var
iEndMemo: Integer;
begin
/// PAREI AQUI !!!
Delete(ALine, 1, 1);
iEndMemo := Pos(STR_MEMO_SEP, ALine);
FValue := Copy(ALine, 1, iEndMemo - 1);
Delete(ALine, 1, iEndMemo);
AValue := ParseMemo;
end;
procedure TStringToFieldParser.CutString(var AValue: String; var ALine: String; const ASize: Integer);
begin
AValue := Trim(Copy(ALine, 1, ASize));
Delete(ALine, 1, ASize);
end;
function TStringToFieldParser.ParseBoolean: Variant;
begin
if Trim(FValue) = '' then
Result := False
else
Result := Boolean(Byte(StrToInt(FValue)));
end;
function TStringToFieldParser.ParseDate: Variant;
begin
if Trim(FValue) = '' then
Result := NULL
else
Result := EncodeDateTime(StrToInt(Copy(FValue, 1, 4)),
StrToInt(Copy(FValue, 5, 2)),
StrToInt(Copy(FValue, 7, 2)),
StrToInt(Copy(FValue, 9, 2)),
StrToInt(Copy(FValue, 11, 2)),
StrToInt(Copy(FValue, 13, 2)),
0
);
end;
function TStringToFieldParser.ParseFloat: Variant;
var
ValorFloat: Currency;
begin
if Trim(FValue) = '' then
Result := NULL
else
begin
ValorFloat := Integer(StrToInt64(FValue)) / Power(10, TAM_DEC);
Result := ValorFloat;
end;
end;
function TStringToFieldParser.ParseLongFloat: Variant;
var
ValorFloat: Currency;
begin
if Trim(FValue) = '' then
Result := NULL
else
begin
ValorFloat := StrToInt64(FValue) / Power(10, TAM_DEC);
Result := ValorFloat;
end;
end;
function TStringToFieldParser.ParseInt: Variant;
begin
if Trim(FValue) = '' then
Result := NULL
else
Result := Integer(StrToInt64(FValue));
end;
function TStringToFieldParser.ParseMemo: Variant;
var
sLine, sResult: String;
begin
if Trim(FValue) = '' then
Result := ''
else
begin
sResult := '';
sLine := FValue;
while Length(sLine) > 1 do
begin
sResult := sResult + Chr(Byte(StrToInt('$' + Copy(sLine, 1, 2))));
Delete(sLine, 1, 2);
end;
Result := sResult;
end;
end;
{ TCDSImportFile }
function TCDSImportFile.AddMapping(AFieldName: String;
AFieldValueKind: TFieldValueKind; ASize: Integer): Integer;
var
FM: TFieldMapping;
begin
FM := TFieldMapping.Create;
with FM do
begin
Found := False;
FieldName := AFieldName;
FieldValueKind := AFieldValueKind;
Size := ASize;
end;
Result := FMappingList.AddObject(AFieldName, FM);
end;
procedure TCDSImportFile.Clear;
var
FM: TFieldMapping;
begin
while FMappingList.Count > 0 do
begin
FM := TFieldMapping(FMappingList.Objects[0]);
FM.Free;
FMappingList.Objects[0] := nil;
FMappingList.Delete(0);;
end;
end;
function TCDSImportFile.Count: Integer;
begin
Result := FMappingList.Count;
end;
constructor TCDSImportFile.Create;
begin
inherited Create;
FStringToFieldParser := TStringToFieldParser.Create;
FCurrentLine := 0;
FMappingList := TStringList.Create;
FData := TStringList.Create;
end;
destructor TCDSImportFile.Destroy;
begin
Reset;
FMappingList.Free;
FData.Clear;
FStringToFieldParser.Free;
inherited Destroy;
end;
function TCDSImportFile.GetFieldMaps(Index: Integer): TFieldMapping;
begin
Result := TFieldMapping(FMappingList.Objects[Index]);
end;
function TCDSImportFile.HasMoreLines: Boolean;
begin
Result := (FData.Count > 0) and (FCurrentLine < FData.Count);
end;
function TCDSImportFile.MappingByName(AName: String): TFieldMapping;
var
Posicao: Integer;
begin
Posicao := FMappingList.IndexOf(AName);
if Posicao >= 0 then
Result := TFieldMapping(FMappingList.Objects[Posicao])
else
result := nil;
end;
function TCDSImportFile.NextLine: String;
begin
Result := FData[FCurrentLine];
Inc(FCurrentLine);
end;
function TCDSImportFile.ReadTableConfig(AININame,
ATableName: String): Boolean;
var
Ini: TINIFile;
stlLinhas: TStringList;
I: Integer;
ATipo : Char;
ASize: string;
begin
Result := True;
try
Reset;
Ini := TINIFile.Create(AININame);
try
stlLinhas := TStringList.Create;
try
Ini.ReadSection(ATableName, stlLinhas);
for I := 0 to stlLinhas.Count - 1 do
begin
ASize := Ini.ReadString(ATableName, stlLinhas[I], 'S0');
ATipo := ASize[1];
Delete(ASize, 1, 1);
case ATipo of
'I': AddMapping(stlLinhas[I], fvkInt);
'F': AddMapping(stlLinhas[I], fvkFloat);
'B': AddMapping(stlLinhas[I], fvkBoolean);
'D': AddMapping(stlLinhas[I], fvkDate);
'S': AddMapping(stlLinhas[I], fvkString, StrToInt(ASize));
'Y': AddMapping(stlLinhas[I], fvkDummy, StrToInt(ASize));
'M': AddMapping(stlLinhas[I], fvkMemo);
end;
end;
finally
stlLinhas.Free;
end;
finally
Ini.Free;
end;
except
Result := False;
end;
end;
procedure TCDSImportFile.Reset;
begin
Clear;
FCurrentLine := 0;
end;
function TCDSImportFile.SaveAll: Boolean;
begin
Result := True;
try
FData.LoadFromFile(FFileName);
if FClientDataSet.Active then
FClientDataSet.Close;
FClientDataSet.DisableControls;
try
FClientDataSet.CreateDataSet;
if FIndexField <> '' then
SetCDSIndex(FClientDataSet, FIndexField);
TestMappings;
while HasMoreLines() do
SaveLine(NextLine);
FClientDataSet.First;
finally
FClientDataSet.EnableControls;
end;
except
Result := False;
end;
end;
procedure TCDSImportFile.TestMappings;
var
I: Integer;
begin
for I:= 0 to FMappingList.Count - 1 do
TFieldMapping(FMappingList.Objects[I]).Found := FClientDataSet.FindField(FMappingList[I]) <> nil;
end;
function TCDSImportFile.SaveLine(ALine: String): Boolean;
var
I: Integer;
sLinha: String;
M: TFieldMapping;
sMemo: String;
begin
Result := True;
try
sLinha := ALine;
FClientDataSet.Append;
try
for I := 0 to FMappingList.Count - 1 do
begin
M := TFieldMapping(FMappingList.Objects[I]);
if M.Found then
begin
FStringToFieldParser.Value := Copy(sLinha, 1, M.Size);
case M.FFieldValueKind of
fvkInt: FClientDataSet.FieldByName(FMappingList[I]).Value := FStringToFieldParser.ParseInt;
fvkFloat: FClientDataSet.FieldByName(FMappingList[I]).Value := FStringToFieldParser.ParseFloat;
fvkDate: FClientDataSet.FieldByName(FMappingList[I]).Value := FStringToFieldParser.ParseDate;
fvkBoolean: FClientDataSet.FieldByName(FMappingList[I]).Value := FStringToFieldParser.ParseBoolean;
fvkString: FClientDataSet.FieldByName(FMappingList[I]).Value := FStringToFieldParser.Value;
fvkMemo:
begin
FStringToFieldParser.CutMemo(sMemo, sLinha);
FClientDataSet.FieldByName(FMappingList[I]).Value := sMemo;
end;
end;
end;
Delete(sLinha, 1, M.Size);
end;
FClientDataSet.Post;
except
FClientDataSet.Cancel;
raise;
end;
except
Result := False;
end;
end;
procedure TCDSImportFile.SetFieldMaps(Index: Integer;
const Value: TFieldMapping);
begin
FMappingList.Objects[Index] := Value;
FMappingList.Strings[Index] := Value.FieldName;
end;
{ TConfigWritter }
function TConfigWritter.SaveConfig: Boolean;
var
I: Integer;
AIni: TIniFile;
begin
Result := True;
try
AIni := TIniFile.Create(FConfigFilename);
try
if AIni.SectionExists(FTableName) then
AIni.EraseSection(FTableName);
for I := 0 to FDataSet.FieldCount - 1 do
SaveFieldConfig(AIni, FDataSet.Fields[I]);
finally
AIni.Free;
end;
except
Result := False;
end;
end;
function TConfigWritter.SaveFieldConfig(AIni: TIniFile; AField: TField): Boolean;
begin
Result := True;
try
case AField.DataType of
ftSmallint,
ftInteger,
ftWord,
ftLargeint,
ftAutoInc:
AIni.WriteString(FTablename, AField.FieldName, 'I0');
ftFloat,
ftCurrency,
ftBCD:
AIni.WriteString(FTablename, AField.FieldName, 'F0');
ftDate,
ftTime,
ftDateTime:
AIni.WriteString(FTablename, AField.FieldName, 'D0');
ftBoolean:
AIni.WriteString(FTablename, AField.FieldName, 'B0');
ftString, ftWideString:
AIni.WriteString(FTablename, AField.FieldName, Format('S%D', [AField.Size]));
ftMemo:
AIni.WriteString(FTablename, AField.FieldName, 'M0');
end;
except
Result := False;
end;
end;
{ TSaleWritter }
function TSaleWritter.AddCustomer(AIDTipoPessoa, AIDTipoPessoaRoot: Integer;
AFirstName, ALastName, AEndereco, ACidade, ABairro, AZip, ADocumento,
ATelefone, AEstado, ATelDDD, ACelDDD, ACelelular, AEmail, AWebSite,
ACPF, AIdentidate, AOrgEmiss, ACustCard, ACMotorista,
ANomeJuridico, AInscEstadual, AInscMunicipal, AContato, AOBS: String;
AJuridico:Boolean; AExpDate, ABirthDate : TDateTime): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'CL';
AValue := AIDTipoPessoa;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDTipoPessoaRoot;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AJuridico;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := AExpDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ABirthDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AFirstName;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := ALastName;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AEndereco;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 80);
AValue := ACidade;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 40);
AValue := ABairro;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 50);
AValue := AZip;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 12);
AValue := ADocumento;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := ATelefone;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 40);
//Novos campos
AValue := AEstado;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 3);
AValue := ATelDDD;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 5);
AValue := ACelDDD;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 5);
AValue := ACelelular;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 18);
AValue := AEmail;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 50);
AValue := AWebSite;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 200);
AValue := ACPF;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AIdentidate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AOrgEmiss;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 50);
AValue := ACustCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ACMotorista;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 15);
AValue := ANomeJuridico;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 50);
AValue := AInscEstadual;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AInscMunicipal;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AContato;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 255);
AValue := AOBS;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 100);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.AddHoldItem(AIDCustomer, AIDHold, AIDModel, AIDStore, AIDDepartment : Integer;
AQty: Double; ADiscount, ASale, ACost: Currency; AIDUser,
AIDCommis: Integer; AMovDate, ADate: TDateTime; AResetDisc,
AManager: Boolean; AIDDescriptionPrice, AIDVendorPrice: Integer;
ASuggPrice: Currency; ADocumentNumber: String; AIDDocumentNumber: Integer; ATotParcial : String): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'AI';
AValue := AIDCustomer;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDHold;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDModel;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDStore;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AQty;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCommis;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDDepartment;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ADiscount;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ASale;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ACost;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AMovDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AResetDisc;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := AManager;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := AIDDescriptionPrice;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDVendorPrice;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ASuggPrice;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ADocumentNumber;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AIDDocumentNumber;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
//PAF
AValue := ATotParcial;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 10);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.AddPayment(AIDPreSale, AIDStore, AIDUser,
AIDCustomer, AIDMeioPag, AIDCashRegMov: Integer; APreSaleDate,
AExpireDate: TDateTime; ANumParcela, AAutotize: String;
ATotalInvoice: Currency; ACheckNumber, ACustomerDocument, ACustomerName,
ACustomerPhone: String; AIDBankCheck: Integer; AOBS: String;
APaymentPlace: Integer; AIsPreDatado: Boolean; APayType: Integer): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'AP';
AValue := AIDPreSale;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDStore;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCustomer;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDMeioPag;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCashRegMov;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDBankCheck;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := APaymentPlace;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := APayType;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := APreSaleDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AExpireDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ATotalInvoice;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AIsPreDatado;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := ANumParcela;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AAutotize;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 50);
AValue := ACheckNumber;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ACustomerDocument;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ACustomerName;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 80);
AValue := ACustomerPhone;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AOBS;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 255);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.AddPettyCash(AIDCashRegMov, AIDUser: Integer;
ACash : Currency;
ADate : TDateTime;
AOBS: String;
ACOO, AGNF : Integer): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := True;
try
sLinha := 'PC';
AValue := AIDCashRegMov;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ACash;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := Copy(AOBS, 1, 255);
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 255);
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AGNF;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
Result := False;
end;
end;
function TSaleWritter.SaveObs(AOBS: String): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'OB';
AValue := AOBS;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 255);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.AbortSale(ACOO: String): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'AS';
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 8);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.CancelItem(Position: Integer): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'CI';
AValue := Position;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.CancelFiscalSale(ACOO: String;
IDUser: Integer): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := True;
try
sLinha := 'CS';
AValue := IDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 8);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
Result := False;
end;
end;
function TSaleWritter.CloseCashRegister(AIDCashRegMov, AIDUser, A100, A50,
A20, A10, A05, A02, A01, A0100, A050, A025, A010, A005, A001: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther: Currency; AEnvolop: String; ADate: TDateTime;
ATotalDebit: Currency; AReducaoZ: TRegReducaoZ): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := True;
try
sLinha := 'FC';
AValue := AIDCashRegMov;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A50;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A20;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A10;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A05;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A02;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A01;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A0100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A050;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A025;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A010;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A005;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A001;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ATotalCount;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCash;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalPreCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCheck;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalOther;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AEnvolop;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ATotalDebit;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
if AReducaoZ.ANumeroSerie <> '' then
begin
sLinha := GetLinhaReducaoZ(AReducaoZ);
FSaleLines.Add(sLinha);
sLinha := GetLinhaTotParcial(AReducaoZ);
FSaleLines.Add(sLinha);
WriteSaleToFile;
end;
CloseSaleFile;
except
Result := False;
end;
end;
procedure TSaleWritter.CloseSaleFile;
begin
if FFileOpened then
begin
Flush(FLogicalFile);
CloseFile(FLogicalFile);
FFileOpened := False;
FFileName := '';
end;
{$I-}
CloseFile(FHiddenFile);
{$I+}
end;
constructor TSaleWritter.Create(iDays, iFileSizeMB : Integer);
begin
inherited Create;
FFileOpened := False;
FFieldToStringParser := TFieldToStringParser.Create;
FSaleLines := TStringList.Create;
DeleteHiddenFileLog(iDays, iFileSizeMB);
OpenHiddenFile;
end;
procedure TSaleWritter.DeleteHiddenFileLog(iDays, iFileSizeMB : Integer);
var
PWinDir: PChar;
sWinDir: String;
sArquivo : String;
bDeleteLog : Boolean;
slHiddenFileLog : TStringList;
dDeleteDate : TDateTime;
begin
try
PWinDir := PChar(StringOfChar(#0, MAX_PATH + 1));
//FillChar(PWinDir, MAX_PATH, 0);
GetWindowsDirectory(pWinDir, MAX_PATH);
sWindir := StrPas(pWinDir);
sArquivo := sWindir + SUB_HIDDEN_NAME;
if not DirectoryExists(ExtractFilePath(sArquivo)) then
ForceDirectories((ExtractFilePath(sArquivo)));
AssignFile(FHiddenFile, sArquivo);
Reset(FHiddenFile);
try
bDeleteLog := ((FileSize(FHiddenFile)/(1024)/(1024)) >= iFileSizeMB);
finally
{$I-}
CloseFile(FHiddenFile);
{$I+}
end;
if bDeleteLog then
try
slHiddenFileLog := TStringList.Create;
slHiddenFileLog.LoadFromFile(sArquivo);
dDeleteDate := (Now - iDays);
bDeleteLog := False;
while EncodeDate(StrToInt(Copy(slHiddenFileLog.Strings[0],1,4)),
StrToInt(Copy(slHiddenFileLog.Strings[0],6,2)),
StrToInt(Copy(slHiddenFileLog.Strings[0],9,2))) <= dDeleteDate do
begin
slHiddenFileLog.Delete(0);
bDeleteLog := True;
end;
if bDeleteLog then
slHiddenFileLog.SaveToFile(sArquivo);
finally
FreeAndNil(slHiddenFileLog);
end;
except
end;
end;
function TSaleWritter.CreateHold(ADeliverType: Integer;
AIsLayaway: Boolean; AIDStore: Integer;
AFName, ALName, AZip: String;
AIDTourGroup: Integer; APreSaleDate: TDateTime;
AIDCustomer, AIDMedia, AIDOtherComm: Integer;
AInvObs, ASaleCode, ACOO:String; ATaxExempt: Boolean;
AIDPreSale: Integer; APuppyTracker: Boolean;
AECFSerial, ACCF : String): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'AV';
// Campos Integer
AValue := AIDPreSale;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := FIDCashreg;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ADeliverType;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDStore;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDTourGroup;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCustomer;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDMedia;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDOtherComm;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
// Campo Boolean
AValue := AIsLayaway;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := ATaxExempt;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := APuppyTracker;
sLinha := sLinha + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
// Campos Data
AValue := APreSaleDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
// Campos String
AValue := AFName;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ALName;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AZip;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AInvObs;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 150);
AValue := ASaleCode;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 8);
AValue := AECFSerial;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
//PAF
AValue := ACCF;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 10);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
procedure TSaleWritter.OpenHiddenFile;
var
PWinDir: PChar;
sWinDir: String;
sArquivo : String;
begin
PWinDir := PChar(StringOfChar(#0, MAX_PATH + 1));
//FillChar(PWinDir, MAX_PATH, 0);
GetWindowsDirectory(pWinDir, MAX_PATH);
sWindir := StrPas(pWinDir);
sArquivo := sWindir + SUB_HIDDEN_NAME;
if not DirectoryExists(ExtractFilePath(sArquivo)) then
ForceDirectories((ExtractFilePath(sArquivo)));
AssignFile(FHiddenFile, sArquivo);
{$I-}
if not FileExists(sArquivo) then
ReWrite(FHiddenFile);
Append(FHiddenFile);
{$I+}
end;
function TSaleWritter.CreateNewFile: Boolean;
begin
try
{$I-}
if FFileOpened then
begin
CloseFile(FLogicalFile);
FFileOpened := False;
end;
{$I+}
if not DirectoryExists(FLocalWorkingDir) then
ForceDirectories(FLocalWorkingDir);
FFilename := 'PDV' + IntToStr(IDCashReg) + FormatDateTime('-YYYYMMDD-HHNNSS', NOW) + '.ven';
AssignFile(FLogicalFile, FLocalWorkingDir + FFilename);
{$I-}
Rewrite(FLogicalFile);
Result := IOResult = 0;
{$I+}
except
Result := False;
end;
FFileOpened := Result;
end;
destructor TSaleWritter.Destroy;
begin
CloseSaleFile;
FFieldToStringParser.Free;
FSaleLines.Free;
inherited Destroy;
end;
function TSaleWritter.OpenCashRegister(A100, A50, A20, A10, A05, A02, A01,
A0100, A050, A025, A010, A005, A001, AIDCashReg, AIDUser: Integer;
ATotalCount, ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther: Currency; ADate: TDateTime; ATotalDebit: Currency;
ACOO, AGNF : Integer; AReducaoZ: TRegReducaoZ): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := True;
try
CreateNewFile;
if AReducaoZ.ANumeroSerie <> '' then
begin
sLinha := GetLinhaReducaoZ(AReducaoZ);
FSaleLines.Add(sLinha);
sLinha := GetLinhaTotParcial(AReducaoZ);
FSaleLines.Add(sLinha);
end;
sLinha := 'AC';
AValue := A100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A50;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A20;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A10;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A05;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A02;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A01;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A0100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A050;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A025;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A010;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A005;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A001;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCashReg;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ATotalCount;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCash;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalPreCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCheck;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalOther;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ATotalDebit;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AGNF;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
Result := False;
end;
end;
function TSaleWritter.OpenFile(AFileName: String): Boolean;
{var
sLinha: String;}
begin
try
FSaleLines.Clear;
Result := FileExists(FLocalWorkingDir + AFileName);
if not Result then
Exit;
FFileName := AFileName;
AssignFile(FLogicalFile, FLocalWorkingDir + AFileName);
(*
// Antigo procedimento para editar o arquivo. Substituido pelo append
// mas ainda está em teste
{$I-}
Reset(FLogicalFile);
while not EOF(FLogicalFile) do
begin
Readln(FLogicalFile, sLinha);
FSaleLines.Add(sLinha);
end;
CloseFile(FLogicalFile);
Rewrite(FLogicalFile);
{$I+}
*)
{$I-}
Reset(FLogicalFile);
Append(FLogicalFile);
{$I+}
FFileOpened := IOResult = 0;
Result := FFileOpened;
if FFileOpened then
Result := WriteSaleToFile;
except
Result := False;
end;
end;
function TSaleWritter.PreSalePay(AIDPreSale, AIDTourGroup, AIDOtherCommis,
AIDCashRegMov, AIDStore: Integer; ADate, APayDate: TDateTime;
ACashReceived, ASaleDiscount: Currency): String;
var
sLinha: String;
begin
Result := '';
try
sLinha := GetSaleCloseLine(AIDPreSale, AIDTourGroup, AIDOtherCommis,
AIDCashRegMov, AIDStore, ADate, APayDate,
ACashReceived, ASaleDiscount);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.WithdrawCashRegister(AIDCashRegMov, AIDUser, A100,
A50, A20, A10, A05, A02, A01, A0100, A050, A025, A010, A005,
A001: Integer; ATotalCash, ATotalCard, ATotalPreCard, ATotalCheck,
ATotalOther: Currency; AEnvolop: String; ADate: TDateTime;
AOBS: String; ATotalDebit: Currency; AIDReason : Integer;
ACOO, AGNF: Integer): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := True;
try
sLinha := 'WC';
AValue := AIDCashRegMov;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A50;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A20;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A10;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A05;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A02;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A01;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A0100;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A050;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A025;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A010;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A005;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := A001;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ATotalCash;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalPreCard;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalCheck;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ATotalOther;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AEnvolop;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := Copy(AOBS, 1, 255);
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 255);
AValue := ATotalDebit;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AIDReason;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ACOO;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AGNF;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
Result := False;
end;
end;
function TSaleWritter.WriteSaleToFile: Boolean;
var
I: Integer;
lstTmp: TStringList;
sArquivoLocal, sArquivoRemoto: String;
begin
Result := True;
{$I-}
for I := 0 to FSaleLines.Count - 1 do
begin
Writeln(FHiddenFile, FormatDateTime('YYYY-MM-DD - ', Date) + FSaleLines[I]);
if IOResult <> 0 then
Break;
Flush(FHiddenFile);
if IOResult <> 0 then
Break;
end;
{$I+}
{$I+}
for I := 0 to FSaleLines.Count - 1 do
begin
Writeln(FLogicalFile, FSaleLines[I]);
Result := IOResult = 0;
if Result then
begin
Flush(FLogicalFile);
Result := Result and (IOResult = 0);
end;
if not Result then
Break;
end;
{$I+}
FSaleLines.Clear;
{
//Removido para a thread
if Result and (FRemoteWorkingDir <> '') then
try
sArquivoLocal := FLocalWorkingDir + FFilename;
sArquivoRemoto := FRemoteWorkingDir + IntToStr(FIDCashReg) + '\' + FFilename;
if not DirectoryExists(ExtractFilePath(sArquivoRemoto)) then
ForceDirectories(ExtractFilePath(sArquivoRemoto));
lstTmp := TStringList.Create;
try
LoadListNoLock(lstTmp, sArquivoLocal);
if FileExists(sArquivoRemoto) then
DeleteFile(PChar(sArquivoRemoto));
lstTmp.SaveToFile(sArquivoRemoto);
finally
lstTmp.Free;
end;
except
end;}
end;
function TSaleWritter.AddRemovedItem(AIDCashReg, AIDModel, AIDStore, AIDDepartment: Integer;
AQty: Double; ADiscount, ASale, ACost: Currency; AIDUser, AIDUserAuto,
AIDCommis: Integer; AMovDate: TDateTime; ASaleCode : String): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'RI-';
AValue := AIDCashReg;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDModel;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDStore;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AQty;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AIDUser;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDUserAuto;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCommis;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDDepartment;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ADiscount;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ASale;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ACost;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AMovDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ASaleCode;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := E.Message;
end;
end;
function TSaleWritter.AddSerialNumber(APosition: Integer;
ASerialNumber, AIdentificationNumber: String): Boolean;
var
sLinha: String;
AValue: Variant;
begin
Result := false;
try
sLinha := 'SN-';
AValue := APosition;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ASerialNumber;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
AValue := AIdentificationNumber;
sLinha := sLinha + FFieldToStringParser.PrepareFieldString(AValue, False, 30);
FSaleLines.Add(sLinha);
WriteSaleToFile;
except
on E: Exception do
Result := False;
end;
end;
function TSaleWritter.GetLinhaReducaoZ(AReducaoZ: TRegReducaoZ): String;
var
i: Integer;
AValue: Variant;
begin
Result := 'RZ';
AValue := AReducaoZ.AMovDate;
Result := Result + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AReducaoZ.ANumeroSerie;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AReducaoZ.ANumeroLoja;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ANumeroECF;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ANumReducaoZ;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ACOOInicial;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ACOOFinal;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ANumCancelamentos;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.AValCancelamentos;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.AValDescontos;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.AGTInicial;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.AGTFinal;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.ASubstituicaoTrib;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.AIsencao;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.ANaoTributavel;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
// PAF-ECF
AValue := AReducaoZ.ATipoECF;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AReducaoZ.AMarcaECF;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AReducaoZ.AModeloECF;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 20);
AValue := AReducaoZ.AVersaoSBECF;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 10);
AValue := AReducaoZ.ADataInstalacaoSBECF;
Result := Result + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := AReducaoZ.AMFAdicional;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 1);
AValue := AReducaoZ.AContadorReducaoZ;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.AContadorOrdemOperacao;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.AContadorReinicioOperacao;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.ANumeroUsuarioECF;
Result := Result + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AReducaoZ.AIncideISSQN;
Result := Result + FFieldToStringParser.PrepareFieldBoolean(AValue, False);
AValue := AReducaoZ.ADataEmissao;
Result := Result + FFieldToStringParser.PrepareFieldDate(AValue, False);
for i := 0 to Pred(Length(AReducaoZ.AAliquota)) do
begin
AValue := AReducaoZ.AAliquota[i];
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.ABaseCalculo[i];
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := AReducaoZ.AValImposto[i];
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
end;
end;
function TSaleWritter.GetSaleCloseLine(AIDPreSale, AIDTourGroup,
AIDOtherCommis, AIDCashRegMov, AIDStore: Integer; ADate,
APayDate: TDateTime; ACashReceived, ASaleDiscount: Currency): String;
var
sLinha: String;
AValue: Variant;
begin
Result := '';
try
sLinha := 'FV';
AValue := AIDPreSale;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDTourGroup;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDOtherCommis;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDCashRegMov;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AIDStore;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ADate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := APayDate;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
AValue := ACashReceived;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
AValue := ASaleDiscount;
sLinha := sLinha + FFieldToStringParser.PrepareFieldReal(AValue, False);
finally
Result := sLinha;
end;
end;
function TSaleWritter.AddVinculadoInfo(ACOOVinc, AGNFVinc, ACDC: Integer;
ADataHora: TDateTime): Boolean;
var
sLinha: String;
AValue: Variant;
begin
try
sLinha := 'VI';
AValue := ACOOVinc;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := AGNFVinc;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ACDC;
sLinha := sLinha + FFieldToStringParser.PrepareFieldInt(AValue, False);
AValue := ADataHora;
sLinha := sLinha + FFieldToStringParser.PrepareFieldDate(AValue, False);
FSaleLines.Add(sLinha);
WriteSaleToFile;
Result := True;
except
on E: Exception do
Result := False;
end;
end;
function TSaleWritter.GetLinhaTotParcial(AReducaoZ: TRegReducaoZ): String;
var
i: Integer;
AValue: Variant;
begin
Result := 'TP';
for i := 0 to Pred(Length(AReducaoZ.ATribReducaoZList)) do
begin
AValue := AReducaoZ.ATribReducaoZList[i].Codigo;
Result := Result + FFieldToStringParser.PrepareFieldString(AValue, False, 10);
AValue := AReducaoZ.ATribReducaoZList[i].ValorAcumulado;
Result := Result + FFieldToStringParser.PrepareFieldReal(AValue, False);
end;
end;
{ TFieldToStringParser }
function TFieldToStringParser.PrepareFieldInt(AValue: Variant; AIsNull: Boolean): String;
var
ValorInt: Integer;
Sinal: Char;
begin
if AIsNull then
Result := StringOfChar(CHR_SPACE, TAM_INT)
else
begin
ValorInt := Trunc(ABS(AValue));
Sinal := GetSignal(AValue);
Result := Sinal + SizedStr(IntToStr(ValorInt), TAM_INT - 1, CHR_ZERO, sspLeft);
end;
end;
function TFieldToStringParser.PrepareFieldReal(AValue: Variant; AIsNull: Boolean): String;
var
ValorInt: Int64;
Sinal: Char;
begin
if AIsNull then
Result := StringOfChar(CHR_SPACE, TAM_REAL)
else
begin
ValorInt := Int64(Trunc(ABS(AValue * Power(10, TAM_DEC))));
Sinal := GetSignal(AValue);
Result := Sinal + SizedStr(IntToStr(ValorInt), TAM_REAL - 1, CHR_ZERO, sspLeft);
end;
end;
function TFieldToStringParser.PrepareFieldDate(AValue: Variant; AIsNull: Boolean): String;
var
ValorDate: TDateTime;
begin
if AIsNull then
Result := StringOfChar(CHR_SPACE, TAM_DATE)
else
begin
ValorDate := AValue;
Result := FormatDateTime(FMT_DATE, ValorDate);
end;
end;
function TFieldToStringParser.PrepareFieldBoolean(AValue: Variant; AIsNull: Boolean): String;
var
ValorBoolean: Boolean;
begin
if AIsNull then
ValorBoolean := False
else
ValorBoolean := AValue;
Result := IntToStr(Byte(ValorBoolean));
end;
function TFieldToStringParser.PrepareFieldString(AValue: String; AIsNull: Boolean; ASize: Integer): String;
var
ValorString: String;
begin
if AIsNull then
Result := StringOfChar(CHR_SPACE, ASize)
else
begin
ValorString := StringReplace(AValue, STR_CRLF, CHR_SPACE, [rfReplaceAll]);
ValorString := Trim(ValorString);
Result := SizedStr(ValorString, ASize, CHR_SPACE, sspRight);
end;
end;
function TFieldToStringParser.GetSignal(Value: Variant): Char;
begin
if Value >= 0 then
Result := '0'
else
Result := '-';
end;
function TFieldToStringParser.PrepareFieldMemo(AValue: Variant;
AIsNull: Boolean): String;
var
strTmp: String;
I: Integer;
begin
Result := STR_MEMO_SEP;
if not AIsNull then
begin
strTmp := VarToStr(AValue);
for I := 1 to Length(strTmp) do
Result := Result + IntToHex(Ord(strTmp[I]), 2);
end;
Result := Result + STR_MEMO_SEP;
end;
{ TSaleLineParser }
constructor TSaleLineParser.Create;
begin
inherited Create;
FStringToFieldParser := TStringToFieldParser.Create;
end;
destructor TSaleLineParser.Destroy;
begin
FStringToFieldParser.Free;
inherited;
end;
procedure TSaleLineParser.GetOpenCash(Const ALine: String; var ROC: TRegOpenCash);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(ROC.A100, strTmp);
CutInteger(ROC.A50, strTmp);
CutInteger(ROC.A20, strTmp);
CutInteger(ROC.A10, strTmp);
CutInteger(ROC.A05, strTmp);
CutInteger(ROC.A02, strTmp);
CutInteger(ROC.A01, strTmp);
CutInteger(ROC.A0100, strTmp);
CutInteger(ROC.A050, strTmp);
CutInteger(ROC.A025, strTmp);
CutInteger(ROC.A010, strTmp);
CutInteger(ROC.A005, strTmp);
CutInteger(ROC.A001, strTmp);
CutInteger(ROC.AIDCashReg, strTmp);
CutInteger(ROC.AIDUser, strTmp);
CutReal(ROC.ATotalCount, strTmp);
CutReal(ROC.ATotalCash, strTmp);
CutReal(ROC.ATotalCard, strTmp);
CutReal(ROC.ATotalPreCard, strTmp);
CutReal(ROC.ATotalCheck, strTmp);
CutReal(ROC.ATotalOther, strTmp);
CutDate(ROC.ADate, strTmp);
CutReal(ROC.ATotalDebit, strTmp);
CutInteger(ROC.ACOO, strTmp);
CutInteger(ROC.AGNF, strTmp);
end;
end;
procedure TSaleLineParser.GetOpenSale(const ALine: String; var ROS: TRegOpenSale);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(ROS.AIDPreSale, strTmp);
CutInteger(ROS.AIDCashreg, strTmp); // Só para limpar a String
CutInteger(ROS.ADeliverType, strTmp);
CutInteger(ROS.AIDStore, strTmp);
CutInteger(ROS.AIDTourGroup, strTmp);
CutInteger(ROS.AIDCustomer, strTmp);
CutInteger(ROS.AIDMedia, strTmp);
CutInteger(ROS.AIDOtherComm, strTmp);
CutBoolean(ROS.AIsLayaway, strTmp);
CutBoolean(ROS.ATaxExempt, strTmp);
CutBoolean(ROS.APuppyTracker, strTmp);
CutDate(ROS.APreSaleDate, strTmp);
CutString(ROS.AFName, strTmp, 20);
CutString(ROS.ALName, strTmp, 20);
CutString(ROS.AZip, strTmp, 20);
CutString(ROS.AInvObs, strTmp, 150);
CutString(ROS.ASaleCode, strTmp, 20);
CutString(ROS.ACOO, strTmp, 8);
CutString(ROS.ASerialECF, strTmp, 20);
CutString(ROS.ACCF, strTmp, 10);
end;
end;
procedure TSaleLineParser.GetAddCustomer(const ALine: String; var RAC: TRegAddCustomer);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RAC.AIDTipoPessoa, strTmp);
CutInteger(RAC.AIDTipoPessoaRoot, strTmp);
CutBoolean(RAC.AJuridico, strTmp);
CutDate(RAC.AExpDate, strTmp);
CutDate(RAC.ABirthDate, strTmp);
CutString(RAC.AFirstName, strTmp, 30);
CutString(RAC.ALastName, strTmp, 30);
CutString(RAC.AEndereco, strTmp, 80);
CutString(RAC.ACidade, strTmp, 40);
CutString(RAC.ABairro, strTmp, 50);
CutString(RAC.AZip, strTmp, 12);
CutString(RAC.ADocumento, strTmp, 30);
CutString(RAC.ATelefone, strTmp, 40);
CutString(RAC.AEstado, strTmp, 3);
CutString(RAC.ATelDDD, strTmp, 5);
CutString(RAC.ACelDDD, strTmp, 5);
CutString(RAC.ACelelular, strTmp, 18);
CutString(RAC.AEmail, strTmp, 50);
CutString(RAC.AWebSite, strTmp, 200);
CutString(RAC.ACPF, strTmp, 30);
CutString(RAC.AIdentidate, strTmp, 30);
CutString(RAC.AOrgEmiss, strTmp, 50);
CutString(RAC.ACustCard, strTmp, 20);
CutString(RAC.ACMotorista, strTmp, 15);
CutString(RAC.ANomeJuridico, strTmp, 50);
CutString(RAC.AInscEstadual, strTmp, 30);
CutString(RAC.AInscMunicipal, strTmp, 30);
CutString(RAC.AContato, strTmp, 255);
CutString(RAC.AOBS, strTmp, 100);
end;
end;
procedure TSaleLineParser.GetRemovedItem(const ALine: String;
var RRI: TRegRemovedItem);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 3);
with FStringToFieldParser do
begin
CutInteger(RRI.AIDCashReg, strTmp);
CutInteger(RRI.AIDModel, strTmp);
CutInteger(RRI.AIDStore, strTmp);
CutDouble(RRI.AQty, strTmp);
CutInteger(RRI.AIDUser, strTmp);
CutInteger(RRI.AIDUserAuto, strTmp);
CutInteger(RRI.AIDCommis, strTmp);
CutInteger(RRI.AIDDepartment, strTmp);
CutReal(RRI.ADiscount, strTmp);
CutReal(RRI.ASale, strTmp);
CutReal(RRI.ACost, strTmp);
CutDate(RRI.AMovDate, strTmp);
CutString(RRI.ASaleCode, strTmp, 20);
end;
end;
procedure TSaleLineParser.GetItemCanceled(const ALine: String; var Position: Integer);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
CutInteger(Position, strTmp);
end;
procedure TSaleLineParser.GetAddItem(const ALine: String; var RAI: TRegAddItem);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RAI.AIDCustomer, strTmp);
CutInteger(RAI.AIDHold, strTmp);
CutInteger(RAI.AIDModel, strTmp);
CutInteger(RAI.AIDStore, strTmp);
CutDouble(RAI.AQty, strTmp);
CutInteger(RAI.AIDUser, strTmp);
CutInteger(RAI.AIDCommis, strTmp);
CutInteger(RAI.AIDDepartment, strTmp);
CutReal(RAI.ADiscount, strTmp);
CutReal(RAI.ASale, strTmp);
CutReal(RAI.ACost, strTmp);
CutDate(RAI.AMovDate, strTmp);
CutDate(RAI.ADate, strTmp);
CutBoolean(RAI.AResetDisc, strTmp);
CutBoolean(RAI.AManager, strTmp);
CutInteger(RAI.AIDDescriptionPrice, strTmp);
CutInteger(RAI.AIDVendorPrice, strTmp);
CutReal(RAI.ASuggPrice, strTmp);
CutString(RAI.ADocumentNumber, strTmp, 20);
CutInteger(RAI.AIDDocumentType, strTmp);
CutString(RAI.ATotParcial, strTmp, 10);
end;
end;
procedure TSaleLineParser.GetAddPayment(const ALine: String; var RAP: TRegAddPayment);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RAP.AIDPreSale, strTmp);
CutInteger(RAP.AIDStore, strTmp);
CutInteger(RAP.AIDUser, strTmp);
CutInteger(RAP.AIDCustomer, strTmp);
CutInteger(RAP.AIDMeioPag, strTmp);
CutInteger(RAP.AIDCashRegMov, strTmp);
CutInteger(RAP.AIDBankCheck, strTmp);
CutInteger(RAP.APaymentPlace, strTmp);
CutInteger(RAP.APayType, strTmp);
CutDate(RAP.APreSaleDate, strTmp);
CutDate(RAP.AExpireDate, strTmp);
CutReal(RAP.ATotalInvoice, strTmp);
CutBoolean(RAP.AIsPreDatado, strTmp);
CutString(RAP.ANumParcela, strTmp, 20);
CutString(RAP.AAutotize, strTmp, 50);
CutString(RAP.ACheckNumber, strTmp, 20);
CutString(RAP.ACustomerDocument, strTmp, 20);
CutString(RAP.ACustomerName, strTmp, 80);
CutString(RAP.ACustomerPhone, strTmp, 20);
CutString(RAP.AOBS, strTmp, 255);
end;
end;
procedure TSaleLineParser.GetAddPC(const ALine: String; var RAPC: TRegAddPC);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RAPC.AIDCashRegMov, strTmp);
CutInteger(RAPC.AIDUser, strTmp);
CutReal(RAPC.ACash, strTmp);
CutDate(RAPC.ADate, strTmp);
CutString(RAPC.AOBS, strTmp, 255);
CutInteger(RAPC.ACOO, strTmp);
CutInteger(RAPC.AGNF, strTmp);
end;
end;
procedure TSaleLineParser.GetAddWC(const Aline: String; var RAWC: TRegAddWC);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RAWC.AIDCashRegMov, strTmp);
CutInteger(RAWC.AIDUser, strTmp);
CutInteger(RAWC.A100, strTmp);
CutInteger(RAWC.A50, strTmp);
CutInteger(RAWC.A20, strTmp);
CutInteger(RAWC.A10, strTmp);
CutInteger(RAWC.A05, strTmp);
CutInteger(RAWC.A02, strTmp);
CutInteger(RAWC.A01, strTmp);
CutInteger(RAWC.A0100, strTmp);
CutInteger(RAWC.A050, strTmp);
CutInteger(RAWC.A025, strTmp);
CutInteger(RAWC.A010, strTmp);
CutInteger(RAWC.A005, strTmp);
CutInteger(RAWC.A001, strTmp);
CutReal(RAWC.ATotalCash, strTmp);
CutReal(RAWC.ATotalCard, strTmp);
CutReal(RAWC.ATotalPreCard, strTmp);
CutReal(RAWC.ATotalCheck, strTmp);
CutReal(RAWC.ATotalOther, strTmp);
CutDate(RAWC.ADate, strTmp);
CutString(RAWC.AEnvolop, strTmp, 20);
CutString(RAWC.AOBS, strTmp, 255);
CutReal(RAWC.ATotalDebit, strTmp);
CutInteger(RAWC.AIDReason, strTmp);
CutInteger(RAWC.ACOO, strTmp);
CutInteger(RAWC.AGNF, strTmp);
end;
end;
procedure TSaleLineParser.GetCloseSale(const ALine: String; var RCS: TRegCloseSale);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RCS.AIDPreSale, strTmp);
CutInteger(RCS.AIDTourGroup, strTmp);
CutInteger(RCS.AIDOtherCommis, strTmp);
CutInteger(RCS.AIDCashRegMov, strTmp);
CutInteger(RCS.AIDStore, strTmp);
CutDate(RCS.ADate, strTmp);
CutDate(RCS.APayDate, strTmp);
CutReal(RCS.ACashReceived, strTmp);
CutReal(RCS.ASaleDiscount, strTmp);
end;
end;
procedure TSaleLineParser.GetCancelSale(const ALine: String;
var RCS: TRegCancelSale);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RCS.AIDUser, strTmp);
CutString(RCS.ACOO, strTmp, 8);
end;
end;
procedure TSaleLineParser.GetCloseCash(ALine: String; var RCC: TRegCloseCash);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RCC.AIDCashRegMov, strTmp);
CutInteger(RCC.AIDUser, strTmp);
CutInteger(RCC.A100, strTmp);
CutInteger(RCC.A50, strTmp);
CutInteger(RCC.A20, strTmp);
CutInteger(RCC.A10, strTmp);
CutInteger(RCC.A05, strTmp);
CutInteger(RCC.A02, strTmp);
CutInteger(RCC.A01, strTmp);
CutInteger(RCC.A0100, strTmp);
CutInteger(RCC.A050, strTmp);
CutInteger(RCC.A025, strTmp);
CutInteger(RCC.A010, strTmp);
CutInteger(RCC.A005, strTmp);
CutInteger(RCC.A001, strTmp);
CutReal(RCC.ATotalCount, strTmp);
CutReal(RCC.ATotalCash, strTmp);
CutReal(RCC.ATotalCard, strTmp);
CutReal(RCC.ATotalPreCard, strTmp);
CutReal(RCC.ATotalCheck, strTmp);
CutReal(RCC.ATotalOther, strTmp);
CutDate(RCC.ADate, strTmp);
CutString(RCC.AEnvolop, strTmp, 20);
CutReal(RCC.ATotalDebit, strTmp);
end;
end;
function TSaleLineParser.LineType(ALine: String) : TSaleLineType;
var
strTmp: String;
begin
// É feio mas não tem outro jeito :-/
strTmp := Copy(ALine, 1, 2);
if strTmp = 'AC' then
Result := sltOpenCash
else
if strTmp = 'AV' then
Result := sltOpenSale
else
if strTmp = 'AI' then
Result := sltAddItem
else
if strTmp = 'AP' then
Result := sltAddPayment
else
if strTmp = 'FV' then
Result := sltCloseSale
else
if strTmp = 'FC' then
Result := sltCloseCash
else
if strTmp = 'CL' then
Result := sltAddCustomer
else
if strTmp = 'PC' then
Result := sltPC
else
if strTmp = 'WC' then
Result := sltWC
else
if strTmp = 'CS' then
Result := sltCancelSale
else
if strTmp = 'RI' then
Result := sltRemovedItem
else
if strTmp = 'RZ' then
Result := sltReducaoZ
else
if strTmp = 'AS' then
Result := sltAbortSale
else
if strTmp = 'CI' then
Result := sltCancelItem
else
if strTmp = 'SN' then
Result := sltAddSerialNumber
else
if strTmp = 'OB' then
Result := sltOBS
else
if strTmp = 'VI' then
Result := sltCupomVinculado
else
if strTmp = 'TP' then
Result := sltTotParcial
else
Result := sltUnknow;
end;
procedure SetCDSIndex(AClientDataSet: TClientDataSet; AIndexField: String);
var
sInidice: string;
stlIndexes: TStringList;
I: Integer;
begin
stlIndexes := TStringList.Create;
try
if not AClientDataSet.Active then
AClientDataSet.Open;
AClientDataSet.IndexName := '';
AClientDataSet.GetIndexNames(stlIndexes);
for I := 0 to stlIndexes.Count - 1 do
if (stlIndexes[I] <> 'DEFAULT_ORDER') and (stlIndexes[I] <> 'CHANGEINDEX') then
AClientDataSet.DeleteIndex(stlIndexes[I]);
sInidice := Format('%S', [AIndexField]);
AClientDataSet.AddIndex(sInidice, AIndexField, [ixCaseInsensitive]);
AClientDataSet.IndexName := sInidice;
finally
stlIndexes.Free;
end;
end;
procedure TSaleLineParser.GetReducaoZ(const ALine: String;
var RRZ: TRegReducaoZ);
var
strTmp: String;
cAliquota, cBaseCalculo, cImposto: Currency;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutDate(RRZ.AMovDate, strTmp);
CutString(RRZ.ANumeroSerie, strTmp, 20);
CutInteger(RRZ.ANumeroLoja, strTmp);
CutInteger(RRZ.ANumeroECF, strTmp);
CutInteger(RRZ.ANumReducaoZ, strTmp);
CutInteger(RRZ.ACOOInicial, strTmp);
CutInteger(RRZ.ACOOFinal, strTmp);
CutInteger(RRZ.ANumCancelamentos, strTmp);
CutReal(RRZ.AValCancelamentos, strTmp);
CutReal(RRZ.AValDescontos, strTmp);
CutLongReal(RRZ.AGTInicial, strTmp);
CutLongReal(RRZ.AGTFinal, strTmp);
CutReal(RRZ.ASubstituicaoTrib, strTmp);
CutReal(RRZ.AIsencao, strTmp);
CutReal(RRZ.ANaoTributavel, strTmp);
//PAF
CutString(RRZ.ATipoECF, strTmp, 20);
CutString(RRZ.AMarcaECF, strTmp, 20);
CutString(RRZ.AModeloECF, strTmp, 20);
CutString(RRZ.AVersaoSBECF, strTmp, 10);
CutDate(RRZ.ADataInstalacaoSBECF, strTmp);
CutString(RRZ.AMFAdicional, strTmp, 1);
CutInteger(RRZ.AContadorReducaoZ, strTmp);
CutInteger(RRZ.AContadorOrdemOperacao, strTmp);
CutInteger(RRZ.AContadorReinicioOperacao, strTmp);
CutInteger(RRZ.ANumeroUsuarioECF, strTmp);
CutBoolean(RRZ.AIncideISSQN, strTmp);
CutDate(RRZ.ADataEmissao, strTmp);
while strTmp <> '' do
begin
CutReal(cAliquota, strTmp);
SetLength(RRZ.AAliquota, Length(RRZ.AAliquota)+1);
RRZ.AAliquota[Length(RRZ.AAliquota)-1] := cAliquota;
CutReal(cBaseCalculo, strTmp);
SetLength(RRZ.ABaseCalculo, Length(RRZ.ABaseCalculo)+1);
RRZ.ABaseCalculo[Length(RRZ.ABaseCalculo)-1] := cBaseCalculo;
CutReal(cImposto, strTmp);
SetLength(RRZ.AValImposto, Length(RRZ.AValImposto)+1);
RRZ.AValImposto[Length(RRZ.AValImposto)-1] := cImposto;
end;
end;
end;
procedure TSaleLineParser.GetAddSerialNumber(const ALine: String;
var RSN: TRegSerialNumber);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 3);
with FStringToFieldParser do
begin
CutInteger(RSN.APosition, strTmp);
CutString(RSN.ASerialNumber, strTmp, 30);
CutString(RSN.AIdentificationNumber, strTmp, 30);
end;
end;
procedure TSaleLineParser.GetOBS(const ALine: String; var ROBS: TRegOBS);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
CutString(ROBS.AOBS, strTmp, 255);
end;
procedure TSaleLineParser.GetCupomVinculado(const ALine: String;
var RCupomVinculado: TRegCupomVinculado);
var
strTmp: String;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
with FStringToFieldParser do
begin
CutInteger(RCupomVinculado.ACOOVinc, strTmp);
CutInteger(RCupomVinculado.AGNFVinc, strTmp);
CutInteger(RCupomVinculado.ACDC, strTmp);
CutDate(RCupomVinculado.ADataHora, strTmp);
end;
end;
procedure TSaleLineParser.GetTotParcial(const ALine: String;
var RRZ: TRegReducaoZ);
var
strTmp, sCodigo: String;
fValorAcumulado : Currency;
i : Integer;
begin
strTmp := ALine;
Delete(strTmp, 1, 2);
i := 0;
with FStringToFieldParser do
while strTmp <> '' do
begin
inc(i);
SetLength(RRZ.ATribReducaoZList, i);
CutString(RRZ.ATribReducaoZList[i-1].Codigo, strTmp, 10);
CutReal(RRZ.ATribReducaoZList[i-1].ValorAcumulado, strTmp);
end;
end;
{ TLastSale }
procedure TLastSale.AddItem(ALine: String);
var
LSI : TLastSaleItem;
begin
LSI := TLastSaleItem.Create;
LSI.FItemLine := ALine;
LSI.FCanceled := False;
FItemList.AddObject('', LSI);
end;
procedure TLastSale.AddItemSerial(ALine: String);
var
LSIS : TLastSaleItemSerial;
begin
LSIS := TLastSaleItemSerial.Create;
LSIS.FItemSerialLine := ALine;
TLastSaleItem(FItemList.Objects[Pred(FItemList.Count)]).FSerialList.Add(LSIS);
end;
procedure TLastSale.AddPayment(ALine: String);
begin
FPaymentList.Add(ALine);
end;
procedure TLastSale.CancelItem(APosition: Integer);
var
LSI : TLastSaleItem;
begin
if FItemList.Count >= APosition then
begin
APosition := APosition-1;
LSI := TLastSaleItem(FItemList.Objects[APosition]);
LSI.FCanceled := True;
FItemList.Objects[APosition] := LSI;
end;
end;
procedure TLastSale.ClearLastSale;
var
LSI : TLastSaleItem;
LSIS : TLastSaleItemSerial;
begin
FOpenSaleLine := '';
FCloseSaleLine := '';
FCustomerLine := '';
FSaleCode := '';
FOBS := '';
FIDCashRegister := -1;
FIDUser := -1;
FCanceled := False;
FPaymentList.Clear;
while FItemList.Count <> 0 do
begin
if FItemList.Objects[0] <> nil then
begin
LSI := TLastSaleItem(FItemList.Objects[0]);
FreeAndNil(LSI);
end;
FItemList.Delete(0);
end;
end;
constructor TLastSale.Create;
begin
inherited Create;
FItemList := TStringList.Create;
FPaymentList := TStringList.Create;
end;
destructor TLastSale.Destroy;
begin
FItemList.Free;
FPaymentList.Free;
inherited Destroy;
end;
{ TLastSaleItem }
constructor TLastSaleItem.Create;
begin
inherited Create;
FSerialList := TList.Create;
end;
procedure TLastSaleItem.ClearSerialList;
var
i: Integer;
LSIS: TLastSaleItemSerial;
begin
for i := 0 to Pred(FSerialList.Count) do
begin
LSIS := TLastSaleItemSerial(FSerialList[i]);
if LSIS <> nil then
FreeAndNil(LSIS);
end;
FSerialList.Clear;
end;
destructor TLastSaleItem.Destroy;
begin
ClearSerialList;
inherited Destroy;
end;
end.
|
unit uSystemConst;
interface
uses Messages;
const
//SOFTVAR CONST
PDV_MD5 = '00fe96bc61c96a87414ab6874098b584';
//Main Retail Const
STORE_MARK = '#STORE_ACCESS_LIST#';
TEMP_TABLE = '*TempTable*';
REGISTRY_PATH = 'SOFTWARE\Applenet\MainRetail';
REPORT_FILE = 'MainReport.exe';
MRREPORT_FILE = 'MRReport.exe';
MR_BRW_REG_PATH = '\SOFTWARE\RetailSystems\MainRetail\CurrentViews\';
MR_IMP_EXP_REG_PATH = '\SOFTWARE\RetailSystems\ImportExport\CurrentViews\';
PET_BRW_REG_PATH = '\SOFTWARE\RetailSystems\MRPet\CurrentViews\';
PAPER_TYPE_4A = 0;
PAPER_TYPE_80COL = 1;
EMPRESA_DEFAULT = 0;
MEDIA_TYPE_TOURGROUP = 1;
MEDIA_TYPE_GUIDE = 2;
XPRESS_SALE_RETAIL = 0;
XPRESS_SALE_SUPERMARKET = 1;
XPRESS_SALE_RETAIL2 = 2;
TAX_MODE_MANAGER = 1;
TAX_MODE_SALEPERSON = 2;
TAX_MODE_AUTO = 3;
//Inventory Count
INV_COUNT_CYCLE = 1;
INV_COUNT_PHYSICAL = 2;
INV_COUNT_LIVE = 3;
INV_COUNT_STARTUP = 4;
//Payments
FORM_OF_PAYMENT_NOW = 0;
FORM_OF_PAYMENT_LATER = 1;
PARAM_START_LAYAWAY = 'start_layaway';
PARAM_START_INVENT_ADJST = 'start_inv_adjst';
TYPE_VENDORID = 1;
TYPE_GUIDEID = 2;
TYPE_AGENCYID = 3;
REQ_TYPE_SALESPERSON = 'P';
REQ_TYPE_COMPUTER = 'C';
REQ_TYPE_BUYER = 'B';
REQ_STATUS_ONREQUEST = 'R';
REQ_STATUS_ONORDER = 'O';
REQ_STATUS_ONARRIVED = 'A';
SQL_STATUS_NO_CONNECTED = 'Not connected';
SQL_STATUS_CONNECTED = 'Connected';
SQL_STATUS_ERROR = 'Connection error';
HIST_RETAIL = 1;
HIST_COST = 2;
HIST_MARKUP = 3;
HIST_GROSS = 4;
HIST_PROFIT = 5;
DRAW_KICK_TYPE_SALE = 1;
DRAW_KICK_TYPO_CLOSE_REG = 2;
DRAW_KICK_TYPO_WIDRAW = 3;
DRAW_KICK_TYPO_PETTY_CASH = 4;
DRAW_KICK_TYPO_NO_SALE = 5;
DRAW_KICK_TYPO_OPEN_CASH = 6;
PESSOA_TIPO_CLIENTE = 1;
PESSOA_TIPO_FORNECEDOR = 2;
PESSOA_TIPO_COMISSIONADO = 3;
PESSOA_TIPO_VENDEDOR = 4;
PESSOA_TIPO_GUIA = 5;
PESSOA_TIPO_AGENCIA = 6;
PESSOA_TIPO_FABRICANTE = 7;
SALE_PRESALE = 0;
SALE_CASHREG = 1;
SALE_INVOICE = 2;
SALE_UNLOCK_PRESALE = 3;
SALE_SPLIT_PRESALE = 4;
SALE_MOVE_PRESALE = 5;
SALE_CANCELED = 6;
USER_TYPE_ADMINISTRATOR = 1;
USER_TYPE_MANAGER = 2;
USER_TYPE_ASSIST_MANAGER = 6; // ** Ivanil
USER_TYPE_CASHIER = 3; // ** Ivanil
USER_TYPE_CASHIER_PO = 5; // ** Ivanil
REC_INVOICE = 1;
REC_SLIP = 2;
PAY_TYPE_CASH = 1;
PAY_TYPE_VISA = 2;
PAY_TYPE_AMERICAN = 3;
PAY_TYPE_MASTER = 4;
PAY_TYPE_CHECK = 5;
// from tipo ( field ) in table MeioPag related to type of payment screen ( label type )
PAYMENT_TYPE_CASH = 1;
PAYMENT_TYPE_CARD = 2;
PAYMENT_TYPE_OTHER = 3;
PAYMENT_TYPE_CHECK = 4;
PAYMENT_TYPE_CREDIT = 5;
PAYMENT_TYPE_GIFTCARD = 6;
PAYMENT_TYPE_DEBIT = 7;
PAYMENT_TYPE_BONUSBUCK = 8;
PAYMENT_TYPE_STOREACCOUNT = 9;
//amfsouza 10.18.2011 - Others gift cards to be processed.
PAYMENT_TYPE_GIFTCARD_OTHERS = 10;
PAYMENT_PLACE_LOJA = 0;
PAYMENT_PLACE_CONTRAENTREGA = 1;
PAYMENT_PLACE_OUTROS = 2;
PAYMENT_PLACE_EMPTY = 3;
DELIVER_TYPE_ONHAND = 1;
LANC_TYPE_SALE = 1;
LANC_TYPE_BUY = 2;
ST_CASHREG_OPEN = 1;
ST_CASHREG_CLOSE = 2;
ST_CASHREG_CONF = 3;
TIPODOC_SALE = 1;
TIPODOC_BUY = 2;
TIPODOC_TRANSF = 3;
TIPODOC_PEDSALE = 4;
MOV_TYPE_SALE = 1;
MOV_TYPE_BUY = 2;
MOV_TYPE_ADJUST = 3;
PARAM_TAX = 1;
PARAM_SALEONNEGATIVE = 2;
PARAM_FASTSALE = 3;
PARAM_REFRESHONINSERT = 4;
PARAM_REFRESHINTERVAL = 5;
PARAM_REFRESHBROWSE = 6;
PARAM_MAXROWS = 7;
PARAM_MODIFYCOST = 8;
PARAM_CASHREGRESTANT = 9;
PARAM_LICENSE = 10;
PARAM_MAXCASHALLOWED = 11;
PARAM_CLOSECASHRANDOM = 12;
PARAM_MAXQTYCOMPUTERREQ = 13;
PARAM_MINSALECOMPUTERREQ = 14;
PARAM_INCLUDEPREPURCHASE = 15;
PARAM_ANYONEMANAGECASHREG = 31;
PARAM_SHOWTABNOCUSTUMERREGISTER = 32;
PARAM_SHOWTABCUSTUMERREGISTER = 33;
PARAM_SHOWTABTOURGROUP = 34;
PARAM_COMMISSIONBONUS = 35;
PARAM_SHOWNAME_NOREGISTERCUSTUMER = 36;
PARAM_MAX_WORKING_HOUR_PER_DAY = 37;
PARAM_SHOW_PRICE_PRE_RECEIVE = 38;
PARAM_SHOW_MENU_ICONS = 39;
PARAM_SHOW_LAYAWAY_CR_HIST = 41;
PARAM_SHOW_LAYAWAY_INVOICE_HIST = 40;
PARAM_PRINT_DEPOSIT = 42;
PARAM_SHOWTABLAYAWAY = 43;
PARAM_CHECKSERIALNUMBER = 44;
PARAM_MARKUPOVERCOST = 45;
PARAM_PRINT_ON_OPENCASHREG = 46;
PARAM_NUM_ITEM_TO_PRINT = 47;
PARAM_DISPLAY_PRE_DATADO = 48;
PARAM_CONFIRM_DELIVERY_ON_SALE = 49;
PARAM_DISPLAY_PAYMENT_PLACE = 50;
PARAM_ENTER_LAYAWAY_FULL_AMOUNT = 51;
PARAM_INVOICE_SHOW_TAB_OTHER_COSTS = 52;
PARAM_INVOICE_SHOW_TAB_PAYMENTS = 53;
PARAM_INVOICE_SHOW_TAB_AGENTS = 54;
PARAM_INVOICE_SHOW_TAB_DELIVERY = 55;
PARAM_INVOICE_SHOW_TAB_DEPOSIT_DATE = 56;
PARAM_INVOICE_SHOW_TAB_DISCOUNT = 57;
PARAM_MAX_NUMBER_PAYMENTS = 58;
PARAM_CONSULTA_SERASA = 59;
PARAM_CONSULTA_ZIPCODE = 60;
PARAM_MAX_NUMBER_DAYS_PAYING_NOW = 61;
PARAM_CONFIRM_DELIVERY_AFTER_FINISH_SALE = 62;
PARAM_SALE_SCREEN_TYPE = 63;
PARAM_TAX_EXEMPT_ON_SALE = 64;
PARAM_DISPLAY_QTY_FLOATING = 65;
PARAM_TAX_IN_COSTPRICE = 66;
PARAM_PETSHOP_OPTIONS = 67;
PARAM_USE_ESTIMATED_COST = 68;
PARAM_MARK_DELIVERY_HOUR = 69;
PARAM_DISPLAY_CUSTOMER_INFO = 70;
PARAM_VERIFY_PGTO_BEFORE_DELIVERY = 71;
PARAM_TAX_COST_USE_MARKUP_ON_COST = 72;
PARAM_PUPPY_TRACKER_INTEGRATION = 73;
PARAM_ASK_PASSWORD_BEFORE_OPEN_SOFTWARE = 74;
PARAM_CALC_MARGIN = 75;
PARAM_CALC_ROUNDING = 76;
PARAM_REMOVE_BARCODE_DIGIT = 77;
PARAM_SEARCH_MODEL_AFTER_BARCODE = 78;
PARAM_AUTO_GENERATE_MODEL = 79;
PARAM_APPLY_PROMO_ON_SALE = 80;
PARAM_PROMPT_COMMISSIONER_ON_SALE = 81;
PARAM_SALECODE_ON_CREATE_SALE = 82;
PARAM_TREAT_HOLD_AS_INVOICE = 83;
PARAM_SEND_ITEM_FOR_TRASH = 84;
PARAM_USE_FRACTIONARY_QTY = 85;
PARAM_GIFT_EXP_DATE = 86;
PARAM_PROGRESSIVE_QTY_DISCOUNT = 87;
PARAM_USE_CATALOG = 88;
PARAM_ASK_SALEPRICE = 89;
PARAM_MIN_BARCODE_LENGTH = 90;
PARAM_PETCENTER_INTEGRATION = 91;
PARAM_APPLY_BONUS_ON_SALE = 92;
PARAM_CREATE_SUBCATEGORY_ON_IMPORT = 93;
PARAM_LIMIT_LAYAWAY_ON_MONTH = 94;
PARAM_VALIDATE_CASE_QTY_ON_HOLD = 95;
PARAM_APPLY_INV_DISCOUNT_ON_ITEMS = 96;
PARAM_USE_PRICE = 97;
PARAM_USE_IDENT_NUMBER_SERIAL = 98;
PARAM_CALC_COMMISSION_ON_INVOICE = 99;
PARAM_AUTO_GENERATE_TRANSF = 100;
PARAM_CALC_COMM_ON_PAID_HOLD = 101;
PARAM_SAVE_UNPOSTED_PAYMENT_ON_CLOSE = 102;
PARAM_DISABLE_INCREASE_PRICE = 103;
PARAM_INVOICE_SHOW_TAB_COMPLEMENT = 104;
PARAM_UPDATE_BUDGET_PRICE = 105;
PARAM_CONFIRM_BUDGET = 106;
PARAM_AUTO_GENERATE_PUR_DOC = 107;
PARAM_DISABLE_FREIGHT_OTHERCOST = 108;
PARAM_REMOVE_REMINDED_PO = 109;
PARAM_SO_TYPE = 110;
PARAM_DISABLE_SO_DEFECTS = 111;
PARAM_USE_LOT_CONTROL = 112;
PARAM_INV_RETURN_WITH_STORECREDIT_ONLY = 113;
PARAM_PURCHASE_HIST_BACK_MONTH = 114;
PARAM_SALE_REPEAT_CUSTOMER_SALESPERSON = 115;
PARAM_ENABLE_INDUSTRY_OPTION = 116;
//amfsouza 06.03.2011
PARAM_INCREASE_SELLINGPRICE_ONLY = 117;
//Antonio 03/20/2017
PARAM_RECALCULATE_DISCOUNT_EACH_ITEM = 118;
PARAM_ASK_MEDIA_FILES = 119;
PO_ONTIME = 0;
PO_ONTIME_ARRIVED = 1;
PO_ONDELAY = 2;
PO_ONDELAY_ARRIVED = 3;
PO_ALL = 4;
PO_ALL_ARRIVED = 5;
CASHREG_OPEN = 0;
CASHREG_CLOSE = 1;
CASHREG_ERROR = 2;
TRIAL_LIMIT = 6000;
CASHREG_TYPE_POS = 1;
CASHREG_TYPE_OFFICE = 2;
CASHREG_TYPE_FULL_POS = 3;
CASHREG_TYPE_SHIPPING = 4;
TAX_OP_TYPE_SALE = 1;
TAX_OP_TYPE_PURCHASE = 2;
SALE_TAX_TYPE_CHARGE = 1;
SALE_TAX_TYPE_GOV = 2;
PURCHASE_PRE = 1;
PURCHASE_FINAL = 2;
PURCHASE_HISTORY = 3;
//Update Pack 3
SQL_REG_PATH = 'Software\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion';
SQL_GO = 'GO';
//Main Retail ID fields
MR_INVENTORY_MOV_ID = 'InventoryMov.IDInventoryMov';
MR_GROUP_COST_ID = 'GroupCost.IDCost';
MR_TIME_CONTROL_ID = 'TMC_TimeControl.IDTime';
MR_MODEL_ID = 'Model.IDModel';
MR_PESSOA_ID = 'Pessoa.IDPessoa';
MR_SYSTEMUSER_ID = 'SystemUser.IDUser';
MR_STORE_ID = 'Store.IDStore';
MR_TAX_CATEG_ID = 'TaxCategory.IDTaxCategory';
MR_CASH_REG_ID = 'CashRegister.IDCashRegister';
MR_CATEGORY_ID = 'TabGroup.IDGroup';
MR_REQUEST_ID = 'Request.IDRequest';
MR_PRESALE_ID = 'Invoice.IDPreSale';
MR_APPHISTORY_ID = 'Sis_AppHistory.IDHistory';
MR_PURCHASE_ITEM_ID = 'Pur_PurchaseItem.IDPurchaseItem';
MR_PURCHASE_ITEM_SN_ID = 'Pur_PurchaseItemSerial.IDPurchaseItemSerial';
MR_REP_FOLDER_ID = 'Rep_Folder.FolderId';
MR_REP_ITEM_ID = 'Rep_Item.ItemId';
MR_INV_FEATURE_ID = 'InvFeatures.IDInvFeatures';
MR_INV_TECH_FEATURE_ID = 'InvTechFeatures.IDInvTechFeatures';
MR_INV_CUSTOMER_CREDIT_ID = 'CustomerCredit.IDCustomerCredit';
MR_INV_ESTIMATED_ID = 'Estimated.IDEstimated';
MR_INV_ESTIMATED_ITEM_ID = 'EstimatedItem.IDEstimatedItem';
MR_PURCHASE_VENDOR_TAX_ID = 'VendorTax.IDVendorTax';
MR_INVOICE_OBS_ID = 'InvoiceOBS.IDInvoiceOBS';
MR_VENDOR_MODEL_CODE = 'VendorModelCode.IDVendorModelCode';
MR_STORE_VENDOR_ACCOUNT = 'Mnt_StoreVendorAccount.IDStoreVendorAccount';
MR_DEFECT_TYPE_ID = 'DefectType.IDDefectType';
MR_MODEL_RECEIPT_ID = 'Inv_ModelReceipt.IDModelReceipt';
MR_MODEL_TRANSFER_DET_ID = 'ModelTransfDet.IDModelTransfDet';
MR_MODEL_TRANSF_SERIAL_ID = 'ModelTransfSerial.IDModelTransfSerial';
APPLENET_REGISTRY_KEY = 'SOFTWARE\AppleNet';
//Replication Server
SYSTEM_STANDALONE_TYPE = 'STAND_ALONE';
SYSTEM_SERVER_TYPE = 'SERVER';
SYSTEM_CLIENT_TYPE = 'CLIENT';
//Detail
TICKET_MODEL = '[MODEL]';
TICKET_DESCRIPTION = '[DESCRIPTION]';
TICKET_SP = '[SP]';
TICKET_SPN = '[SP_#]';
TICKET_BARCODE = '[BARCODE]';
TICKET_SERIALNUMBER = '[SN]';
TICKET_QTY = '[QTY]';
TICKET_UNIT_PRICE = '[UNITPRICE]';
TICKET_UNIT_TOTAL = '[UNIT_TOTAL]';
TICKET_UNIT = '[UNIT]';
TICKET_MANUFACTURER = '[MANUFACTURER]';
TICKET_ALIGN_RIGHT = '{> <}';
TICKET_CATEG_TEXT = '[CATNOTE]';
//Header
TICKET_DATE = '[DATE]';
TICKET_TIME = '[TIME]';
TICKET_CUSTOMER = '[CUSTOMER]';
TICKET_MEDIA = '[MEDIA]';
TICKET_CASHIER = '[CASHIER]';
TICKET_HOLD = '[HOLD]';
TICKET_INVOICE = '[INVOICE]';
//Totals
TICKET_NO_TAXABLE = '[NOTAXABLE]';
TICKET_TAXABLE = '[TAXABLE]';
TICKET_TAX = '[TAX]';
TICKET_SUBTOTAL = '[SUBTOTAL]';
TICKET_TOTAL = '[TOTAL]';
TICKET_CASH_RECEIVED = '[CASH]';
TICKET_CHANGE = '[CHANGE]';
TICKET_ITEM_DISCOUNT = '[ITEMDISCOUNT]';
TICKET_DISCOUNT = '[DISCOUNT]';
TICKET_REFUND = '[REFUND]';
TICKET_PAYDATE_TYPE = '[DATE/TYPE/$]';
//Layaway
TICKET_PAYMENT_TOTAL = '[PAYMENT_TOTALS]';
TICKET_PAYMENT_BALANCE = '[PAYMENT_BALANCE]';
COD_GERAL= '_COD_GERAL';
WM_Start = WM_USER+100;
INC_VALUE = '*';
DAY_ADJUST = 1 -(1/86400);
ORDER_AUTO = -1;
ORDER_ASC = 0;
ORDER_DESC = 1;
QuitacaoMeioTipo_Especie = 1;
QuitacaoMeioTipo_Cartao = 2;
QuitacaoMeioTipo_Outros = 3;
QuitacaoMeioTipo_Cheque = 4;
SIS_IDMOEDA_PADRAO = 4;
SIS_IDMOEDACOTACAO_PADRAO = 6;
ffValor = '#,##0.00;-#,##.00;0.00';
ffQtde = '#,##0.00;-#,##.00;0.00';
ffDataHora = 'ddddd hh:mm';
ffHora = '#,##0.0;-#,##.0;0.0';
ffPerc = '#,##0.00 %';
fdSQLDate = 'yyyymmdd';
MaxModulos = 200;
//Main menu navigator
WEB_PRIOR = 0;
WEB_NEXT = 1;
// Constantes do MainRetail Copatibilidade
SUGG_CLASS = 'CLASS';
SUGG_NAME = 'NAME';
SUGG_VALUE = 'VALUE';
QUICK_REP_TOTALSALES = 1;
QUICK_REP_ITEMSHOLD = 2;
QUICK_REP_ITEMSPO = 3;
// Model Types
MODEL_TYPE_MASTER = 'M';
MODEL_TYPE_SUB = 'S';
MODEL_TYPE_REGULAR = 'R';
MODEL_TYPE_SERVICE = 'V';
MODEL_TYPE_CREDIT = 'C';
MODEL_TYPE_PACKAGE = 'K';
MODEL_TYPE_GIFTCARD = 'G';
//Purchase Fomrula
PUR_COST = 'c';
PUR_FREIGHT = 'f';
PUR_OTHER = 'o';
PUR_PERCENT = 'p';
PUR_MVA = 'm';
PUR_DISCOUNT = 'd';
PUR_TYPE_INVOICE = 'Invoice';
PUR_TYPE_PACKING_SLIP = 'Packing Slip';
PUR_TYPE_COD = 'C.O.D';
//InvMovType
INV_MOVTYPE_SALE = 1;
INV_MOVTYPE_BOUGHT = 2;
INV_MOVTYPE_DECREASEONHAND = 3;
INV_MOVTYPE_INCREASEONHAND = 4;
INV_MOVTYPE_RESETUPTOZERO = 11;
INV_MOVTYPE_RESETDOWNTOZERO = 12;
INV_MOVTYPE_PHYSICALINCREASE = 21;
INV_MOVTYPE_PHYSICALDECREASE = 22;
//PromoType
PROMO_TYPE_SALE = 1;
PROMO_TYPE_FREQUENTBUYER = 2;
PROMO_TYPE_COUPON = 3;
PROMO_TYPE_LOYALTY = 4;
// Antonio 2014 Jul 24
// New Promo Types
NEW_PROMO_TYPE_COUPON = 0;
NEW_PROMO_TYPE_PROMO = 1;
{ some types are disabled until all type of promo be implemented by new sps.}
// Antonio 2014 Jul 24
// Amount Types
NEW_PROMO_SALE_PRICE = 0;
NEW_PROMO_QUANTITY = 9; // disabled ( was 1 )
NEW_PROMO_AMOUNT_OFITEM = 1; // replaced ( was 2 )
NEW_PROMO_AMOUNT_OFSUBTOTAL = 8; // disabled ( was 3 )
NEW_PROMO_PERCENT_OFITEM = 2; // replaced ( was 4 )
NEW_PROMO_PERCENT_OFSUBTOTAL = 7; // disabled ( was 5 )
//DiscountType
DISCOUNT_PROMO_TYPE_PERCENTUAL = 1;
DISCOUNT_PROMO_TYPE_VALUE = 2;
DISCOUNT_PROMO_TYPE_QTY = 3;
DISCOUNT_PROMO_TYPE_SALE = 4;
//InvoiceOBS Type
INVOICE_OBS_TYPE_PAYMENT = 1;
INVOICE_OBS_TYPE_CUSTOMER = 2;
INVOICE_OBS_TYPE_SALESPERSON = 3;
//PO
PO_FILE_DIR = 'POFiles\';
//Credit CardProcessor
//PROCESSOR_PCCHARGE = 1;
NO_PROCESSOR = 0;
PROCESSOR_MERCURY = 1;
PROCESSOR_WORLDPAY = 2;
//PROCESSOR_EMV = 4;
// Processing Type
PROCESSING_TYPE_MANUAL_CHARGE = 0;
PROCESSING_TYPE_DSICLIENTX = 1;
PROCESSING_TYPE_DSIPDCX = 2;
PROCESSING_TYPE_DSIEMVUS = 3;
IMPORT_TYPE_PO = 1;
IMPORT_TYPE_PET = 2;
IMPORT_TYPE_COSTUMER = 3;
IMPORT_TYPE_VENDOR = 4;
IMPORT_TYPE_COMMISSIONED = 5;
IMPORT_TYPE_SALESMAN = 6;
IMPORT_TYPE_GUIDES = 7;
IMPORT_TYPE_AGENCY = 8;
IMPORT_TYPE_MANUFACTORER = 9;
IMPORT_TYPE_ANOTHER = 10;
IMPORT_TYPE_PROSPECTS = 11;
IMPORT_TYPE_INVENTORY = 12;
{ Alex 03/04/2011 }
IMPORT_TYPE_VC = 13;
EXPORT_TYPE_PO = 1;
EXPORT_TYPE_QBOOKS = 2;
EXPORT_TYPE_PEACHTREE = 3;
//TAX TYPE
TAX_NENHUMA = 0;
TAX_TRIBUTAVEL = 1;
TAX_NAOTRIBUTAVEL = 2;
TAX_SUBSTITUICAO = 3;
TAX_ISENTO = 4;
TAX_ISS = 5;
// Antonio 2013 Dec 04 - Type of promo
PROMO_COUPON_TYPE = 1;
PROMO_FREQBUYER_TYPE = 2;
PROMO_LOYALTY_TYPE = 3;
PROMO_SALE_TYPE = 4;
// Antonio 2013 Dec 05 - Type of discount to promo
PROMO_DISCOUNT_AMOUNT = 1;
PROMO_DISCOUNT_PERCENT = 2;
PROMO_DISCOUNT_QTY = 3;
PROMO_DISCOUNT_SALE = 4;
implementation
end.
|
unit DataConnection;
interface
uses
Aurelius.Drivers.Interfaces,
Aurelius.SQL.MySql,
Aurelius.Schema.MySql,
Aurelius.Drivers.MyDac,
System.SysUtils,
System.Classes, Data.DB, DBAccess, MyAccess;
type
TMyDacConnection = class(TDataModule)
Connection: TMyConnection;
private
public
class function CreateConnection: IDBConnection;
class function CreateFactory: IDBConnectionFactory;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses
Aurelius.Drivers.Base;
{$R *.dfm}
{ TMyConnectionModule }
class function TMyDacConnection.CreateConnection: IDBConnection;
var
DataModule: TMyDacConnection;
begin
DataModule := TMyDacConnection.Create(nil);
Result := TMyDacConnectionAdapter.Create(DataModule.Connection, 'MySql', DataModule);
end;
class function TMyDacConnection.CreateFactory: IDBConnectionFactory;
begin
Result := TDBConnectionFactory.Create(
function: IDBConnection
begin
Result := CreateConnection;
end
);
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uSimpleServer;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls, System.Math,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, Spin, ExtCtrls, Math,
{$ENDIF}
uCEFInterfaces, uCEFServerComponent, uCEFTypes, uCEFMiscFunctions;
type
TSimpleServerFrm = class(TForm)
CEFServerComponent1: TCEFServerComponent;
ButtonPnl: TPanel;
ConnectionLogMem: TMemo;
AddressLbl: TLabel;
AddressEdt: TEdit;
PortLbl: TLabel;
PortEdt: TSpinEdit;
BacklogLbl: TLabel;
BacklogEdt: TSpinEdit;
StartBtn: TButton;
StopBtn: TButton;
procedure StartBtnClick(Sender: TObject);
procedure AddressEdtChange(Sender: TObject);
procedure CEFServerComponent1ServerCreated(Sender: TObject;
const server: ICefServer);
procedure CEFServerComponent1ServerDestroyed(Sender: TObject;
const server: ICefServer);
procedure CEFServerComponent1ClientConnected(Sender: TObject;
const server: ICefServer; connection_id: Integer);
procedure CEFServerComponent1ClientDisconnected(Sender: TObject;
const server: ICefServer; connection_id: Integer);
procedure StopBtnClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
procedure CEFServerComponent1HttpRequest(Sender: TObject;
const server: ICefServer; connection_id: Integer;
const client_address: ustring; const request: ICefRequest);
protected
FClosing : boolean;
function BufferToString(const aBuffer : TBytes) : string;
procedure ShowRequestInfo(const aRequest : ICefRequest);
procedure ShowPostDataInfo(const aPostData : ICefPostData);
public
{ Public declarations }
end;
var
SimpleServerFrm: TSimpleServerFrm;
implementation
{$R *.dfm}
// Server capacity is limited and is intended to handle only a small number of
// simultaneous connections (e.g. for communicating between applications on localhost).
// To test it follow these steps :
// 1- Build and run this demo.
// 2- Click on the Start button.
// 3- Open your web browser and visit this address http://127.0.0.1:8099
// 4- You should see some connection details in the server log and a "Hellow world" text in your web browser.
procedure TSimpleServerFrm.AddressEdtChange(Sender: TObject);
begin
if not(CEFServerComponent1.IsRunning) then
StartBtn.Enabled := (length(trim(AddressEdt.Text)) > 0);
end;
procedure TSimpleServerFrm.StartBtnClick(Sender: TObject);
begin
if (length(trim(AddressEdt.Text)) > 0) then
CEFServerComponent1.CreateServer(AddressEdt.Text, PortEdt.Value, BacklogEdt.Value);
end;
procedure TSimpleServerFrm.StopBtnClick(Sender: TObject);
begin
CEFServerComponent1.Shutdown;
end;
procedure TSimpleServerFrm.CEFServerComponent1ClientConnected(
Sender: TObject; const server: ICefServer; connection_id: Integer);
begin
ConnectionLogMem.Lines.Add('Client connected : ' + inttostr(connection_id));
end;
procedure TSimpleServerFrm.CEFServerComponent1ClientDisconnected(
Sender: TObject; const server: ICefServer; connection_id: Integer);
begin
ConnectionLogMem.Lines.Add('Client disconnected : ' + inttostr(connection_id));
end;
procedure TSimpleServerFrm.CEFServerComponent1HttpRequest(Sender: TObject;
const server: ICefServer; connection_id: Integer;
const client_address: ustring; const request: ICefRequest);
var
TempData : string;
TempParts : TUrlParts;
begin
ConnectionLogMem.Lines.Add('---------------------------------------');
ConnectionLogMem.Lines.Add('HTTP request received from connection ' + inttostr(connection_id));
ConnectionLogMem.Lines.Add('Client address : ' + client_address);
ShowRequestInfo(request);
ConnectionLogMem.Lines.Add('---------------------------------------');
if (request <> nil) and CefParseUrl(Request.URL, TempParts) then
begin
if (TempParts.path = '') or (TempParts.path = '/') then
begin
TempData := 'Hello world from Simple Server';
CEFServerComponent1.SendHttp200response(connection_id, 'text/html', @TempData[1], length(TempData) * SizeOf(char));
end
else
CEFServerComponent1.SendHttp404response(connection_id);
end
else
CEFServerComponent1.SendHttp404response(connection_id);
end;
procedure TSimpleServerFrm.ShowRequestInfo(const aRequest : ICefRequest);
begin
if (aRequest = nil) then exit;
ConnectionLogMem.Lines.Add('Request URL : ' + aRequest.URL);
ConnectionLogMem.Lines.Add('Request Method : ' + aRequest.Method);
if (length(aRequest.ReferrerUrl) > 0) then
ConnectionLogMem.Lines.Add('Request Referrer : ' + aRequest.ReferrerUrl);
ShowPostDataInfo(aRequest.PostData);
end;
procedure TSimpleServerFrm.ShowPostDataInfo(const aPostData : ICefPostData);
var
i, j : integer;
TempLen : NativeUInt;
TempList : IInterfaceList;
TempElement : ICefPostDataElement;
TempBytes : TBytes;
begin
if (aPostData = nil) then exit;
i := 0;
j := aPostData.GetCount;
TempList := aPostData.GetElements(j);
while (i < j) do
begin
TempElement := TempList.Items[i] as ICefPostDataElement;
if (TempElement.GetBytesCount > 0) then
begin
SetLength(TempBytes, TempElement.GetBytesCount);
TempLen := TempElement.GetBytes(TempElement.GetBytesCount, @TempBytes[0]);
if (TempLen > 0) then
begin
ConnectionLogMem.Lines.Add('Post contents length : ' + inttostr(TempLen));
ConnectionLogMem.Lines.Add('Post contents sample : ' + BufferToString(TempBytes));
end;
end;
inc(i);
end;
end;
function TSimpleServerFrm.BufferToString(const aBuffer : TBytes) : string;
var
i, j : integer;
begin
Result := '';
i := 0;
j := min(length(aBuffer), 5);
while (i < j) do
begin
Result := Result + IntToHex(aBuffer[i], 2);
inc(i);
end;
end;
procedure TSimpleServerFrm.CEFServerComponent1ServerCreated(Sender: TObject; const server: ICefServer);
begin
if CEFServerComponent1.Initialized then
begin
ConnectionLogMem.Lines.Add('Server created');
StartBtn.Enabled := False;
StopBtn.Enabled := True;
end
else
ConnectionLogMem.Lines.Add('Server creation error!');
end;
procedure TSimpleServerFrm.CEFServerComponent1ServerDestroyed(Sender: TObject; const server: ICefServer);
begin
if FClosing then
PostMessage(Handle, WM_CLOSE, 0, 0)
else
begin
ConnectionLogMem.Lines.Add('Server destroyed');
StartBtn.Enabled := True;
StopBtn.Enabled := False;
end;
end;
procedure TSimpleServerFrm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if CEFServerComponent1.Initialized then
begin
CanClose := False;
FClosing := True;
Visible := False;
CEFServerComponent1.Shutdown;
end
else
CanClose := True;
end;
procedure TSimpleServerFrm.FormCreate(Sender: TObject);
begin
FClosing := False;
end;
end.
|
unit Dmitry.Graphics.Utils;
interface
uses
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Graphics.Types;
const
CHalf64: Double = 0.5;
MaxBrushRadius = 250;
type
TBrushToDraw = record
Mask: array [-MaxBrushRadius .. MaxBrushRadius, -MaxBrushRadius .. MaxBrushRadius] of Boolean;
TransMask: array [-MaxBrushRadius .. MaxBrushRadius, -MaxBrushRadius .. MaxBrushRadius] of Byte;
end;
procedure StretchCoolEx0(X, Y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
procedure StretchCoolEx90(X, Y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
procedure StretchCoolEx180(X, Y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
procedure StretchCoolEx270(X, Y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
procedure FlipHorizontal(S, D: TBitmap);
procedure FlipVertical(S, D: TBitmap);
procedure XFillRect(X, Y, Width, Height: Integer; D: TBitmap; Color: TColor);
procedure StretchCoolW(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap);
procedure StretchCoolW32(X, Y, Width, Height: Integer; Rect: TRect; S, D: TBitmap; Mode: Integer = 0);
procedure StretchCoolW24To32(X, Y, Width, Height: Integer; Rect: TRect; S, D: TBitmap; Transparencity: Byte = 255);
procedure StretchCoolWTransparent(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap; T: Integer;
UseFirstColor: Boolean = False);
procedure StretchFast(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap); overload;
procedure StretchFast(X, Y, Width, Height: Integer; Rect: TRect; var S, D: PARGBArray); overload;
procedure StretchFastA(X, Y, SWidth, SHeight, DWidth, DHeight: Integer; var S, D: PARGBArray);
procedure StretchFastATrans(X, Y, SWidth, SHeight, DWidth, DHeight: Integer; var S: PARGB32Array; var D: PARGBArray;
Transparency: Extended; Effect: Integer = 0);
procedure StretchFastATransW(X, Y, Width, Height: Integer; Rect: TRect; var S: PARGB32Array; var D: PARGBArray;
Transparency: Extended; Effect: Integer = 0);
procedure CreateBrush(var Brush: TBrushToDraw; Radius: Integer);
procedure DoBrush(Image: PARGB32Array; Brush: TBrushToDraw; W, H: Integer; X_begin, Y_begin, X_end, Y_end: Integer;
R, G, B: Byte; Radius: Integer; Effect: Integer = 0);
procedure DrawCopyRightA(B: TBitmap; BkColor: TColor; Text: string);
procedure CoolDrawText(Bitmap: Tbitmap; X, Y: Integer; Text: string; Coolcount: Integer; Coolcolor: Tcolor);
procedure FillRectNoCanvas(B: TBitmap; Color: TColor);
function FastTrunc(const Value: Double): Integer; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure HightliteBitmap(B: TBitmap);
implementation
procedure FillRectNoCanvas(B: TBitmap; Color: TColor);
var
I, J: Integer;
Xdp: array of PARGB;
Rc, Gc, Bc: Byte;
begin
Color := ColorToRGB(Color);
rc := GetRValue(Color);
gc := GetGValue(Color);
bc := GetBValue(Color);
SetLength(Xdp, B.height);
for I := 0 to B.Height - 1 do
Xdp[I] := B.ScanLine[I];
for I := 0 to B.Height - 1 do
for J := 0 to B.Width - 1 do
begin
Xdp[I, J].R := rc;
Xdp[I, J].G := gc;
Xdp[I, J].B := bc;
end;
end;
procedure XFillRect(X, Y, Width, Height: Integer; D: TBitmap; Color: TColor);
var
I, J: Integer;
Xdp: array of PARGB;
Rc, Gc, Bc: Byte;
begin
Color := ColorToRGB(Color);
Rc := GetRValue(Color);
Gc := GetGValue(Color);
Bc := GetBValue(Color);
D.PixelFormat := pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
SetLength(Xdp, D.Height);
for I := 0 to D.Height - 1 do
Xdp[I] := D.ScanLine[I];
for I := 0 to Y do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y + Height to D.Height - 1 do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := 0 to X do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := X + Width to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
end;
procedure StretchCoolEx0(X, Y, Width, Height : Integer; var S, D : TBitmap; Color : TColor);
var
I, J, K, P, Sheight1, Dheight: Integer;
Col, R, G, B, SWidth1: Integer;
Sh, Sw: Extended;
Xdp, Xsp: array of PARGB;
Rc, Gc, Bc: Byte;
YMin, YMax : Integer;
XAW : array of Integer;
begin
Color := ColorToRGB(Color);
Rc := GetRValue(Color);
Gc := GetGValue(Color);
Bc := GetBValue(Color);
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
Sh := S.Height / Height;
Sw := S.Width / Width;
SWidth1 := S.Width - 1;
Dheight := D.Height;
Sheight1 := S.Height - 1;
SetLength(Xsp, S.Height);
for I := 0 to Sheight1 do
Xsp[I] := S.ScanLine[I];
SetLength(Xdp, D.Height);
for I := 0 to D.Height - 1 do
Xdp[I] := D.ScanLine[I];
for I := 0 to Y do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Y + Height to D.Height - 1 do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := 0 to X do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := X + Width to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Height + Y - 1 do
begin
YMin := Round(Sh * (I - Y));
YMax := Min(S.Height - 1, Round(Sh * (I + 1 - Y)) - 1);
for J := 0 to Width - 1 do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XAW[J] to Min(XAW[J + 1] - 1, SWidth1) do
begin
Inc(Col);
Inc(R, Xsp[K, P].R);
Inc(G, Xsp[K, P].G);
Inc(B, Xsp[K, P].B);
end;
end;
if Col <> 0 then
begin
Xdp[I, J + X].R := R div Col;
Xdp[I, J + X].G := G div Col;
Xdp[I, J + X].B := B div Col;
end;
end;
end;
end;
procedure StretchCoolEx180(x, y, Width, Height : Integer; var S, D : TBitmap; Color : TColor);
var
I, J, K, P, Sheight1, Dheight: Integer;
Col, R, G, B, SWidth1: Integer;
Sh, Sw: Extended;
Xdp, Xsp: array of PARGB;
Rc, Gc, Bc: Byte;
YMin, YMax, _2YHeight1 : Integer;
XAW : array of Integer;
begin
Color := ColorToRGB(Color);
Rc := GetRValue(Color);
Gc := GetGValue(Color);
Bc := GetBValue(Color);
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
Sh := S.Height / Height;
Sw := S.Width / Width;
Dheight := D.Height;
Sheight1 := S.Height - 1;
SWidth1 := S.Width - 1;
SetLength(Xsp, S.Height);
for I := 0 to Sheight1 do
Xsp[I] := S.ScanLine[I];
SetLength(Xdp, D.Height);
for I := 0 to D.Height - 1 do
Xdp[I] := D.ScanLine[I];
for I := 0 to Y do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y + Height to D.Height - 1 do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := 0 to X do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y to Min(Y + Height, D.Height - 1) do
for J := X + Width to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Y to Height + Y - 1 do
begin
YMin := Round(Sh*(i-y));
YMax := Min(S.Height-1,Round(Sh*(i+1-y))-1);
_2YHeight1 := 2 * Y + Height - I - 1;
for J := 0 to Width - 1 do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XAW[J] to Min(XAW[J + 1] - 1, SWidth1) do
begin
Inc(Col);
Inc(R, Xsp[K, P].R);
Inc(G, Xsp[K, P].G);
Inc(B, Xsp[K, P].B);
end;
end;
if Col <> 0 then
begin
Xdp[_2YHeight1, J + X].R := R div Col;
Xdp[_2YHeight1, J + X].G := G div Col;
Xdp[_2YHeight1, J + X].B := B div Col;
end;
end;
end;
end;
procedure StretchCoolEx270(X, Y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
var
I, J, K, P, Sheight1, Dheight: Integer;
Col, R, G, B, SWidth1: Integer;
Sh, Sw: Extended;
Xdp, Xsp: array of PARGB;
Rc, Gc, Bc: Byte;
YMin, YMax: Integer;
XAW: array of Integer;
begin
Color := ColorToRGB(Color);
Rc := GetRValue(Color);
Gc := GetGValue(Color);
Bc := GetBValue(Color);
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
if Height + X > D.Width then
D.Width := Height + X;
if Width + Y > D.Height then
D.Height := Width + Y;
Sh := S.Height / Height;
Sw := S.Width / Width;
Dheight := D.Height;
Sheight1 := S.Height - 1;
SWidth1 := S.Width - 1;
SetLength(Xsp, S.Height);
for I := 0 to Sheight1 do
Xsp[I] := S.ScanLine[I];
SetLength(Xdp, D.Height);
for I := 0 to D.Height - 1 do
Xdp[I] := D.ScanLine[I];
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(SW * I);
for I := 0 to Y do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y + Width to D.Height - 1 do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Max(0, Y) to Min(Y + Width, D.Height - 1) do
for J := 0 to X do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Max(0, Y) to Min(Y + Width, D.Height - 1) do
for J := X + Height to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Max(0, Y) to Height + Y - 1 do
begin
YMin := Round(Sh * (I - Y));
YMax := Min(S.Height - 1, Round(Sh * (I + 1 - Y)) - 1);
for J := 0 to Width - 1 - Max(0, -Y) do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XAW[J] to Min(XAW[J + 1] - 1, SWidth1) do
begin
Inc(Col);
Inc(R, Xsp[K, P].R);
Inc(G, Xsp[K, P].G);
Inc(B, Xsp[K, P].B);
end;
end;
if Col <> 0 then
begin
Xdp[Width - (-Y + J) - 1, X + I - Y].R := R div Col;
Xdp[Width - (-Y + J) - 1, X + I - Y].G := G div Col;
Xdp[Width - (-Y + J) - 1, X + I - Y].B := B div Col;
end;
end;
end;
end;
procedure StretchCoolEx90(x, y, Width, Height: Integer; var S, D: TBitmap; Color: TColor);
var
I, J, K, P, Sheight1, Dheight: Integer;
Col, R, G, B, YC, SWidth1: Integer;
Sh, Sw: Extended;
Xdp, Xsp: array of PARGB;
Rc, Gc, Bc: Byte;
XAW: array of Integer;
YMin, YMax: Integer;
begin
Rc := GetRValue(Color);
Gc := GetGValue(Color);
Bc := GetBValue(Color);
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
if Height + X > D.Width then
D.Width := Height + X;
if Width + Y > D.Height then
D.Height := Width + Y;
Sh := S.Height / Height;
Sw := S.Width / Width;
Dheight := D.Height;
Sheight1 := S.Height - 1;
SWidth1 := S.Width - 1;
SetLength(Xsp, S.Height);
for I := 0 to Sheight1 do
Xsp[I] := S.ScanLine[I];
SetLength(Xdp, D.Height);
for I := 0 to D.Height - 1 do
Xdp[I] := D.ScanLine[I];
for I := 0 to Y do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Y + Width to D.Height - 1 do
for J := 0 to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Max(0, Y) to Min(Y + Width, D.Height - 1) do
for J := 0 to X do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
for I := Max(0, Y) to Min(Y + Width, D.Height - 1) do
for J := X + Height to D.Width - 1 do
begin
Xdp[I, J].R := Rc;
Xdp[I, J].G := Gc;
Xdp[I, J].B := Bc;
end;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Max(0, Y) to Height + Y - 1 do
begin
YMin := Round(Sh * (I - Y));
YMax := Min(S.Height - 1, Round(Sh * (I + 1 - Y)) - 1);
YC := Height - I + X + Y - 1;
for J := Max(-Y, 0) to Width - 1 do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XAW[J] to Min(XAW[J + 1] - 1, SWidth1) do
begin
Inc(Col);
Inc(R, Xsp[K, P].R);
Inc(G, Xsp[K, P].G);
Inc(B, Xsp[K, P].B);
end;
end;
if Col <> 0 then
begin
Xdp[Y + J, YC].R := R div Col;
Xdp[Y + J, YC].G := G div Col;
Xdp[Y + J, YC].B := B div Col;
end;
end;
end;
end;
procedure FlipHorizontal(S, D: TBitmap);
var
I, J: Integer;
PS, PD: PARGB;
SW: Integer;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
SW := S.Width;
D.Width := S.Width;
D.Height := S.Height;
for I := 0 to S.Height - 1 do
begin
PS := S.ScanLine[I];
PD := D.ScanLine[I];
for J := 0 to SW - 1 do
PD[J] := PS[SW - 1 - J];
end;
end;
procedure FlipVertical(S,D : TBitmap);
var
I, J: Integer;
Ps, Pd: PARGB;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Width;
D.Height := S.Height;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
Pd := D.ScanLine[S.Height - 1 - I];
for J := 0 to S.Width - 1 do
Pd[J] := Ps[J];
end;
end;
procedure StretchCoolW24To32(X, Y, Width, Height : Integer; Rect : TRect; S, D : TBitmap; Transparencity: Byte = 255);
var
I, J, K, P: Integer;
P1: PARGB32;
Col, R, G, B, SWidth1Left: Integer;
Sh, Sw: Extended;
XP: array of PARGB;
YMin, YMax: Integer;
XAW: array of Integer;
XAWJ, XAWJ1: Integer;
PS: PARGB;
RGBS: PRGB;
begin
S.PixelFormat := pf24Bit;
D.PixelFormat := pf32Bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
if (Width = 0) or (Height = 0) then
Exit;
Sw := (Rect.Right - Rect.Left) / Width;
Sh := (Rect.Bottom - Rect.Top) / Height;
SWidth1Left := S.Width - 1 - Rect.Left;
SetLength(Xp, S.Height);
for I := 0 to S.Height - 1 do
XP[I] := S.ScanLine[I];
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
YMin := Round(Sh * (I - Y)) + Rect.Top;
YMax := Min(S.Height - 1 - Rect.Top, Round(Sh * (I + 1 - Y)) - 1) + Rect.Top;
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
XAWJ := XAW[J];
XAWJ1 := Min(XAW[J + 1] - 1, SWidth1Left) + Rect.Left;
Col := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1) + Rect.Left;
for K := YMin to YMax do
begin
PS := XP[K];
RGBS := @PS[XAWJ];
for P := XAWJ to XAWJ1 do
begin
Inc(R, RGBS^.R);
Inc(G, RGBS^.G);
Inc(B, RGBS^.B);
Inc(RGBS);
end;
end;
if Col <> 0 then
begin
P1[J + X].R := R div Col;
P1[J + X].G := G div Col;
P1[J + X].B := B div Col;
P1[J + X].L := Transparencity;
end;
end;
end;
end;
procedure StretchCoolW32(X, Y, Width, Height: Integer; Rect: TRect; S, D: TBitmap; Mode: Integer = 0);
var
I, J, K, P: Integer;
P1: PARGB32;
Col, R, G, B, L, SWidth1Left: Integer;
Sh, Sw: Extended;
XP: array of PARGB32;
W, W1: Byte;
YMin, YMax: Integer;
XAW: array of Integer;
XAWJ, XAWJ1: Integer;
PS: PARGB32;
RGBAS: PRGB32;
begin
InitSumLMatrix;
S.PixelFormat := pf32Bit;
D.PixelFormat := pf32Bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
if (Width = 0) or (Height = 0) then
Exit;
Sw := (Rect.Right - Rect.Left) / Width;
Sh := (Rect.Bottom - Rect.Top) / Height;
SWidth1Left := S.Width - 1 - Rect.Left;
SetLength(Xp, S.Height);
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
if MODE = 0 then
begin
for I := 0 to S.Height - 1 do
XP[I] := S.ScanLine[I];
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
YMin := Round(Sh * (I - Y));
YMax := Min(S.Height - 1 - Rect.Top, Round(Sh * (I + 1 - Y)) - 1);
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
L := 0;
XAWJ := XAW[J] + Rect.Left;
XAWJ1 := Min(XAW[J + 1] - 1, SWidth1Left) + Rect.Left;
Col := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS := XP[K];
RGBAS := @PS[XAWJ];
for P := XAWJ to XAWJ1 do
begin
Inc(R, RGBAS^.R);
Inc(G, RGBAS^.G);
Inc(B, RGBAS^.B);
Inc(L, RGBAS^.L);
Inc(RGBAS);
end;
end;
if Col <> 0 then
begin
W := L div Col;
W1 := 255 - W;
P1[J + X].R := (P1[J + X].R * W1 + (R div Col) * W + $7F) div 255;
P1[J + X].G := (P1[J + X].G * W1 + (G div Col) * W + $7F) div 255;
P1[J + X].B := (P1[J + X].B * W1 + (B div Col) * W + $7F) div 255;
P1[J + X].L := SumLMatrix[P1[J + X].L, W];
end;
end;
end;
end else
begin
for I := 0 to S.Height - 1 do
XP[I] := S.ScanLine[I];
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
YMin := Round(Sh * (I - Y)) + Rect.Top;
YMax := Min(S.Height - 1 - Rect.Top, Round(Sh * (I + 1 - Y)) - 1) + Rect.Top;
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
L := 0;
XAWJ := XAW[J] + Rect.Left;
XAWJ1 := Min(XAW[J + 1] - 1, SWidth1Left) + Rect.Left;
Col := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS := XP[K];
RGBAS := @PS[XAWJ];
for P := XAWJ to XAWJ1 do
begin
Inc(R, RGBAS^.R);
Inc(G, RGBAS^.G);
Inc(B, RGBAS^.B);
Inc(L, RGBAS^.L);
Inc(RGBAS);
end;
end;
if Col <> 0 then
begin
P1[J + X].R := R div Col;
P1[J + X].G := G div Col;
P1[J + X].B := B div Col;
P1[J + X].L := L div Col;
end;
end;
end;
end;
end;
procedure StretchCoolW(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap);
var
I, J, K, P: Integer;
P1: Pargb;
Col, R, G, B, SWidth1Left: Integer;
Sh, SW: Extended;
Xp: array of PARGB;
YMin, YMax: Integer;
XAW: array of Integer;
XAWJ, XAWJ1: Integer;
RGBS, RGBD: PRGB;
PS: PARGB;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
if (Width = 0) or (Height = 0) then
Exit;
Sw := (Rect.Right - Rect.Left) / Width;
Sh := (Rect.Bottom - Rect.Top) / Height;
SWidth1Left := S.Width - 1 - Rect.Left;
SetLength(Xp, S.Height);
for I := 0 to S.Height - 1 do
Xp[I] := S.ScanLine[I];
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
RGBD := @P1[X];
YMin := Round(Sh * (I - Y)) + Rect.Top;
YMax := Min(S.Height - 1 - Rect.Top, Round(Sh * (I + 1 - Y)) - 1) + Rect.Top;
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
XAWJ := XAW[J] + Rect.Left;
XAWJ1 := Min(XAW[J + 1] - 1, SWidth1Left) + Rect.Left;
Col := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS := XP[K];
RGBS := @PS[XAWJ];
for P := XAWJ to XAWJ1 do
begin
Inc(R, RGBS^.R);
Inc(G, RGBS^.G);
Inc(B, RGBS^.B);
Inc(RGBS);
end;
end;
if Col <> 0 then
begin
RGBD^.R := R div Col;
RGBD^.G := G div Col;
RGBD^.B := B div Col;
end;
Inc(RGBD);
end;
end;
end;
procedure StretchCoolWTransparent(x, y, Width, Height : Integer; Rect : TRect; var S, D : TBitmap; T : integer; UseFirstColor : Boolean = false);
var
I, J, K, P, Sheight1: Integer;
P1: Pargb;
TC: TRGB;
Col, R, G, B, SWidth1Left: Integer;
Sh, Sw, L: Extended;
Xp: array of PARGB;
W1, W: Byte;
YMin, YMax : Integer;
XAW : array of Integer;
function TrColor(TC: TRGB; R, G, B: Byte): Boolean; inline;
begin
Result := (R = TC.R) and (G = TC.G) and (B = TC.B);
end;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
W := T;
W1 := 255 - T;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
if (Width = 0) or (Height = 0) then
Exit;
Sw := (Rect.Right - Rect.Left) / Width;
Sh := (Rect.Bottom - Rect.Top) / Height;
Sheight1 := (Rect.Bottom - Rect.Top) - 1;
SWidth1Left := S.Width - 1 - Rect.Left;
SetLength(Xp, S.Height);
for I := 0 to S.Height - 1 do
Xp[I] := S.ScanLine[I];
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I);
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
YMin := Round(Sh * (I - Y));
YMax := Min(S.Height - 1 - Rect.Top, Round(Sh * (I + 1 - Y)) - 1);
if I = Y then
TC := P1[0];
for J := 0 to Width - 1 do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XAW[J] to Min(XAW[J + 1] - 1, SWidth1Left) do
begin
Inc(Col);
Inc(R, Xp[K + Rect.Top, P + Rect.Left].R);
Inc(G, Xp[K + Rect.Top, P + Rect.Left].G);
Inc(B, Xp[K + Rect.Top, P + Rect.Left].B);
end;
end;
if Col <> 0 then
begin
if not UseFirstColor or not TrColor(TC, R, G, B) then
begin
P1[J + X].R := (P1[J + X].R * W1 + (R div Col) * W) shr 8;
P1[J + X].G := (P1[J + X].G * W1 + (G div Col) * W) shr 8;
P1[J + X].B := (P1[J + X].B * W1 + (B div Col) * W) shr 8;
end;
end;
end;
end;
end;
procedure StretchFast(x, y, Width, Height : Integer; Rect : TRect; var S, D : TBitmap);
var
I, J, CX, CY: Integer;
P1: pargb;
SH, Sw: Extended;
Xp: array of PARGB;
XAW : array of Integer;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
SW := (Rect.Right - Rect.Left) / Width;
SH := (Rect.Bottom - Rect.Top) / Height;
SetLength(Xp, S.Height);
for I := 0 to S.Height - 1 do
Xp[I] := S.ScanLine[I];
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I) + Rect.Left;
for I := Y to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
CY := Round(SH * (I - Y)) + Rect.Top;
for J := 0 to Width - 1 do
begin
CX := XAW[J];
P1[J + X] := Xp[CY, CX];
end;
end;
end;
procedure StretchFast(X, Y, Width, Height: Integer; Rect: TRect; var S, D: PARGBArray);
var
I, J: Integer;
Sh, Sw: Extended;
Ay, Ax: Integer;
Jx: Integer;
XAW : array of Integer;
begin
Sw := (Rect.Right - Rect.Left) / Width;
Sh := (Rect.Bottom - Rect.Top) / Height;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(Sw * I) + Rect.Left;
for I := Y to Height + Y - 1 do
begin
Ay := Round(Sh * (I - Y)) + Rect.Top;
for J := 0 to Width - 1 do
begin
Ax := XAW[J];
Jx := J + X;
D[I, Jx] := S[Ay, Ax];
end;
end;
end;
procedure StretchFastA(X, Y, SWidth, SHeight, DWidth, DHeight: Integer; var S, D: PARGBArray);
var
I, J, YC, XC: Integer;
Sh, Sw: Extended;
XAW : array of Integer;
begin
Sw := SWidth / DWidth;
Sh := SHeight / DHeight;
SetLength(XAW, DWidth + 1);
for I := 0 to DWidth do
XAW[I] := Round(Sw * I);
for I := Y to DHeight + Y - 1 do
begin
YC := Round(Sh * (I - Y));
for J := 0 to DWidth - 1 do
begin
XC := XAW[J];
D[I, J + X].R := S[YC, XC].R;
D[I, J + X].G := S[YC, XC].G;
D[I, J + X].B := S[YC, XC].B;
end;
end;
end;
procedure StretchFastATrans(X, Y, SWidth, SHeight, DWidth, DHeight: Integer; var S : PARGB32Array; var D : PARGBArray; Transparency : extended; Effect : integer = 0);
var
I, J: Integer;
Sh, Sw : Extended;
XT : array[0..255] of Byte;
AX, AY, JX : Integer;
LL, L, LL1, ld, R, G, B : Byte;
W, W1 : Byte;
WX : Integer;
XAW : array of Integer;
begin
W := Round(Transparency * 255);
W1 := 255 - W;
Sw := SWidth / DWidth;
Sh := SHeight / DHeight;
for I := 0 to 255 do
XT[I] := Round((255 - (255 - I) * Transparency));
SetLength(XAW, DWidth + 1);
for I := 0 to DWidth do
XAW[I] := Round(Sw * I);
if Effect = 0 then
begin
for I := Y to DHeight + Y - 1 do
begin
AY := Round(Sh * (I - Y));
for J := 0 to DWidth - 1 do
begin
AX := XAW[J];
LL := XT[S[AY, AX].L];
JX := J + X;
LL1 := 255 - LL;
D[I, JX].R := (S[AY, AX].R * LL1 + D[I, JX].R * LL) shr 8;
D[I, JX].G := (S[AY, AX].G * LL1 + D[I, JX].G * LL) shr 8;
D[I, JX].B := (S[AY, AX].B * LL1 + D[I, JX].B * LL) shr 8;
end;
end;
end else
begin
for I := Y to DHeight + Y - 1 do
begin
AY := Round(Sh * (I - Y));
for J := 0 to DWidth - 1 do
begin
AX := XAW[J];
JX := J + X;
LD := (D[I, JX].R * 77 + D[I, JX].G * 151 + D[I, JX].B * 28) shr 8;
L := (S[AY, AX].R * 77 + S[AY, AX].G * 151 + S[AY, AX].B * 28) shr 8;
if L >= 2 then
begin
LL := XT[S[AY, AX].L];
if LL = 255 then
Continue;
LL1 := 255 - LL;
WX := (W * LD);
R := Min(255, ((S[AY, AX].R * WX) div L + D[I, JX].R * W1) shr 8);
G := Min(255, ((S[AY, AX].G * WX) div L + D[I, JX].G * W1) shr 8);
B := Min(255, ((S[AY, AX].B * WX) div L + D[I, JX].B * W1) shr 8);
D[I, JX].R := (R * LL1 + D[I, JX].R * LL + $7F) shr 8;
D[I, JX].G := (G * LL1 + D[I, JX].G * LL + $7F) shr 8;
D[I, JX].B := (B * LL1 + D[I, JX].B * LL + $7F) shr 8;
end;
end;
end;
end;
end;
procedure StretchFastATransW(x, y, Width, Height : Integer; Rect : TRect; var S : PARGB32Array; var D : PARGBArray; Transparency : extended; Effect : integer = 0);
var
I, J: Integer;
Sh, Sw: Extended;
XT: array [0 .. 255] of Byte;
Ay, Ax, Jx: Integer;
L, LD, W, W1, LL, LL1, R, G, B: Byte;
WX: Integer;
XAW : array of Integer;
begin
W := Round(Transparency * 255);
W1 := 255 - W;
if (Width = 0) or (Height = 0) then
Exit;
for I := 0 to 255 do
XT[I]:= Round(255 - (255 - I) * Transparency);
SW := (Rect.Right - Rect.Left) / Width;
SH := (Rect.Bottom - Rect.Top) / Height;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Round(SW * I);
if Effect = 0 then
begin
for I := Y to Height + Y - 1 do
begin
AY := FastTrunc(SH * (I - Y)) + Rect.Top;
for J := 0 to Width - 1 do
begin
AX := XAW[J] + Rect.Left;
LL := XT[S[AY, AX].L];
JX := J + X;
LL1 := 255 - LL;
D[I, JX].R := (S[AY, AX].R * LL1 + D[I, JX].R * LL) shr 8;
D[I, JX].G := (S[AY, AX].G * LL1 + D[I, JX].G * LL) shr 8;
D[I, JX].B := (S[AY, AX].B * LL1 + D[I, JX].B * LL) shr 8;
end;
end;
end else
begin
for I := Y to Height + Y - 1 do
begin
AY := FastTrunc(SH * (I - Y)) + Rect.Top;
for J := 0 to Width - 1 do
begin
AX := XAW[J] + Rect.Left;
JX := J + X;
LD := (D[I, JX].R * 77 + D[I, JX].G * 151 + D[I, JX].B * 28) shr 8;
L := (S[AY, AX].R * 77 + S[AY, AX].G * 151 + S[AY, AX].B * 28) shr 8;
if L >= 2 then
begin
LL := XT[S[AY, AX].L];
if LL = 255 then
Continue;
LL1 := 255 - LL;
WX := (W * LD);
R := Min(255, ((S[AY, AX].R * WX) div L + D[I, JX].R * W1) shr 8);
G := Min(255, ((S[AY, AX].G * WX) div L + D[I, JX].G * W1) shr 8);
B := Min(255, ((S[AY, AX].B * WX) div L + D[I, JX].B * W1) shr 8);
D[I, JX].R := (R * LL1 + D[I, JX].R * LL) div $FF;
D[I, JX].G := (G * LL1 + D[I, JX].G * LL) div $FF;
D[I, JX].B := (B * LL1 + D[I, JX].B * LL) div $FF;
end;
end;
end;
end;
end;
procedure CreateBrush(var Brush : TBrushToDraw; Radius : Integer);
var
I, J: Integer;
X1, X2, Rd2: Integer;
X3: Extended;
begin
Rd2 := Radius div 2;
X2 := Max(1, Sqr(Rd2));
X3 := X2 / Sqrt(255);
for I := -Rd2 to Rd2 do
begin
for J := -Rd2 to Rd2 do
begin
X1 := Sqr(I) + Sqr(J);
Brush.Mask[J, I] := False;
if X1 <= X2 then
begin
Brush.Mask[J, I] := True;
Brush.TransMask[J, I] := Round(Sqr(X1 / X3));
end;
end;
end;
end;
procedure DoPoint(const Brush : TBrushToDraw; S : PARGB32Array; w,h : integer; x, y : integer; r,g,b: byte; Radius : Integer; Effect : integer = 0);
var
I, J, L, Rd2: Integer;
begin
Rd2 := Radius div 2;
//every effect
if Effect <> 2 then
begin
for I := Max(0, Y - Rd2) to Min(H - 1, Y + Radius - Rd2) do
begin
for J := Max(0, X - Rd2) to Min(W - 1, X + Radius - Rd2) do
begin
if Brush.Mask[J - X, I - Y] then
begin
S[I, J].R := R;
S[I, J].G := G;
S[I, J].B := B;
L := Brush.TransMask[J - X, I - Y];
if L < S[I, J].L then
S[I, J].L := L;
end;
end;
end;
end else
begin
//TODO: implement fast drawing here
end;
end;
procedure DoBrush(Image: PARGB32Array; Brush : TBrushToDraw; W, H: Integer; X_begin, Y_begin, X_end, Y_end: Integer; R, G, B: Byte;
Radius: Integer; Effect: Integer = 0);
var
Rd2, L : Integer;
L1, L2 : Extended;
procedure DrawBrush;
var
I, J: Integer;
XB, XE, YB, YE : Integer;
K, KK,
P1, P2,
AAI, AA, BB, CC, DD : Extended;
begin
XB := Min(X_begin, x_end);
XE := Max(X_begin, x_end);
YB := Min(Y_begin, Y_end);
YE := Max(Y_begin, Y_end);
AA := Y_begin - Y_end;
BB := X_end - X_begin;
DD := Hypot(AA, BB);
CC := X_begin * Y_end - X_end * Y_begin;
AAI := -AA;
for I := Max(0, YB - Rd2) to Min(H - 1, YE + Rd2) do
begin
for J := Max(0, XB - Rd2) to Min(W - 1, XE + Rd2) do
begin
P1 := (I - y_begin) * AAI + (J - X_begin) * BB;
P2 := (I - y_end) * AAI + (J - X_end) * BB;
if P1 * P2 < 0 then
begin
L := Abs(Round((AA * J + BB * I + CC) / DD));
end else
begin
L1 := Sqrt((I - Y_begin) * (I - Y_begin) + (J - X_begin) * (J - X_begin));
L2 := Sqrt((I - Y_end) * (I - Y_end) + (J - x_end) * (J - x_end));
L := Round(Min(L1, L2));
end;
if L < Rd2 then
begin
Image[I, J].R := R;
Image[I, J].G := G;
Image[I, J].B := B;
L := Brush.TransMask[0, L];
if L < Image[I, J].L then
Image[I, J].L := L;
end;
end;
end;
end;
begin
InitSumLMatrix;
if ((Y_end - Y_begin) = 0) and ((X_end - X_begin) = 0) then
begin
DoPoint(Brush, Image, W, H, X_begin, Y_begin, R, G, B, Radius, Effect);
Exit;
end;
Rd2 := Radius div 2;
DrawBrush;
end;
procedure CoolDrawText(bitmap:Tbitmap; x,y:integer; text:string; coolcount:integer; coolcolor:Tcolor);
var
Drawrect:trect;
c:integer;
tempb,temp:Tbitmap;
i,j,k:integer;
p,p1,pv,pn,pc:pargb;
begin
tempb:=tbitmap.create;
tempb.PixelFormat:=pf24bit;
tempb.Canvas.Font.Assign(bitmap.Canvas.Font);
tempb.canvas.brush.Color:=$ffffff;
tempb.Width:=tempb.Canvas.TextWidth(text)+2*coolcount;
tempb.height:=tempb.Canvas.Textheight(text)+2*coolcount;
tempb.Canvas.Brush.style:=bsClear;
tempb.canvas.font.Color:=$0;
DrawRect:=Rect(point(coolcount,0),point(tempb.Width+coolcount,tempb.Height+coolcount));
DrawText(tempb.Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_NOCLIP);
temp:=tbitmap.create;
temp.PixelFormat:=pf24bit;
temp.canvas.brush.Color:=$0;
temp.Width:=tempb.Canvas.TextWidth(text)+coolcount;
temp.height:=tempb.Canvas.Textheight(text)+coolcount;
tempb.Canvas.Font.Assign(bitmap.Canvas.Font);
for i:=0 to temp.height-1 do
begin
p1:=temp.ScanLine[i];
p:=tempb.ScanLine[i];
for j:=0 to temp.width-1 do
begin
if p[j].r<>$ff then
begin
p1[j].r:=$ff;
p1[j].g:=$ff;
p1[j].b:=$ff;
end;
end;
end;
tempb.Canvas.brush.color:=$0;
tempb.Canvas.pen.color:=$0;
tempb.Canvas.Rectangle(0,0,tempb.Width,tempb.Height);
for k:=1 to coolcount do
begin
for i:=1 to temp.height-2 do
begin
p:=tempb.ScanLine[i];
pv:=temp.ScanLine[i-1];
pc:=temp.ScanLine[i];
pn:=temp.ScanLine[i+1];
for j:=1 to temp.width-2 do
begin
c:=9;
if (pv[j-1].r<>0) then dec(c);
if (pv[j+1].r<>0) then dec(c);
if (pn[j-1].r<>0) then dec(c);
if (pn[j+1].r<>0) then dec(c);
if (pc[j-1].r<>0) then dec(c);
if (pc[j+1].r<>0) then dec(c);
if (pn[j].r<>0) then dec(c);
if (pv[j].r<>0) then dec(c);
if c<>9 then
begin
p[j].r:=min($ff,p[j].r+(pv[j-1].r+pv[j+1].r+pn[j-1].r+pn[j+1].r+pc[j-1].r+pc[j+1].r+pn[j].r+pv[j].r) div (c+1));
p[j].g:=min($ff,p[j].g+(pv[j-1].g+pv[j+1].g+pn[j-1].g+pn[j+1].g+pc[j-1].g+pc[j+1].g+pn[j].g+pv[j].g) div (c+1));
p[j].b:=min($ff,p[j].b+(pv[j-1].b+pv[j+1].b+pn[j-1].b+pn[j+1].b+pc[j-1].b+pc[j+1].b+pn[j].b+pv[j].b) div (c+1));
end;
end;
end;
temp.Assign(tempb);
end;
bitmap.PixelFormat:=pf24bit;
if bitmap.Width=0 then exit;
for i:=Max(0,y) to min(tempb.Height-1+y,bitmap.height-1) do
begin
p:=bitmap.ScanLine[i];
p1:=tempb.ScanLine[i-y];
for j:=Max(0,x) to min(tempb.Width+x-1,bitmap.width-1) do
begin
p[j].r:=min(Round(p[j].r*(1-p1[j-x].r/255))+Round(getrvalue(coolcolor)*p1[j-x].r/255),255);
p[j].g:=min(Round(p[j].g*(1-p1[j-x].g/255))+Round(getgvalue(coolcolor)*p1[j-x].g/255),255);
p[j].b:=min(Round(p[j].b*(1-p1[j-x].b/255))+Round(getbvalue(coolcolor)*p1[j-x].b/255),255);
end;
end;
DrawRect:=Rect(point(x+coolcount,y),point(x+temp.Width+coolcount,temp.Height+y+coolcount));
bitmap.Canvas.Brush.style:=bsClear;
DrawText(bitmap.Canvas.Handle, PChar(text), Length(text), DrawRect, DT_NOCLIP);
temp.free;
tempb.free;
end;
procedure DrawCopyRightA(B: TBitmap; BkColor: TColor; Text: string);
var
CoolSize, FontSize, X, Y: Integer;
begin
FontSize := Min(B.Width div (Length(Text)), 16);
B.Canvas.Font.Size := FontSize;
CoolSize := Min(5, Round(B.Canvas.Font.Size / 2.5));
X := B.Width - B.Canvas.TextWidth(Text) - CoolSize * 3;
Y := B.Height - B.Canvas.TextHeight(Text) - CoolSize * 2;
CoolDrawText(B, X, Y, Text, CoolSize, BkColor);
end;
function FastTrunc(const Value: Double): Integer;
asm
fld Value.Double
fsub CHalf64
fistp Result.Integer
end;
procedure HightliteBitmap(B: TBitmap);
var
I, J: Integer;
P: PARGB;
function HightLite(B: Byte) : Byte; inline;
begin
Result := Round(255 * Sqrt(B / 255));
end;
begin
for I := 0 to B.Height - 1 do
begin
P := B.ScanLine[I];
for J := 0 to B.Width - 1 do
begin
P[J].R := HightLite(P[J].R);
P[J].G := HightLite(P[J].G);
P[J].B := HightLite(P[J].B);
end;
end;
end;
end.
|
unit MyKonversi;
{
Component : MyKonversi
Version : 1.0
Coder : Much. Yusron Arif <yusron.arif4@gmail.com>
Copyright © Mata Air Teknologi - Januari 2017
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TBahasa = (Indonesia, Inggris);
TMyKonversi = class(TComponent)
private
NullValS : string;
FAuthor : string;
FBahasa : TBahasa;
FSatuan : string;
FValue : double;
procedure SetBahasa(value:TBahasa);
procedure SetSatuan(value:string);
procedure SetValue(value:double);
function GetNumStr:string;
function Terbilang(value:string):string;
function TerbilangKoma(value: string): string;
protected
{ Protected declarations }
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
function NumToStr(vLang:TBahasa; vNum:double; vCurr:string):string;
published
property Author : string read FAuthor write NullValS;
property Bahasa : TBahasa read FBahasa write setBahasa;
property Satuan : string read FSatuan write setSatuan;
property Nilai : double read FValue write SetValue;
property HasilKonversi : string read GetNumStr write NullValS;
end;
procedure Register;
implementation
function TMyKonversi.Terbilang(value: string):string;
const
Angka : array [1..20] of string = ('', 'Satu', 'Dua', 'Tiga', 'Empat',
'Lima', 'Enam', 'Tujuh', 'Delapan',
'Sembilan', 'Sepuluh', 'Sebelas',
'Duabelas', 'Tigabelas', 'Empatbelas',
'Limabelas', 'Enambelas', 'Tujuhbelas',
'Delapanbelas', 'Sembilanbelas');
sPattern: string = '000000000000000';
var
S,kata : string;
Satu, Dua, Tiga, Belas, Gabung: string;
Sen, Sen1, Sen2: string;
Hitung : integer;
one, two, three: integer;
begin
One := 4;
Two := 5;
Three := 6;
Hitung := 1;
Kata := '';
S := copy(sPattern, 1, length(sPattern) - length(trim(value))) + value;
Sen1 := Copy(S, 14, 1);
Sen2 := Copy(S, 15, 1);
Sen := Sen1 + Sen2;
while Hitung < 5 do
begin
Satu := Copy(S, One, 1);
Dua := Copy(S, Two, 1);
Tiga := Copy(S, Three, 1);
Gabung := Satu + Dua + Tiga;
if StrToInt(Satu) = 1 then
begin
Kata := Kata + 'Seratus '
end else
begin
if StrToInt(Satu) > 1 Then
Kata := Kata + Angka[StrToInt(satu)+1] + ' Ratus ';
end;
if StrToInt(Dua) = 1 then
begin
Belas := Dua + Tiga;
Kata := Kata + Angka[StrToInt(Belas)+1];
end
else if StrToInt(Dua) > 1 Then
begin
Kata := Kata + Angka[StrToInt(Dua)+1] + ' Puluh ' + Angka[StrToInt(Tiga)+1];
end else
begin
if (StrToInt(Dua) = 0) and (StrToInt(Tiga) > 0) Then
begin
if ((Hitung = 3) and (Gabung = '001')) or ((Hitung = 3) and (Gabung = ' 1')) then
begin
Kata := Kata + 'Seribu ';
end else
begin
Kata := Kata + Angka[StrToInt(Tiga)+1];
end;
end;
end;
if (hitung = 1) and (StrToInt(Gabung) > 0) then
Kata := Kata + ' Milyar '
else if (Hitung = 2) and (StrToInt(Gabung) > 0) then
Kata := Kata + ' Juta '
else if (Hitung = 3) and (StrToInt(Gabung) > 0) then
begin
if (Gabung = '001') or (Gabung = ' 1') then
Kata := Kata + ''
else
Kata := Kata + ' Ribu ';
end;
Hitung := Hitung + 1;
One := One + 3;
Two := Two + 3;
Three := Three + 3;
end;
if length(Kata) > 1 then Kata := Kata;
Result := Kata;
end;
function TMyKonversi.TerbilangKoma(value: string): string;
var
a,b,c,Poskoma,PosTitik : integer;
temp,angka,dpnKoma,BlkKoma : string;
AdaKoma: boolean;
begin
PosKoma:= pos(',', value);
PosTitik:= pos('.', value);
if (Poskoma<>0) or (posTitik<> 0) then
begin
adaKoma:= true;
if PosKoma= 0 then
posKoma:= PosTitik;
end else
begin
adakoma:= False;
DpnKoma:= value;
end;
// Jika ada Koma
if adakoma then
begin
dpnkoma:= copy(value,1,posKoma-1);
blkKoma:= Copy(value,posKoma+1,length(value)-posKoma);
if trim(DpnKoma)='0' then
temp:= 'Nol'+ ' Koma ' + terbilang(blkKoma)
else
temp:= Terbilang(dpnKoma)+ ' Koma ' + Terbilang(blkKoma);
// Jika Tidak ada Koma
end else
begin
temp:=Terbilang(dpnKoma);
end;
Result:= temp;
end;
function TMyKonversi.NumToStr(vLang:TBahasa; vNum:double; vCurr:string):string;
begin
FValue := vNum;
result := TerbilangKoma(FloatToStr(FValue)) + ' ' + vCurr;
end;
function TMyKonversi.GetNumStr:string;
begin
result := NumToStr(FBahasa, FValue, FSatuan);
end;
procedure TMyKonversi.SetBahasa(value:TBahasa);
begin
if value <> FBahasa then FBahasa :=value;
end;
procedure TMyKonversi.SetSatuan(value:string);
begin
if value <> FSatuan then FSatuan :=value;
end;
procedure TMyKonversi.SetValue(value:double);
begin
if value <> FValue then FValue :=value;
end;
constructor TMyKonversi.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FAuthor :='Much. Yusron Arif <yusron.arif4 *at* gmail *dot* com>';
FValue :=0;
FSatuan :='Rupiah';
FBahasa :=Indonesia;
end;
destructor TMyKonversi.Destroy;
begin
inherited;
end;
procedure Register;
begin
RegisterComponents('MATek', [TMyKonversi]);
end;
end.
|
unit ibSHWizardConstraintFrm;
interface
uses
SHDesignIntf, ibSHDesignIntf, ibSHDDLWizardCustomFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SynEdit, pSHSynEdit, StdCtrls, ExtCtrls, ComCtrls, CheckLst,
Buttons, StrUtils;
type
TibSHWizardConstraintForm = class(TibSHDDLWizardCustomForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Bevel1: TBevel;
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
TabSheet2: TTabSheet;
Bevel2: TBevel;
Panel2: TPanel;
pSHSynEdit1: TpSHSynEdit;
Label3: TLabel;
ComboBox1: TComboBox;
GroupBox1: TGroupBox;
Label6: TLabel;
Label7: TLabel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
CheckListBox1: TCheckListBox;
ListBox1: TListBox;
Label2: TLabel;
ComboBox2: TComboBox;
Label4: TLabel;
ComboBox3: TComboBox;
GroupBox2: TGroupBox;
Label5: TLabel;
Label8: TLabel;
BitBtn3: TBitBtn;
BitBtn4: TBitBtn;
CheckListBox2: TCheckListBox;
ListBox2: TListBox;
ComboBox4: TComboBox;
Label9: TLabel;
ComboBox5: TComboBox;
Label10: TLabel;
CheckPanel: TPanel;
pSHSynEdit2: TpSHSynEdit;
GroupBox3: TGroupBox;
Label11: TLabel;
Label12: TLabel;
ComboBox6: TComboBox;
Edit2: TEdit;
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure ComboBox3Change(Sender: TObject);
procedure CheckListBox1ClickCheck(Sender: TObject);
procedure CheckListBox1DblClick(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure CheckListBox2ClickCheck(Sender: TObject);
procedure CheckListBox2DblClick(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
private
{ Private declarations }
procedure GetDataType;
procedure ChangeConstraintType;
procedure GetFields;
procedure GetReferenceFields;
protected
{ Protected declarations }
procedure SetTMPDefinitions; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
end;
var
ibSHWizardConstraintForm: TibSHWizardConstraintForm;
implementation
{$R *.dfm}
uses
ibSHConsts, ibSHValues;
{ TibSHWizardConstraintForm }
constructor TibSHWizardConstraintForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
var
I: Integer;
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
InitPageCtrl(PageControl1);
InitDescrEditor(pSHSynEdit1);
SetFormSize(540, 525);
Editor := pSHSynEdit2;
Editor.Lines.Clear;
RegisterEditors;
PageCtrl.Pages[1].TabVisible := False;
CheckPanel.Left := 4;
CheckPanel.Top := 92;
CheckPanel.Height := 390;
CheckPanel.Width := 500;
for I := 0 to Pred(ComponentCount) do
begin
if (Components[I] is TComboBox) then (Components[I] as TComboBox).Text := EmptyStr;
if (Components[I] is TEdit) then (Components[I] as TEdit).Text := EmptyStr;
end;
CheckListBox1.Items.Clear;
ListBox1.Items.Clear;
CheckListBox2.Items.Clear;
ListBox2.Items.Clear;
GetDataType;
Edit1.Text := DBObject.Caption;
ComboBox1.ItemIndex := ComboBox1.Items.IndexOf((DBObject as IibSHConstraint).TableName);
ComboBox6.ItemIndex := ComboBox6.Items.IndexOf('ASCENDING');
if DBState <> csCreate then
begin
ComboBox2.ItemIndex := ComboBox2.Items.IndexOf((DBObject as IibSHConstraint).ConstraintType);
ComboBox3.ItemIndex := ComboBox3.Items.IndexOf((DBObject as IibSHConstraint).ReferenceTable);
ComboBox4.ItemIndex := ComboBox4.Items.IndexOf((DBObject as IibSHConstraint).OnUpdateRule);
ComboBox5.ItemIndex := ComboBox5.Items.IndexOf((DBObject as IibSHConstraint).OnDeleteRule);
// ComboBox4.ItemIndex := ComboBox4.Items.IndexOf((DBObject as IibSHIndex).Sorting);
Editor.Lines.Assign((DBObject as IibSHConstraint).CheckSource);
Edit2.Text := (DBObject as IibSHConstraint).IndexName;
ComboBox6.ItemIndex := ComboBox6.Items.IndexOf((DBObject as IibSHConstraint).IndexSorting);
end;
ChangeConstraintType;
ComboBox1Change(ComboBox1);
ComboBox3Change(ComboBox3);
Edit1.Enabled := not (DBState = csAlter);
end;
destructor TibSHWizardConstraintForm.Destroy;
begin
inherited Destroy;
end;
procedure TibSHWizardConstraintForm.SetTMPDefinitions;
var
I: Integer;
begin
TMPObject.Caption := NormalizeCaption(Trim(Edit1.Text));
(TMPObject as IibSHConstraint).TableName := NormalizeCaption(Trim(ComboBox1.Text));
(TMPObject as IibSHConstraint).ConstraintType := Trim(ComboBox2.Text);
// if ComboBox3.ItemIndex <> 0 then
// (TMPObject as IibSHIndex).IndexType := Trim(ComboBox3.Text);
// (TMPObject as IibSHIndex).Sorting := Trim(ComboBox4.Text);
for I := 0 to Pred(ListBox1.Items.Count) do
(TMPObject as IibSHConstraint).Fields.Add(NormalizeCaption(Trim(ListBox1.Items[I])));
(TMPObject as IibSHConstraint).ReferenceTable := NormalizeCaption(Trim(ComboBox3.Text));
(TMPObject as IibSHConstraint).OnUpdateRule := Trim(ComboBox4.Text);
(TMPObject as IibSHConstraint).OnDeleteRule := Trim(ComboBox5.Text);
for I := 0 to Pred(ListBox2.Items.Count) do
(TMPObject as IibSHConstraint).ReferenceFields.Add(NormalizeCaption(Trim(ListBox2.Items[I])));
(TMPObject as IibSHConstraint).CheckSource.Assign(Editor.Lines);
(TMPObject as IibSHConstraint).IndexName := Trim(Edit2.Text);
(TMPObject as IibSHConstraint).IndexSorting := Trim(ComboBox6.Text);
end;
procedure TibSHWizardConstraintForm.GetDataType;
var
I: Integer;
begin
for I := 0 to Pred(DBObject.BTCLDatabase.GetObjectNameList(IibSHTable).Count) do
begin
ComboBox1.Items.Add(DBObject.BTCLDatabase.GetObjectNameList(IibSHTable)[I]);
ComboBox3.Items.Add(DBObject.BTCLDatabase.GetObjectNameList(IibSHTable)[I]);
end;
ComboBox2.Items.Text := GetConstraintType;
ComboBox4.Items.Text := GetConstraintRule;
ComboBox5.Items.Text := GetConstraintRule;
ComboBox6.Items.Text := GetSorting;
end;
procedure TibSHWizardConstraintForm.ChangeConstraintType;
var
I: Integer;
S: string;
begin
S := DBObject.BTCLDatabase.BTCLServer.Version;
for I := 0 to Pred(ComponentCount) do
begin
if (Components[I] is TCheckListBox) then (Components[I] as TCheckListBox).Enabled := True;
if (Components[I] is TCheckListBox) then (Components[I] as TCheckListBox).Color := clWindow;
if (Components[I] is TListBox) then (Components[I] as TListBox).Enabled := True;
if (Components[I] is TListBox) then (Components[I] as TListBox).Color := clWindow;
if (Components[I] is TComboBox) then (Components[I] as TComboBox).Enabled := True;
if (Components[I] is TComboBox) then (Components[I] as TComboBox).Color := clWindow;
if (Components[I] is TComboBox) then (Components[I] as TComboBox).Enabled := True;
if (Components[I] is TComboBox) then (Components[I] as TComboBox).Color := clWindow;
if (Components[I] is TEdit) then (Components[I] as TEdit).Enabled := True;
if (Components[I] is TEdit) then (Components[I] as TEdit).Color := clWindow;
end;
GroupBox1.Visible := True;
GroupBox2.Visible := True;
GroupBox3.Visible :=
AnsiContainsText(S, SFirebird15) or AnsiContainsText(S, SFirebird20) or AnsiContainsText(S, SFirebird21) ;
ComboBox3.Visible := True;
ComboBox4.Visible := True;
ComboBox5.Visible := True;
CheckPanel.Visible := False;
case ComboBox2.ItemIndex of
-1: begin
CheckListBox1.Enabled := False;
CheckListBox1.Color := clBtnFace;
CheckListBox1.Clear;
ListBox1.Enabled := False;
ListBox1.Color := clBtnFace;
ListBox1.Clear;
ComboBox3.Enabled := False;
ComboBox3.Color := clBtnFace;
ComboBox3.ItemIndex := -1;
ComboBox4.Enabled := False;
ComboBox4.Color := clBtnFace;
ComboBox4.ItemIndex := -1;
ComboBox5.Enabled := False;
ComboBox5.Color := clBtnFace;
ComboBox5.ItemIndex := -1;
CheckListBox2.Enabled := False;
CheckListBox2.Color := clBtnFace;
CheckListBox2.Clear;
ListBox2.Enabled := False;
ListBox2.Color := clBtnFace;
ListBox2.Clear;
Edit2.Enabled := False;
Edit2.Color := clBtnFace;
Edit2.Text := EmptyStr;
ComboBox6.Enabled := False;
ComboBox6.Color := clBtnFace;
// ComboBox6.ItemIndex := -1;
end;
0,
1: begin
CheckListBox1.Enabled := True;
CheckListBox1.Color := clWindow;
CheckListBox1.Clear;
ListBox1.Enabled := True;
ListBox1.Color := clWindow;
ListBox1.Clear;
ComboBox3.Enabled := False;
ComboBox3.Color := clBtnFace;
ComboBox3.ItemIndex := -1;
ComboBox4.Enabled := False;
ComboBox4.Color := clBtnFace;
ComboBox4.ItemIndex := -1;
ComboBox5.Enabled := False;
ComboBox5.Color := clBtnFace;
ComboBox5.ItemIndex := -1;
CheckListBox2.Enabled := False;
CheckListBox2.Color := clBtnFace;
CheckListBox2.Clear;
ListBox2.Enabled := False;
ListBox2.Color := clBtnFace;
ListBox2.Clear;
end;
2: begin
{
CheckListBox1.Enabled := True;
CheckListBox1.Color := clWindow;
CheckListBox1.Clear;
ListBox1.Enabled := True;
ListBox1.Color := clWindow;
ListBox1.Clear;
ComboBox3.Enabled := False;
ComboBox3.Color := clBtnFace;
ComboBox3.ItemIndex := -1;
ComboBox4.Enabled := False;
ComboBox4.Color := clBtnFace;
ComboBox4.ItemIndex := -1;
ComboBox5.Enabled := False;
ComboBox5.Color := clBtnFace;
ComboBox5.ItemIndex := -1;
CheckListBox2.Enabled := False;
CheckListBox2.Color := clBtnFace;
CheckListBox2.Clear;
ListBox2.Enabled := False;
ListBox2.Color := clBtnFace;
ListBox2.Clear;
ComboBox6.Enabled := False;
ComboBox6.Color := clBtnFace;
ComboBox6.ItemIndex := -1;
ComboBox7.Enabled := False;
ComboBox7.Color := clBtnFace;
ComboBox7.ItemIndex := -1;
Editor.Lines.Clear;
}
end;
3: begin
GroupBox1.Visible := False;
GroupBox2.Visible := False;
GroupBox3.Visible := False;
ComboBox3.Visible := False;
ComboBox4.Visible := False;
ComboBox5.Visible := False;
CheckPanel.Visible := True;
end;
end;
end;
procedure TibSHWizardConstraintForm.GetFields;
var
I: Integer;
Table: TSHComponent;
TableClass: TSHComponentClass;
TableName: string;
DBTable: IibSHTable;
begin
CheckListBox1.Items.Clear;
ListBox1.Items.Clear;
TableName := ComboBox1.Text;
TableClass := nil;
Table := Designer.FindComponent(DBObject.OwnerIID, IibSHTable, TableName);
Supports(Table, IibSHTable, DBTable);
if not Assigned(Table) then
begin
TableClass := Designer.GetComponent(IibSHTable);
if Assigned(TableClass) then
begin
Table := TableClass.Create(nil);
Supports(Table, IibSHTable, DBTable);
DBTable.Caption := TableName;
DBTable.OwnerIID := DBObject.OwnerIID;
DBTable.State := csSource;
try
Screen.Cursor := crHourGlass;
DDLGenerator.GetDDLText(DBTable);
finally
Screen.Cursor := crDefault;
end;
end;
end;
if Assigned(Table) then
begin
for I := 0 to Pred(DBTable.Fields.Count) do
CheckListBox1.Items.Add(DBTable.Fields[I]);
end;
DBTable := nil;
if Assigned(TableClass) then FreeAndNil(Table);
if DBState <> csCreate then
begin
if ComboBox1.Text = (DBObject as IibSHConstraint).TableName then
for I := 0 to Pred((DBObject as IibSHConstraint).Fields.Count) do
ListBox1.Items.Add((DBObject as IibSHConstraint).Fields[I]);
for I := 0 to Pred(ListBox1.Items.Count) do
if CheckListBox1.Items.IndexOf(ListBox1.Items[I]) <> -1 then
CheckListBox1.Checked[CheckListBox1.Items.IndexOf(ListBox1.Items[I])] := True;
end;
end;
procedure TibSHWizardConstraintForm.GetReferenceFields;
var
I: Integer;
Table: TSHComponent;
TableClass: TSHComponentClass;
TableName: string;
DBTable: IibSHTable;
begin
CheckListBox2.Items.Clear;
ListBox2.Items.Clear;
TableName := ComboBox3.Text;
TableClass := nil;
Table := Designer.FindComponent(DBObject.OwnerIID, IibSHTable, TableName);
Supports(Table, IibSHTable, DBTable);
if not Assigned(Table) then
begin
TableClass := Designer.GetComponent(IibSHTable);
if Assigned(TableClass) then
begin
Table := TableClass.Create(nil);
Supports(Table, IibSHTable, DBTable);
DBTable.Caption := TableName;
DBTable.OwnerIID := DBObject.OwnerIID;
DBTable.State := csSource;
try
Screen.Cursor := crHourGlass;
DDLGenerator.GetDDLText(DBTable);
finally
Screen.Cursor := crDefault;
end;
end;
end;
if Assigned(Table) then
begin
for I := 0 to Pred(DBTable.Fields.Count) do
CheckListBox2.Items.Add(DBTable.Fields[I]);
end;
DBTable := nil;
if Assigned(TableClass) then FreeAndNil(Table);
if DBState <> csCreate then
begin
if ComboBox3.Text = (DBObject as IibSHConstraint).ReferenceTable then
for I := 0 to Pred((DBObject as IibSHConstraint).ReferenceFields.Count) do
ListBox2.Items.Add((DBObject as IibSHConstraint).ReferenceFields[I]);
for I := 0 to Pred(ListBox2.Items.Count) do
if CheckListBox2.Items.IndexOf(ListBox2.Items[I]) <> -1 then
CheckListBox2.Checked[CheckListBox2.Items.IndexOf(ListBox2.Items[I])] := True;
end;
if DBState = csCreate then
begin
ComboBox4.ItemIndex := 0;
ComboBox5.ItemIndex := 0;
end;
end;
procedure TibSHWizardConstraintForm.ComboBox1Change(Sender: TObject);
begin
if ComboBox1.ItemIndex <> - 1 then
case ComboBox2.ItemIndex of
0, 1, 2: GetFields;
end
end;
procedure TibSHWizardConstraintForm.ComboBox2Change(Sender: TObject);
begin
ChangeConstraintType;
ComboBox1Change(ComboBox1);
end;
procedure TibSHWizardConstraintForm.ComboBox3Change(Sender: TObject);
begin
if ComboBox2.ItemIndex = 2 then GetReferenceFields;
end;
procedure TibSHWizardConstraintForm.CheckListBox1ClickCheck(
Sender: TObject);
begin
if CheckListBox1.Checked[CheckListBox1.ItemIndex] then
ListBox1.Items.Add(CheckListBox1.Items[CheckListBox1.ItemIndex])
else
ListBox1.Items.Delete(ListBox1.Items.IndexOf(CheckListBox1.Items[CheckListBox1.ItemIndex]));
end;
procedure TibSHWizardConstraintForm.CheckListBox1DblClick(Sender: TObject);
begin
CheckListBox1.Checked[CheckListBox1.ItemIndex] := not CheckListBox1.Checked[CheckListBox1.ItemIndex];
CheckListBox1ClickCheck(CheckListBox1);
end;
procedure TibSHWizardConstraintForm.BitBtn1Click(Sender: TObject);
var
I: Integer;
begin
I := ListBox1.ItemIndex;
if (DBState <> csAlter) and (I <> -1) and (I <> 0) then
begin
ListBox1.Items.Move(I, I - 1);
ListBox1.ItemIndex := I - 1;
if ListBox1.CanFocus then ListBox1.SetFocus;
end;
end;
procedure TibSHWizardConstraintForm.BitBtn2Click(Sender: TObject);
var
I: Integer;
begin
I := ListBox1.ItemIndex;
if (DBState <> csAlter) and (I <> -1) and (I <> Pred(ListBox1.Items.Count)) then
begin
ListBox1.Items.Move(I, I + 1);
ListBox1.ItemIndex := I + 1;
if ListBox1.CanFocus then ListBox1.SetFocus;
end;
end;
procedure TibSHWizardConstraintForm.CheckListBox2ClickCheck(
Sender: TObject);
begin
if CheckListBox2.Checked[CheckListBox2.ItemIndex] then
ListBox2.Items.Add(CheckListBox2.Items[CheckListBox2.ItemIndex])
else
ListBox2.Items.Delete(ListBox2.Items.IndexOf(CheckListBox2.Items[CheckListBox2.ItemIndex]));
end;
procedure TibSHWizardConstraintForm.CheckListBox2DblClick(Sender: TObject);
begin
CheckListBox2.Checked[CheckListBox2.ItemIndex] := not CheckListBox2.Checked[CheckListBox2.ItemIndex];
CheckListBox2ClickCheck(CheckListBox2);
end;
procedure TibSHWizardConstraintForm.BitBtn3Click(Sender: TObject);
var
I: Integer;
begin
I := ListBox2.ItemIndex;
if (DBState <> csAlter) and (I <> -1) and (I <> 0) then
begin
ListBox2.Items.Move(I, I - 1);
ListBox2.ItemIndex := I - 1;
if ListBox2.CanFocus then ListBox2.SetFocus;
end;
end;
procedure TibSHWizardConstraintForm.BitBtn4Click(Sender: TObject);
var
I: Integer;
begin
I := ListBox2.ItemIndex;
if (DBState <> csAlter) and (I <> -1) and (I <> Pred(ListBox2.Items.Count)) then
begin
ListBox2.Items.Move(I, I + 1);
ListBox2.ItemIndex := I + 1;
if ListBox2.CanFocus then ListBox2.SetFocus;
end;
end;
end.
|
{
Copyright (c) 2021 Adrian Siekierka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
{$I-}
{$V-}
unit DebugWnd;
interface
uses GameVars;
procedure DebugShowElementMessage(msg: string; x, y: integer);
procedure DebugShowSizeTooLarge(expected, actual: word; id: integer; name, desc: TString50);
implementation
uses Game, Sounds, TxtWind;
procedure DebugShowElementMessage(msg: string; x, y: integer);
var
statId: integer;
xStr, yStr, zStr: string[11];
textWindow: TTextWindowState;
begin
Str(x, xStr);
Str(y, yStr);
textWindow.Title := '[Debug] Element Error';
TextWindowInitState(textWindow);
TextWindowAppend(textWindow, '$' + msg);
TextWindowAppend(textWindow, '');
TextWindowAppend(textWindow, 'Position: ' + xStr + ', ' + yStr);
Str(World.Info.CurrentBoard, xStr);
TextWindowAppend(textWindow, 'Board: #' + xStr);
Str(Board.Tiles[x][y].Element, xStr);
TextWindowAppend(textWindow, 'Element: ' + ElementDefs[Board.Tiles[x][y].Element].Name + ' (' + xStr + ')');
statId := GetStatIdAt(x, y);
if statId >= 0 then begin
with Board.Stats[statId] do begin
Str(statId, xStr);
TextWindowAppend(textWindow, 'Stat: #' + xStr);
Str(StepX, xStr);
Str(StepY, yStr);
TextWindowAppend(textWindow, '- Step: ' + xStr + ', ' + yStr);
Str(Cycle, xStr);
TextWindowAppend(textWindow, '- Cycle: ' + xStr);
Str(P1, xStr);
Str(P2, yStr);
Str(P3, zStr);
TextWindowAppend(textWindow, '- Param: ' + xStr + ', ' + yStr + ', ' + zStr);
Str(Follower, xStr);
Str(Leader, yStr);
TextWindowAppend(textWindow, '- Follower: ' + xStr + ', Leader: ' + yStr);
if DataLen <> 0 then begin
Str(DataPos, xStr);
Str(DataLen, yStr);
TextWindowAppend(textWindow, '- DataPos: ' + xStr + '/' + yStr);
end;
end;
end;
SoundQueue(5, #80#10);
TextWindowDrawOpen(textWindow);
TextWindowSelect(textWindow, 0);
TextWindowDrawClose(textWindow);
TextWindowFree(textWindow);
end;
procedure DebugShowSizeTooLarge(expected, actual: word; id: integer; name, desc: TString50);
var
xStr, yStr: string[11];
textWindow: TTextWindowState;
begin
textWindow.Title := '[Debug] ' + name + ' size too large';
TextWindowInitState(textWindow);
Str(id, xStr);
TextWindowAppend(textWindow, '$The size of ' + name + ' ' + xStr);
TextWindowAppend(textWindow, '$' + desc);
Str(expected, xStr);
Str(actual, yStr);
TextWindowAppend(textWindow, '$(' + yStr + '/' + xStr + ' bytes)');
TextWindowDrawOpen(textWindow);
TextWindowSelect(textWindow, 0);
TextWindowDrawClose(textWindow);
TextWindowFree(textWindow);
end;
end.
|
unit TestUContasPagarVO;
interface
uses
TestFramework, SysUtils, Atributos, UCondominioVO, Generics.Collections, UGenericVO,
Classes, Constantes, UHistoricoVO, UPessoasVO, UContasPagarVO, UPlanoContasVO;
type
TestTContasPagarVO = class(TTestCase)
strict private
FContasPagarVO: TContasPagarVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCampos;
procedure TestValidarCamposErro;
procedure TestValidarBaixa;
procedure TestValidarBaixaErro;
end;
implementation
procedure TestTContasPagarVO.SetUp;
begin
FContasPagarVO := TContasPagarVO.Create;
end;
procedure TestTContasPagarVO.TearDown;
begin
FContasPagarVO.Free;
FContasPagarVO := nil;
end;
procedure TestTContasPagarVO.TestValidarCampos;
var
ContasPagar : TContasPagarVO;
begin
ContasPagar:= TContasPagarVO.Create;
ContasPagar.DtCompetencia := StrToDate('01/01/2016');
ContasPagar.DtEmissao := StrToDate('01/01/2016');
ContasPagar.DtVencimento := StrToDate('20/01/2016');
ContasPagar.NrDocumento := 'Teste 01';
ContasPagar.VlValor := StrToFloat('10,00');
try
ContasPagar.ValidarCampos;
Check(true,'sucesso!')
except on E: Exception do
Check(false,'Erro');
end;
end;
procedure TestTContasPagarVO.TestValidarCamposErro;
var
ContasPagar : TContasPagarVO;
begin
ContasPagar:= TContasPagarVO.Create;
ContasPagar.DtCompetencia := StrToDate('01/01/2016');
ContasPagar.DtEmissao := StrToDate('01/01/2016');
ContasPagar.DtVencimento := StrToDate('20/01/2016');
ContasPagar.NrDocumento := 'Teste 01';
ContasPagar.VlValor := StrToFloat('0');
try
ContasPagar.ValidarCampos;
Check(false,'Erro!')
except on E: Exception do
Check(true,'sucesso!');
end;
end;
procedure TestTContasPagarVO.TestValidarBaixa;
var
ContasPagar : TContasPagarVO;
begin
ContasPagar := TContasPagarVO.Create;
ContasPagar:= TContasPagarVO.Create;
ContasPagar.DtCompetencia := StrToDate('01/01/2016');
ContasPagar.DtEmissao := StrToDate('01/01/2016');
ContasPagar.DtVencimento := StrToDate('20/01/2016');
ContasPagar.NrDocumento := 'Teste 01';
ContasPagar.VlValor := StrToFloat('10,00');
ContasPagar.DtBaixa := StrToDate('20/01/2016');
ContasPagar.VlPago := StrToFloat('10,00');
ContasPagar.VlBaixa := StrToFloat('10,00');
ContasPagar.IdContaBaixa := StrToInt('4');
try
ContasPagar.ValidarBaixa;
Check(True,'Sucesso!')
except on E: Exception do
Check(false,'Erro');
end;
end;
procedure TestTContasPagarVO.TestValidarBaixaErro;
var
ContasPagar : TContasPagarVO;
begin
ContasPagar := TContasPagarVO.Create;
ContasPagar:= TContasPagarVO.Create;
ContasPagar.DtCompetencia := StrToDate('01/01/2016');
ContasPagar.DtEmissao := StrToDate('01/01/2016');
ContasPagar.DtVencimento := StrToDate('20/01/2016');
ContasPagar.NrDocumento := 'Teste 01';
ContasPagar.VlValor := StrToFloat('10,00');
ContasPagar.DtBaixa := StrToDate('20/01/2016');
ContasPagar.VlPago := StrToFloat('10,00');
ContasPagar.VlBaixa := StrToFloat('0');
ContasPagar.IdContaBaixa := StrToInt('4');
try
ContasPagar.ValidarBaixa;
Check(false,'Erro!')
except on E: Exception do
Check(true,'Sucesso');
end;
end;
initialization
RegisterTest(TestTContasPagarVO.Suite);
end.
|
unit UnitFunctions;
interface
uses SysUtils, Classes, Windows, IdFTPList, Math;
function CalcSpeed(eOld, eNew: Integer): String;
// local
function GetAllFiles(Mask: String; Attr: Integer; Recursive: Boolean; ShowDirs: Boolean; ShowPath: Boolean = True): TStringList;
// ftp
function GetAllDirs: TStringList;
implementation
uses UnitfrmMain;
function CalcSpeed(eOld, eNew: Integer): String;
begin
Result := frmMain.Caption;
if (eOld < eNew) and (eOld <> 0) then begin
eOld := eNew - eOld;
//eOld := eOld *2; // this is only used for faster updates...
Result := 'Metamod:Source - Uploading with ' + FloatToStr(RoundTo(eOld / 1024, -2)) + ' kb/s';
end;
end;
function GetAllFiles(Mask: String; Attr: Integer; Recursive: Boolean; ShowDirs: Boolean; ShowPath: Boolean = True): TStringList;
var eSearch: TSearchRec;
begin
Result := TStringList.Create;
// Find all files
if FindFirst(Mask, Attr, eSearch) = 0 then
begin
repeat
if eSearch.Name[1] <> '.' then begin
if ShowPath then begin
if ((eSearch.Attr and Attr) = eSearch.Attr) and ((eSearch.Attr and faDirectory) <> eSearch.Attr) then
Result.Add(ExtractFilePath(Mask) + eSearch.Name)
else if (ShowDirs) and ((eSearch.Attr and faDirectory) = eSearch.Attr) then
Result.Add(ExtractFilePath(Mask) + eSearch.Name);
end
else begin
if ((eSearch.Attr and Attr) = eSearch.Attr) and ((eSearch.Attr and faDirectory) <> eSearch.Attr) then
Result.Add(eSearch.Name)
else if (ShowDirs) and ((eSearch.Attr and faDirectory) = eSearch.Attr) then
Result.Add(eSearch.Name);
end;
if ((eSearch.Attr and faDirectory) = eSearch.Attr) and (Recursive) then begin
with GetAllFiles(ExtractFilePath(Mask) + eSearch.Name + '\' + ExtractFileName(Mask), Attr, True, ShowDirs, ShowPath) do begin
Result.Text := Result.Text + Text;
Free;
end;
end;
end;
until FindNext(eSearch) <> 0;
end;
end;
function GetAllDirs: TStringList;
var eList: TStringList;
i: integer;
begin
eList := TStringList.Create;
frmMain.IdFTP.List(eList);
frmMain.IdFTP.DirectoryListing.LoadList(eList);
eList.Clear;
for i := 0 to frmMain.IdFTP.DirectoryListing.Count -1 do begin
if frmMain.IdFTP.DirectoryListing.Items[i].ItemType = ditDirectory then
eList.Add(frmMain.IdFTP.DirectoryListing.Items[i].FileName);
end;
Result := eList;
end;
{ This is another possibility I coded because I couldn't find another bug...
function GetAllDirs: TStringList;
var eList: TStringList;
i, eStart: integer;
begin
eList := TStringList.Create;
frmMain.IdFTP.List(eList, '', True);
eStart := 0;
// +----------------------------------------------------------------+
// | drwxr-xr-x 5 web3 ftponly 2048 Jun 25 19:43 files |
// | drwxr-xr-x 2 web3 ftponly 2048 Jun 25 19:57 html |
// | drwxr-xr-x 3 root root 2048 Jun 20 05:03 log |
// | drwxrwxrwx 2 web3 ftponly 2048 Jun 19 2004 phptmp |
// +----------------------------------------------------------------+
// at first remove all non-directories from the list
for i := eList.Count -1 downto 0 do begin
if Pos('d', eList[i]) <> 1 then
eList.Delete(i);
end;
// then we have to find the position where ALL filenames start...
for i := 0 to eList.Count -1 do begin
if (eStart = 0) and (Pos(':', eList[i]) <> 0) then
eStart := Pos(':', eList[i]);
end;
if eStart = 0 then
eList.Clear
else begin
// find the position
for i := 0 to eList.Count -1 do begin
if Pos(':', eList[i]) <> 0 then begin
while (eStart <> Length(eList[i])) and (eList[i][eStart] <> #32) do
Inc(eStart, 1);
end;
end;
// remove the detail stuff...
for i := 0 to eList.Count -1 do
eList[i] := Copy(eList[i], eStart +1, Length(eList[i]));
end;
Result := eList;
end; }
end.
|
unit DBGrid_DBNavigator_MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Themes, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.ComCtrls,
Vcl.Tabs, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.ActnCtrls,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.ToolWin, Vcl.ActnMan,
Vcl.ActnMenus, Data.DB, Datasnap.DBClient, Vcl.DBGrids, Vcl.ExtCtrls,
Vcl.DBCtrls, Vcl.Buttons, Vcl.Mask, Vcl.DBCGrids, System.ImageList,
Vcl.ImgList, Vcl.VirtualImageList;
type
TDBGrid_DBNavigator_Form1 = class(TForm)
DBNavigator1: TDBNavigator;
DBGrid1: TDBGrid;
ClientDataSet1: TClientDataSet;
DataSource1: TDataSource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
private
procedure UpdateCaption;
{ Private declarations }
public
{ Public declarations }
end;
var
DBGrid_DBNavigator_Form1: TDBGrid_DBNavigator_Form1;
implementation
{$R *.dfm}
procedure TDBGrid_DBNavigator_Form1.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
begin
UpdateCaption;
end;
procedure TDBGrid_DBNavigator_Form1.UpdateCaption;
begin
Self.Caption := 'TDBGrid - TDBNavigator - DPI: ' + IntToStr(Round(Self.ScaleFactor * 100)) + '%';
end;
procedure TDBGrid_DBNavigator_Form1.FormCreate(Sender: TObject);
var
I: Integer;
begin
UpdateCaption;
ClientDataSet1.Open;
for I := 1 to 10 do
ClientDataSet1.InsertRecord(['Item' + IntToStr(I), 'Value' + IntToStr(I)]);
ClientDataSet1.First;
end;
end.
|
unit fre_configuration;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage UTF8}
interface
uses
Classes, SysUtils,IniFiles,FRE_SYSTEM,FOS_TOOL_INTERFACES,fre_db_interface;
procedure Initialize_Read_FRE_CFG_Parameter(const cleanup_in_cfgmode : boolean=false);
implementation
{$I fos_version_helper.inc}
// Read config file order:
// (1) .fre_ini in current dir
// (2) .fre_ini in global dir
// (3) .fre_ini in HOMEDIR/.fre_ini
procedure Initialize_Read_FRE_CFG_Parameter(const cleanup_in_cfgmode: boolean);
var cfgfile : string;
inifile : string;
procedure ReadConfigFileandConfigureLogger;
var ini : TMemIniFile;
machineuids : string;
procedure ConfigureLogging;
var sl : TStringList;
i : integer;
target : string;
targetdir : string;
targetdir_relative : boolean;
turnaround : integer;
generations : integer;
loglevel : TFOS_LOG_LEVEL;
facility : TFOS_LOG_FACILITY;
category : string;
no_log : TFOS_BoolType;
not_in_fulllog : TFOS_BoolType;
filename : string;
rule : string;
logaction : TFOS_LOG_RULE_ACTION;
stoprule : boolean;
defaultdir : string;
fullfilename : string;
section : string;
logcat : TFRE_DB_LOGCATEGORY;
rl : TStringList;
stopstring : string;
begin
GFRE_Log.ClearLogRules;
section := 'LOGGER_'+cFOS_PRODUCT_NAME;
if ini.SectionExists(section) then begin
if ini.ReadBool(section,'SYSLOG',false) then begin
GFRE_LOG.EnableSyslog;
end;
sl:=TStringList.Create;
rl:=TStringList.Create;
try
defaultdir := ini.ReadString (section,'DEFAULT_DIR',cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'log'+DirectorySeparator+cFOS_PRODUCT_NAME);
turnaround := ini.ReadInteger(section,'DEFAULT_TURNAROUND',1000000);
generations := ini.ReadInteger(section,'DEFAULT_GENERATIONS',10);
filename := ini.ReadString (section,'DEFAULT_FILENAME','main.log');
fullfilename := ini.ReadString (section,'DEFAULT_FULLFILENAME','full.log');
loglevel := FOSTI_StringToLogLevel (ini.ReadString(section,'DEFAULT_LOGLEVEL','DEBUG'));
facility := FOSTI_StringToLogFacility (ini.ReadString(section,'DEFAULT_FACILITY','KERNEL'));
GFRE_LOG.SetDefaults(filename,fullfilename,defaultdir,turnaround,generations,loglevel,facility);
sl.CommaText := ini.ReadString(section,'TARGETS','');
for i:=0 to sl.Count-1 do begin
target := Uppercase(trim(sl[i]));
targetdir := ini.ReadString (section,'TARGET_SUBFILEPATH_'+target,'');
turnaround := ini.ReadInteger(section,'TARGET_TURNAROUND_'+target,-1);
generations := ini.ReadInteger(section,'TARGET_GENERATIONS_'+target,-1);
loglevel := FOSTI_StringToLogLevel (ini.ReadString(section,'TARGET_LOGLEVEL_'+target,'DEBUG'));
facility := FOSTI_StringToLogFacility (ini.ReadString(section,'TARGET_FACILITY_'+target,'USER'));
GFRE_LOG.RegisterTarget(target,targetdir,turnaround,generations,loglevel,facility);
end;
sl.CommaText := ini.ReadString(section,'CATEGORIES','');
for i:=0 to sl.Count-1 do begin
category := Uppercase(trim(sl[i]));
logcat := FREDB_IniLogCategory2LogCategory(category);
filename := ini.ReadString (section,'CATEGORY_FILENAME_'+category,'');
turnaround := ini.ReadInteger(section,'CATEGORY_TURNAROUND_'+category,-1);
generations := ini.ReadInteger(section,'CATEGORY_GENERATIONS_'+category,-1);
loglevel := FOSTI_StringToLogLevel (ini.ReadString(section,'CATEGORY_LOGLEVEL_'+category,'DEBUG'));
if ini.ValueExists(section,'CATEGORY_NOLOG_'+category) then begin
if ini.ReadBool (section,'CATEGORY_NOLOG_'+category,false) then begin
no_log:=fbtTrue;
end else begin
no_log:=fbtFalse;
end;
end else begin
no_log := fbtNotSet;
end;
if ini.ValueExists(section,'CATEGORY_NOTINFULLLOG_'+category) then begin
if ini.ReadBool (section,'CATEGORY_NOTINFULLLOG_'+category,false) then begin
not_in_fulllog:=fbtTrue;
end else begin
not_in_fulllog:=fbtFalse;
end;
end else begin
not_in_fulllog :=fbtNotSet;
end;
GFRE_LOG.RegisterCategory(CFRE_DB_LOGCATEGORY[logcat],filename,turnaround,generations,loglevel,no_log,not_in_fulllog);
end;
ini.ReadSectionValues(section+'_RULES',sl); // read all values in rules section for product, key is irrelevant
rl.Delimiter:=',';
for i:=0 to sl.count-1 do
begin
if Pos(';',trim(sl[i]))=1 then // ignor commented lines
continue;
rl.DelimitedText:=GFRE_BT.SepRight(sl[i],'=');
if (rl.count<4) or (rl.count>5) then
raise EFRE_Exception.CreateFmt('Error parsing ini file, rule [%s] does not match the rule format with 4 or 5 parametes',[sl[i]]); //PERSISTANCE,DEBUG,*,DROPENTRY,FALSE
category := Uppercase(trim(rl[0]));
if category <>'*' then
logcat := FREDB_IniLogCategory2LogCategory(category);
loglevel := FOSTI_StringToLogLevel (uppercase(rl[1]));
target := rl[2];
logaction := FOSTI_StringToLogRuleAction (uppercase(rl[3]));
if rl.count=5 then
if uppercase(rl[4])='TRUE' then
stoprule := true
else
if uppercase(rl[4])='FALSE' then
stoprule :=false
else
raise EFRE_Exception.CreateFmt('Error parsing ini file, rule [%s] has an invalid stoprule configuration [TRUE|FALSE].',[sl[i]]) //PERSISTANCE,DEBUG,*,DROPENTRY,TRUE
else
stoprule := true;
if category<>'*' then
category := CFRE_DB_LOGCATEGORY[logcat];
GFRE_LOG.AddRule(category,loglevel,target,logaction,stoprule);
end;
finally
rl.free;
sl.Free;
end;
end else begin
GFRE_LOG.EnableSyslog;
end;
GFRE_LOG.SetLocalZone(cFRE_SERVER_DEFAULT_TIMEZONE);
end;
begin
try
//writeln('READING CONFIG FILE [',cfgfile,']');
ini := TMemIniFile.Create(cfgfile);
try
cFRE_SERVER_DEFAULT_DIR := ini.ReadString('BASE','DIR' , cFRE_SERVER_DEFAULT_DIR_NRM);
if cFRE_OVERRIDE_DEFAULT_DIR<>'' then
cFRE_SERVER_DEFAULT_DIR := cFRE_OVERRIDE_DEFAULT_DIR;
FREDB_ShellExpandFixUserPath(cFRE_SERVER_DEFAULT_DIR);
cFRE_SERVER_DEFAULT_SSL_DIR := ini.ReadString('SSL','DIR' , cFRE_SERVER_DEFAULT_SSL_DIR);
cFRE_SERVER_WWW_ROOT_DIR := ini.ReadString('BASE','WWWROOT' , cFRE_SERVER_WWW_ROOT_DIR);
cFRE_SERVER_WWW_ROOT_DYNAMIC := ini.ReadString('BASE','WWWROOT_DYNAMIC' , cFRE_SERVER_WWW_ROOT_DYNAMIC);
cFRE_SERVER_DEFAULT_TIMEZONE := ini.ReadString('BASE','TIMEZONE' , cFRE_SERVER_DEFAULT_TIMEZONE);
cFRE_DEFAULT_DOMAIN := ini.ReadString('BASE','DEFAULTDOMAIN' , cFRE_DEFAULT_DOMAIN);
cFRE_WebServerLocation_HixiedWS := ini.ReadString('BASE','HIXIE_WS_LOCATION' , cFRE_WebServerLocation_HixiedWS);
cFRE_SAFEJOB_BIN := ini.ReadString('BASE','SAFEJOB_BIN' , cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'bin'+DirectorySeparator+'fre_safejob');
cFRE_SSL_CERT_FILE := ini.ReadString('SSL','CERT' , cFRE_SSL_CERT_FILE);
cFRE_SSL_PRIVATE_KEY_FILE := ini.ReadString('SSL','KEY' , cFRE_SSL_PRIVATE_KEY_FILE);
cFRE_SSL_ROOT_CA_FILE := ini.ReadString('SSL','CA' , cFRE_SSL_ROOT_CA_FILE);
cG_OVERRIDE_USER := ini.ReadString('DBG','USER' , cG_OVERRIDE_USER);
cG_OVERRIDE_PASS := ini.ReadString('DBG','PASS' , cG_OVERRIDE_PASS);
cFRE_MONITORING_HOST := ini.ReadString('MONITORING','HOST' , cFRE_MONITORING_HOST);
cFRE_MONITORING_USER := ini.ReadString('MONITORING','USER' , cFRE_MONITORING_USER);
cFRE_MONITORING_KEY_FILE := ini.ReadString('MONITORING','KEY_FILE' , cFRE_MONITORING_KEY_FILE);
cFRE_MONITORING_DEST_DIR := ini.ReadString('MONITORING','DIRECTORY' , cFRE_MONITORING_DEST_DIR);
cFRE_DC_NAME := ini.ReadString('DC','NAME' , cFRE_DC_NAME);
cFRE_MACHINE_NAME := ini.ReadString('MACHINE','NAME' , cFRE_MACHINE_NAME);
cFRE_MACHINE_MAC := ini.ReadString('MACHINE','MAC' , cFRE_MACHINE_MAC);
cFRE_MACHINE_IP := ini.ReadString('MACHINE','IP' , cFRE_MACHINE_IP);
cFRE_PL_ADMINS := ini.ReadString('PL','ADMINLIST' , cFRE_PL_ADMINS);
cFRE_PL_ADMINS_PWS := ini.ReadString('PL','ADMINPASSLIST' , cFRE_PL_ADMINS_PWS); { plaintext passwords }
machineuids := ini.ReadString('MACHINE','UID' , CFRE_DB_NullGUID.AsHexString);
if machineuids <> CFRE_DB_NullGUID.AsHexString then
try
cFRE_MACHINE_UID.SetFromHexString(machineuids);
except
writeln('MACHINE UID FROM CONFIG FILE IS BAD');
halt;
end;
ConfigureLogging;
finally
ini.Free;
end;
except
on E:Exception do begin
GFRE_LOG.LogEmergency('EXCEPTION ON LOADING CONFIG FILE:'+E.Message);
end;
end;
end;
procedure SetupCreateDirectoriesAndSpecialFiles;
procedure DoIt(var cfg_dir : string ; const expand_string : string);
begin
cfg_dir := expand_string;
FREDB_ShellExpandFixUserPath(cfg_dir);
ForceDirectories(cfg_dir);
if not DirectoryExists(cFRE_HAL_CFG_DIR) then
GFRE_BT.CriticalAbort('FRE_SYSTEM STARTUP COULD NOT/CREATE BASEDIR [%s]',[cfg_dir]);
end;
begin
if cFRE_SERVER_DEFAULT_DIR_NRM='' then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'invalid empty default server directory');
DoIt(cFRE_HAL_CFG_DIR,cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'hal'+DirectorySeparator);
DoIt(cFRE_PID_LOCK_DIR,cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'pidlocks'+DirectorySeparator);
DoIt(cFRE_JOB_RESULT_DIR,cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'job'+DirectorySeparator);
DoIt(cFRE_TMP_DIR,cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'tmp'+DirectorySeparator);
DoIt(cFRE_UX_SOCKS_DIR,cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'sockets'+DirectorySeparator);
//cFRE_JOB_PROGRESS_DIR:= cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'jobprogress'+DirectorySeparator;
//cFRE_JOB_ARCHIVE_DIR := cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'jobarchive'+DirectorySeparator;
FREDB_ShellExpandFixUserPath(cFRE_SERVER_DEFAULT_SSL_DIR);
FREDB_ShellExpandFixUserPath(cFRE_SERVER_WWW_ROOT_DIR);
FREDB_ShellExpandFixUserPath(cFRE_SERVER_WWW_ROOT_DYNAMIC);
FREDB_ShellExpandFixUserPath(cFRE_SERVER_FLEX_UX_SOCKET);
FREDB_ShellExpandFixUserPath(cFRE_SAFEJOB_BIN);
end;
begin
GFOS_VHELP_INIT;
if cFRE_CONFIG_MODE then
begin
FREDB_ShellExpandFixUserPath(cFRE_SERVER_DEFAULT_DIR_NRM);
cFRE_SERVER_DEFAULT_DIR := cFRE_SERVER_DEFAULT_DIR_CFG;
if cFRE_OVERRIDE_DEFAULT_DIR<>'' then
cFRE_SERVER_DEFAULT_DIR := cFRE_OVERRIDE_DEFAULT_DIR;
FREDB_ShellExpandFixUserPath(cFRE_SERVER_DEFAULT_DIR);
if cleanup_in_cfgmode then
begin
writeln('CONFIGMODE : DELETING ',cFRE_SERVER_DEFAULT_DIR);
if not GFRE_BT.Delete_Directory(cFRE_SERVER_DEFAULT_DIR) then
raise EFRE_DB_Exception.Create(edb_ERROR,'failed to delete '+cFRE_SERVER_DEFAULT_DIR);
writeln('CONFIGMODE : DELETING ',cFRE_SERVER_DEFAULT_DIR,' DONE');
end;
SetupCreateDirectoriesAndSpecialFiles;
cFRE_MWS_UX := cFRE_SERVER_FLEX_UX_SOCKET;
exit;
end;
if FileExists('.fre_ini') then
begin { current dir }
cfgfile:='.fre.ini';
end
else
begin
inifile := cFRE_GLOBAL_INI_DIRECTORY+DirectorySeparator+'.fre_ini';
FREDB_ShellExpandFixUserPath(inifile);
if FileExists(inifile) then
begin
cfgfile:=cFRE_GLOBAL_INI_DIRECTORY+DirectorySeparator+'.fre_ini';
end
else
begin
inifile := GetUserDir+'.fre_ini';
FREDB_ShellExpandFixUserPath(inifile);
if FileExists(inifile) then
cfgfile:=inifile;
end;
end;
if cfgfile<>'' then
ReadConfigFileandConfigureLogger
else
begin { not configmode no inifile }
cFRE_SERVER_DEFAULT_DIR := cFRE_SERVER_DEFAULT_DIR_NRM;
if cFRE_OVERRIDE_DEFAULT_DIR<>'' then
cFRE_SERVER_DEFAULT_DIR := cFRE_OVERRIDE_DEFAULT_DIR;
FREDB_ShellExpandFixUserPath(cFRE_SERVER_DEFAULT_DIR);
end;
SetupCreateDirectoriesAndSpecialFiles;
//cFRE_ALERTING_CONFIG_FILE := cFRE_HAL_CFG_DIR+'alerting_config.dbo';
//cFRE_ALERTING_STATUS_FILE := cFRE_HAL_CFG_DIR+'alerting_status.dbo';
end;
end.
|
unit UtilLib;
interface
uses
SysUtils,ADODB,Variants,Forms,Windows,AdvGrid,StrUtils,Dialogs;
function GetExePath:string;
function TryCheckField(AADOCon:TADOConnection;AField,ATable:string;Args:array of Variant):Integer;
function TryCheckExist(AADOCon:TADOConnection;ATable:string;Args:array of Variant;AAddtional:string=''):Boolean;
function TrySqlExecute(AADOCon:TADOConnection;ASQL:string):Boolean;
function TryDeleteDB(AADOCon:TADOConnection;ASQL:string):Boolean;
function TryFormatCode(AValue,ALength:Integer;AHead:Boolean;const AText:string):string;
function FormatCode(AValue,ALength:Integer):string;
function FormatFloat(AValue:Double;ADigit:Integer=2):string;
function ShowBox(str:string):integer;
function WarnBox(str:string):Integer;
function EchoMidLeft(AParentWidth,ASelfWidth:Integer):Integer;
procedure ClearAdvGrid(Adv:TAdvStringGrid;ARowCount:integer);
procedure SetGridChkBox(Adv:TAdvStringGrid;ACol:Integer;ABoolCheck:Boolean);
function GetAdvGridCheckCount(AAdvGrid:TAdvStringGrid):Integer;
procedure SetDialogParam(ADialog:TForm);
implementation
function GetExePath:string;
begin
Result:=ExtractFilePath(ParamStr(0));
end;
function TryCheckExist(AADOCon:TADOConnection;ATable:string;Args:array of Variant;AAddtional:string):Boolean;
var
ADODS:TADODataSet;
ASQL :string;
Temp :string;
AValue:Variant;
I,ALen :Integer;
begin
Result:=False;
if (Length(Args) mod 2)<>0 then
begin
raise Exception.Create('函数调用出错,[Length(Args) Mod 2 <> 0]');
end;
ALen:=Length(Args) div 2;
ASQL:=Format('Select 1 From %s Where 1=1',[ATable]);
if ALen<>0 then
begin
for I:=1 to ALen do
begin
AValue:=Args[I*2-1];
Temp:='';
if VarIsStr(AValue) then
begin
Temp:=QuotedStr(AValue);
end else
if VarIsNumeric(AValue) then
begin
Temp:=AValue;
end;
ASQL:=ASQL+Format(' AND %s=%s',[VarToStr(Args[I*2-2]),Temp]);
end;
end;
if AAddtional<>'' then
begin
ASQL:=ASQL+' AND '+AAddtional;
end;
try
ADODS:=TADODataSet.Create(nil);
ADODS.Connection:=AADOCon;
ADODS.Prepared:=True;
ADODS.CommandText:=ASQL;
ADODS.Open;
ADODS.First;
if ADODS.RecordCount=0 then Exit;
if ADODS.RecordCount>0 then Result:=True;
finally
FreeAndNil(ADODS);
end;
end;
function TrySqlExecute(AADOCon:TADOConnection;ASQL:string):Boolean;
var
ADOCmd:TADOCommand;
begin
Result:=False;
try
ADOCmd:=TADOCommand.Create(nil);
ADOCmd.Connection:=AADOCon;
ADOCmd.Prepared :=True;
ADOCmd.CommandText:=ASQL;
ADOCmd.Execute;
finally
FreeAndNil(ADOCmd);
end;
Result:=True;
end;
function TryDeleteDB(AADOCon:TADOConnection;ASQL:string):Boolean;
begin
Result:=TrySqlExecute(AADOCon,ASQL);
end;
function TryFormatCode(AValue,ALength:Integer;AHead:Boolean;const AText:string):string;
begin
if AHead then
begin
Result:=DupeString(AText,ALength-(Length(IntToStr(AValue))))+IntToStr(AValue);
end else
begin
Result:=IntToStr(AValue)+DupeString(AText,ALength-(Length(IntToStr(AValue))));
end;
end;
function FormatCode(AValue,ALength:Integer):string;
begin
Result:=TryFormatCode(AValue,ALength,True,'0');
end;
function TryCheckField(AADOCon:TADOConnection;AField,ATable:string;Args:array of Variant):Integer;
var
ADODS:TADODataSet;
ASQL :string;
Temp :string;
AValue:Variant;
I,ALen :Integer;
begin
Result:=-1;
if (Length(Args) mod 2)<>0 then
begin
raise Exception.Create('函数调用出错,[Length(Args) Mod 2 <> 0]');
end;
ALen:=Length(Args) div 2;
ASQL:=Format('Select Max( %s )+1 As MaxValue From %s Where 1=1',[AField,ATable]);
if ALen<>0 then
begin
for I:=1 to ALen do
begin
AValue:=Args[I*2-1];
Temp:='';
if VarIsStr(AValue) then
begin
Temp:=QuotedStr(AValue);
end else
if VarIsNumeric(AValue) then
begin
Temp:=AValue;
end;
ASQL:=ASQL+Format(' AND %s=%s',[VarToStr(Args[I*2-2]),Temp]);
end;
end;
try
ADODS:=TADODataSet.Create(nil);
ADODS.Connection :=AADOCon;
ADODS.Prepared :=True;
ADODS.CommandText:=ASQL;
ADODS.Open;
if ADODS.RecordCount=0 then Exit;
Result:=ADODS.FieldByName('MaxValue').AsInteger;
if Result=0 then Result:=1;
finally
FreeAndNil(ADODS);
end;
end;
function FormatFloat(AValue:Double;ADigit:Integer):string;
begin
Result:=FloatToStrF(AValue,ffNumber,18,ADigit);
end;
function ShowBox(str:string):integer;
begin
Result:=Application.MessageBox(pchar(Str),'提示',MB_OKCANCEL +MB_ICONQUESTION);
end;
function WarnBox(str:string):Integer;
begin
//Application.MessageBox('', '', MB_OKCANCEL + MB_ICONWARNING);
//Result:=Application.MessageBox(pchar(Str),'提示',MB_OKCANCEL +mb_);
Result:=Application.MessageBox(pchar(Str), '警告', MB_OKCANCEL + MB_ICONWARNING);
end;
function EchoMidLeft(AParentWidth,ASelfWidth:Integer):Integer;
begin
Result:=(AParentWidth - ASelfWidth) div 2;
end;
procedure ClearAdvGrid(Adv:TAdvStringGrid;ARowCount:integer);
begin
with ADV do
begin
BeginUpdate;
Filter.Clear;
Filteractive:=False;
ClearRows(1,RowCount - 1);
RemoveRows(2,RowCount - 2);
if ARowCount > 1 then
RowCount:=ARowCount+1
else
RowCount:=2;
EndUpdate;
end;
end;
procedure SetGridChkBox(Adv:TAdvStringGrid;ACol:Integer;ABoolCheck:Boolean);
var
I:Integer;
begin
with Adv do
begin
BeginUpdate;
for I:=1 to RowCount-1 do
begin
SetCheckBoxState(ACol,I,ABoolCheck);
end;
EndUpdate;
end;
end;
function GetAdvGridCheckCount(AAdvGrid:TAdvStringGrid):Integer;
var
I:Integer;
State:Boolean;
begin
Result:=0;
with AAdvGrid do
begin
for I:=1 to AAdvGrid.RowCount-1 do
begin
State:=False;
GetCheckBoxState(1,I,State);
if State then
begin
Inc(Result);
end;
end;
end;
end;
procedure SetDialogParam(ADialog:TForm);
begin
ADialog.Position :=poScreenCenter;
ADialog.BorderStyle:=bsDialog;
end;
end.
|
{..............................................................................}
{ Summary Demo how to create a new footprint in the PCB library }
{ }
{ Creates a Resistor footprint and has a Resistor name }
{ Copyright (c) 2005 by Altium Limited }
{..............................................................................}
{..............................................................................}
Var
CurrentLib : IPCB_Library;
{..............................................................................}
{..............................................................................}
Procedure CreateALibComponent;
Var
NewPCBLibComp : IPCB_LibComponent;
NewPad : IPCB_Pad;
NewTrack : IPCB_Track;
Begin
If PCBServer = Nil Then Exit;
CurrentLib := PcbServer.GetCurrentPCBLibrary;
If CurrentLib = Nil Then Exit;
NewPCBLibComp := PCBServer.CreatePCBLibComp;
NewPcbLibComp.Name := 'Resistor';
CurrentLib.RegisterComponent(NewPCBLibComp);
PCBServer.PreProcess;
NewPad := PcbServer.PCBObjectFactory(ePadObject,eNoDimension,eCreate_Default);
NewPad.X := MilsToCoord(0);
NewPad.Y := MilsToCoord(0);
NewPad.TopXSize := MilsToCoord(62);
NewPad.TopYSize := MilsToCoord(62);
NewPad.HoleSize := MilsToCoord(28);
NewPad.Layer := eMultiLayer;
NewPad.Name := '1';
NewPCBLibComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
NewPad := PcbServer.PCBObjectFactory(ePadObject,eNoDimension,eCreate_Default);
NewPad.X := MilsToCoord(400);
NewPad.Y := MilsToCoord(0);
NewPad.TopXSize := MilsToCoord(62);
NewPad.TopYSize := MilsToCoord(62);
NewPad.HoleSize := MilsToCoord(28);
NewPad.Layer := eMultiLayer;
NewPad.Name := '2';
NewPCBLibComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(40);
NewTrack.Y1 := MilsToCoord(0);
NewTrack.X2 := MilsToCoord(80);
NewTrack.Y2 := MilsToCoord(0);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(80);
NewTrack.Y1 := MilsToCoord(40);
NewTrack.X2 := MilsToCoord(80);
NewTrack.Y2 := MilsToCoord(-40);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(80);
NewTrack.Y1 := MilsToCoord(40);
NewTrack.X2 := MilsToCoord(320);
NewTrack.Y2 := MilsToCoord(40);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(80);
NewTrack.Y1 := MilsToCoord(-40);
NewTrack.X2 := MilsToCoord(320);
NewTrack.Y2 := MilsToCoord(-40);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(320);
NewTrack.Y1 := MilsToCoord(40);
NewTrack.X2 := MilsToCoord(320);
NewTrack.Y2 := MilsToCoord(-40);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
NewTrack := PcbServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
NewTrack.X1 := MilsToCoord(320);
NewTrack.Y1 := MilsToCoord(0);
NewTrack.X2 := MilsToCoord(360);
NewTrack.Y2 := MilsToCoord(0);
NewTrack.Layer := eTopOverlay;
NewTrack.Width := MilsToCoord(10);
NewPCBLibComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewPCBLibComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
PCBServer.SendMessageToRobots(CurrentLib.Board.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPCBLibComp.I_ObjectAddress);
PCBServer.PostProcess;
CurrentLib.CurrentComponent := NewPcbLibComp;
CurrentLib.Board.ViewManager_FullUpdate;
End;
{..............................................................................}
{..............................................................................}
End.
|
unit FmWarErr;
{
Exports TWarningBox which can display warnings while the application
keeps running. and terminate the application when its method
Error is called.
C.A. van Beest, R.P. Sterkenburg, TNO-PML, Rijswijk, The Netherlands
28 Feb 97: - replaced Windows with Wintypes, WinProcs in uses clause
to make compilation under Delphi 1 possible
23 Apr 97: - Form changed
- Proc. ModalWarning added
- Proc. Warning changed
- Unnecessary button related procedures deleted
24 Apr 97: - added use of unit MoreUtil (imports Sleep for Delphi1)
- added comments
- ShowTime now rounded to msec in stead of seconds
}
interface
uses
WinProcs, WinTypes, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls;
type
TWarningForm = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Memo1: TMemo;
procedure ModalWarning( MessageStr: string);
procedure Warning( ShowTime: single; MessageStr: string);
procedure Error( MessageStr: string);
private
{ Private declarations }
public
{ Public declarations }
end;
var
WarningForm: TWarningForm;
implementation
{$R *.DFM}
uses
MoreUtil; { Imports Sleep }
procedure TWarningForm.Error( MessageStr: string);
begin { TWarningForm.Error }
Caption := 'Fatal error';
Memo1.Lines.Add( MessageStr);
OKBtn.Show;
ShowModal;
Halt;
end; { TWarningForm.Error }
procedure TWarningForm.ModalWarning( MessageStr: string);
begin { TWarningForm.ModalWarning }
Memo1.Lines.Add( MessageStr);
CancelBtn.Show;
ShowModal;
CancelBtn.Hide;
end; { TWarningForm.ModalWarning }
procedure TWarningForm.Warning( ShowTime: single; MessageStr: string);
{ ShowTime supposed to be in seconds }
begin { TWarningForm.Warning }
Memo1.Lines.Add( MessageStr);
Show;
Application.ProcessMessages;
Sleep( Round(1000 * ShowTime));
Hide;
end; { TWarningForm.Warning }
end.
|
unit LCMOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntX;
type
{ TTestLCMOp }
TTestLCMOp = class(TTestCase)
published
procedure LCMIntXBothPositive();
procedure LCMIntXBothNegative();
procedure LCMIntXBothSigns();
end;
implementation
{ TTestLCMOp }
procedure TTestLCMOp.LCMIntXBothPositive;
var
res: TIntX;
begin
res := TIntX.LCM(4, 6);
AssertTrue(res = 2);
res := TIntX.LCM(24, 18);
AssertTrue(res = 6);
res := TIntX.LCM(234, 100);
AssertTrue(res = 2);
res := TIntX.LCM(235, 100);
AssertTrue(res = 5);
end;
procedure TTestLCMOp.LCMIntXBothNegative;
var
res: TIntX;
begin
res := TIntX.LCM(-4, -6);
AssertTrue(res = 2);
res := TIntX.LCM(-24, -18);
AssertTrue(res = 6);
res := TIntX.LCM(-234, -100);
AssertTrue(res = 2);
end;
procedure TTestLCMOp.LCMIntXBothSigns;
var
res: TIntX;
begin
res := TIntX.LCM(-4, +6);
AssertTrue(res = 2);
res := TIntX.LCM(+24, -18);
AssertTrue(res = 6);
res := TIntX.LCM(-234, +100);
AssertTrue(res = 2);
end;
initialization
RegisterTest(TTestLCMOp);
end.
|
unit Gr_Stud_IndexEdit_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, cxDropDownEdit, cxControls,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, ActnList,
StdCtrls, cxButtons, ExtCtrls,gr_uCommonConsts,gr_uCommonProc, cxCheckBox;
type
TFormStudIndex_Edit = class(TForm)
Panel1: TPanel;
ButtonYes: TcxButton;
ButtonCancel: TcxButton;
Actions: TActionList;
ActionCancel: TAction;
LabelDate: TcxLabel;
EditMonth: TcxComboBox;
EditYear: TcxSpinEdit;
EditMonthBase: TcxComboBox;
EditYearBase: TcxSpinEdit;
LabelBaseDate: TcxCheckBox;
cxCheckBox2: TcxCheckBox;
cxMaskEdit1: TcxMaskEdit;
cxCheckBox1: TcxCheckBox;
EditSumma: TcxMaskEdit;
Action1: TAction;
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
procedure LabelBaseDatePropertiesChange(Sender: TObject);
procedure cxCheckBox2PropertiesChange(Sender: TObject);
procedure cxCheckBox1PropertiesChange(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure ButtonYesClick(Sender: TObject);
private
{ Private declarations }
public
PLanguageIndex:byte;
constructor create(Owner:TComponent);reintroduce;
end;
implementation
constructor TFormStudIndex_Edit.create(Owner:TComponent);
begin
inherited create(Owner);
PLanguageIndex := IndexLanguage;
//******************************************************************************
EditMonth.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
EditMonthBase.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
LabelDate.Caption := GridClDateAcc_Caption[PLanguageIndex];
LabelBaseDate.Properties.Caption := BasePeriod_Caption[PLanguageIndex];
ButtonYes.Caption := YesBtn_Caption[PLanguageIndex];
ButtonCancel.Caption := CancelBtn_Caption[PLanguageIndex];
//******************************************************************************
end;
{$R *.dfm}
procedure TFormStudIndex_Edit.ActionYesExecute(Sender: TObject);
begin
if cxCheckBox2.checked and (cxMaskEdit1.text='') then
begin
ShowMessage('"Сума фіксована" не заповнено');
cxMaskEdit1.SetFocus;
exit;
end;
if cxCheckBox1.checked and (EditSumma.text='') then
begin
ShowMessage('"Сума фактична" не заповнено');
EditSumma.SetFocus;
exit;
end;
ModalResult:=mrYes;
end;
procedure TFormStudIndex_Edit.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormStudIndex_Edit.LabelBaseDatePropertiesChange(
Sender: TObject);
begin
EditMonthBase.Enabled:=not EditMonthBase.Enabled;
EditYearBase.Enabled:=not EditYearBase.Enabled;
end;
procedure TFormStudIndex_Edit.cxCheckBox2PropertiesChange(Sender: TObject);
begin
cxMaskEdit1.Enabled:=not cxMaskEdit1.Enabled;
end;
procedure TFormStudIndex_Edit.cxCheckBox1PropertiesChange(Sender: TObject);
begin
EditSumma.Enabled:=not EditSumma.Enabled;
end;
procedure TFormStudIndex_Edit.Action1Execute(Sender: TObject);
begin
if ButtonYes.Focused Then ActionYesExecute(Sender);
if ButtonCancel.Focused Then ActionCancelExecute(Sender);
//selectnext(ActiveControl, TRUE, FALSE);
SendKeyDown(Self.ActiveControl,VK_TAB,[ssShift]);
end;
procedure TFormStudIndex_Edit.ButtonYesClick(Sender: TObject);
begin
ActionYesExecute(Sender);
end;
end.
|
unit ModflowMawWriterUnit;
interface
uses
System.UITypes, Winapi.Windows, System.Classes, Vcl.Forms, System.SysUtils,
System.Generics.Collections, CustomModflowWriterUnit, ScreenObjectUnit,
GoPhastTypes, ModflowPackageSelectionUnit, PhastModelUnit, ModflowMawUnit,
ModflowBoundaryDisplayUnit, Modflow6ObsUnit;
type
TMawObservation = record
FName: string;
FWellNumber: Integer;
FBoundName: string;
FCount: Integer;
FObsTypes: TMawObs;
FModflow6Obs: TModflow6Obs;
end;
TMawObservationList = TList<TMawObservation>;
TModflowMAW_Writer = class(TCustomTransientWriter)
private
FMawObjects: TScreenObjectList;
FMawNames: TStringList;
FWellProperties: array of TMawSteadyWellRecord;
FWellConnections: TList<TMawSteadyConnectionRecord>;
FNameOfFile: string;
FMawPackage: TMawPackage;
FFlowingWells: Boolean;
FMawObservations: TMawObservationList;
procedure AssignWellScreensAndWellProperties;
procedure WriteOptions;
procedure WriteDimensions;
procedure WritePackageData;
procedure WriteConnectionData;
procedure WriteStressPeriods;
function CheckOK(AScreenObject: TScreenObject;
Boundary: TMawBoundary): Boolean;
protected
function Package: TModflowPackageSelection; override;
class function Extension: string; override;
procedure Evaluate; override;
// @name is the file extension used for the observation input file.
class function ObservationExtension: string; override;
// @name is the file extension used for the observation output file.
function IsMf6Observation(AScreenObject: TScreenObject): Boolean; override;
// function IsMf6ToMvrObservation(AScreenObject: TScreenObject): Boolean; override;
function Mf6ObservationsUsed: Boolean; override;
public
Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override;
destructor Destroy; override;
procedure WriteFile(const AFileName: string);
procedure UpdateDisplay(TimeLists: TModflowBoundListOfTimeLists);
procedure UpdateSteadyData;
class function ObservationOutputExtension: string; override;
end;
implementation
uses
frameScreenObjectMawUnit, frmProgressUnit,
frmErrorsAndWarningsUnit, ModflowCellUnit, RbwParser, frmFormulaErrorsUnit,
DataSetUnit, GIS_Functions, AbstractGridUnit, System.Math, ModflowUnitNumbers,
MeshRenumberingTypes, Vcl.Dialogs, Modflow6ObsWriterUnit,
ModflowMvrUnit, ModflowMvrWriterUnit;
resourcestring
StrTheFollowingObject = 'The following objects can not be used to define m' +
'ulti-aquifer wells in the MAW package because they do not contain exactly one ' +
'vertex.';
StrECountZero = 'The following objects can not be used to define multi-aqu' +
'ifer wells in the MAW package because they do not have an elevation count' +
' of zero.';
StrNoTransientDataFo = 'No transient data for the MAW package has been def' +
'ined for the following objects. They will be skipped.';
StrNoWellScreensInT = 'No well screens in the MAW package have been define' +
'd for the following objects. They will be skipped';
StrBecauseTheFollowin = 'Because the following objects do not set values o' +
'f intersected cells, they can not define MAW wells.';
StrAssignedBy0sUsi = 'Assigned by %0:s using the formula ''%1:s''';
StrMAWRadius = 'MAW Radius';
StrMAWBottom = 'MAW Bottom';
StrMAWInitialHead = 'MAW Initial Head';
StrMAWScreenBottom = 'MAW Screen Bottom';
StrMAWSkinK = 'MAW Skin K';
StrMAWSkinRadius = 'MAW Skin Radius';
StrWritingMAWPackag = ' Writing MAW Package Data';
StrWritingMAWStre = ' Writing MAW Stress Period %d';
StrWritingMAWConnec = ' Writing MAW Connection Data';
StrWritingMAWStress = ' Writing MAW Stress Period Data';
StrTheFollowingObjectGrid = 'The following objects do not intersect the grid s' +
'o they will not be used to define wells in the MAW package.';
StrWritingMAWPackage = 'Writing MAW Package input.';
StrMAWScreenTop = 'MAW Screen Top';
StrTheMultiaquiferWe = 'The multi-aquifer well package was not included in' +
' the model because no multi-aquifer wells have been defined.'
+ sLineBreak
+ 'Multi-aquifer wells can be defined with point objects on the top view of '
+ 'the model that have zero Z-formulas.';
StrMAWPackageSkipped = 'MAW package skipped.';
StrMoreThanOneMAWSc = 'More than one MAW screen in the same cell';
StrTheObject0sDefi = 'The object %0:s defines two or more MAW well screen' +
's in the same cell (%1:d, %2:d, %3:d). This is only allowed if MEAN is selcted for the conductance equation.';
StrMAWSkinRadiusLess = 'MAW skin radius less than or equal to well radius';
StrInSTheMAWSkin = 'In %s, the MAW skin radius less than or equal to well ' +
'radius';
StrEvaluatingS = ' Evaluating %s';
StrEvaluatingMAWPacka = 'Evaluating MAW Package data.';
StrWritingMAWObservat = 'Writing MAW observations';
StrFormulaErrorInMAW = 'Formula Error in MAW';
StrThereWasAnErrorI = 'There was an error in a MAW formula in %s.';
StrMAWWellScreenInva = 'MAW Well screen invalid';
StrWellScreen0dOf = 'Well screen %0:d of the MAW boundary defined by %1:s ' +
'does not intersect any active cells.';
StrMAWWellScreensInv = 'MAW Well screens invalid';
StrNoneOfTheWellScr = 'None of the well screens of the MAW boundary define' +
'd by %0:s intersect any active cells.';
{ TModflowMAW_Writer }
constructor TModflowMAW_Writer.Create(Model: TCustomModel;
EvaluationType: TEvaluationType);
begin
inherited;
FMawObjects := TScreenObjectList.Create;
FMawNames := TStringList.Create;
FWellConnections := TList<TMawSteadyConnectionRecord>.Create;
FMawObservations := TMawObservationList.Create;
FMawPackage := Package as TMawPackage
end;
destructor TModflowMAW_Writer.Destroy;
begin
FMawObservations.Free;
FWellConnections.Free;
FMawObjects.Free;
FMawNames.Free;
inherited;
end;
function TModflowMAW_Writer.CheckOK(AScreenObject: TScreenObject;
Boundary: TMawBoundary): Boolean;
begin
result := True;
if AScreenObject.Count <> 1 then
begin
frmErrorsAndWarnings.AddWarning(Model, StrTheFollowingObject,
AScreenObject.Name, AScreenObject);
result := False;
end;
if AScreenObject.ElevationCount <> ecZero then
begin
frmErrorsAndWarnings.AddWarning(Model, StrECountZero,
AScreenObject.Name, AScreenObject);
result := False;
end;
if not AScreenObject.SetValuesOfIntersectedCells then
begin
frmErrorsAndWarnings.AddWarning(Model, StrBecauseTheFollowin,
AScreenObject.Name, AScreenObject);
result := False;
end;
if Boundary.Values.Count = 0 then
begin
frmErrorsAndWarnings.AddWarning(Model, StrNoTransientDataFo,
AScreenObject.Name, AScreenObject);
result := False;
end;
if Boundary.WellScreens.Count = 0 then
begin
frmErrorsAndWarnings.AddWarning(Model, StrNoWellScreensInT,
AScreenObject.Name, AScreenObject);
result := False;
end;
if AScreenObject.Segments[Model].Count = 0 then
begin
frmErrorsAndWarnings.AddWarning(Model, StrTheFollowingObjectGrid,
AScreenObject.Name, AScreenObject);
result := False;
end;
end;
procedure TModflowMAW_Writer.Evaluate;
var
ObjectIndex: Integer;
AScreenObject: TScreenObject;
Boundary: TMawBoundary;
Dummy: TStringList;
MawItem: TMawItem;
StartTime: Double;
FirstItem: TMawItem;
ItemIndex: Integer;
begin
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrTheFollowingObject);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrECountZero);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrNoTransientDataFo);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrNoWellScreensInT);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrBecauseTheFollowin);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrTheFollowingObjectGrid);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrMAWPackageSkipped);
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrMAWWellScreenInva);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrMoreThanOneMAWSc);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrMAWSkinRadiusLess);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrFormulaErrorInMAW);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrMAWWellScreensInv);
FFlowingWells := False;
StartTime := Model.ModflowFullStressPeriods.First.StartTime;
// StartTime := Model.ModflowStressPeriods.First.StartTime;
FMawObjects.Clear;
FMawNames.Clear;
Dummy := TStringList.Create;
try
for ObjectIndex := 0 to Model.ScreenObjectCount - 1 do
begin
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
AScreenObject := Model.ScreenObjects[ObjectIndex];
if AScreenObject.Deleted then
begin
Continue;
end;
if not AScreenObject.UsedModels.UsesModel(Model) then
begin
Continue;
end;
Boundary := AScreenObject.ModflowMawBoundary;
if (Boundary = nil) or not Boundary.Used then
begin
Continue;
end;
if not CheckOK(AScreenObject, Boundary) then
begin
Continue;
end;
frmProgressMM.AddMessage(Format(StrEvaluatingS, [AScreenObject.Name]));
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
// if AScreenObject.Count <> 1 then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrTheFollowingObject,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
// if AScreenObject.ElevationCount <> ecZero then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrECountZero,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
// if not AScreenObject.SetValuesOfIntersectedCells then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrBecauseTheFollowin,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
// if Boundary.Values.Count = 0 then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrNoTransientDataFo,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
// if Boundary.WellScreens.Count = 0 then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrNoWellScreensInT,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
// if AScreenObject.Segments[Model].Count = 0 then
// begin
// frmErrorsAndWarnings.AddWarning(Model, StrTheFollowingObjectGrid,
// AScreenObject.Name, AScreenObject);
// Continue;
// end;
MawItem := Boundary.Values[0] as TMawItem;
if MawItem.StartTime > StartTime then
begin
FirstItem := Boundary.Values.Insert(0) as TMawItem;
FirstItem.Assign(MawItem);
FirstItem.StartTime := StartTime;
FirstItem.EndTime := MawItem.StartTime;
FirstItem.MawStatus := mwInactive;
end;
Boundary.WellNumber := FMawObjects.Add(AScreenObject) + 1;
FMawNames.AddObject(AScreenObject.Name, AScreenObject);
Boundary.GetCellValues(Values, Dummy, Model);
if not FFlowingWells then
begin
for ItemIndex := 0 to Boundary.Values.Count - 1 do
begin
MawItem := Boundary.Values[ItemIndex] as TMawItem;
if MawItem.FlowingWell = fwFlowing then
begin
FFlowingWells := True;
break;
end;
end;
end;
end;
finally
Dummy.Free;
end;
FMawNames.Sorted := True;
AssignWellScreensAndWellProperties;
end;
class function TModflowMAW_Writer.Extension: string;
begin
result := '.maw6';
end;
function TModflowMAW_Writer.IsMf6Observation(
AScreenObject: TScreenObject): Boolean;
var
MfObs: TModflow6Obs;
begin
MfObs := AScreenObject.Modflow6Obs;
Result := (MfObs <> nil) and MfObs.Used and (MfObs.MawObs <> []);
end;
class function TModflowMAW_Writer.ObservationExtension: string;
begin
result := '.ob_maw';
end;
class function TModflowMAW_Writer.ObservationOutputExtension: string;
begin
result := '.ob_maw_out';
end;
function TModflowMAW_Writer.Mf6ObservationsUsed: Boolean;
begin
result := (Model.ModelSelection = msModflow2015)
and Model.ModflowPackages.Mf6ObservationUtility.IsSelected;
end;
function TModflowMAW_Writer.Package: TModflowPackageSelection;
begin
result := Model.ModflowPackages.MawPackage;
end;
procedure TModflowMAW_Writer.UpdateDisplay(
TimeLists: TModflowBoundListOfTimeLists);
var
// WellRadiusTimes: TModflowBoundaryDisplayTimeList;
// List: TValueCellList;
// Well : TMultinodeWell;
WellIndex: integer;
DataSets: TList;
UsedIndicies: TByteSet;
TimeIndex: Integer;
// Boundary: TMnw2Boundary;
DataTypeIndex: Integer;
TimeListIndex: Integer;
TimeList: TModflowBoundaryDisplayTimeList;
DataArray: TModflowBoundaryDisplayDataArray;
DataSetIndex: Integer;
WellElevationTimeList: TModflowBoundaryDisplayTimeList;
// Well: TMawCell;
// Boundary: TMawBoundary;
WellList: TValueCellList;
begin
if not Package.IsSelected then
begin
UpdateNotUsedDisplay(TimeLists);
Exit;
end;
try
DataSets := TList.Create;
try
Evaluate;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
if Values.Count = 0 then
begin
SetTimeListsUpToDate(TimeLists);
Exit;
end;
// TMawCell = class(TValueCell)
// private
// FValues: TMawTransientRecord;
// property WellNumber: Integer read GetWellNumber;
// property MawStatus: TMawStatus read GetMawStatus;
// property FlowingWell: TFlowingWell read GetFlowingWell;
// // ShutOff and RateScaling can not be used simultaneously.
// property ShutOff: Boolean read GetShutOff;
// property RateScaling: Boolean read GetRateScaling;
// property HeadLimitChoice: Boolean read GetHeadLimitChoice;
//
// property FlowingWellElevation: double read GetFlowingWellElevation;
// property FlowingWellConductance: double read GetFlowingWellConductance;
// property Rate: double read GetRate;
// property WellHead: double read GetWellHead;
// property HeadLimit: double read GetHeadLimit;
// property MinRate: double read GetMinRate;
// property MaxRate: double read GetMaxRate;
// property PumpElevation: double read GetPumpElevation;
// property ScalingLength: double read GetScalingLength;
//
// property FlowingWellElevationAnnotation: string read GetFlowingWellElevationAnnotation;
// property FlowingWellConductanceAnnotation: string read GetFlowingWellConductanceAnnotation;
// property RateAnnotation: string read GetRateAnnotation;
// property WellHeadAnnotation: string read GetWellHeadAnnotation;
// property HeadLimitAnnotation: string read GetHeadLimitAnnotation;
// property MinRateAnnotation: string read GetMinRateAnnotation;
// property MaxRateAnnotation: string read GetMaxRateAnnotation;
// property PumpElevationAnnotation: string read GetPumpElevationAnnotation;
// property ScalingLengthAnnotation: string read GetScalingLengthAnnotation;
WellElevationTimeList := TimeLists[0];
for TimeIndex := 0 to WellElevationTimeList.Count - 1 do
begin
DataSets.Clear;
for TimeListIndex := 0 to TimeLists.Count - 1 do
begin
TimeList := TimeLists[TimeListIndex];
DataArray := TimeList[TimeIndex]
as TModflowBoundaryDisplayDataArray;
DataSets.Add(DataArray);
end;
//
for WellIndex := 0 to Values.Count - 1 do
begin
WellList := Values[WellIndex];// as TValueCellList;
// Boundary := Well.MawBoundary;
// UsedIndicies := [];
for DataTypeIndex := FlowingWellElevationPosition to ScalingLengthPosition do
begin
// if Boundary.DataTypeUsed(DataTypeIndex) then
begin
Include(UsedIndicies, DataTypeIndex);
end;
end;
// if UsedIndicies <> [] then
// begin
// List := Well.FCells;
// // List.CheckRestore;
//
UpdateCellDisplay(WellList, DataSets, [], nil, UsedIndicies);
// List.Cache;
// end;
end;
for DataSetIndex := 0 to DataSets.Count - 1 do
begin
DataArray := DataSets[DataSetIndex];
DataArray.UpToDate := True;
DataArray.CacheData;
end;
end;
SetTimeListsUpToDate(TimeLists);
finally
DataSets.Free;
end;
except on E: EInvalidTime do
begin
Beep;
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
end;
procedure TModflowMAW_Writer.UpdateSteadyData;
var
RadiusDataArray: TModflowBoundaryDisplayDataArray;
WellIndex: Integer;
AWell: TMawSteadyWellRecord;
WellConnection: TMawSteadyConnectionRecord;
ConnectionIndex: Integer;
Index: Integer;
BottomDataArray: TModflowBoundaryDisplayDataArray;
InitialHeadDataArray: TModflowBoundaryDisplayDataArray;
ScreenTopArray: TModflowBoundaryDisplayDataArray;
ScreenBottomArray: TModflowBoundaryDisplayDataArray;
SkinKArray: TModflowBoundaryDisplayDataArray;
SkinRadiusArray: TModflowBoundaryDisplayDataArray;
begin
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
Model.UpdateModflowFullStressPeriods;
Model.ModflowFullStressPeriods.BeginUpdate;
try
for Index := Model.ModflowFullStressPeriods.Count - 1 downto 1 do
begin
Model.ModflowFullStressPeriods.Delete(Index);
end;
finally
Model.ModflowFullStressPeriods.EndUpdate;
end;
Evaluate;
RadiusDataArray := Model.DataArrayManager.GetDataSetByName(KMAWRadius)
as TModflowBoundaryDisplayDataArray;
if RadiusDataArray <> nil then
begin
RadiusDataArray.Clear;
if Length(FWellProperties) > 0 then
begin
WellIndex := 0;
AWell := FWellProperties[WellIndex];
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
if AWell.WellNumber <> WellConnection.WellNumber then
begin
Inc(WellIndex);
AWell := FWellProperties[WellIndex];
Assert(AWell.WellNumber = WellConnection.WellNumber);
end;
RadiusDataArray.AddDataValue(AWell.RadiusAnnotation,
AWell.Radius, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
RadiusDataArray.ComputeAverage;
end;
RadiusDataArray.UpToDate := True;
end;
BottomDataArray := Model.DataArrayManager.GetDataSetByName(KMAWBottom)
as TModflowBoundaryDisplayDataArray;
if BottomDataArray <> nil then
begin
BottomDataArray.Clear;
if Length(FWellProperties) > 0 then
begin
WellIndex := 0;
AWell := FWellProperties[WellIndex];
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
if AWell.WellNumber <> WellConnection.WellNumber then
begin
Inc(WellIndex);
AWell := FWellProperties[WellIndex];
Assert(AWell.WellNumber = WellConnection.WellNumber);
end;
BottomDataArray.AddDataValue(AWell.BottomAnnotation,
AWell.Bottom, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
BottomDataArray.ComputeAverage;
end;
BottomDataArray.UpToDate := True;
end;
InitialHeadDataArray := Model.DataArrayManager.GetDataSetByName(KMAWInitialHead)
as TModflowBoundaryDisplayDataArray;
if InitialHeadDataArray <> nil then
begin
InitialHeadDataArray.Clear;
if Length(FWellProperties) > 0 then
begin
WellIndex := 0;
AWell := FWellProperties[WellIndex];
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
if AWell.WellNumber <> WellConnection.WellNumber then
begin
Inc(WellIndex);
AWell := FWellProperties[WellIndex];
Assert(AWell.WellNumber = WellConnection.WellNumber);
end;
InitialHeadDataArray.AddDataValue(AWell.StartingHeadAnnotation,
AWell.StartingHead, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
InitialHeadDataArray.ComputeAverage;
end;
InitialHeadDataArray.UpToDate := True;
end;
ScreenTopArray := Model.DataArrayManager.GetDataSetByName(KMAWScreenTop)
as TModflowBoundaryDisplayDataArray;
if ScreenTopArray <> nil then
begin
ScreenTopArray.Clear;
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
ScreenTopArray.AddDataValue(WellConnection.ScreenTopAnnotation,
WellConnection.ScreenTop, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
ScreenTopArray.ComputeAverage;
ScreenTopArray.UpToDate := True;
end;
ScreenBottomArray := Model.DataArrayManager.GetDataSetByName(KMAWScreenBottom)
as TModflowBoundaryDisplayDataArray;
if ScreenBottomArray <> nil then
begin
ScreenBottomArray.Clear;
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
ScreenBottomArray.AddDataValue(WellConnection.ScreenBottomAnnotation,
WellConnection.ScreenBottom, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
ScreenBottomArray.ComputeAverage;
ScreenBottomArray.UpToDate := True;
end;
SkinKArray := Model.DataArrayManager.GetDataSetByName(KMAWSkinK)
as TModflowBoundaryDisplayDataArray;
if SkinKArray <> nil then
begin
SkinKArray.Clear;
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
SkinKArray.AddDataValue(WellConnection.SkinKAnnotation,
WellConnection.SkinK, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
SkinKArray.ComputeAverage;
SkinKArray.UpToDate := True;
end;
SkinRadiusArray := Model.DataArrayManager.GetDataSetByName(KMAWSkinRadius)
as TModflowBoundaryDisplayDataArray;
if SkinRadiusArray <> nil then
begin
SkinRadiusArray.Clear;
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
WellConnection := FWellConnections[ConnectionIndex];
SkinRadiusArray.AddDataValue(WellConnection.SkinRadiusAnnotation,
WellConnection.SkinRadius, WellConnection.Cell.Column,
WellConnection.Cell.Row, WellConnection.Cell.Layer);
end;
SkinRadiusArray.ComputeAverage;
SkinRadiusArray.UpToDate := True;
end;
end;
procedure TModflowMAW_Writer.WriteConnectionData;
var
ConnectionIndex: Integer;
AWellConnection: TMawSteadyConnectionRecord;
ExistingConnections: array of array of array of String;
ExistingName: string;
ObjectIndex: Integer;
ASCreenObject: TScreenObject;
begin
SetLength(ExistingConnections, Model.LayerCount, Model.RowCount, Model.ColumnCount);
WriteBeginConnectionData;
WriteString('# <wellno> <icon> <cellid(ncelldim)> <scrn_top> <scrn_bot> <hk_skin> <radius_skin>');
NewLine;
for ConnectionIndex := 0 to FWellConnections.Count - 1 do
begin
AWellConnection := FWellConnections[ConnectionIndex];
ObjectIndex := FMawNames.IndexOf(AWellConnection.ScreenObjectName);
Assert(ObjectIndex >= 0);
ASCreenObject := FMawNames.Objects[ObjectIndex] as TScreenObject;
ExistingName := ExistingConnections[AWellConnection.Cell.Layer,
AWellConnection.Cell.Row,
AWellConnection.Cell.Column];
if ExistingName = AWellConnection.ScreenObjectName then
begin
if (ASCreenObject.ModflowMawBoundary.ConductanceMethod <> mcmMean) then
begin
frmErrorsAndWarnings.AddError(Model, StrMoreThanOneMAWSc,
Format(StrTheObject0sDefi, [ExistingName,
AWellConnection.Cell.Layer+1,
AWellConnection.Cell.Row+1,
AWellConnection.Cell.Column+1]), ASCreenObject);
end;
end;
ExistingConnections[AWellConnection.Cell.Layer,
AWellConnection.Cell.Row,
AWellConnection.Cell.Column] := AWellConnection.ScreenObjectName;
WriteInteger(AWellConnection.WellNumber);
WriteInteger(AWellConnection.ConnectionNumber);
WriteInteger(AWellConnection.Cell.Layer+1);
if not Model.DisvUsed then
begin
WriteInteger(AWellConnection.Cell.Row+1);
end;
WriteInteger(AWellConnection.Cell.Column+1);
WriteFloat(AWellConnection.ScreenTop);
WriteFloat(AWellConnection.ScreenBottom);
WriteFloat(AWellConnection.SkinK);
WriteFloat(AWellConnection.SkinRadius);
NewLine;
end;
WriteEndConnectionData;
end;
procedure TModflowMAW_Writer.WriteDimensions;
var
NMAWWELLS: Integer;
begin
NMAWWELLS := Length(FWellProperties);
WriteBeginDimensions;
WriteString(' NMAWWELLS');
WriteInteger(NMAWWELLS);
NewLine;
WriteEndDimensions;
end;
procedure TModflowMAW_Writer.WriteFile(const AFileName: string);
var
ObsWriter: TMawObsWriter;
begin
if Model.ModelSelection <> msModflow2015 then
begin
Exit
end;
if not Package.IsSelected then
begin
Exit
end;
if Model.PackageGeneratedExternally(StrMAW) then
begin
Exit;
end;
frmProgressMM.AddMessage(StrEvaluatingMAWPacka);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
Evaluate;
if Values.Count = 0 then
begin
frmErrorsAndWarnings.AddWarning(Model, StrMAWPackageSkipped,
StrTheMultiaquiferWe);
Exit;
end;
FNameOfFile := FileName(AFileName);
WriteToNameFile(StrMAW, 0, FNameOfFile, foInput, Model);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
FInputFileName := FNameOfFile;
OpenFile(FNameOfFile);
try
frmProgressMM.AddMessage(StrWritingMAWPackage);
Application.ProcessMessages;
WriteDataSet0;
frmProgressMM.AddMessage(StrWritingOptions);
WriteOptions;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDimensions);
WriteDimensions;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingMAWPackag);
WritePackageData;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingMAWConnec);
Application.ProcessMessages;
WriteConnectionData;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingMAWStress);
WriteStressPeriods;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
finally
CloseFile;
end;
if FMawObservations.Count > 0 then
begin
frmProgressMM.AddMessage(StrWritingMAWObservat);
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
ObsWriter := TMawObsWriter.Create(Model, etExport, FMawObservations);
try
ObsWriter.WriteFile(ChangeFileExt(FNameOfFile, ObservationExtension));
finally
ObsWriter.Free;
end;
end;
end;
procedure TModflowMAW_Writer.WriteOptions;
var
AFileName: string;
// ObsName: string;
NameOfFile: string;
begin
WriteBeginOptions;
WriteBoundNamesOption;
PrintListInputOption;
if FMawPackage.PrintHead then
begin
WriteString(' PRINT_HEAD');
NewLine;
end;
if FMawPackage.SaveMnwHeads then
begin
WriteString(' HEAD FILEOUT ');
AFileName := ChangeFileExt(FNameOfFile, '.maw_head');
Model.AddModelOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
WriteString(AFileName);
NewLine;
end;
PrintFlowsOption;
WriteSaveFlowsOption;
if FMawPackage.SaveMnwFlows then
begin
WriteString(' BUDGET FILEOUT ');
AFileName := ChangeFileExt(FNameOfFile, '.maw_bud');
Model.AddModelOutputFile(AFileName);
AFileName := ExtractFileName(AFileName);
WriteString(AFileName);
NewLine;
end;
if not FMawPackage.IncludeWellStorage then
begin
WriteString(' NO_WELL_STORAGE');
NewLine;
end;
if FFlowingWells then
begin
WriteString(' FLOWING_WELLS');
NewLine;
end;
WriteString(' SHUTDOWN_THETA');
WriteFloat(FMawPackage.ShutDownTheta);
NewLine;
WriteString(' SHUTDOWN_KAPPA');
WriteFloat(FMawPackage.ShutDownKappa);
NewLine;
if FMawObservations.Count > 0 then
begin
WriteString(' OBS6 FILEIN ');
NameOfFile := ObservationFileName(FNameOfFile);
Model.AddModelInputFile(NameOfFile);
NameOfFile := ExtractFileName(NameOfFile);
WriteString(NameOfFile);
NewLine;
end;
if (MvrWriter <> nil) then
begin
if spcMaw in TModflowMvrWriter(MvrWriter).UsedPackages then
begin
WriteString(' MOVER');
NewLine
end;
end;
{
[TS6 FILEIN <ts6_filename>] not supported
[MOVER] not supported
}
WriteEndOptions
end;
procedure TModflowMAW_Writer.WritePackageData;
var
WellIndex: Integer;
AWell: TMawSteadyWellRecord;
BoundName: string;
begin
WriteBeginPackageData;
WriteString('# <wellno> <radius> <bottom> <strt> <condeqn> <ngwfnodes> [<aux(naux)>] [<boundname>]');
NewLine;
for WellIndex := 0 to Length(FWellProperties) - 1 do
begin
AWell := FWellProperties[WellIndex];
WriteInteger(AWell.WellNumber);
WriteFloat(AWell.Radius);
WriteFloat(AWell.Bottom);
WriteFloat(AWell.StartingHead);
case AWell.ConductanceMethod of
mcmSpecified:
begin
WriteString(' SPECIFIED');
end;
mcmTheim, mcmThiem:
begin
WriteString(' THIEM');
end;
mcmSkin:
begin
WriteString(' SKIN');
end;
mcmCumulative:
begin
WriteString(' CUMULATIVE');
end;
mcmMean:
begin
WriteString(' MEAN');
end;
else
Assert(False);
end;
WriteInteger(AWell.CellCount);
BoundName := Copy(AWell.BoundName, 1, MaxBoundNameLength);
BoundName := ' ''' + BoundName + ''' ';
WriteString(BoundName);
NewLine;
end;
WriteEndPackageData;
end;
procedure TModflowMAW_Writer.WriteStressPeriods;
var
StressPeriodIndex: Integer;
Cells: TValueCellList;
CellIndex: Integer;
ACell: TMawCell;
MoverWriter: TModflowMvrWriter;
MvrReceiver: TMvrReceiver;
MvrSource: TMvrRegisterKey;
begin
if MvrWriter <> nil then
begin
MoverWriter := MvrWriter as TModflowMvrWriter;
end
else
begin
MoverWriter := nil;
end;
MvrReceiver.ReceiverKey.ReceiverPackage := rpcMaw;
MvrReceiver.ReceiverValues.StreamCells := nil;
for StressPeriodIndex := 0 to Model.ModflowFullStressPeriods.Count -1 do
begin
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(Format(
StrWritingMAWStre, [StressPeriodIndex+1]));
MvrSource.StressPeriod := StressPeriodIndex;
WriteBeginPeriod(StressPeriodIndex);
WriteString('# <wellno> <mawsetting>');
NewLine;
MvrReceiver.ReceiverKey.StressPeriod := StressPeriodIndex;
Cells := Values[StressPeriodIndex];
for CellIndex := 0 to Cells.Count - 1 do
begin
ACell := Cells[CellIndex] as TMawCell;
MvrReceiver.ReceiverKey.ScreenObject :=
ACell.MawBoundary.ScreenObject;
MvrReceiver.ReceiverValues.Index := ACell.WellNumber;
if MoverWriter <> nil then
begin
MoverWriter.AddMvrReceiver(MvrReceiver);
end;
WriteInteger(ACell.WellNumber);
WriteString(' STATUS');
case ACell.MawStatus of
mwActive:
begin
WriteString(' ACTIVE');
end;
mwInactive:
begin
WriteString(' INACTIVE,');
end;
mwConstantHead:
begin
WriteString(' CONSTANT');
end;
end;
NewLine;
case ACell.FlowingWell of
fwNotFlowing:
begin
// do nothing
end;
fwFlowing:
begin
WriteInteger(ACell.WellNumber);
WriteString(' FLOWING_WELL');
WriteFloat(ACell.FlowingWellElevation);
WriteFloat(ACell.FlowingWellConductance);
NewLine;
end;
end;
if ACell.MawStatus <> mwInactive then
begin
WriteInteger(ACell.WellNumber);
WriteString(' RATE');
WriteFloat(ACell.Rate);
NewLine;
end;
if ACell.MawStatus in [mwInactive, mwConstantHead] then
begin
WriteInteger(ACell.WellNumber);
WriteString(' WELL_HEAD');
WriteFloat(ACell.WellHead);
NewLine;
end;
if ACell.HeadLimitChoice then
begin
WriteInteger(ACell.WellNumber);
WriteString(' HEAD_LIMIT');
WriteFloat(ACell.HeadLimit);
NewLine;
end;
if ACell.ShutOff then
begin
WriteInteger(ACell.WellNumber);
WriteString(' SHUT_OFF');
WriteFloat(ACell.MinRate);
WriteFloat(ACell.MaxRate);
NewLine;
end;
if ACell.RateScaling then
begin
WriteInteger(ACell.WellNumber);
WriteString(' RATE_SCALING');
WriteFloat(ACell.PumpElevation);
WriteFloat(ACell.ScalingLength);
NewLine;
end;
if ACell.MvrUsed and (MvrWriter <> nil) and (ACell.MawStatus <> mwInactive) then
begin
MvrSource.Index := ACell.WellNumber;
MvrSource.SourceKey.MvrIndex := ACell.MvrIndex;
MvrSource.SourceKey.ScreenObject := ACell.MawBoundary.ScreenObject;
MoverWriter.AddMvrSource(MvrSource);
end;
end;
WriteEndPeriod;
end;
end;
procedure TModflowMAW_Writer.AssignWellScreensAndWellProperties;
var
AScreenObject: TScreenObject;
Boundary: TMawBoundary;
UsedVariables: TStringList;
Compiler: TRbwParser;
CellList: TValueCellList;
WellIndex: Integer;
AWell: TMawCell;
Expression: TExpression;
AWellRecord: TMawSteadyWellRecord;
Formula: string;
AWellConnection: TMawSteadyConnectionRecord;
ScreenIndex: Integer;
AWellScreen: TMawWellScreenItem;
Cell: TCellLocation;
Grid: TCustomModelGrid;
LayerIndex: Integer;
CellTop: double;
CellBottom: double;
Mesh: IMesh3D;
AWellSteady: TMawSteadyWellRecord;
MfObs: TModflow6Obs;
Obs: TMawObservation;
ConnectionFound: Boolean;
ValidScreensFound: Boolean;
IDomainArray: TDataArray;
procedure CompileFormula(Formula: string; const FormulaName: string;
var OutFormula: string; SpecifiedLayer: Integer = 0);
var
VarIndex: Integer;
VarName: string;
VarPosition: Integer;
Variable: TCustomValue;
AnotherDataSet: TDataArray;
Column: Integer;
Row: Integer;
Layer: Integer;
ASegment: TCellElementSegment;
begin
OutFormula := Formula;
try
Compiler.Compile(OutFormula);
except
on E: ErbwParserError do
begin
frmFormulaErrors.AddFormulaError(AScreenObject.Name, FormulaName,
OutFormula, E.Message);
frmErrorsAndWarnings.AddError(Model, StrFormulaErrorInMAW,
Format(StrThereWasAnErrorI, [AScreenObject.Name]) , AScreenObject);
OutFormula := '0';
Compiler.Compile(OutFormula);
end;
end;
UsedVariables.Clear;
Expression := Compiler.CurrentExpression;
AScreenObject.InitilizeVariablesWithNilDataSet(Expression, Model, nil, UsedVariables, Compiler);
for VarIndex := 0 to UsedVariables.Count - 1 do
begin
VarName := UsedVariables[VarIndex];
VarPosition := Compiler.IndexOfVariable(VarName);
if VarPosition >= 0 then
begin
Variable := Compiler.Variables[VarPosition];
AnotherDataSet := Model.DataArrayManager.GetDataSetByName(VarName);
if AnotherDataSet <> nil then
begin
Column := AWell.Column;
Row := AWell.Row;
Layer := SpecifiedLayer;
// AnotherDataSet := (FModel as TPhastModel).DataSets[DataSetIndex];
// Assert(AnotherDataSet <> DataSet);
Assert(AnotherDataSet.DataType = Variable.ResultType);
if AnotherDataSet.Orientation = dsoTop then
begin
Layer := 0;
end;
if AnotherDataSet.Orientation = dsoFront then
begin
Row := 0;
end;
if AnotherDataSet.Orientation = dsoSide then
begin
Column := 0;
end;
case Variable.ResultType of
rdtDouble:
begin
TRealVariable(Variable).Value := AnotherDataSet.RealData[Layer, Row, Column];
end;
rdtInteger:
begin
TIntegerVariable(Variable).Value := AnotherDataSet.IntegerData[Layer, Row, Column];
end;
rdtBoolean:
begin
TBooleanVariable(Variable).Value := AnotherDataSet.BooleanData[Layer, Row, Column];
end;
rdtString:
begin
TStringVariable(Variable).Value := AnotherDataSet.StringData[Layer, Row, Column];
end;
else
Assert(False);
end;
end;
end;
end;
UpdateCurrentModel(Model);
Column := AWell.Column;
Row := AWell.Row;
Layer := SpecifiedLayer;
UpdateGlobalLocations(Column, Row, Layer, eaBlocks, Model);
UpdateCurrentScreenObject(AScreenObject);
ASegment := AScreenObject.Segments[Model][0];
UpdateCurrentSegment(ASegment);
end;
function LayerCount: integer;
begin
if Grid <> nil then
begin
result := Grid.LayerCount;
end
else
begin
Assert(Mesh <> nil);
result := Mesh.LayerCount;
end;
end;
function GetCellTop(const Column, Row, Layer: integer): double;
begin
if Grid <> nil then
begin
result := Grid.CellElevation[Column, Row, Layer];
end
else
begin
Assert(Mesh <> nil);
result := Mesh.ElementArrayI[Layer, Column].UpperElevation;
end;
end;
function GetCellBottom(const Column, Row, Layer: integer): double;
begin
if Grid <> nil then
begin
result := Grid.CellElevation[Column, Row, Layer+1];
end
else
begin
Assert(Mesh <> nil);
result := Mesh.ElementArrayI[Layer, Column].LowerElevation;
end;
end;
begin
// evaluate well screens and well steady data.
FWellConnections.Capacity := FMawObjects.Count;
Grid := Model.Grid;
Mesh := Model.Mesh3D;
IDomainArray := Model.DataArrayManager.GetDataSetByName(K_IDOMAIN);
UsedVariables := TStringList.Create;
try
Compiler := Model.GetCompiler(dsoTop, eaBlocks);
if Values.Count > 0 then
begin
CellList := Values[0];
Assert(CellList.Count = FMawObjects.Count);
SetLength(FWellProperties, CellList.Count);
for WellIndex := 0 to CellList.Count - 1 do
begin
AWell := CellList[WellIndex] as TMawCell;
AScreenObject := FMawObjects[WellIndex];
Boundary := AScreenObject.ModflowMawBoundary;
AWellRecord.WellNumber := Boundary.WellNumber;
AWellRecord.ScreenObjectName := AScreenObject.Name;
CompileFormula(Boundary.Radius, StrMAWRadius, Formula);
Expression.Evaluate;
AWellRecord.Radius := Expression.DoubleResult;
AWellRecord.RadiusAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
CompileFormula(Boundary.Bottom, StrMAWBottom, Formula);
Expression.Evaluate;
AWellRecord.Bottom := Expression.DoubleResult;
AWellRecord.BottomAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
CompileFormula(Boundary.InitialHead, StrMAWInitialHead, Formula);
Expression.Evaluate;
AWellRecord.StartingHead := Expression.DoubleResult;
AWellRecord.StartingHeadAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
AWellRecord.ConductanceMethod := Boundary.ConductanceMethod;
AWellRecord.BoundName := AScreenObject.Name;
AWellConnection.WellNumber := Boundary.WellNumber;
AWellConnection.ScreenObjectName := AScreenObject.Name;
Cell.Column := AWell.Column;
Cell.Row := AWell.Row;
Cell.Layer := AWell.Layer;
AWellRecord.CellCount := 0;
ValidScreensFound := False;
for ScreenIndex := 0 to Boundary.WellScreens.Count - 1 do
begin
AWellScreen := Boundary.WellScreens[ScreenIndex] as TMawWellScreenItem;
CompileFormula(AWellScreen.ScreenTop, StrMAWScreenTop, Formula);
Expression.Evaluate;
AWellConnection.ScreenTop := Expression.DoubleResult;
AWellConnection.ScreenTopAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
CompileFormula(AWellScreen.ScreenBottom, StrMAWScreenBottom, Formula);
Expression.Evaluate;
AWellConnection.ScreenBottom := Expression.DoubleResult;
AWellConnection.ScreenBottomAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
ConnectionFound := False;
for LayerIndex := 0 to LayerCount - 1 do
begin
CellTop := GetCellTop(Cell.Column, Cell.Row, LayerIndex);
CellBottom := GetCellBottom(Cell.Column, Cell.Row, LayerIndex);
if (Min(CellTop, AWellConnection.ScreenTop)
- Max(CellBottom, AWellConnection.ScreenBottom) > 0) then
begin
if IDomainArray.IntegerData[LayerIndex, Cell.Row, Cell.Column] > 0 then
begin
Cell.Layer := LayerIndex;
AWellConnection.Cell := Cell;
CompileFormula(AWellScreen.SkinK, StrMAWSkinK, Formula, LayerIndex);
Expression.Evaluate;
AWellConnection.SkinK := Expression.DoubleResult;
AWellConnection.SkinKAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
CompileFormula(AWellScreen.SkinRadius, StrMAWSkinRadius, Formula, LayerIndex);
Expression.Evaluate;
AWellConnection.SkinRadius := Expression.DoubleResult;
AWellConnection.SkinRadiusAnnotation := Format(
StrAssignedBy0sUsi, [AScreenObject.Name, Formula]);
if (AWellConnection.SkinRadius <= AWellRecord.Radius)
and not (Boundary.ConductanceMethod in [mcmSpecified, mcmThiem]) then
begin
frmErrorsAndWarnings.AddError(Model, StrMAWSkinRadiusLess,
Format(StrInSTheMAWSkin, [AScreenObject.Name]), AScreenObject);
end;
Inc(AWellRecord.CellCount);
AWellConnection.ConnectionNumber := AWellRecord.CellCount;
FWellConnections.Add(AWellConnection);
ConnectionFound := True;
ValidScreensFound := True;
end;
end;
end;
if not ConnectionFound then
begin
frmErrorsAndWarnings.AddWarning(Model, StrMAWWellScreenInva,
Format(StrWellScreen0dOf, [ScreenIndex+1, AScreenObject.Name]), AScreenObject);
end;
end;
if not ValidScreensFound then
begin
frmErrorsAndWarnings.AddError(Model, StrMAWWellScreensInv,
Format(StrNoneOfTheWellScr, [AScreenObject.Name]), AScreenObject);
end;
FWellProperties[WellIndex] := AWellRecord;
end;
end;
finally
UsedVariables.Free;
end;
for WellIndex := 0 to Length(FWellProperties) - 1 do
begin
AWellSteady := FWellProperties[WellIndex];
AScreenObject := Model.GetScreenObjectByName(AWellSteady.ScreenObjectName);
if IsMf6Observation(AScreenObject) then
begin
Boundary := AScreenObject.ModflowMawBoundary;
MfObs := AScreenObject.Modflow6Obs;
Obs.FName := MfObs.Name;
Obs.FBoundName := AScreenObject.Name;
Obs.FWellNumber := Boundary.WellNumber;
Obs.FObsTypes := MfObs.MawObs;
Obs.FModflow6Obs := MfObs;
if (moFlowRateCells in Obs.FObsTypes)
or (moConductanceCells in Obs.FObsTypes) then
begin
Obs.FCount := AWellSteady.CellCount;
end
else
begin
Obs.FCount := 0;
end;
FMawObservations.Add(Obs);
end;
end;
end;
end.
|
//------------------------------------------------------------------------------
//GMCommands UNIT
//------------------------------------------------------------------------------
// What it does-
// Holds all of our GMCommand related routines.
//
// Changes -
// March 19th, 2007 - RaX - Created.
// [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide.
//
//------------------------------------------------------------------------------
unit GMCommands;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
Classes,
{Project}
Character,
GMCommandsOptions
{3rd Party}
;
const
TYPE_BROADCAST = 0; //All zone receive, no player involved
TYPE_RETURNBACK = 1; //Orignal zone receiv, no player involved
TYPE_ALLPLAYERS = 2; //All players in all zone involved
TYPE_TARGETCHAR = 3; //Specific player(character) involved
TYPE_TARGETMAP = 4; //All players in specific map involved
GMFLAG_NORMAL = 0; //Normal mode, argument will be splitted for use
GMFLAG_NOSPLIT = 1; //NO Split mode, use for only one argument, eg #broadcast, prevent split space and ","
type
TGMCommand = procedure(
const Arguments : array of String;
const FromChar : TCharacter;
const TargetChar : TCharacter;
const Error : TStringList
);
TGMCommands = class(TObject)
protected
fCommandPrefix : Char;
fCommands : TStringList;
fTmpCommandList : TStringList; // Initial use only
CommandOptions : TGMCommandsOptions;
public
// Replacement XD
function GetCommandFunc(Index: Integer): TGMCommand;
property Commands[Index: Integer]: TGMCommand read GetCommandFunc;
Constructor Create;
Destructor Destroy; override;
function AddCommand(
const Name : String;
const CommandFunc : TGMCommand;
const Level : Byte;
const AType : Byte;
const ASyntax : String;
const NoBreak : Boolean = False
) : Word;
function IsCommand(
const
Chat : String
) : Boolean;
function GetCommandID(
const
Name : String
) : Integer;
function GetCommandGMLevel(
CommandID : Integer
): Byte;
Function GetCommandName(
const
Chat : String
) : String;
function GetCommandType(
const
CommandID : Word
): Byte;
function GetCommandNoBreak(
const CommandID : Word
): Boolean;
function GetSyntax(
const
CommandID : Word
): String;
end;
TCommand = class
Name : String;
Level : Byte;
CommandType : Byte; //Should the command send to single zone/broadcast? or something else
NoParseParameter : Boolean; //To tell inter server don't break parameter!
Syntax : String; //Help message XD
CommandFunc : TGMCommand;
end;
implementation
uses
{RTL/VCL}
SysUtils,
{Project}
Main,
GMCommandExe
{3rd Party}
//none
;
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Creates our gm command component.
//
// Changes -
// March 19th, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
Constructor TGMCommands.Create;
begin
inherited;
fCommands := TStringList.Create;
fTmpCommandList := TStringList.Create;
CommandOptions := TGMCommandsOptions.Create(MainProc.Options.ConfigDirectory+'/GMCommands.ini');
//AddCommand(Command Name, Calling Function, Lvl required, command type, argument parsing mode, Syntax Help Message)
AddCommand('ZoneStatus', GMZoneStatus, 1, TYPE_BROADCAST, '');
// - - - Warps
AddCommand('Warp', GMWarp, 99, TYPE_RETURNBACK, '<Map Name>,<X>,<Y>');
AddCommand('WarpDev', GMWarpDev, 99, TYPE_RETURNBACK, '<Map Name>,<X>,<Y>');
AddCommand('Jump', GMJump, 99, TYPE_RETURNBACK, '[X],[Y]');
AddCommand('CharMove', GMCharMove, 99, TYPE_TARGETCHAR, '<Player Name>,<Map Name>,<X>,<Y>');
AddCommand('Recall', GMRecall, 99, TYPE_TARGETCHAR, '<Player Name>',True);
// - - - Player Control
AddCommand('GiveBaseExp', GMGiveBaseExperience, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('GiveJobExp', GMGiveJobExperience, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('BaseLevelUp', GMBaseLevelUp, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('JobLevelUp', GMJobLevelUp, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('AddStatusPoints', GMAddStatusPoints, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('AddSkillPoints', GMAddSkillPoints, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('GiveZeny', GMGiveZeny, 99, TYPE_TARGETCHAR, '<Player Name>,<Amount>');
AddCommand('GiveStat', GMGiveStat, 99, TYPE_TARGETCHAR, '<Player Name>,<Type>,<Amount>');
AddCommand('ResetStats', GMResetStats, 99, TYPE_TARGETCHAR, '<Player Name>', True);
AddCommand('Speed', GMSpeed, 99, TYPE_RETURNBACK, '<Speed>');
AddCommand('Die', GMDie, 99, TYPE_RETURNBACK, '');
AddCommand('Job', GMJob, 99, TYPE_RETURNBACK, '<Job ID>');
AddCommand('ResetLook', GMResetLook, 99, TYPE_RETURNBACK, '<Player Name>,<Value>');
// - - - Broadcast Sets
AddCommand('BroadCast', GMBroadCast, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastN', GMBroadCastNoName, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastL', GMBroadCastLocal, 99, TYPE_RETURNBACK, '<Message>', True);
AddCommand('BroadCastLN', GMBroadCastLocalNoName, 99, TYPE_RETURNBACK, '<Message>', True);
AddCommand('BroadCastLB', GMBroadCastLocalBlue, 99, TYPE_RETURNBACK, '<Message>', True);
AddCommand('BroadCastColor', GMBroadCastColor, 99, TYPE_ALLPLAYERS, '<Color>,<Message>');
AddCommand('BroadCastR', GMBroadCastRed, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastP', GMBroadCastPurple, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastG', GMBroadCastGreen, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastBLK', GMBroadCastBlack, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastB', GMBroadCastBlue, 99, TYPE_ALLPLAYERS, '<Message>', True);
AddCommand('BroadCastW', GMBroadCastWhite, 99, TYPE_ALLPLAYERS, '<Message>', True);
// - - - Management
AddCommand('Kick', GMKick, 99, TYPE_TARGETCHAR, '<Player Name>', True);
AddCommand('KickAll', GMKickAll, 99, TYPE_ALLPLAYERS, '');
AddCommand('Ban', GMBan, 99, TYPE_TARGETCHAR, '<Player Name>', True);
// - - - Misc stuffs
AddCommand('Item', GMItem, 99, TYPE_RETURNBACK, '<ID/Name>,[Amount]');
// - - - Debug
AddCommand('Effect', GMEffect, 99, TYPE_RETURNBACK, '<Effect Id>');
AddCommand('Where', GMWhere, 99, TYPE_RETURNBACK, '');
AddCommand('CreateInstance', GMCreateInstance, 99, TYPE_RETURNBACK, '<Identifier>,<MapName>');
AddCommand('Spawn', GMSpawn, 99, TYPE_RETURNBACK, '');
// Use temperary list!!!
fCommandPrefix := CommandOptions.Load(fTmpCommandList, fCommands);
CommandOptions.Save(fTmpCommandList);
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// destroys our component.
//
// Changes -
// March 19th, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
Destructor TGMCommands.Destroy;
var
Index : Cardinal;
begin
for Index := fTmpCommandList.Count -1 downto 0 do
fTmpCommandList.Objects[Index].Free;
fCommands.Clear;
fCommands.Free;
fTmpCommandList.Free;
CommandOptions.Free;
inherited;
end;{Create}
//------------------------------------------------------------------------------
(*- Function ------------------------------------------------------------------*
TGMCommands.AddCommand
--------------------------------------------------------------------------------
Overview:
--
Adds a GM command to the list.
Returns the index in the Commands array where this newly added command was
inserted.
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/03/19] RaX - Created
[2007/06/01] CR - Added to explanation of routine (return value). Made all
parameters constant.
*-----------------------------------------------------------------------------*)
function TGMCommands.AddCommand(
const Name : String;
const CommandFunc : TGMCommand;
const Level : Byte;
const AType : Byte;
const ASyntax : String;
const NoBreak : Boolean = False
) : Word;
var
Command : TCommand;
Begin
Command := TCommand.Create;
Command.Name := Name;
Command.Level := Level;
Command.CommandType := AType;
Command.NoParseParameter := NoBreak;
Command.Syntax := ASyntax;
Command.CommandFunc := CommandFunc;
Result := fTmpCommandList.AddObject(Name, Command);
end; (* Func TGMCommands.AddCommand
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TGMCommands.GetCommandName
--------------------------------------------------------------------------------
Overview:
--
Parses a GM command and returns the command name
--
Pre:
TODO
Post:
TODO
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/03/21] RaX - Created.
[2007/06/01] CR - Altered comment header, used try-finally as a resource
protection for our local Stringlist until freed.
*-----------------------------------------------------------------------------*)
Function TGMCommands.GetCommandName(
const
Chat : String
) : String;
Var
TempList : TStringList;
TempChat : String;
Begin
TempChat := Trim(Chat);
TempList := TStringList.Create;
try
TempList.DelimitedText := TempChat;
TempList[0] := Copy(TempList[0], 2, Length(TempList[0]));
Result := TempList[0];
finally
TempList.Free;
end;//t-f
End; (* Func TGMCommands.GetCommandName
*-----------------------------------------------------------------------------*)
//------------------------------------------------------------------------------
//GetCommandName PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Parses a gm command and returns the command name
//
// Changes -
// March 21st, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
function TGMCommands.GetCommandGMLevel(CommandID: Integer) : Byte;
var
Command : TCommand;
begin
Command := fCommands.Objects[CommandID] as TCommand;
Result := Command.Level;
end;
//------------------------------------------------------------------------------
(*- Function ------------------------------------------------------------------*
TGMCommands.IsCommand
--------------------------------------------------------------------------------
Overview:
--
Checks to see if a supplied chat string is a gm command.
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/03/19] RaX - Created.
[2007/06/01] CR - Altered Comment Header. Boolean simplification for Result
assignment (no if statement needed). Used try-finally resource protection for
local StringList variable.
*-----------------------------------------------------------------------------*)
Function TGMCommands.IsCommand(
const
Chat : String
) : Boolean;
Var
TempList : TStringList;
TempChat : String;
Begin
Result := FALSE;
TempChat := Trim(Chat);
if (TempChat[1] = fCommandPrefix) then
begin
TempList := TStringList.Create;
try
TempList.DelimitedText := TempChat;
TempList[0] := Copy(TempList[0], 2, Length(TempList[0]));
Result := (GetCommandID(TempList[0]) <> -1);
finally
TempList.Free;
end;//t-f
end;
End; (* Func TGMCommands.IsCommand
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TGMCommands.GetCommandID
--------------------------------------------------------------------------------
Overview:
--
Gets the command ID for a gm command.
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/03/19] RaX - Created
[2007/06/01] CR - Made string parameter constant (speedup/efficiency)
*-----------------------------------------------------------------------------*)
Function TGMCommands.GetCommandID(
const
Name : String
) : Integer;
Begin
Result := fCommands.IndexOf(LowerCase(Name));
End; (* Func TGMCommands.GetCommandID
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TGMCommands.GetCommandType
--------------------------------------------------------------------------------
Overview:
--
Gets the command type (used in inter server)
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/08/08] Aeomin - Created
*-----------------------------------------------------------------------------*)
function TGMCommands.GetCommandType(
const
CommandID : Word
): Byte;
var
Command : TCommand;
begin
Command := fCommands.Objects[CommandID] as TCommand;
Result := Command.CommandType;
end; (* Func TGMCommands.GetCommandType
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TGMCommands.GetCommandNoBreak
--------------------------------------------------------------------------------
Overview:
--
Should command parse parameters?
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/08/09] Aeomin - Created
*-----------------------------------------------------------------------------*)
function TGMCommands.GetCommandNoBreak(
const CommandID : Word
):Boolean;
var
Command : TCommand;
begin
Command := fCommands.Objects[CommandID] as TCommand;
Result := Command.NoParseParameter;
end; (* Func TGMCommands.GetCommandNoBreak
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TGMCommands.GetSyntax
--------------------------------------------------------------------------------
Overview:
--
Gets the command Syntax help message (used in inter server)
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/08/10] Aeomin - Created
*-----------------------------------------------------------------------------*)
function TGMCommands.GetSyntax(
const
CommandID : Word
): String;
var
Command : TCommand;
begin
Command := fCommands.Objects[CommandID] as TCommand;
Result := Command.Syntax;
end; (* Func TGMCommands.GetSyntax
*-----------------------------------------------------------------------------*)
function TGMCommands.GetCommandFunc(Index: Integer): TGMCommand;
var
Command : TCommand;
begin
Command := fCommands.Objects[Index] as TCommand;
Result := Command.CommandFunc;
end;
end{GMCommands}.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFChromiumEvents;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFTypes, uCEFInterfaces;
type
// ICefClient
TOnProcessMessageReceived = procedure(Sender: TObject; const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage; out Result: Boolean) of object;
// ICefLoadHandler
TOnLoadStart = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; transitionType: TCefTransitionType) of object;
TOnLoadEnd = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer) of object;
TOnLoadError = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring) of object;
TOnLoadingStateChange = procedure(Sender: TObject; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean) of object;
// ICefFocusHandler
TOnTakeFocus = procedure(Sender: TObject; const browser: ICefBrowser; next: Boolean) of object;
TOnSetFocus = procedure(Sender: TObject; const browser: ICefBrowser; source: TCefFocusSource; out Result: Boolean) of object;
TOnGotFocus = procedure(Sender: TObject; const browser: ICefBrowser) of object;
// ICefContextMenuHandler
TOnBeforeContextMenu = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel) of object;
TOnRunContextMenu = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel; const callback: ICefRunContextMenuCallback; var aResult : Boolean) of object;
TOnContextMenuCommand = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; out Result: Boolean) of object;
TOnContextMenuDismissed = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame) of object;
// ICefKeyboardHandler
TOnPreKeyEvent = procedure(Sender: TObject; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean; out Result: Boolean) of object;
TOnKeyEvent = procedure(Sender: TObject; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out Result: Boolean) of object;
// ICefDisplayHandler
TOnAddressChange = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const url: ustring) of object;
TOnTitleChange = procedure(Sender: TObject; const browser: ICefBrowser; const title: ustring) of object;
TOnFavIconUrlChange = procedure(Sender: TObject; const browser: ICefBrowser; const iconUrls: TStrings) of object;
TOnFullScreenModeChange = procedure(Sender: TObject; const browser: ICefBrowser; fullscreen: Boolean) of object;
TOnTooltip = procedure(Sender: TObject; const browser: ICefBrowser; var text: ustring; out Result: Boolean) of object;
TOnStatusMessage = procedure(Sender: TObject; const browser: ICefBrowser; const value: ustring) of object;
TOnConsoleMessage = procedure(Sender: TObject; const browser: ICefBrowser; const message, source: ustring; line: Integer; out Result: Boolean) of object;
TOnAutoResize = procedure(Sender: TObject; const browser: ICefBrowser; const new_size: PCefSize; out Result: Boolean) of object;
// ICefDownloadHandler
TOnBeforeDownload = procedure(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback) of object;
TOnDownloadUpdated = procedure(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback) of object;
// ICefGeolocationHandler
TOnRequestGeolocationPermission = procedure(Sender: TObject; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean) of object;
TOnCancelGeolocationPermission = procedure(Sender: TObject; const browser: ICefBrowser; requestId: Integer) of object;
// ICefJsDialogHandler
TOnJsdialog = procedure(Sender: TObject; const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean; out Result: Boolean) of object;
TOnBeforeUnloadDialog = procedure(Sender: TObject; const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback; out Result: Boolean) of object;
TOnResetDialogState = procedure(Sender: TObject; const browser: ICefBrowser) of object;
TOnDialogClosed = procedure(Sender: TObject; const browser: ICefBrowser) of object;
// ICefLifeSpanHandler
TOnBeforePopup = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean) of object;
TOnAfterCreated = procedure(Sender: TObject; const browser: ICefBrowser) of object;
TOnBeforeClose = procedure(Sender: TObject; const browser: ICefBrowser) of object;
TOnClose = procedure(Sender: TObject; const browser: ICefBrowser; out Result: Boolean) of object;
// ICefRequestHandler
TOnBeforeBrowse = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; out Result: Boolean) of object;
TOnOpenUrlFromTab = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; out Result: Boolean) of Object;
TOnBeforeResourceLoad = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback; out Result: TCefReturnValue) of object;
TOnGetResourceHandler = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; out Result: ICefResourceHandler) of object;
TOnResourceRedirect = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring) of object;
TOnResourceResponse = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; out Result: Boolean) of Object;
TOnGetResourceResponseFilter = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; out Result: ICefResponseFilter) of object;
TOnResourceLoadComplete = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64) of object;
TOnGetAuthCredentials = procedure(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; out Result: Boolean) of object;
TOnQuotaRequest = procedure(Sender: TObject; const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback; out Result: Boolean) of object;
TOnProtocolExecution = procedure(Sender: TObject; const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean) of object;
TOnCertificateError = procedure(Sender: TObject; const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback; out Result: Boolean) of Object;
TOnSelectClientCertificate = procedure(Sender: TObject; const browser: ICefBrowser; isProxy: boolean; const host: ustring; port: integer; certificatesCount: NativeUInt; const certificates: TCefX509CertificateArray; const callback: ICefSelectClientCertificateCallback; var aResult : boolean) of object;
TOnPluginCrashed = procedure(Sender: TObject; const browser: ICefBrowser; const pluginPath: ustring) of object;
TOnRenderViewReady = procedure(Sender: Tobject; const browser: ICefBrowser) of Object;
TOnRenderProcessTerminated = procedure(Sender: TObject; const browser: ICefBrowser; status: TCefTerminationStatus) of object;
// ICefDialogHandler
TOnFileDialog = procedure(Sender: TObject; const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback; out Result: Boolean) of Object;
// ICefRenderHandler
TOnGetAccessibilityHandler = procedure(Sender: TObject; var aAccessibilityHandler : ICefAccessibilityHandler) of Object;
TOnGetRootScreenRect = procedure(Sender: TObject; const browser: ICefBrowser; var rect: TCefRect; out Result: Boolean) of Object;
TOnGetViewRect = procedure(Sender: TObject; const browser: ICefBrowser; var rect: TCefRect; out Result: Boolean) of Object;
TOnGetScreenPoint = procedure(Sender: TObject; const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer; out Result: Boolean) of Object;
TOnGetScreenInfo = procedure(Sender: TObject; const browser: ICefBrowser; var screenInfo: TCefScreenInfo; out Result: Boolean) of Object;
TOnPopupShow = procedure(Sender: TObject; const browser: ICefBrowser; show: Boolean) of Object;
TOnPopupSize = procedure(Sender: TObject; const browser: ICefBrowser; const rect: PCefRect) of Object;
TOnPaint = procedure(Sender: TObject; const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer) of Object;
TOnCursorChange = procedure(Sender: TObject; const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo) of Object;
TOnStartDragging = procedure(Sender: TObject; const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean) of Object;
TOnUpdateDragCursor = procedure(Sender: TObject; const browser: ICefBrowser; operation: TCefDragOperation) of Object;
TOnScrollOffsetChanged = procedure(Sender: TObject; const browser: ICefBrowser; x, y: Double) of Object;
TOnIMECompositionRangeChanged = procedure(Sender: TObject; const browser: ICefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect) of Object;
// ICefDragHandler
TOnDragEnter = procedure(Sender: TObject; const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean) of Object;
TOnDraggableRegionsChanged = procedure(Sender: TObject; const browser: ICefBrowser; regionsCount: NativeUInt; regions: PCefDraggableRegionArray)of Object;
// ICefFindHandler
TOnFindResult = procedure(Sender: TObject; const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean) of Object;
// Custom
TOnTextResultAvailableEvent = procedure(Sender: TObject; const aText : string) of object;
TOnPdfPrintFinishedEvent = procedure(Sender: TObject; aResultOK : boolean) of object;
TOnPrefsAvailableEvent = procedure(Sender: TObject; aResultOK : boolean) of object;
TOnCookiesDeletedEvent = procedure(Sender: TObject; numDeleted : integer) of object;
TOnResolvedIPsAvailableEvent = procedure(Sender: TObject; result: TCefErrorCode; const resolvedIps: TStrings) of object;
implementation
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [VIEW_FIN_CHEQUE_NAO_COMPENSADO]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ViewFinChequeNaoCompensadoController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, ZDataset, ViewFinChequeNaoCompensadoVO;
type
TViewFinChequeNaoCompensadoController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaViewFinChequeNaoCompensadoVO;
class function ConsultaObjeto(pFiltro: String): TViewFinChequeNaoCompensadoVO;
class procedure Insere(pObjeto: TViewFinChequeNaoCompensadoVO);
class function Altera(pObjeto: TViewFinChequeNaoCompensadoVO): Boolean;
end;
implementation
uses UDataModule, T2TiORM;
var
ObjetoLocal: TViewFinChequeNaoCompensadoVO;
class function TViewFinChequeNaoCompensadoController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TViewFinChequeNaoCompensadoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TViewFinChequeNaoCompensadoController.ConsultaLista(pFiltro: String): TListaViewFinChequeNaoCompensadoVO;
begin
try
ObjetoLocal := TViewFinChequeNaoCompensadoVO.Create;
Result := TListaViewFinChequeNaoCompensadoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TViewFinChequeNaoCompensadoController.ConsultaObjeto(pFiltro: String): TViewFinChequeNaoCompensadoVO;
begin
try
Result := TViewFinChequeNaoCompensadoVO.Create;
Result := TViewFinChequeNaoCompensadoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
class procedure TViewFinChequeNaoCompensadoController.Insere(pObjeto: TViewFinChequeNaoCompensadoVO);
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TViewFinChequeNaoCompensadoController.Altera(pObjeto: TViewFinChequeNaoCompensadoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
initialization
Classes.RegisterClass(TViewFinChequeNaoCompensadoController);
finalization
Classes.UnRegisterClass(TViewFinChequeNaoCompensadoController);
end.
/// EXERCICIO: CRIE UMA JANELA DE CADASTRO QUE PERMITA O LANCAMENTO DE DO SALDO DISPONIVEL NA TABELA FIN_FECHAMENTO_CAIXA_BANCO
/// ESSE SERÁ O SALDO INICIAL DA CONTA
/// VERIFIQUE SE JÁ EXISTEM FECHAMENTOS REALIZADOS. NESSE CASO NÃO PERMITA O CADASTRO
/// EXERCICIO: CRIE UMA JANELA QUE PERMITA A TRANSFERENCIA DE VALORES ENTRE CONTA/CAIXAS
/// SERÁ PRECISO CRIAR UMA TABELA PARA CONTROLAR ISSO?
/// EXERCICIO: CRIE O RELATÓRIO DE DEMONSTRAÇÕES FINANCEIRAS CONFORME ABAIXO:
/// ===========================================================================
/// DADOS MENSAIS - PERIODO: 01/2016
/// ===========================================================================
/// SALDO ANTERIOR 100,00
/// TOTAL DE RECEBIMENTOS 50,00
/// TOTAL DE PAGAMENTOS 40,00
/// SALDO DISPONIVEL 110,00
/// CHEQUES NAO COMPENSADOS 100,00
/// SALDO DE BANCO 10,00
/// ===========================================================================
/// DADOS ANUAIS - ANO: 2016
/// ===========================================================================
/// SALDO ANTERIOR 100,00
/// TOTAL DE RECEBIMENTOS 50,00
/// TOTAL DE PAGAMENTOS 40,00
/// SALDO DISPONIVEL 110,00
/// CHEQUES NAO COMPENSADOS 100,00
/// SALDO DE BANCO 10,00
/// ===========================================================================
|
unit uoptions;
interface
uses
SysUtils, IniFiles;
type
TOptions = class
private
FIniFile: TIniFile;
FCommPort: integer;
FCommBps: integer;
FSmsc: AnsiString;
FOraSID: AnsiString;
FOraIPAddress: AnsiString;
FOraPwd: AnsiString;
FOraUser: AnsiString;
FOraIPPort: integer;
procedure SetCommBps(const Value: integer);
procedure SetCommPort(const Value: integer);
procedure SetSmsc(const Value: AnsiString);
procedure SetOraIPAddress(const Value: AnsiString);
procedure SetOraIPPort(const Value: integer);
procedure SetOraPwd(const Value: AnsiString);
procedure SetOraSID(const Value: AnsiString);
procedure SetOraUser(const Value: AnsiString);
public
procedure AfterConstruction; override;
destructor Destroy; override;
property CommPort: integer read FCommPort write SetCommPort;
property CommBps: integer read FCommBps write SetCommBps;
property Smsc: AnsiString read FSmsc write SetSmsc;
property OraIPAddress: AnsiString read FOraIPAddress write SetOraIPAddress;
property OraIPPort: integer read FOraIPPort write SetOraIPPort;
property OraSID: AnsiString read FOraSID write SetOraSID;
property OraUser: AnsiString read FOraUser write SetOraUser;
property OraPwd: AnsiString read FOraPwd write SetOraPwd;
procedure LoadOptions;
procedure SaveOptions;
end;
function Options: TOptions;
implementation
var
FOptions: TOptions;
function Options: TOptions;
begin
if FOptions=nil then
begin
FOptions := TOptions.Create;
FOptions.LoadOptions;
end;
Result := FOptions;
end;
{ TOptions }
procedure TOptions.AfterConstruction;
begin
inherited;
FIniFile := TIniFile.Create('.\Options.ini');
end;
destructor TOptions.Destroy;
begin
FIniFile.Free;
inherited;
end;
procedure TOptions.LoadOptions;
begin
FCommPort := FIniFile.ReadInteger('System','CommPort',1);
FCommBps := FIniFile.ReadInteger('System','CommBps',115200);
FSmsc := FIniFile.ReadString('System','SMSCCode','13700571500');
FOraIPAddress := FIniFile.ReadString('DbSource','IP','127.0.0.1');
FOraIPPort := FIniFile.ReadInteger('DbSource','Port',1521);
FOraSID := FIniFile.ReadString('DbSource','SID','pss');
FOraUser := FIniFile.ReadString('DbSource','User','pss');
FOraPwd := FIniFile.ReadString('DbSource','Password','pss');
end;
procedure TOptions.SaveOptions;
begin
FIniFile.WriteInteger('System','CommPort',FCommPort);
FIniFile.WriteInteger('System','CommBps',FCommBps);
FIniFile.WriteString('System','SMSCCode',FSmsc);
FIniFile.WriteString('DbSource','IP',FOraIPAddress);
FIniFile.WriteInteger('DbSource','Port',FOraIPPort);
FIniFile.WriteString('DbSource','SID',FOraSID);
FIniFile.WriteString('DbSource','User',FOraUser);
FIniFile.WriteString('DbSource','Password',FOraPwd);
end;
procedure TOptions.SetCommBps(const Value: integer);
begin
FCommBps := Value;
end;
procedure TOptions.SetCommPort(const Value: integer);
begin
FCommPort := Value;
end;
procedure TOptions.SetOraIPAddress(const Value: AnsiString);
begin
FOraIPAddress := Value;
end;
procedure TOptions.SetOraIPPort(const Value: integer);
begin
FOraIPPort := Value;
end;
procedure TOptions.SetOraPwd(const Value: AnsiString);
begin
FOraPwd := Value;
end;
procedure TOptions.SetOraSID(const Value: AnsiString);
begin
FOraSID := Value;
end;
procedure TOptions.SetOraUser(const Value: AnsiString);
begin
FOraUser := Value;
end;
procedure TOptions.SetSmsc(const Value: AnsiString);
begin
FSmsc := Value;
end;
initialization
FOptions := nil;
finalization
FreeAndNil(FOptions);
end.
|
unit uDadosAssinantes;
interface
uses
System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Datasnap.DBClient,
Datasnap.Provider, Data.SqlExpr, Vcl.Dialogs, System.UITypes,
System.DateUtils, Data.DBXCommon, Math, System.Variants;
const
NENHUM_ASSINANTE_SELECIONADA = 'Nenhum assinante está selecionado.';
NENHUMA_ASSINATURA_SELECIONADA = 'Nenhuma assinatura está selecionada.';
NENHUM_HISTORICO_SELECIONADO = 'Nenhum histórico está selecionado.';
NENHUMA_BAIXA_SELECIONADA = 'Nenhuma baixa está selecionada.';
type
TOperacao = (oNone, oInsert, oUpdate, oDelete);
type
TdmDadosAssinantes = class(TDataModule)
sqlTblass: TSQLDataSet;
dspTblass: TDataSetProvider;
cdsTblass: TClientDataSet;
cdsTblassasscod: TIntegerField;
cdsTblassasscpf: TStringField;
cdsTblassassrazaosocial: TStringField;
cdsTblassasscnpj: TStringField;
cdsTblassassstatus: TIntegerField;
cdsTblassassdtinativo: TDateField;
cdsTblassassdtnasc: TDateField;
cdsTblassrdzcod: TIntegerField;
cdsTblassassnroent: TStringField;
cdsTblassasscomplent: TStringField;
cdsTblassassbairroent: TStringField;
cdsTblasscepcepent: TStringField;
cdsTblassassendercobr: TStringField;
cdsTblassassfonecomer: TStringField;
cdsTblassassfonecomerramal: TStringField;
cdsTblassassfoneresid: TStringField;
cdsTblassassfonefax: TStringField;
cdsTblassassfonecelul: TStringField;
cdsTblassvencod: TIntegerField;
cdsTblasscobcod: TIntegerField;
cdsTblassassimpretiq: TStringField;
cdsTblassassemail: TStringField;
cdsTblassassobs: TStringField;
cdsTblassLookupStatus: TStringField;
cdsTblassLookupImpretiq: TStringField;
sqlTblcep: TSQLDataSet;
sqlTblcepcepcep: TStringField;
sqlTblcepcepmunicipio: TStringField;
sqlTblcepcepeuf: TStringField;
sqlRuaZona: TSQLDataSet;
sqlRuaZonardzcod: TIntegerField;
sqlRuaZonardzender: TStringField;
sqlRuaZonazondescr: TStringField;
sqlLookupVendedores: TSQLDataSet;
dspLookupVendedores: TDataSetProvider;
cdsLookupVendedores: TClientDataSet;
cdsLookupVendedoresvencod: TIntegerField;
cdsLookupVendedoresvennome: TStringField;
cdsTblassLookupVencod: TStringField;
sqlLookupCobradores: TSQLDataSet;
dspLookupCobradores: TDataSetProvider;
cdsLookupCobradores: TClientDataSet;
cdsLookupCobradorescobcod: TIntegerField;
cdsLookupCobradorescobnome: TStringField;
cdsTblassLookupCobcod: TStringField;
cdsTblassCalcFonecomerCompleto: TStringField;
cdsTblassCalcImpretiq: TStringField;
sqlTblada: TSQLDataSet;
cdsTblada: TClientDataSet;
cdsTbladaasscod: TIntegerField;
cdsTbladaadacod: TIntegerField;
cdsTbladaadatipo: TStringField;
cdsTbladaadadtini: TDateField;
cdsTbladaadadtvenc: TDateField;
cdsTbladaadavl: TFloatField;
cdsTbladaadavlpend: TFloatField;
cdsTbladaadaobs: TStringField;
cdsTbladaadacancel: TStringField;
cdsTbladaCalcAdatipo: TStringField;
cdsTbladaCalcAdacancel: TStringField;
sqlTblbda: TSQLDataSet;
cdsTblbda: TClientDataSet;
cdsTblbdaasscod: TIntegerField;
cdsTblbdaadacod: TIntegerField;
cdsTblbdabdacod: TIntegerField;
cdsTblbdausucod: TIntegerField;
cdsTblbdabdadt: TDateField;
cdsTblbdabdavl: TFloatField;
sqlExisteCnpj: TSQLDataSet;
sqlExisteCnpjasscnpj: TStringField;
sqlExisteCnpjassnome: TStringField;
sqlExisteCpf: TSQLDataSet;
sqlExisteCpfasscpf: TStringField;
sqlExisteCpfassnome: TStringField;
sqlExisteCnpjasscod: TIntegerField;
sqlExisteCpfasscod: TIntegerField;
cdsTbladaLookupAdacancel: TStringField;
cdsLookupTipoAssinatura: TClientDataSet;
cdsLookupTipoAssinaturaCodigo: TStringField;
cdsLookupTipoAssinaturaDescr: TStringField;
cdsTbladaLookupAdatipo: TStringField;
sqlMaxAdacod: TSQLDataSet;
sqlMaxAdacodadacod: TIntegerField;
sqlAssinaturaAnterior: TSQLDataSet;
sqlAssinaturaAnteriorasscod: TIntegerField;
sqlAssinaturaAnterioradacod: TIntegerField;
sqlAssinaturaAnterioradatipo: TStringField;
sqlAssinaturaAnterioradadtini: TDateField;
sqlAssinaturaAnterioradadtvenc: TDateField;
sqlAssinaturaAnterioradavl: TFloatField;
sqlAssinaturaAnterioradavlpend: TFloatField;
sqlAssinaturaAnterioradaobs: TStringField;
sqlAssinaturaAnterioradacancel: TStringField;
sqlTotalBaixas: TSQLDataSet;
sqlTotalBaixasvltotbaixas: TFloatField;
sqlMaxBdacod: TSQLDataSet;
sqlMaxBdacodbdacod: TIntegerField;
sqlPesquisaEndereco: TSQLDataSet;
dspPesquisaEndereco: TDataSetProvider;
cdsPesquisaEndereco: TClientDataSet;
cdsPesquisaEnderecordzcod: TIntegerField;
cdsPesquisaEnderecordzender: TStringField;
cdsPesquisaEnderecozoncod: TStringField;
cdsPesquisaEnderecozondescr: TStringField;
sqlAssinaturasAuto: TSQLDataSet;
dspAssinaturasAuto: TDataSetProvider;
cdsAssinaturasAuto: TClientDataSet;
cdsAssinaturasAutoasscod: TIntegerField;
cdsAssinaturasAutoassnome: TStringField;
cdsAssinaturasAutoadadtini: TDateField;
cdsAssinaturasAutoadadtvenc: TDateField;
sqlTblgaa: TSQLDataSet;
dspTblgaa: TDataSetProvider;
cdsTblgaa: TClientDataSet;
cdsTblgaagaaanomes: TDateField;
cdsTblgaagaadtgerauto: TDateField;
cdsTblgaausucod: TIntegerField;
dspTblada: TDataSetProvider;
dspTblbda: TDataSetProvider;
sqlTblbdaasscod: TIntegerField;
sqlTblbdaadacod: TIntegerField;
sqlTblbdabdacod: TIntegerField;
sqlTblbdausucod: TIntegerField;
sqlTblbdabdadt: TDateField;
sqlTblbdabdavl: TFloatField;
sqlTblbdausunome: TStringField;
cdsTblbdausunome: TStringField;
sqlFiltroZona: TSQLDataSet;
dspFiltroZona: TDataSetProvider;
cdsFiltroZona: TClientDataSet;
cdsFiltroZonazoncod: TStringField;
cdsFiltroZonazondescr: TStringField;
cdsTblasszondescr: TStringField;
sqlTblassasscod: TIntegerField;
sqlTblassassnome: TStringField;
sqlTblassasscpf: TStringField;
sqlTblassassrazaosocial: TStringField;
sqlTblassasscnpj: TStringField;
sqlTblassassstatus: TIntegerField;
sqlTblassassdtinativo: TDateField;
sqlTblassassdtnasc: TDateField;
sqlTblassrdzcod: TIntegerField;
sqlTblassassnroent: TStringField;
sqlTblassasscomplent: TStringField;
sqlTblassassbairroent: TStringField;
sqlTblasscepcepent: TStringField;
sqlTblassassendercobr: TStringField;
sqlTblassassfonecomer: TStringField;
sqlTblassassfonecomerramal: TStringField;
sqlTblassassfoneresid: TStringField;
sqlTblassassfonefax: TStringField;
sqlTblassassfonecelul: TStringField;
sqlTblassvencod: TIntegerField;
sqlTblasscobcod: TIntegerField;
sqlTblassassimpretiq: TStringField;
sqlTblassassemail: TStringField;
sqlTblassassobs: TStringField;
sqlTblasszondescr: TStringField;
sqlExisteEndereco: TSQLDataSet;
sqlExisteEnderecoasscod: TIntegerField;
sqlExisteEnderecoassnome: TStringField;
cdsTbladaadadtcancel: TDateField;
sqlExisteProxAss: TSQLDataSet;
sqlExisteProxAssnroreg: TLargeintField;
sqlTblasszoncod: TStringField;
cdsTblasszoncod: TStringField;
cdsTblassCalcCodigoDescrZona: TStringField;
sqlRuaZonazoncod: TStringField;
cdsTblassCalcDescrStatus: TStringField;
sqlBaixaRapida: TSQLDataSet;
dspBaixaRapida: TDataSetProvider;
cdsBaixaRapida: TClientDataSet;
cdsBaixaRapidaasscod: TIntegerField;
cdsBaixaRapidaassnome: TStringField;
cdsBaixaRapidaadacod: TIntegerField;
cdsBaixaRapidaadadtvenc: TDateField;
cdsBaixaRapidaadavlpend: TFloatField;
sqlTblassassdtalt: TDateField;
sqlTblassusucodalt: TIntegerField;
cdsTblassassdtalt: TDateField;
cdsTblassusucodalt: TIntegerField;
cdsTbladaadadtalt: TDateField;
cdsTbladausucodalt: TIntegerField;
cdsTblgaagaavlass: TFloatField;
cdsTblgaagaanromes: TIntegerField;
cdsTblgaagaacod: TIntegerField;
sqlMaxGaacod: TSQLDataSet;
sqlMaxGaacodgaacod: TLargeintField;
cdsTbladagaacod: TIntegerField;
cdsTblgaagaavennome: TStringField;
sqlTblhas: TSQLDataSet;
dspTblhas: TDataSetProvider;
cdsTblhas: TClientDataSet;
cdsTblhasasscod: TIntegerField;
cdsTblhashasseg: TIntegerField;
cdsTblhashasdt: TDateField;
cdsTblhashasdescr: TMemoField;
sqlMaxHasseg: TSQLDataSet;
sqlMaxHasseghasseg: TIntegerField;
cdsTblhasCalcHasdescr: TStringField;
cdsTblassassnome: TStringField;
cdsTbladaadavldesc: TFloatField;
sqlTblcpa: TSQLDataSet;
dspTblcpa: TDataSetProvider;
cdsTblcpa: TClientDataSet;
cdsTblcpaasscod: TIntegerField;
cdsTblcpaadacod: TIntegerField;
cdsTblcpacpadtvenc: TDateField;
cdsTblcpacpadtemis: TDateField;
cdsTblcpacpavl: TFloatField;
sqlUpdateTblada: TSQLDataSet;
sqlInsertTblada: TSQLDataSet;
sqlDeleteTblcpa: TSQLDataSet;
sqlInsertTblcpa: TSQLDataSet;
sqlDeleteTblada: TSQLDataSet;
sqlDeleteTblbda: TSQLDataSet;
sqlUpdateTblbda: TSQLDataSet;
sqlInsertTblbda: TSQLDataSet;
sqlInsertTblgaa: TSQLDataSet;
sqlInsertTblass: TSQLDataSet;
sqlUpdateTblass: TSQLDataSet;
sqlDeleteTblass: TSQLDataSet;
sqlMaxGaaanomes: TSQLDataSet;
sqlMaxGaaanomesgaaanomes: TDateField;
sqlInsertTblhma: TSQLDataSet;
sqlMaxAsscod: TSQLDataSet;
sqlMaxAsscodasscod: TIntegerField;
cdsTblcpaBkp: TClientDataSet;
cdsTblcpaBkpcpadtvenc: TDateField;
cdsTblcpaBkpcpavl: TFloatField;
cdsTblcpacpanroparc: TIntegerField;
cdsTbladaadacortesia: TStringField;
cdsTbladaLookupAdacortesia: TStringField;
cdsAssinaturasAutoadacortesia: TStringField;
procedure cdsTblassNewRecord(DataSet: TDataSet);
procedure cdsTblassCalcFields(DataSet: TDataSet);
procedure cdsTbladaCalcFields(DataSet: TDataSet);
procedure dspTblassUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTblasscepcepentValidate(Sender: TField);
procedure cdsTblassBeforePost(DataSet: TDataSet);
procedure cdsTblassAfterScroll(DataSet: TDataSet);
procedure cdsTblassassnomeValidate(Sender: TField);
procedure cdsTblassasscnpjValidate(Sender: TField);
procedure cdsTblassasscpfValidate(Sender: TField);
procedure cdsTblassassnroentValidate(Sender: TField);
procedure cdsTblassassemailValidate(Sender: TField);
procedure DataModuleCreate(Sender: TObject);
procedure cdsTblassassstatusValidate(Sender: TField);
procedure cdsTbladaNewRecord(DataSet: TDataSet);
procedure cdsTbladaadadtvencValidate(Sender: TField);
procedure cdsTbladaadavlValidate(Sender: TField);
procedure cdsTblbdaNewRecord(DataSet: TDataSet);
procedure cdsTblbdabdadtValidate(Sender: TField);
procedure cdsTblbdabdavlValidate(Sender: TField);
procedure cdsTblassrdzcodValidate(Sender: TField);
procedure dspAssinaturasAutoUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure dspTblgaaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure dspTbladaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure dspTblbdaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTbladaAfterScroll(DataSet: TDataSet);
procedure cdsTblassBeforeOpen(DataSet: TDataSet);
procedure cdsTbladaadacancelValidate(Sender: TField);
procedure cdsTblbdaBeforePost(DataSet: TDataSet);
procedure cdsTbladaadadtcancelValidate(Sender: TField);
procedure cdsTblassassdtinativoValidate(Sender: TField);
procedure dspTblhasUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTblhasNewRecord(DataSet: TDataSet);
procedure cdsTblhashasdtValidate(Sender: TField);
procedure cdsTblhashasdescrValidate(Sender: TField);
procedure cdsTblhasCalcFields(DataSet: TDataSet);
procedure cdsTbladaadavldescValidate(Sender: TField);
procedure dspTblcpaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTblcpacpavlValidate(Sender: TField);
procedure cdsTblcpaNewRecord(DataSet: TDataSet);
procedure cdsTbladaBeforePost(DataSet: TDataSet);
private
{ Private declarations }
FOperacao: TOperacao;
procedure AtualizarDadosAssinante(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
procedure AtualizarMudancaDadosAssinante(AOperacao: TOperacao);
procedure AtualizarDadosAssinatura(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
procedure AtualizarMudancaDadosAssinatura(AOperacao: TOperacao);
procedure AtualizarDadosBaixa(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
procedure AtualizarMudancaDadosBaixa(AOperacao: TOperacao);
procedure AtualizarDadosHistorico(AOperacao: TOperacao);
procedure AtualizarValorPendenteAssinatura(ANovoValorPendente: Double); overload;
procedure AtualizarValorPendenteAssinatura; overload;
procedure PosicionarAssinante(ACodigoAssinante: Integer; ACodigoAssinatura: Integer);
procedure AtualizarTabelaTblhma(AAsscod, AUsucod: Integer; AHmadescr: String);
function GetValorTotalBaixas(Aasscod, Aadacod: Integer; Abdacod: Integer = 0): Double;
function GetDescricaoStatusAssinante(Aassstatus: Integer): String;
public
{ Public declarations }
procedure FiltrarEnderecos(AEnderecoZona: String);
procedure FiltrarAssinantes(ACodigo: Integer = 0; ANomeAssinante: String = ''; AEndereco: String = ''; ANroEndereco: String = ''; ACodigoZona: String = ''; ADescrZona: String = ''; AStatus: Integer = -1);
// Métodos referente ao Assinante
procedure AdicionarAssinante;
procedure EditarAssinante;
procedure ExcluirAssinante;
procedure CancelarManutencaoAssinante;
procedure SalvarAssinante(AValidarDados: Boolean = true);
// Métodos referente a Assinatura
procedure AdicionarAssinatura;
procedure EditarAssinatura;
procedure ExcluirAssinatura;
procedure CancelarManutencaoAssinatura;
procedure SalvarAssinatura(AValidarDados: Boolean = true);
procedure GerarCondicoesParcelas(AQtdeParcelas: Integer; APrimeiroVenc: TDate; AValorPagar: Double);
// Métodos referente ao Histórico do Assinante
procedure AdicionarHistorico;
procedure EditarHistorico;
procedure ExcluirHistorico;
procedure CancelarManutencaoHistorico;
procedure SalvarHistorico(AValidarDados: Boolean = true);
// Métodos referente a Baixa da assinatura
procedure AdicionarBaixa; overload;
procedure AdicionarBaixa(ACodigoAssinante: integer; ACodigoAssinatura: Integer; ADataBaixa: TDate; AValorBaixa: Double); overload;
procedure EditarBaixa;
procedure ExcluirBaixa;
procedure CancelarManutencaoBaixa;
procedure SalvarBaixa(AValidarDados: Boolean = true);
procedure FiltrarAssinantesBaixaRapida(ANomeAssinante: String = '');
// Métodos referente a Renovação automática
procedure RenovarAssinaturasAutomaticamente(AMes, AAno: Integer; AValorAssinatura: Double; ANroMesesAssinatura: Integer; AVencod: Integer; AVennome: String);
function RetornaDataUltimaRenovacaoAuto: TDate;
function GetDescricaoTipoAssinatura(Aadatipo: String): String;
end;
var
dmDadosAssinantes: TdmDadosAssinantes;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses uConexao, uDadosGlobal, uUsuario, uMensagem, uDadosCobradores, uDadosVendedores,
uDadosZonasRuas;
{$R *.dfm}
procedure TdmDadosAssinantes.AdicionarAssinante;
begin
if not cdsTblass.Active then
FiltrarAssinantes;
CancelarManutencaoAssinante;
cdsTblass.Append;
FOperacao := oInsert;
end;
procedure TdmDadosAssinantes.AdicionarAssinatura;
begin
if not cdsTblass.Active then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if cdsTblass.RecordCount = 0 then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if not cdsTblada.Active then
cdsTblada.Open;
if not cdsTblcpa.Active then
cdsTblcpa.Open;
CancelarManutencaoAssinatura;
cdsTblada.Insert;
FOperacao := oInsert;
end;
procedure TdmDadosAssinantes.AdicionarBaixa(ACodigoAssinante,
ACodigoAssinatura: Integer; ADataBaixa: TDate; AValorBaixa: Double);
begin
FiltrarAssinantes(ACodigoAssinante);
if cdsTblass.RecordCount = 0 then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
PosicionarAssinante(ACodigoAssinante, ACodigoAssinatura);
if cdsTblada.RecordCount = 0 then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
AdicionarBaixa;
cdsTblbdabdadt.Value := ADataBaixa;
cdsTblbdabdavl.Value := AValorBaixa;
SalvarBaixa(true);
end;
procedure TdmDadosAssinantes.AdicionarHistorico;
begin
if not cdsTblass.Active then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if cdsTblass.RecordCount = 0 then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if not cdsTblhas.Active then
cdsTblhas.Open;
CancelarManutencaoHistorico;
cdsTblhas.Insert;
FOperacao := oInsert;
end;
procedure TdmDadosAssinantes.AdicionarBaixa;
begin
if not cdsTblada.Active then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
if cdsTblada.RecordCount = 0 then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
if not cdsTblbda.Active then
cdsTblbda.Open;
CancelarManutencaoBaixa;
cdsTblbda.Insert;
FOperacao := oInsert;
end;
procedure TdmDadosAssinantes.AtualizarValorPendenteAssinatura(
ANovoValorPendente: Double);
begin
// Coloca em estado de Edição caso não esteja.
if cdsTblada.State in [dsBrowse] then
cdsTblada.Edit;
cdsTbladaadavlpend.Value := ANovoValorPendente;
end;
procedure TdmDadosAssinantes.AtualizarDadosAssinante(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
var
lAsscodNovo: Integer;
begin
try
if cdsTblass.State in [dsEdit, dsInsert] then
cdsTblass.Post;
case AOperacao of
oNone:
begin
raise Exception.Create('Operação não definida para esta atualização.');
end;
oInsert:
begin
// Pega um novo número para o novo assinate.
sqlMaxAsscod.Close;
sqlMaxAsscod.Open;
lAsscodNovo := sqlMaxAsscodasscod.Value + 1;
// atualiza o novo número do CDS
cdsTblass.Edit;
cdsTblassasscod.Value := lAsscodNovo;
cdsTblass.Post;
sqlInsertTblass.Close;
sqlInsertTblass.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlInsertTblass.ParamByName('assnome').AsAnsiString := cdsTblassassnome.Value;
sqlInsertTblass.ParamByName('asscpf').AsAnsiString := cdsTblassasscpf.Value;
sqlInsertTblass.ParamByName('assrazaosocial').AsAnsiString := cdsTblassassrazaosocial.Value;
sqlInsertTblass.ParamByName('asscnpj').AsAnsiString := cdsTblassasscnpj.Value;
sqlInsertTblass.ParamByName('assstatus').AsInteger := cdsTblassassstatus.Value;
sqlInsertTblass.ParamByName('assdtinativo').AsDate := cdsTblassassdtinativo.Value;
sqlInsertTblass.ParamByName('assdtnasc').AsDate := cdsTblassassdtnasc.Value;
sqlInsertTblass.ParamByName('rdzcod').AsInteger := cdsTblassrdzcod.Value;
sqlInsertTblass.ParamByName('assnroent').AsAnsiString := cdsTblassassnroent.Value;
sqlInsertTblass.ParamByName('asscomplent').AsAnsiString := cdsTblassasscomplent.Value;
sqlInsertTblass.ParamByName('assbairroent').AsAnsiString := cdsTblassassbairroent.Value;
sqlInsertTblass.ParamByName('cepcepent').AsAnsiString := cdsTblasscepcepent.Value;
sqlInsertTblass.ParamByName('assendercobr').AsAnsiString := cdsTblassassendercobr.Value;
sqlInsertTblass.ParamByName('assfonecomer').AsAnsiString := cdsTblassassfonecomer.Value;
sqlInsertTblass.ParamByName('assfonecomerramal').AsAnsiString := cdsTblassassfonecomerramal.Value;
sqlInsertTblass.ParamByName('assfoneresid').AsAnsiString := cdsTblassassfoneresid.Value;
sqlInsertTblass.ParamByName('assfonefax').AsAnsiString := cdsTblassassfonefax.Value;
sqlInsertTblass.ParamByName('assfonecelul').AsAnsiString := cdsTblassassfonecelul.Value;
sqlInsertTblass.ParamByName('vencod').AsInteger := cdsTblassvencod.Value;
sqlInsertTblass.ParamByName('cobcod').AsInteger := cdsTblasscobcod.Value;
sqlInsertTblass.ParamByName('assimpretiq').AsAnsiString := cdsTblassassimpretiq.Value;
sqlInsertTblass.ParamByName('assemail').AsAnsiString := cdsTblassassemail.Value;
sqlInsertTblass.ParamByName('assobs').AsAnsiString := cdsTblassassobs.Value;
sqlInsertTblass.ParamByName('assdtalt').AsDate := cdsTblassassdtalt.Value;
sqlInsertTblass.ParamByName('usucodalt').AsInteger := cdsTblassusucodalt.Value;
sqlInsertTblass.ExecSQL;
end;
oUpdate:
begin
sqlUpdateTblass.Close;
sqlUpdateTblass.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlUpdateTblass.ParamByName('assnome').AsAnsiString := cdsTblassassnome.Value;
sqlUpdateTblass.ParamByName('asscpf').AsAnsiString := cdsTblassasscpf.Value;
sqlUpdateTblass.ParamByName('assrazaosocial').AsAnsiString := cdsTblassassrazaosocial.Value;
sqlUpdateTblass.ParamByName('asscnpj').AsString := cdsTblassasscnpj.Value;
sqlUpdateTblass.ParamByName('assstatus').AsInteger := cdsTblassassstatus.Value;
sqlUpdateTblass.ParamByName('assdtinativo').AsDate := cdsTblassassdtinativo.Value;
if cdsTblassassdtinativo.Value = StrToDate('30/12/1899') then
sqlUpdateTblass.ParamByName('assdtinativo').Clear
else
sqlUpdateTblass.ParamByName('assdtinativo').AsDate := cdsTblassassdtinativo.Value;
sqlUpdateTblass.ParamByName('assdtnasc').AsDate := cdsTblassassdtnasc.Value;
sqlUpdateTblass.ParamByName('rdzcod').AsInteger := cdsTblassrdzcod.Value;
sqlUpdateTblass.ParamByName('assnroent').AsAnsiString := cdsTblassassnroent.Value;
sqlUpdateTblass.ParamByName('asscomplent').AsAnsiString := cdsTblassasscomplent.Value;
sqlUpdateTblass.ParamByName('assbairroent').AsAnsiString := cdsTblassassbairroent.Value;
sqlUpdateTblass.ParamByName('cepcepent').AsAnsiString := cdsTblasscepcepent.Value;
sqlUpdateTblass.ParamByName('assendercobr').AsAnsiString := cdsTblassassendercobr.Value;
sqlUpdateTblass.ParamByName('assfonecomer').AsAnsiString := cdsTblassassfonecomer.Value;
sqlUpdateTblass.ParamByName('assfonecomerramal').AsAnsiString := cdsTblassassfonecomerramal.Value;
sqlUpdateTblass.ParamByName('assfoneresid').AsAnsiString := cdsTblassassfoneresid.Value;
sqlUpdateTblass.ParamByName('assfonefax').AsAnsiString := cdsTblassassfonefax.Value;
sqlUpdateTblass.ParamByName('assfonecelul').AsAnsiString := cdsTblassassfonecelul.Value;
sqlUpdateTblass.ParamByName('vencod').AsInteger := cdsTblassvencod.Value;
sqlUpdateTblass.ParamByName('cobcod').AsInteger := cdsTblasscobcod.Value;
sqlUpdateTblass.ParamByName('assimpretiq').AsAnsiString := cdsTblassassimpretiq.Value;
sqlUpdateTblass.ParamByName('assemail').AsAnsiString := cdsTblassassemail.Value;
sqlUpdateTblass.ParamByName('assobs').AsAnsiString := cdsTblassassobs.Value;
sqlUpdateTblass.ParamByName('assdtalt').AsDate := cdsTblassassdtalt.Value;
sqlUpdateTblass.ParamByName('usucodalt').AsInteger := cdsTblassusucodalt.Value;
sqlUpdateTblass.ExecSQL;
end;
oDelete:
begin
sqlDeleteTblass.Close;
sqlDeleteTblass.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlDeleteTblass.ExecSQL;
end;
end;
// Verifica se teve mudanças nos campos e atualiza a tabela de histórico de
// mudanças do assinante
if AAtualizarHistorico then
AtualizarMudancaDadosAssinante(AOperacao);
except
on E: Exception do
begin
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Assinante informado já está cadastrada.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Assinante informado já está cadastrada.')
else if pos('foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir este Assinante, pois existem assinaturas/baixas cadastradas para este mesmo assinante.')
else
raise Exception.Create(e.Message);
end;
end;
end;
procedure TdmDadosAssinantes.AtualizarDadosAssinatura(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
var
i: Integer;
begin
try
if cdsTblada.State in [dsEdit, dsInsert] then
cdsTblada.Post;
if AOperacao = oInsert then
begin
sqlInsertTblada.Close;
sqlInsertTblada.ParamByName('asscod').AsInteger := cdsTbladaasscod.Value;
sqlInsertTblada.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
sqlInsertTblada.ParamByName('adatipo').AsAnsiString := cdsTbladaadatipo.Value;
sqlInsertTblada.ParamByName('adadtini').AsDate := cdsTbladaadadtini.Value;
sqlInsertTblada.ParamByName('adadtvenc').AsDate := cdsTbladaadadtvenc.Value;
sqlInsertTblada.ParamByName('adavl').AsFloat := cdsTbladaadavl.Value;
sqlInsertTblada.ParamByName('adavldesc').AsFloat := cdsTbladaadavldesc.Value;
sqlInsertTblada.ParamByName('adavlpend').AsFloat := cdsTbladaadavlpend.Value;
if (cdsTbladaadaobs.IsNull) or (trim(cdsTbladaadaobs.Value) = '') then
sqlInsertTblada.ParamByName('adaobs').Clear
else
sqlInsertTblada.ParamByName('adaobs').AsAnsiString := cdsTbladaadaobs.Value;
sqlInsertTblada.ParamByName('adacancel').AsAnsiString := cdsTbladaadacancel.Value;
if cdsTbladaadadtcancel.Value = StrToDate('30/12/1899') then
sqlInsertTblada.ParamByName('adadtcancel').Clear
else
sqlInsertTblada.ParamByName('adadtcancel').AsDate := cdsTbladaadadtcancel.Value;
sqlInsertTblada.ParamByName('adacortesia').AsAnsiString := cdsTbladaadacortesia.Value;
if cdsTbladagaacod.IsNull then
sqlInsertTblada.ParamByName('gaacod').clear
else
sqlInsertTblada.ParamByName('gaacod').AsInteger := cdsTbladagaacod.Value;
sqlInsertTblada.ParamByName('adadtalt').AsDate := cdsTbladaadadtalt.Value;
sqlInsertTblada.ParamByName('usucodalt').AsInteger := cdsTbladausucodalt.Value;
sqlInsertTblada.ExecSQL;
end;
if AOperacao = oUpdate then
begin
sqlUpdateTblada.Close;
sqlUpdateTblada.ParamByName('asscod').AsInteger := cdsTbladaasscod.Value;
sqlUpdateTblada.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
sqlUpdateTblada.ParamByName('adatipo').AsAnsiString := cdsTbladaadatipo.Value;
sqlUpdateTblada.ParamByName('adadtini').AsDate := cdsTbladaadadtini.Value;
sqlUpdateTblada.ParamByName('adadtvenc').AsDate := cdsTbladaadadtvenc.Value;
sqlUpdateTblada.ParamByName('adavl').AsFloat := cdsTbladaadavl.Value;
sqlUpdateTblada.ParamByName('adavldesc').AsFloat := cdsTbladaadavldesc.Value;
sqlUpdateTblada.ParamByName('adavlpend').AsFloat := cdsTbladaadavlpend.Value;
if (cdsTbladaadaobs.IsNull) or (trim(cdsTbladaadaobs.Value) = '') then
sqlUpdateTblada.ParamByName('adaobs').Clear
else
sqlUpdateTblada.ParamByName('adaobs').AsAnsiString := cdsTbladaadaobs.Value;
sqlUpdateTblada.ParamByName('adacancel').AsAnsiString := cdsTbladaadacancel.Value;
if cdsTbladaadadtcancel.Value = StrToDate('30/12/1899') then
sqlUpdateTblada.ParamByName('adadtcancel').Clear
else
sqlUpdateTblada.ParamByName('adadtcancel').AsDate := cdsTbladaadadtcancel.Value;
sqlUpdateTblada.ParamByName('adacortesia').AsAnsiString := cdsTbladaadacortesia.Value;
if cdsTbladagaacod.IsNull then
sqlUpdateTblada.ParamByName('gaacod').clear
else
sqlUpdateTblada.ParamByName('gaacod').AsInteger := cdsTbladagaacod.Value;
sqlUpdateTblada.ParamByName('adadtalt').AsDate := cdsTbladaadadtalt.Value;
sqlUpdateTblada.ParamByName('usucodalt').AsInteger := cdsTbladausucodalt.Value;
sqlUpdateTblada.ExecSQL;
end;
if AOperacao = oDelete then
begin
sqlDeleteTblada.Close;
sqlDeleteTblada.ParamByName('asscod').AsInteger := cdsTbladaasscod.Value;
sqlDeleteTblada.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
sqlDeleteTblada.ExecSQL;
end;
except
on E: Exception do
begin
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Assinatura informada já está cadastrada.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Assinatura informada já está cadastrada.')
else if pos('cannot delete or update a parent row: a foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir esta assinatura, pois existem baixas cadastradas para esta mesma assinatura.')
else if pos('cannot delete master record with details', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir esta assinatura, pois existem baixas cadastradas para esta mesma assinatura.')
else
raise Exception.Create(e.Message);
end;
end;
try
if cdsTblcpa.State in [dsEdit, dsInsert] then
cdsTblcpa.Post;
if AOperacao <> oDelete then
begin
sqlDeleteTblcpa.Close;
sqlDeleteTblcpa.ParamByName('asscod').AsInteger := cdsTbladaasscod.Value;
sqlDeleteTblcpa.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
sqlDeleteTblcpa.ExecSQL;
i := 0;
cdsTblcpa.First;
while not cdsTblcpa.Eof do
begin
inc(i);
sqlInsertTblcpa.Close;
sqlInsertTblcpa.ParamByName('asscod').AsInteger := cdsTblcpaasscod.Value;
sqlInsertTblcpa.ParamByName('adacod').AsInteger := cdsTblcpaadacod.Value;
sqlInsertTblcpa.ParamByName('cpadtvenc').AsDate := cdsTblcpacpadtvenc.Value;
sqlInsertTblcpa.ParamByName('cpadtemis').AsDate := cdsTblcpacpadtemis.Value;
sqlInsertTblcpa.ParamByName('cpanroparc').AsInteger := i;
sqlInsertTblcpa.ParamByName('cpavl').AsFloat := cdsTblcpacpavl.Value;
sqlInsertTblcpa.ExecSQL;
cdsTblcpa.Next;
end;
end;
except
on E: Exception do
begin
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Condição de pagamento já está cadastrada.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Condição de pagamento já está cadastrada.')
else if pos('cannot delete or update a parent row: a foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir esta condição de pagamento.')
else
raise Exception.Create(e.Message);
end;
end;
if AAtualizarHistorico then
AtualizarMudancaDadosAssinatura(AOperacao);
end;
procedure TdmDadosAssinantes.AtualizarDadosBaixa(AOperacao: TOperacao; AAtualizarHistorico: Boolean);
begin
try
if cdsTblbda.State in [dsEdit, dsInsert] then
cdsTblbda.Post;
if AOperacao = oInsert then
begin
sqlInsertTblbda.Close;
sqlInsertTblbda.ParamByName('asscod').AsInteger := cdsTblbdaasscod.Value;
sqlInsertTblbda.ParamByName('adacod').AsInteger := cdsTblbdaadacod.Value;
sqlInsertTblbda.ParamByName('bdacod').AsInteger := cdsTblbdabdacod.Value;
sqlInsertTblbda.ParamByName('usucod').AsInteger := cdsTblbdausucod.Value;
sqlInsertTblbda.ParamByName('bdadt').AsDate := cdsTblbdabdadt.Value;
sqlInsertTblbda.ParamByName('bdavl').AsFloat := cdsTblbdabdavl.Value;
sqlInsertTblbda.ExecSQL;
end;
if AOperacao = oUpdate then
begin
sqlUpdateTblbda.Close;
sqlUpdateTblbda.ParamByName('asscod').AsInteger := cdsTblbdaasscod.Value;
sqlUpdateTblbda.ParamByName('adacod').AsInteger := cdsTblbdaadacod.Value;
sqlUpdateTblbda.ParamByName('bdacod').AsInteger := cdsTblbdabdacod.Value;
sqlUpdateTblbda.ParamByName('usucod').AsInteger := cdsTblbdausucod.Value;
sqlUpdateTblbda.ParamByName('bdadt').AsDate := cdsTblbdabdadt.Value;
sqlUpdateTblbda.ParamByName('bdavl').AsFloat := cdsTblbdabdavl.Value;
sqlUpdateTblbda.ExecSQL;
end;
if AOperacao = oDelete then
begin
sqlDeleteTblbda.Close;
sqlDeleteTblbda.ParamByName('asscod').AsInteger := cdsTblbdaasscod.Value;
sqlDeleteTblbda.ParamByName('adacod').AsInteger := cdsTblbdaadacod.Value;
sqlDeleteTblbda.ParamByName('bdacod').AsInteger := cdsTblbdabdacod.Value;
sqlDeleteTblbda.ExecSQL;
end;
if AAtualizarHistorico then
AtualizarMudancaDadosBaixa(AOperacao);
except
on E: Exception do
begin
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Baixa informada já está cadastrada.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Baixa informada já está cadastrada.')
else if pos('foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir esta baixa, pois esta baixa está relacionada a outras tabelas.')
else
raise Exception.Create(e.Message);
end;
end;
end;
procedure TdmDadosAssinantes.AtualizarDadosHistorico(AOperacao: TOperacao);
begin
try
if cdsTblhas.State in [dsEdit, dsInsert] then
cdsTblhas.Post;
if AOperacao = oDelete then
cdstblhas.Delete;
cdsTblhas.ApplyUpdates(0);
except
on E: Exception do
begin
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Histórico digitado já está cadastrada.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Histórico digitado já está cadastrada.')
else if pos('cannot delete or update a parent row: a foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir este histórico.')
else
raise Exception.Create(e.Message);
end;
end;
end;
procedure TdmDadosAssinantes.AtualizarMudancaDadosAssinante(
AOperacao: TOperacao);
var
Descr: String;
cdsDelta: TClientDataSet;
ldmDadosCobradores: TdmDadosCobradores;
ldmDadosVendedores: TdmDadosVendedores;
ldmDadosZonasRuas: TdmDadosZonasRuas;
procedure AdicionarDescricao(AMsg: String);
begin
if Descr <> '' then
Descr := Descr + sLineBreak;
Descr := Descr + AMsg;
end;
begin
Descr := '';
case AOperacao of
oInsert:
begin
AdicionarDescricao('Novo assinante cadastrado, número ' + trim(cdsTblassasscod.AsString) + ' - ' + trim(cdsTblassassnome.AsAnsiString));
end;
oUpdate:
begin
if cdstblass.ChangeCount = 0 then
Exit;
cdsDelta := TClientDataSet.Create(Self);
try
cdsDelta.Close;
cdsDelta.Data := cdstblass.Delta;
cdsDelta.Open;
// Localiza o registro original (usUnmodified) no Delta do CDS
cdsDelta.First;
if not cdsDelta.Locate('asscod', cdsTblassasscod.Value, []) then
exit;
// Inicia a comparação dos campos.
// O cdsDelta com o registro original e o cdsTblass com o registro em
// alteração pelo usuário.
if cdsTblassassnome.Value <> cdsDelta.FieldByName('assnome').AsAnsiString then
AdicionarDescricao('Alterou Nome de: ' + trim(cdsDelta.FieldByName('assnome').AsAnsiString) + ' para: ' + cdsTblassassnome.AsAnsiString);
if cdsTblassasscpf.Value <> cdsDelta.FieldByName('asscpf').AsAnsiString then
AdicionarDescricao('Alterou CPF de: ' + trim(cdsDelta.FieldByName('asscpf').AsAnsiString) + ' para: ' + cdsTblassasscpf.AsAnsiString);
if cdsTblassassrazaosocial.Value <> cdsDelta.FieldByName('assrazaosocial').AsAnsiString then
AdicionarDescricao('Alterou Razão Social de: ' + trim(cdsDelta.FieldByName('assrazaosocial').AsAnsiString) + ' para: ' + cdsTblassassrazaosocial.AsAnsiString);
if cdsTblassasscnpj.Value <> cdsDelta.FieldByName('asscnpj').AsAnsiString then
AdicionarDescricao('Alterou CNPJ de: ' + trim(cdsDelta.FieldByName('asscnpj').AsAnsiString) + ' para: ' + cdsTblassasscnpj.AsAnsiString);
if cdsTblassassstatus.Value <> cdsDelta.FieldByName('assstatus').AsInteger then
AdicionarDescricao('Alterou Status de: ' + GetDescricaoStatusAssinante(cdsDelta.FieldByName('assstatus').AsInteger) + ' para: ' + GetDescricaoStatusAssinante(cdsTblassassstatus.Value));
if cdsTblassassdtinativo.Value <> cdsDelta.FieldByName('assdtinativo').AsDateTime then
AdicionarDescricao('Alterou Data Inativo de: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('assdtinativo').AsDateTime) + ' para: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTblassassdtinativo.Value));
if cdsTblassassdtnasc.Value <> cdsDelta.FieldByName('assdtnasc').AsDateTime then
AdicionarDescricao('Alterou Data de Nascimento de: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('assdtnasc').AsDateTime) + ' para: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTblassassdtnasc.Value));
if cdsTblassassimpretiq.Value <> cdsDelta.FieldByName('assimpretiq').AsAnsiString then
AdicionarDescricao('Alterou Imprime Etiqueta de: ' + dmDadosGlobal.GetDescricaoSimNao(cdsDelta.FieldByName('assimpretiq').AsAnsiString) + ' para: ' + dmDadosGlobal.GetDescricaoSimNao(cdsTblassassimpretiq.AsAnsiString));
if cdsTblasscobcod.Value <> cdsDelta.FieldByName('cobcod').AsInteger then
begin
ldmDadosCobradores := TdmDadosCobradores.Create(self);
try
AdicionarDescricao('Alterou Cobrador de: ' + trim(cdsDelta.FieldByName('cobcod').AsString) + '-' + ldmDadosCobradores.GetNomeCobrador(cdsDelta.FieldByName('cobcod').AsInteger) + ' para: ' + trim(cdsTblasscobcod.AsString) + '-' + ldmDadosCobradores.GetNomeCobrador(cdsTblasscobcod.Value));
finally
FreeAndNil(ldmDadosCobradores);
end
end;
if cdsTblassvencod.Value <> cdsDelta.FieldByName('vencod').AsInteger then
begin
ldmDadosVendedores := TdmDadosVendedores.Create(self);
try
AdicionarDescricao('Alterou Vendedor de: ' + trim(cdsDelta.FieldByName('vencod').AsString) + '-' + ldmDadosVendedores.GetNomeVendedor(cdsDelta.FieldByName('vencod').AsInteger) + ' para: ' + trim(cdsTblassvencod.AsString) + '-' + ldmDadosVendedores.GetNomeVendedor(cdsTblassvencod.Value));
finally
FreeAndNil(ldmDadosVendedores);
end
end;
// Compara a Rua e ao mesmo tempo o número da rua
if (cdsTblassrdzcod.Value <> cdsDelta.FieldByName('rdzcod').AsInteger) or (cdsTblassassnroent.Value <> cdsDelta.FieldByName('assnroent').AsString) then
begin
ldmDadosZonasRuas := TdmDadosZonasRuas.Create(self);
try
AdicionarDescricao(
'Alterou Endereço de: ' + ldmDadosZonasRuas.GetDescricaoRua(cdsDelta.FieldByName('rdzcod').AsInteger) +
', ' + trim(cdsDelta.FieldByName('assnroent').AsAnsiString) +
' (' + ldmDadosZonasRuas.GetDescricaoZona('', cdsDelta.FieldByName('rdzcod').AsInteger) +
') para: ' + ldmDadosZonasRuas.GetDescricaoRua(cdsTblassrdzcod.Value) +
', ' + trim(cdsTblassassnroent.Value) +
' (' + ldmDadosZonasRuas.GetDescricaoZona('', cdsTblassrdzcod.Value) + ')' );
finally
FreeAndNil(ldmDadosZonasRuas);
end;
end;
if cdsTblassasscomplent.Value <> cdsDelta.FieldByName('asscomplent').AsAnsiString then
AdicionarDescricao('Alterou Complemento do Endereço de: ' + trim(cdsDelta.FieldByName('asscomplent').AsAnsiString) + ' para: ' + trim(cdsTblassasscomplent.AsAnsiString));
if cdsTblassassbairroent.Value <> cdsDelta.FieldByName('assbairroent').AsAnsiString then
AdicionarDescricao('Alterou Bairro do Endereço de: ' + trim(cdsDelta.FieldByName('assbairroent').AsAnsiString) + ' para: ' + trim(cdsTblassassbairroent.AsAnsiString));
if cdsTblasscepcepent.Value <> cdsDelta.FieldByName('cepcepent').AsAnsiString then
AdicionarDescricao('Alterou CEP do Endereço de: ' + trim(cdsDelta.FieldByName('cepcepent').AsAnsiString) + ' para: ' + trim(cdsTblasscepcepent.AsAnsiString));
if cdsTblassassendercobr.Value <> cdsDelta.FieldByName('assendercobr').AsAnsiString then
AdicionarDescricao('Alterou Endereço de Cobrança de: ' + trim(cdsDelta.FieldByName('assendercobr').AsAnsiString) + ' para: ' + trim(cdsTblassassendercobr.AsAnsiString));
if cdsTblassassemail.Value <> cdsDelta.FieldByName('assemail').AsAnsiString then
AdicionarDescricao('Alterou E-mail de: ' + trim(cdsDelta.FieldByName('assemail').AsAnsiString) + ' para: ' + trim(cdsTblassassemail.AsAnsiString));
if cdsTblassassobs.Value <> cdsDelta.FieldByName('assobs').AsAnsiString then
AdicionarDescricao('Alterou Observação de: ' + trim(cdsDelta.FieldByName('assobs').AsAnsiString) + ' para: ' + trim(cdsTblassassobs.AsAnsiString));
if (cdsTblassassfonecomer.Value <> cdsDelta.FieldByName('assfonecomer').AsAnsiString) or (cdsTblassassfonecomerramal.Value <> cdsDelta.FieldByName('assfonecomerramal').AsAnsiString) then
AdicionarDescricao(
'Alterou Telefone Comercial de: ' + trim(cdsDelta.FieldByName('assfonecomer').AsAnsiString) +
'-' + trim(cdsDelta.FieldByName('assfonecomerramal').AsAnsiString) +
' para: ' + trim(cdsTblassassfonecomer.AsAnsiString) + '-' + trim(cdsTblassassfonecomerramal.AsAnsiString));
if cdsTblassassfoneresid.Value <> cdsDelta.FieldByName('assfoneresid').AsAnsiString then
AdicionarDescricao('Alterou Telefone Residencial de: ' + trim(cdsDelta.FieldByName('assfoneresid').AsAnsiString) + ' para: ' + trim(cdsTblassassfoneresid.AsAnsiString));
if cdsTblassassfonefax.Value <> cdsDelta.FieldByName('assfonefax').AsAnsiString then
AdicionarDescricao('Alterou Telefone Fax de: ' + trim(cdsDelta.FieldByName('assfonefax').AsAnsiString) + ' para: ' + trim(cdsTblassassfonefax.AsAnsiString));
if cdsTblassassfonecelul.Value <> cdsDelta.FieldByName('assfonecelul').AsAnsiString then
AdicionarDescricao('Alterou Telefone Celular de: ' + trim(cdsDelta.FieldByName('assfonecelul').AsAnsiString) + ' para: ' + trim(cdsTblassassfonecelul.AsAnsiString));
finally
FreeAndNil(cdsDelta);
end;
end;
end;
AtualizarTabelaTblhma(cdsTblassasscod.Value, dmUsuario.cdsUsuariousucod.Value, Descr);
end;
procedure TdmDadosAssinantes.AtualizarMudancaDadosAssinatura(
AOperacao: TOperacao);
var
Descr: String;
DescrParcelas: String;
cdsDelta: TClientDataSet;
ParcelarAlteradas: Boolean;
procedure AdicionarDescricao(AMsg: String);
begin
if Descr <> '' then
Descr := Descr + sLineBreak;
Descr := Descr + AMsg;
end;
begin
Descr := '';
DescrParcelas := '';
ParcelarAlteradas := false;
case AOperacao of
oInsert:
begin
AdicionarDescricao('Nova assinatura número ' + FormatFloat('00', cdsTbladaadacod.Value) + ' cadastrada.');
end;
oUpdate:
begin
if cdsTblada.ChangeCount <> 0 then
begin
cdsDelta := TClientDataSet.Create(Self);
try
cdsDelta.Close;
cdsDelta.Data := cdsTblada.Delta;
cdsDelta.Open;
// Localiza o registro original (usUnmodified) no Delta do CDS
cdsDelta.First;
if not cdsDelta.Locate('asscod;adacod', VarArrayOf([cdsTbladaasscod.Value,cdsTbladaadacod.Value]), []) then
exit;
// Inicia a comparação dos campos.
// O cdsDelta com o registro original e o cdsTblada com o registro em
// alteração pelo usuário.
if cdsTbladaadatipo.Value <> cdsDelta.FieldByName('adatipo').AsAnsiString then
AdicionarDescricao('Alterou Tipo de Assinatura de: ' + GetDescricaoTipoAssinatura(cdsDelta.FieldByName('adatipo').AsAnsiString) + ' para: ' + GetDescricaoTipoAssinatura(cdsTbladaadatipo.AsAnsiString));
if (cdsTbladaadadtini.Value <> cdsDelta.FieldByName('adadtini').AsDateTime) or (cdsTbladaadadtvenc.Value <> cdsDelta.FieldByName('adadtvenc').AsDateTime) then
AdicionarDescricao(
'Alterou Período da Assinatura de: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('adadtini').AsDateTime) +
' até ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('adadtvenc').AsDateTime) +
' para: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTbladaadadtini.Value) +
' até ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTbladaadadtvenc.Value));
if cdsTbladaadavl.Value <> cdsDelta.FieldByName('adavl').AsFloat then
AdicionarDescricao('Alterou Valor da Assinatura de: ' + FormatFloat('0.00', cdsDelta.FieldByName('adavl').AsFloat) + ' para: ' + FormatFloat('0.00', cdsTbladaadavl.AsFloat));
if cdsTbladaadavldesc.Value <> cdsDelta.FieldByName('adavldesc').AsFloat then
AdicionarDescricao('Alterou Valor de Desconto da Assinatura de: ' + FormatFloat('0.00', cdsDelta.FieldByName('adavldesc').AsFloat) + ' para: ' + FormatFloat('0.00', cdsTbladaadavldesc.AsFloat));
if cdsTbladaadacancel.Value <> cdsDelta.FieldByName('adacancel').AsAnsiString then
AdicionarDescricao('Alterou Indicador de Cancelamento de Assinatura de: ' + dmDadosGlobal.GetDescricaoSimNao(cdsDelta.FieldByName('adacancel').AsAnsiString) + ' para: ' + dmDadosGlobal.GetDescricaoSimNao(cdsTbladaadacancel.AsAnsiString));
if cdsTbladaadadtcancel.Value <> cdsDelta.FieldByName('adadtcancel').AsDateTime then
AdicionarDescricao('Alterou Data de Cancelamento da Assinatura de: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('adadtcancel').AsDateTime) + ' para: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTbladaadadtcancel.Value));
if cdsTbladaadacortesia.Value <> cdsDelta.FieldByName('adacortesia').AsAnsiString then
AdicionarDescricao('Alterou Indicador de Cortesia de Assinatura de: ' + dmDadosGlobal.GetDescricaoSimNao(cdsDelta.FieldByName('adacortesia').AsAnsiString) + ' para: ' + dmDadosGlobal.GetDescricaoSimNao(cdsTbladaadacortesia.AsAnsiString));
if cdsTbladaadaobs.Value <> cdsDelta.FieldByName('adaobs').AsAnsiString then
AdicionarDescricao('Alterou Observação da Assinatura de: ' + trim(cdsDelta.FieldByName('adaobs').AsAnsiString) + ' para: ' + trim(cdsTbladaadaobs.AsAnsiString));
finally
FreeAndNil(cdsDelta);
end;
end;
// -----------------------------------------------------------------------
// Procedimento para verifiar se o array de parcelas também sofreu
// alguma alteração.
// -----------------------------------------------------------------------
if cdsTblcpa.RecordCount <> cdsTblcpaBkp.RecordCount then
begin
ParcelarAlteradas := true;
end
else
begin
cdsTblcpa.First;
cdsTblcpaBkp.First;
while not cdsTblcpa.Eof do
begin
if (cdsTblcpacpadtvenc.Value <> cdsTblcpaBkpcpadtvenc.Value) or (cdsTblcpacpavl.Value <> cdsTblcpaBkpcpavl.Value) then
begin
ParcelarAlteradas := true;
Break;
end;
cdsTblcpaBkp.Next;
cdsTblcpa.Next;
end;
end;
if ParcelarAlteradas then
begin
DescrParcelas := 'Alterou Condições pagto de:';
cdsTblcpaBkp.First;
while not cdsTblcpaBkp.Eof do
begin
DescrParcelas := DescrParcelas + ' ' +
IntToStr(cdsTblcpaBkp.RecNo) + 'º-' +
FormatDateTime('dd/mm/yyyy', cdsTblcpaBkpcpadtvenc.Value) + '-' +
FormatFloat('0.00', cdsTblcpaBkpcpavl.Value);
cdsTblcpaBkp.Next;
end;
DescrParcelas := trim(DescrParcelas) + ' para:';
cdsTblcpa.First;
while not cdsTblcpa.Eof do
begin
DescrParcelas := DescrParcelas + ' ' +
IntToStr(cdsTblcpa.RecNo) + 'º-' +
FormatDateTime('dd/mm/yyyy', cdsTblcpacpadtvenc.Value) + '-' +
FormatFloat('0.00', cdsTblcpacpavl.Value);
cdsTblcpa.Next;
end;
AdicionarDescricao(DescrParcelas);
end;
// A primeira linha sempre vai ser código da assinatura, pois a tabela tblhma
// não tem o atributo do código da assinatura
if Descr <> EmptyStr then
Descr := 'Alteração referente a Assinatura Número: ' + FormatFloat('00', cdsTbladaadacod.Value) + sLineBreak + Descr;
end;
oDelete:
begin
AdicionarDescricao('Excluída a assinatura número ' + trim(cdsTbladaadacod.AsString));
end;
end;
AtualizarTabelaTblhma(cdsTblassasscod.Value, dmUsuario.cdsUsuariousucod.Value, Descr);
end;
procedure TdmDadosAssinantes.AtualizarMudancaDadosBaixa(AOperacao: TOperacao);
var
Descr: String;
cdsDelta: TClientDataSet;
procedure AdicionarDescricao(AMsg: String);
begin
if Descr <> '' then
Descr := Descr + sLineBreak;
Descr := Descr + AMsg;
end;
begin
Descr := '';
case AOperacao of
oInsert:
begin
AdicionarDescricao(
'Incluída Nova Baixa Código: ' + FormatFloat('00', cdsTblbdabdacod.Value) +
' - Data: ' + trim(cdsTblbdabdadt.AsString) +
' - Valor: ' + FormatFloat('#,##0.00', cdsTblbdabdavl.Value));
end;
oUpdate:
begin
if cdsTblbda.ChangeCount = 0 then
Exit;
cdsDelta := TClientDataSet.Create(Self);
try
cdsDelta.Close;
cdsDelta.Data := cdsTblbda.Delta;
cdsDelta.Open;
// Localiza o registro original (usUnmodified) no Delta do CDS
cdsDelta.First;
if not cdsDelta.Locate('asscod;adacod;bdacod', VarArrayOf([cdsTblbdaasscod.Value, cdsTblbdaadacod.Value, cdsTblbdabdacod.Value]), []) then
exit;
// Inicia a comparação dos campos.
// O cdsDelta com o registro original e o cdsTblbda com o registro em
// alteração pelo usuário.
if cdsTblbdabdadt.Value <> cdsDelta.FieldByName('bdadt').AsDateTime then
AdicionarDescricao(
'Alterou Data da Baixa de: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsDelta.FieldByName('bdadt').AsDateTime) +
' para: ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTblbdabdadt.Value));
if cdsTblbdabdavl.Value <> cdsDelta.FieldByName('bdavl').AsFloat then
AdicionarDescricao(
'Alterou Valor da Baixa do dia ' + dmDadosGlobal.FormatDateTimeToString('dd/mm/yyyy', cdsTblbdabdadt.Value) +
' de: ' + FormatFloat('0.00', cdsDelta.FieldByName('bdavl').AsFloat) +
' para: ' + FormatFloat('0.00', cdsTblbdabdavl.AsFloat));
finally
FreeAndNil(cdsDelta);
end;
end;
oDelete:
begin
AdicionarDescricao(
'Excluída a Baixa Código: ' + FormatFloat('00', cdsTblbdabdacod.Value) +
' - Data: ' + trim(cdsTblbdabdadt.AsString) +
' - Valor: ' + FormatFloat('#,##0.00', cdsTblbdabdavl.Value));
end;
end;
if Descr <> EmptyStr then
begin
// A primeira linha sempre vai ser código da assinatura, pois a tabela tblhma
// não tem o atributo do código da assinatura
Descr := 'Alteração referente a Assinatura Número: ' + FormatFloat('00', cdsTblbdaadacod.Value) + sLineBreak + Descr;
AtualizarTabelaTblhma(cdsTblassasscod.Value, dmUsuario.cdsUsuariousucod.Value, Descr);
end;
end;
procedure TdmDadosAssinantes.AtualizarTabelaTblhma(AAsscod, AUsucod: Integer;
AHmadescr: String);
var
i: integer;
begin
i := 0;
if AHmadescr = EmptyStr then
exit;
while true do
begin
Inc(i);
try
sqlInsertTblhma.Close;
sqlInsertTblhma.ParamByName('asscod').AsInteger := AAsscod;
sqlInsertTblhma.ParamByName('usucod').AsInteger := AUsucod;
sqlInsertTblhma.ParamByName('hmaseq').AsInteger := i;
sqlInsertTblhma.ParamByName('hmadescr').AsAnsiString := AHmadescr;
sqlInsertTblhma.ExecSQL;
Break;
except
on E: Exception do
begin
if pos('duplicate entry', LowerCase(e.Message)) > 0 then
Continue
else
raise;
end;
end;
end;
end;
procedure TdmDadosAssinantes.AtualizarValorPendenteAssinatura;
begin
// Coloca em estado de Edição caso não esteja.
if cdsTblada.State in [dsBrowse] then
cdsTblada.Edit;
// Calcula o valor pendente
cdsTbladaadavlpend.Value := cdsTbladaadavl.Value - GetValorTotalBaixas(cdsTbladaasscod.AsInteger, cdsTbladaadacod.AsInteger);
if cdsTbladaadavlpend.Value < 0 then
raise Exception.Create('Valor pendente não pode ser negativo.');
end;
procedure TdmDadosAssinantes.CancelarManutencaoAssinante;
begin
if not cdsTblass.Active then
exit;
if cdsTblass.State in [dsEdit, dsInsert] then
cdsTblass.Cancel;
if cdsTblass.ChangeCount > 0 then
cdsTblass.CancelUpdates;
FOperacao := oNone;
end;
procedure TdmDadosAssinantes.CancelarManutencaoAssinatura;
begin
if cdsTblcpa.State in [dsEdit, dsInsert] then
cdsTblcpa.Cancel;
if cdsTblcpa.ChangeCount > 0 then
cdsTblcpa.CancelUpdates;
// ---------------------------------------------------------------------------
if cdsTblada.State in [dsEdit, dsInsert] then
cdsTblada.Cancel;
if cdsTblada.ChangeCount > 0 then
cdsTblada.CancelUpdates;
// ---------------------------------------------------------------------------
CancelarManutencaoAssinante;
FOperacao := oNone;
end;
procedure TdmDadosAssinantes.CancelarManutencaoBaixa;
begin
if not cdsTblbda.Active then
exit;
if cdsTblbda.State in [dsEdit, dsInsert] then
cdsTblbda.Cancel;
if cdsTblbda.ChangeCount > 0 then
cdsTblbda.CancelUpdates;
// ---------------------------------------------------------------------------
CancelarManutencaoAssinatura;
FOperacao := oNone;
end;
procedure TdmDadosAssinantes.CancelarManutencaoHistorico;
begin
if not cdsTblhas.Active then
exit;
if cdsTblhas.State in [dsEdit, dsInsert] then
cdsTblhas.Cancel;
if cdsTblhas.ChangeCount > 0 then
cdsTblhas.CancelUpdates;
FOperacao := oNone;
end;
procedure TdmDadosAssinantes.cdsTbladaadacancelValidate(Sender: TField);
begin
if cdsTblada.Tag = 1 then
exit;
if cdsTbladaadacancel.AsString = 'S' then
cdsTbladaadadtcancel.AsDateTime := dmDadosGlobal.GetDataHoraBanco
else
cdsTbladaadadtcancel.AsString := EmptyStr;
end;
procedure TdmDadosAssinantes.cdsTbladaadadtcancelValidate(Sender: TField);
begin
if cdsTblada.Tag = 1 then
exit;
if cdsTbladaadacancel.AsString = 'S' then
if cdsTbladaadadtcancel.AsDateTime = 0 then
raise Exception.Create('Data de cancelamento da assinatura deve ser informada.');
end;
procedure TdmDadosAssinantes.cdsTbladaadadtvencValidate(Sender: TField);
begin
if cdsTblada.Tag = 1 then
exit;
if cdsTbladaadadtvenc.AsDateTime <= cdsTbladaadadtini.AsDateTime then
raise Exception.Create('Data de vencimento da assinatura não pode ser menor ou igual a data de início da assinatura.');
end;
procedure TdmDadosAssinantes.cdsTbladaadavldescValidate(Sender: TField);
begin
if cdsTblada.Tag = 1 then
exit;
if cdsTbladaadavldesc.Value < 0 then
raise Exception.Create('Valor de desconto não pode ser negativo.');
end;
procedure TdmDadosAssinantes.cdsTbladaadavlValidate(Sender: TField);
begin
if cdsTblada.Tag = 1 then
exit;
if cdsTbladaadavl.Value <= 0 then
raise Exception.Create('Valor da assinatura não pode ser menor ou igual a zero.');
// Calcula o valor pendente
AtualizarValorPendenteAssinatura;
end;
procedure TdmDadosAssinantes.cdsTbladaAfterScroll(DataSet: TDataSet);
begin
sqlTblbda.Close;
cdsTblbda.Close;
sqlTblbda.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlTblbda.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
cdsTblbda.Open;
sqlTblcpa.Close;
cdsTblcpa.Close;
sqlTblcpa.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlTblcpa.ParamByName('adacod').AsInteger := cdsTbladaadacod.Value;
cdsTblcpa.Open;
// Faz um backup do cdsTblcpa, para poder realizar comparações de mudança
// nos campos no momento de salvar a assinatura.
cdsTblcpaBkp.Close;
cdsTblcpaBkp.CreateDataSet;
cdsTblcpaBkp.Open;
cdsTblcpa.First;
while not cdsTblcpa.Eof do
begin
cdsTblcpaBkp.AppendRecord([cdsTblcpacpadtvenc.Value, cdsTblcpacpavl.Value]);
cdsTblcpa.Next;
end;
cdsTblcpa.First;
end;
procedure TdmDadosAssinantes.cdsTbladaBeforePost(DataSet: TDataSet);
begin
if cdsTbladaadavldesc.IsNull then
cdsTbladaadavldesc.Value := 0;
// Procedimento de gravação de Logs do último usuário que alterou o registro.
cdsTbladaadadtalt.AsDateTime := dmDadosGlobal.GetDataHoraBanco;
cdsTbladausucodalt.Value := dmUsuario.cdsUsuariousucod.Value;
end;
procedure TdmDadosAssinantes.cdsTbladaCalcFields(DataSet: TDataSet);
begin
cdsTbladaCalcAdatipo.AsString := GetDescricaoTipoAssinatura(cdsTbladaadatipo.AsString);
cdsTbladaCalcAdacancel.AsString := dmDadosGlobal.GetDescricaoSimNao(cdsTbladaadacancel.AsString);
end;
procedure TdmDadosAssinantes.cdsTbladaNewRecord(DataSet: TDataSet);
var
CodigoAssinatura: Integer;
NovaDataInicio: TDateTime;
NovaDataVencimento: TDateTime;
begin
cdsTblada.Tag := 1;
try
// Novo número para uma nova assinatura
sqlMaxAdacod.Close;
sqlMaxAdacod.ParamByName('asscod').AsInteger := cdsTblassasscod.AsInteger;
sqlMaxAdacod.Open;
CodigoAssinatura := sqlMaxAdacodadacod.AsInteger + 1;
cdsTbladaasscod.AsInteger := cdsTblassasscod.AsInteger;
cdsTbladaadacod.AsInteger := CodigoAssinatura;
sqlAssinaturaAnterior.Close;
sqlAssinaturaAnterior.ParamByName('asscod').AsInteger := cdsTblassasscod.AsInteger;
sqlAssinaturaAnterior.ParamByName('adacod').AsInteger := CodigoAssinatura -1;
sqlAssinaturaAnterior.Open;
if not sqlAssinaturaAnterior.Eof then
begin
cdsTbladaadatipo.AsString := 'R';
// Nova data de início da nova assinatura
NovaDataInicio := sqlAssinaturaAnterioradadtvenc.AsDateTime;
// Nova data de vencimento para a nova assinatura.
NovaDataVencimento := IncYear(NovaDataInicio);
end
else
begin
cdsTbladaadatipo.AsString := 'A';
// Nova data de início da nova assinatura
NovaDataInicio := dmDadosGlobal.GetDataHoraBanco;
// Nova data de vencimento para a nova assinatura.
NovaDataVencimento := IncYear(NovaDataInicio);
end;
// Nova data de início da nova assinatura
cdsTbladaadadtini.AsDateTime := NovaDataInicio;
// Nova data de vencimento para a nova assinatura.
cdsTbladaadadtvenc.AsDateTime := NovaDataVencimento;
cdsTbladaadavl.Value := 0;
cdsTbladaadavldesc.Value := 0;
cdsTbladaadavlpend.Value := 0;
cdsTbladaadacancel.AsString := 'N';
cdsTbladaadacortesia.AsAnsiString := 'N';
finally
cdsTblada.Tag := 0;
end;
end;
procedure TdmDadosAssinantes.cdsTblassAfterScroll(DataSet: TDataSet);
begin
sqlRuaZona.Close;
sqlRuaZona.ParamByName('rdzcod').AsInteger := cdsTblassrdzcod.AsInteger;
sqlRuaZona.Open;
sqlTblcep.Close;
sqlTblcep.ParamByName('cepcepent').AsString := cdsTblasscepcepent.AsString;
sqlTblcep.Open;
// -------------
sqlTblhas.Close;
cdsTblhas.Close;
sqlTblhas.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
cdsTblhas.Open;
cdsTblbda.Close;
cdsTblcpa.Close;
cdsTblcpaBkp.Close;
sqlTblada.Close;
cdsTblada.Close;
sqlTblada.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
cdsTblada.Open;
end;
procedure TdmDadosAssinantes.cdsTblassasscnpjValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if (trim(cdsTblassasscnpj.Value) = '') or
(trim(cdsTblassasscnpj.Value) = '. . / -') then
begin
exit;
end;
dmDadosGlobal.ValidarCNPJ(cdsTblassasscnpj.AsString);
sqlExisteCnpj.Close;
sqlExisteCnpj.ParamByName('asscnpj').AsString := cdsTblassasscnpj.AsString;
sqlExisteCnpj.Open;
if not sqlExisteCnpj.Eof then
if sqlExisteCnpjasscod.AsInteger <> cdsTblassasscod.AsInteger then
raise Exception.Create('CNPJ ' + cdsTblassasscnpj.AsString + ' já cadastrado para o assinante ' + trim(sqlExisteCnpjassnome.AsString));
end;
procedure TdmDadosAssinantes.cdsTblassasscpfValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if (trim(cdsTblassasscpf.Value) = '') or
(trim(cdsTblassasscpf.Value) = '. . -') then
begin
exit;
end;
dmDadosGlobal.ValidarCPF(cdsTblassasscpf.AsString);
sqlExisteCpf.Close;
sqlExisteCpf.ParamByName('asscpf').AsString := cdsTblassasscpf.AsString;
sqlExisteCpf.Open;
if not sqlExisteCpf.Eof then
if sqlExisteCpfasscod.AsInteger <> cdsTblassasscod.AsInteger then
raise Exception.Create('CPF ' + cdsTblassasscpf.AsString + ' já cadastrado para o assinante ' + trim(sqlExisteCpfassnome.AsString));
end;
procedure TdmDadosAssinantes.cdsTblassassdtinativoValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if cdsTblassassstatus.AsInteger = 1 then // Inativo
if cdsTblassassdtinativo.Value = 0 then
raise Exception.Create('Data de inatividade deve ser informada.');
end;
procedure TdmDadosAssinantes.cdsTblassassemailValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if cdsTblassassemail.AsString = EmptyStr then
exit;
if not dmDadosGlobal.ValidarEmail(cdsTblassassemail.AsString) then
abort;
end;
procedure TdmDadosAssinantes.cdsTblassassnomeValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if trim(cdsTblassassnome.AsString) = EmptyStr then
raise Exception.Create('Nome do assinante não pode ser nulo.');
end;
procedure TdmDadosAssinantes.cdsTblassassnroentValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if trim(cdsTblassassnroent.AsString) = EmptyStr then
raise Exception.Create('Número do endereço de entrega não pode ser nulo.');
if cdsTblass.Tag = 2 then
exit;
sqlExisteEndereco.Close;
sqlExisteEndereco.ParamByName('rdzcod').AsInteger := cdsTblassrdzcod.AsInteger;
sqlExisteEndereco.ParamByName('assnroent').AsString := trim(cdsTblassassnroent.AsString);
sqlExisteEndereco.Open;
if not sqlExisteEndereco.Eof then
if MessageDlg('O endereço de entrega e número já está cadastrado para o assinante ' + trim(sqlExisteEnderecoassnome.AsString) + ', deseja cadastrar assim mesmo?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
Abort;
end;
procedure TdmDadosAssinantes.cdsTblassassstatusValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
if cdsTblassassstatus.AsInteger = 0 then // Ativo
cdsTblassassdtinativo.AsString := EmptyStr
else
cdsTblassassdtinativo.Value := dmDadosGlobal.GetDataHoraBanco;
end;
procedure TdmDadosAssinantes.cdsTblassBeforeOpen(DataSet: TDataSet);
begin
sqlRuaZona.Close;
sqlTblcep.Close;
cdsTblcpa.Close;
cdsTblcpaBkp.Close;
cdsTblbda.Close;
cdsTblada.Close;
end;
procedure TdmDadosAssinantes.cdsTblassBeforePost(DataSet: TDataSet);
begin
// Faço isso para que, caso não seja informado o CPF,
// para não gravar na base de dados apenas os " . . - "
if (trim(cdsTblassasscpf.AsString) = '. . -') then
cdsTblassasscpf.AsString := '';
// Faço isso para que, caso não seja informado o CNPJ,
// para não gravar na base de dados apenas os " . . / - "
if (trim(cdsTblassasscnpj.AsString) = '. . / -') then
cdsTblassasscnpj.AsString := '';
if trim(cdsTblassassdtnasc.AsString) = '/ /' then
cdsTblassassdtnasc.AsString := '';
// Faço isso para que, caso não seja informado os telefones,
// para não gravar na base de dados apenas os "( )"
if trim(cdsTblassassfonecomer.AsString) = '( )' then
cdsTblassassfonecomer.AsString := '';
if trim(cdsTblassassfoneresid.AsString) = '( )' then
cdsTblassassfoneresid.AsString := '';
if trim(cdsTblassassfonefax.AsString) = '( )' then
cdsTblassassfonefax.AsString := '';
if trim(cdsTblassassfonecelul.AsString) = '( )' then
cdsTblassassfonecelul.AsString := '';
// Procedimento de gravação de Logs do último usuário que alterou o registro.
cdsTblassassdtalt.AsDateTime := dmDadosGlobal.GetDataHoraBanco;
cdsTblassusucodalt.Value := dmUsuario.cdsUsuariousucod.Value;
end;
procedure TdmDadosAssinantes.cdsTblassCalcFields(DataSet: TDataSet);
begin
if DataSet.State <> dsInternalCalc then
exit;
if cdsTblassassfonecomer.AsString <> EmptyStr then
cdsTblassCalcFonecomerCompleto.AsString := cdsTblassassfonecomer.AsString
else
cdsTblassCalcFonecomerCompleto.AsString := '( )';
if cdsTblassassfonecomerramal.AsString <> EmptyStr then
cdsTblassCalcFonecomerCompleto.AsString := cdsTblassassfonecomer.AsString + ' R.' + trim(cdsTblassassfonecomerramal.AsString);
if cdsTblassassimpretiq.AsString = 'S' then
cdsTblassCalcImpretiq.AsString := 'Sim'
else
cdsTblassCalcImpretiq.AsString := 'Não';
cdsTblassCalcCodigoDescrZona.AsString := trim(cdsTblasszoncod.AsString) + ' - ' + trim(cdsTblasszondescr.AsString);
if cdsTblassassstatus.AsInteger = 0 then
cdsTblassCalcDescrStatus.AsString := 'Ativo'
else
// Deixo 6 espaços em branco na frente devido a imagem que será colocada no DBGrid
cdsTblassCalcDescrStatus.AsString := ' Inativo';
end;
procedure TdmDadosAssinantes.cdsTblasscepcepentValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
sqlTblcep.Close;
// Validar CEP
dmDadosGlobal.ValidarCEP(cdsTblasscepcepent.AsString);
sqlTblcep.ParamByName('cepcepent').AsString := cdsTblasscepcepent.AsString;
sqlTblcep.Open;
if sqlTblcep.Eof then
raise Exception.Create('CEP informado não está cadastrado.');
end;
procedure TdmDadosAssinantes.cdsTblassNewRecord(DataSet: TDataSet);
begin
cdsTblass.Tag := 1;
try
cdsTblassasscod.Value := 0; // campo auto-incremento
cdsTblassassstatus.AsInteger := 0; // Ativo
cdsTblasscepcepent.AsString := '95700-000'; // Bento
cdsLookupVendedores.First;
cdsTblassvencod.AsInteger := cdsLookupVendedoresvencod.AsInteger;
cdsLookupCobradores.First;
cdsTblasscobcod.AsInteger := cdsLookupCobradorescobcod.AsInteger;
cdsTblassassimpretiq.AsString := 'S';
finally
cdsTblass.Tag := 0;
end;
end;
procedure TdmDadosAssinantes.cdsTblassrdzcodValidate(Sender: TField);
begin
if cdsTblass.Tag = 1 then
exit;
sqlRuaZona.Close;
sqlRuaZona.ParamByName('rdzcod').AsInteger := cdsTblassrdzcod.Value;
sqlRuaZona.Open;
if sqlRuaZona.Eof then
raise Exception.Create('Endereço informado não está cadastrado.');
end;
procedure TdmDadosAssinantes.cdsTblbdabdadtValidate(Sender: TField);
begin
if cdsTblbda.Tag = 1 then
exit;
if cdsTblbdabdadt.AsDateTime = 0 then
raise Exception.Create('Data da baixa deve ser informada.');
end;
procedure TdmDadosAssinantes.cdsTblbdabdavlValidate(Sender: TField);
var
ValorPendente: Double;
ValorTotalBaixas: Double;
begin
if cdsTblbda.Tag = 1 then
exit;
ValorTotalBaixas := 0;
ValorPendente := 0;
if cdsTblbda.State in [dsInsert] then
begin
ValorTotalBaixas := GetValorTotalBaixas(cdsTblbdaasscod.AsInteger, cdsTblbdaadacod.AsInteger);
ValorPendente := cdsTbladaadavl.Value - ValorTotalBaixas;
end
else
begin
ValorTotalBaixas := GetValorTotalBaixas(cdsTblbdaasscod.AsInteger, cdsTblbdaadacod.AsInteger, cdsTblbdabdacod.AsInteger);
ValorTotalBaixas := ValorTotalBaixas + cdsTblbdabdavl.Value;
ValorPendente := cdsTbladaadavl.Value - ValorTotalBaixas;
end;
try
if cdsTblbdabdavl.Value <= 0 then
raise Exception.Create('Valor da baixa não pode ser menor ou igual a zero.');
if cdsTblbda.State in [dsInsert] then
begin
if cdsTblbdabdavl.Value > ValorPendente then
raise Exception.Create('Valor da baixa não pode ser maior que o valor pendente da assinatura.');
// Atualiza o valor pendente na assinatura
AtualizarValorPendenteAssinatura(ValorPendente - cdsTblbdabdavl.Value);
end
else
begin
if ValorPendente < 0 then
raise Exception.Create('Valor pendente da assinatura não pode ser negativo.');
// Atualiza o valor pendente na assinatura
AtualizarValorPendenteAssinatura(ValorPendente);
end;
except
on E: Exception do
begin
AtualizarValorPendenteAssinatura(ValorPendente);
raise;
end;
end;
end;
procedure TdmDadosAssinantes.cdsTblbdaBeforePost(DataSet: TDataSet);
begin
// Grava o usuário que fez a manutenção
cdsTblbdausucod.AsInteger := dmUsuario.cdsUsuariousucod.AsInteger;
end;
procedure TdmDadosAssinantes.cdsTblbdaNewRecord(DataSet: TDataSet);
begin
cdsTblbda.Tag := 1;
try
cdsTblbdaasscod.Value := cdsTbladaasscod.Value;
cdsTblbdaadacod.Value := cdsTbladaadacod.Value;
sqlMaxBdacod.Close;
sqlMaxBdacod.ParamByName('asscod').AsInteger := cdsTblbdaasscod.AsInteger;
sqlMaxBdacod.ParamByName('adacod').AsInteger := cdsTblbdaadacod.AsInteger;
sqlMaxBdacod.Open;
cdsTblbdabdacod.AsInteger := sqlMaxBdacodbdacod.AsInteger + 1;
cdsTblbdausucod.AsInteger := dmUsuario.cdsUsuariousucod.AsInteger;
cdsTblbdabdadt.AsDateTime := dmDadosGlobal.GetDataHoraBanco;
cdsTblbdabdavl.Value := 0;
finally
cdsTblbda.Tag := 0;
end;
end;
procedure TdmDadosAssinantes.cdsTblcpacpavlValidate(Sender: TField);
begin
if cdsTblcpa.Tag = 1 then
exit;
if cdsTblcpacpavl.Value <= 0 then
raise Exception.Create('Valor da parcela não pode ser menor ou igual a zero.');
end;
procedure TdmDadosAssinantes.cdsTblcpaNewRecord(DataSet: TDataSet);
begin
cdsTblcpa.Tag := 1;
try
cdsTblcpaasscod.Value := cdsTbladaasscod.Value;
cdsTblcpaadacod.Value := cdsTbladaadacod.Value;
cdsTblcpacpadtemis.Value := dmDadosGlobal.GetDataHoraBanco;
finally
cdsTblcpa.Tag := 0;
end;
end;
procedure TdmDadosAssinantes.cdsTblhasCalcFields(DataSet: TDataSet);
begin
cdsTblhasCalcHasdescr.Value := cdsTblhashasdescr.AsString;
end;
procedure TdmDadosAssinantes.cdsTblhashasdescrValidate(Sender: TField);
begin
if cdsTblhas.Tag = 1 then
exit;
if trim(cdsTblhashasdescr.AsString) = '' then
raise Exception.Create('Descrição deve ser informada.');
end;
procedure TdmDadosAssinantes.cdsTblhashasdtValidate(Sender: TField);
begin
if cdsTblhas.Tag = 1 then
exit;
if trim(cdsTblhashasdt.AsString) = '' then
raise Exception.Create('Data deve ser informada.');
end;
procedure TdmDadosAssinantes.cdsTblhasNewRecord(DataSet: TDataSet);
begin
cdsTblhas.Tag := 1;
try
cdsTblhasasscod.Value := cdsTblassasscod.Value;
sqlMaxHasseg.Close;
sqlMaxHasseg.ParamByName('asscod').AsInteger := cdsTblassasscod.Value;
sqlMaxHasseg.Open;
cdsTblhashasseg.Value := sqlMaxHasseghasseg.AsInteger + 1;
cdsTblhashasdt.Value := dmDadosGlobal.GetDataHoraBanco;
finally
cdsTblhas.Tag := 0;
end;
end;
procedure TdmDadosAssinantes.DataModuleCreate(Sender: TObject);
begin
FOperacao := oNone;
cdsFiltroZona.Close;
cdsFiltroZona.Open;
cdsFiltroZona.First;
cdsLookupTipoAssinatura.Close;
cdsLookupTipoAssinatura.CreateDataSet;
cdsLookupTipoAssinatura.Open;
cdsLookupTipoAssinatura.AppendRecord(['A', 'Assinatura']);
cdsLookupTipoAssinatura.AppendRecord(['R', 'Renovação']);
cdsLookupTipoAssinatura.First;
cdsLookupVendedores.Close;
cdsLookupVendedores.Open;
cdsLookupCobradores.Close;
cdsLookupCobradores.Open;
end;
procedure TdmDadosAssinantes.dspTblhasUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspAssinaturasAutoUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspTbladaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspTblassUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspTblbdaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspTblcpaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.dspTblgaaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosAssinantes.EditarAssinante;
begin
if not cdsTblass.Active then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if cdsTblass.RecordCount = 0 then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if cdsTblass.State in [dsBrowse] then
cdsTblass.Edit;
FOperacao := oUpdate;
end;
procedure TdmDadosAssinantes.EditarAssinatura;
begin
if not cdsTblada.Active then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
if cdsTblada.RecordCount = 0 then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
CancelarManutencaoAssinatura;
// Coloca o regitro principal em estado de edição.
cdsTblada.Edit;
FOperacao := oUpdate;
end;
procedure TdmDadosAssinantes.EditarBaixa;
begin
if not cdsTblbda.Active then
raise Exception.Create(NENHUMA_BAIXA_SELECIONADA);
if cdsTblbda.RecordCount = 0 then
raise Exception.Create(NENHUMA_BAIXA_SELECIONADA);
cdsTblbda.Edit;
FOperacao := oUpdate;
end;
procedure TdmDadosAssinantes.EditarHistorico;
begin
if not cdsTblhas.Active then
raise Exception.Create(NENHUM_HISTORICO_SELECIONADO);
if cdsTblhas.RecordCount = 0 then
raise Exception.Create(NENHUM_HISTORICO_SELECIONADO);
if cdsTblhas.State in [dsBrowse] then
cdsTblada.Edit;
FOperacao := oUpdate;
end;
procedure TdmDadosAssinantes.ExcluirAssinante;
var
Transaction: TDBXTransaction;
begin
if not cdsTblass.Active then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if cdsTblass.RecordCount = 0 then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
if MessageDlg('Deseja realmente excluir o assinante selecionada?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
exit;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosAssinante(oDelete, true);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.ExcluirAssinatura;
var
Transaction: TDBXTransaction;
begin
if not cdsTblada.Active then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
if cdsTblada.RecordCount = 0 then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
if MessageDlg('Deseja realmente excluir a assinatura selecionada?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
exit;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosAssinatura(oDelete, true);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.ExcluirBaixa;
var
ValorPendente: Double;
Transaction: TDBXTransaction;
begin
if not cdsTblbda.Active then
raise Exception.Create(NENHUMA_BAIXA_SELECIONADA);
if cdsTblbda.RecordCount = 0 then
raise Exception.Create(NENHUMA_BAIXA_SELECIONADA);
if MessageDlg('Deseja realmente excluir a baixa selecionada?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
exit;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
FOperacao := oDelete;
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// ---------------------------------------------------------------------------
// Atualiza o novo valor pendente na assinatura do assinante
// ---------------------------------------------------------------------------
ValorPendente := cdsTbladaadavlpend.Value + cdsTblbdabdavl.Value;
AtualizarValorPendenteAssinatura(ValorPendente);
// ---------------------------------------------------------------------------
// Grava os dados nas tabelas do Banco
AtualizarDadosBaixa(oDelete, true);
// Grava os dados nas tabelas do Banco
// Chamo este método pois o valor pendente da assinatura pode ter mudado
AtualizarDadosAssinatura(oUpdate, false);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.ExcluirHistorico;
var
Transaction: TDBXTransaction;
begin
if not cdsTblhas.Active then
raise Exception.Create(NENHUM_HISTORICO_SELECIONADO);
if cdsTblhas.RecordCount = 0 then
raise Exception.Create(NENHUM_HISTORICO_SELECIONADO);
if MessageDlg('Deseja realmente excluir o histórico selecionado?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then
exit;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosHistorico(oDelete);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.FiltrarAssinantes(ACodigo: Integer; ANomeAssinante: String;
AEndereco: String; ANroEndereco: String; ACodigoZona: String; ADescrZona: String;
AStatus: Integer);
var
SQL: String;
CodigoAssinante: Integer;
CodigoAssinatura: Integer;
begin
CodigoAssinante := -1;
CodigoAssinatura := -1;
// Será utilizado para posicionar na lista
if cdsTblass.Active then
begin
CodigoAssinante := cdsTblassasscod.AsInteger;
// Será utilizado para posicionar na lista
if cdsTblada.Active then
CodigoAssinatura := cdsTbladaadacod.AsInteger
end;
// ---------------------------------------------------------------------------
// Montagem do SQL da consulta
// ---------------------------------------------------------------------------
ANomeAssinante := trim(ANomeAssinante);
AEndereco := trim(AEndereco);
ANroEndereco := trim(ANroEndereco);
ACodigoZona := trim(ACodigoZona);
ADescrZona := trim(ADescrZona);
SQL :=
'select tblass.*, tblzon.zoncod, tblzon.zondescr ' +
' from tblass, tblrdz, tblzon ' +
' where tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ';
if (ACodigo = 0) and (ANomeAssinante = EmptyStr) and (AEndereco = EmptyStr) and (ANroEndereco = EmptyStr) and (ACodigoZona = EmptyStr) and (ADescrZona = EmptyStr) and (AStatus = -1) then
begin
SQL := SQL + ' and 1 = 2';
end
else
begin
if ACodigo > 0 then
SQL := SQL + ' and tblass.asscod = ' + IntToStr(ACodigo);
if ANomeAssinante <> EmptyStr then
SQL := SQL + ' and tblass.assnome like "%' + ANomeAssinante + '%"';
if AEndereco <> EmptyStr then
SQL := SQL + ' and tblrdz.rdzender like "%' + AEndereco + '%"';
if ANroEndereco <> EmptyStr then
SQL := SQL + ' and tblass.assnroent like "%' + ANroEndereco + '%"';
if ACodigoZona <> EmptyStr then
SQL := SQL + ' and tblzon.zoncod like "%' + ACodigoZona + '%"';
if ADescrZona <> EmptyStr then
SQL := SQL + ' and tblzon.zondescr like "%' + ADescrZona + '%"';
if AStatus <> -1 then
SQL := SQL + ' and tblass.assstatus = ' + IntToStr(AStatus);
end;
SQL := SQL + ' order by tblass.assnome';
sqlTblass.Close;
sqlTblass.CommandText := SQL;
cdsTblass.DisableControls;
try
cdsTblass.Close;
cdsTblass.Open;
// posiciona na lista
PosicionarAssinante(CodigoAssinante, CodigoAssinatura);
finally
cdsTblass.EnableControls;
end;
end;
procedure TdmDadosAssinantes.FiltrarAssinantesBaixaRapida(
ANomeAssinante: String);
var
SQL: String;
begin
ANomeAssinante := trim(ANomeAssinante);
if ANomeAssinante = EmptyStr then
begin
cdsBaixaRapida.Close;
exit;
end;
// ---------------------------------------------------------------------------
// Montagem do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblass.asscod, tblass.assnome, ' +
' tblada.adacod, tblada.adadtvenc, tblada.adavlpend ' +
' from tblass, tblada ' +
' where tblass.asscod = tblada.asscod ' +
' and tblass.assstatus = 0 ' +
' and tblada.adacancel = "N" ' +
' and tblada.adavlpend > 0 ' +
' and tblass.assnome like "%' + ANomeAssinante + '%" ' +
' order by tblass.asscod, tblada.adacod desc ';
sqlBaixaRapida.Close;
sqlBaixaRapida.CommandText := SQL;
cdsBaixaRapida.Close;
cdsBaixaRapida.Open;
end;
procedure TdmDadosAssinantes.FiltrarEnderecos(AEnderecoZona: String);
var
ListWord: TStringList;
SQL: String;
SQLWhere: String;
i: Integer;
begin
AEnderecoZona := trim(AEnderecoZona);
if AEnderecoZona = EmptyStr then
begin
sqlPesquisaEndereco.Close;
cdsPesquisaEndereco.Close;
exit;
end;
SQLWhere := '';
ListWord := TStringList.Create;
try
ExtractStrings([' '], [' '], pchar(AEnderecoZona), ListWord);
for I := 0 to ListWord.Count -1 do
begin
if SQLWhere <> EmptyStr then
SQLWhere := SQLWhere + ' and ';
SQLWhere := SQLWhere +
' (tblrdz.rdzender like ' + '''' + '%' + ListWord[i] + '%' + '''' +
' or tblzon.zoncod like ' + '''' + '%' + ListWord[i] + '%' + '''' +
' or tblzon.zondescr like ' + '''' + '%' + ListWord[i] + '%' + '''' +
')';
end;
finally
FreeAndNil(ListWord);
end;
SQL :=
'select tblrdz.rdzcod, tblrdz.rdzender, tblzon.zoncod, tblzon.zondescr ' +
' from tblrdz, tblzon ' +
' where tblrdz.zoncod = tblzon.zoncod ' +
' and ' + SQLWhere +
' order by tblrdz.rdzender ';
sqlPesquisaEndereco.Close;
sqlPesquisaEndereco.CommandText := SQL;
cdsPesquisaEndereco.Close;
cdsPesquisaEndereco.Open;
end;
procedure TdmDadosAssinantes.RenovarAssinaturasAutomaticamente(AMes, AAno: Integer;
AValorAssinatura: Double; ANroMesesAssinatura: Integer; AVencod: Integer; AVennome: String);
var
DataGeracaoAuto: TDate;
DataAtual: TDate;
ContadorAssinaturas: Integer;
DataIniNovoVenc: TDate;
DataFimNovoVenc: TDate;
DataIniNovoVencTeste: TDate;
DataFimNovoVencTeste: TDate;
Transaction: TDBXTransaction;
begin
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
DataAtual := dmDadosGlobal.GetDataHoraBanco;
DataGeracaoAuto := EncodeDate(AAno, AMes, 01);
if AValorAssinatura <= 0 then
raise Exception.Create('Valor da renovação não pode ser menor ou igual a zero.');
if ANroMesesAssinatura <= 0 then
raise Exception.Create('Número de meses não pode ser menor ou igual a zero.');
// Verifica se já não foi realizada uma renovação automática para o período
// informado.
sqlTblgaa.Close;
sqlTblgaa.ParamByName('gaaanomes').AsString := FormatDateTime('yyyy-mm-dd', DataGeracaoAuto);
cdsTblgaa.Close;
cdsTblgaa.Open;
if cdsTblgaa.RecordCount > 0 then
raise Exception.Create('Já foi gerado assinaturas automáticas para o Mês e Ano informado.');
TfrmMensagem.MostrarMesagem('Aguarde, gerando renovação de assinaturas...');
try
ContadorAssinaturas := 0;
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Seleciona um novo número de lote da geração automática.
sqlMaxGaacod.Close;
sqlMaxGaacod.Open;
// Atualiza a tabela que guarda o ano e mes da atualização automática
sqlInsertTblgaa.Close;
sqlInsertTblgaa.ParamByName('gaacod').AsInteger := sqlMaxGaacodgaacod.Value;
sqlInsertTblgaa.ParamByName('gaaanomes').AsDate := DataGeracaoAuto;
sqlInsertTblgaa.ParamByName('gaadtgerauto').AsDate := DataAtual;
sqlInsertTblgaa.ParamByName('gaavennome').AsString := AVennome;
sqlInsertTblgaa.ParamByName('gaavlass').AsFloat := AValorAssinatura;
sqlInsertTblgaa.ParamByName('gaanromes').AsInteger := ANroMesesAssinatura;
sqlInsertTblgaa.ParamByName('usucod').AsInteger := dmUsuario.cdsUsuariousucod.Value;
sqlInsertTblgaa.ExecSQL;
// Seleciona todas as assinaturas de assinantes ativos com o vencimento
// no período informado e que estas assinaturas não estejam canceladas.
sqlAssinaturasAuto.Close;
sqlAssinaturasAuto.ParamByName('adadtini').AsString := FormatDateTime('yyyy-mm-dd', DataGeracaoAuto);
sqlAssinaturasAuto.ParamByName('adadtfim').AsString := FormatDateTime('yyyy-mm-dd', EndOfTheMonth(DataGeracaoAuto));
cdsAssinaturasAuto.Close;
cdsAssinaturasAuto.Open;
while not cdsAssinaturasAuto.Eof do
begin
// Nova data de vencimento da assinatura
DataIniNovoVenc := cdsAssinaturasAutoadadtvenc.AsDateTime;
DataFimNovoVenc := IncMonth(cdsAssinaturasAutoadadtvenc.AsDateTime, ANroMesesAssinatura);
// Verificar se já não existe uma assinatura para o novo vencimento
DataIniNovoVencTeste := EncodeDate(YearOf(DataFimNovoVenc), MonthOf(DataFimNovoVenc), 01);
DataFimNovoVencTeste := EncodeDate(YearOf(DataFimNovoVenc), MonthOf(DataFimNovoVenc), DayOf(EndOfTheMonth(DataFimNovoVenc)));
sqlExisteProxAss.Close;
sqlExisteProxAss.ParamByName('asscod').AsInteger := cdsAssinaturasAutoasscod.AsInteger;
sqlExisteProxAss.ParamByName('adadtvencini').AsString := FormatDateTime('yyyy-mm-dd', DataIniNovoVencTeste);
sqlExisteProxAss.ParamByName('adadtvencfim').AsString := FormatDateTime('yyyy-mm-dd', DataFimNovoVencTeste);
sqlExisteProxAss.Open;
if sqlExisteProxAssnroreg.AsInteger > 0 then
begin
cdsAssinaturasAuto.Next;
Continue;
end;
// Filtra e posiciona no assinante
FiltrarAssinantes(cdsAssinaturasAutoasscod.Value);
if cdsTblass.RecordCount = 0 then
begin
cdsAssinaturasAuto.Next;
Continue;
end;
// ---------------------------------------------------------------------
EditarAssinante; // Coloca o registro do Assinante em editção
cdsTblassvencod.AsInteger := AVencod; // Altera o Vendedor com o seleciono
AtualizarDadosAssinante(oUpdate, false); // Salva as alterações no Assinante.
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
AdicionarAssinatura; // Coloca a assinatura em estado de Insersão.
cdsTbladaadadtini.AsDateTime := DataIniNovoVenc; // Data de início da nova assinatura
cdsTbladaadadtvenc.AsDateTime := DataFimNovoVenc; // Data de vencimento da nova assinatura
cdsTbladaadavl.Value := AValorAssinatura;
cdsTbladaadavldesc.Value := 0;
cdsTbladaadavlpend.Value := AValorAssinatura;
cdsTbladaadacortesia.Value := cdsAssinaturasAutoadacortesia.Value;
cdsTbladagaacod.Value := sqlMaxGaacodgaacod.Value; // Novo nro. de lote
cdsTbladaadadtalt.AsDateTime := dmDadosGlobal.GetDataHoraBanco;
cdsTbladausucodalt.Value := dmUsuario.cdsUsuariousucod.Value;
AtualizarDadosAssinatura(oInsert, False); // Salva a nova assinatura
// ---------------------------------------------------------------------
Inc(ContadorAssinaturas);
cdsAssinaturasAuto.Next;
end;
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
TfrmMensagem.MostrarMesagem;
MessageDlg('Foram geradas ' + FormatFloat('0', ContadorAssinaturas) + ' novas assinaturas para o Lote ' + sqlMaxGaacodgaacod.AsString, mtInformation, [mbOK], 0);
except
on E: Exception do
begin
TfrmMensagem.MostrarMesagem;
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
CancelarManutencaoAssinatura;
raise Exception.Create(e.Message);
end;
end;
finally
TfrmMensagem.MostrarMesagem;
cdsTblgaa.Close;
cdsAssinaturasAuto.Close;
FiltrarAssinantes;
end;
end;
function TdmDadosAssinantes.RetornaDataUltimaRenovacaoAuto: TDate;
begin
sqlMaxGaaanomes.Close;
sqlMaxGaaanomes.Open;
Result := sqlMaxGaaanomesgaaanomes.Value;
end;
procedure TdmDadosAssinantes.GerarCondicoesParcelas(AQtdeParcelas: Integer;
APrimeiroVenc: TDate; AValorPagar: Double);
var
I: Integer;
ValorParcela: Double;
SomaParcelas: Double;
Residuo: Double;
DataVencimento: TDate;
begin
i := 0;
ValorParcela := 0;
SomaParcelas := 0;
Residuo := 0;
DataVencimento := 0;
if AQtdeParcelas > 5 then
raise Exception.Create('Quantidade de parcelas inválida, é permitido no máximo 5 parcelas.');
if APrimeiroVenc = StrToDate('30/12/1899') then
APrimeiroVenc := IncMonth(dmDadosGlobal.GetDataHoraBanco, 1);
if AValorPagar <= 0 then
raise Exception.Create('Valor Total da Assinatura não pode ser menor ou igual a zero.');
if cdsTblcpa.State in [dsEdit, dsInsert] then
cdsTblcpa.CancelUpdates;
if cdsTblcpa.RecordCount > 0 then
begin
cdsTblcpa.First;
Repeat
cdsTblcpa.Delete;
Until cdsTblcpa.Eof;
end;
if AQtdeParcelas < 1 then
exit;
for I := 1 to AQtdeParcelas do
begin
if i = 1 then
DataVencimento := APrimeiroVenc
else
DataVencimento := IncMonth(DataVencimento, 1);
cdsTblcpa.Append;
cdsTblcpaasscod.Value := cdsTbladaasscod.Value;
cdsTblcpaadacod.Value := cdsTbladaadacod.Value;
cdsTblcpacpadtvenc.Value := DataVencimento;
cdsTblcpacpadtemis.Value := dmDadosGlobal.GetDataHoraBanco;
cdsTblcpacpanroparc.Value := i;
cdsTblcpacpavl.Value := SimpleRoundTo((AValorPagar / AQtdeParcelas), -2);
cdsTblcpa.Post;
SomaParcelas := SomaParcelas + cdsTblcpacpavl.Value;
end;
Residuo := AValorPagar - SomaParcelas;
cdsTblcpa.Edit;
cdsTblcpacpavl.Value := cdsTblcpacpavl.Value + Residuo;
cdsTblcpa.Post;
cdstblcpa.First;
end;
function TdmDadosAssinantes.GetDescricaoStatusAssinante(
Aassstatus: Integer): String;
begin
if Aassstatus = 0 then
Result := 'Ativo'
else
Result := 'Inativo';
end;
function TdmDadosAssinantes.GetDescricaoTipoAssinatura(
Aadatipo: String): String;
begin
if UpperCase(Aadatipo) = 'A' then
Result := 'Assinatura'
else
Result := 'Renovação';
end;
function TdmDadosAssinantes.GetValorTotalBaixas(Aasscod, Aadacod,
Abdacod: Integer): Double;
var
SQL: String;
begin
SQL :=
'select sum(bdavl) as vltotbaixas ' +
' from tblbda ' +
' where asscod = ' + IntToStr(Aasscod) +
' and adacod = ' + IntToStr(Aadacod);
// Se for informado uma determinada baixa, isso significa que é
// para desconsiderar a baixa informada no somatório;
if Abdacod > 0 then
SQL := SQL + ' and bdacod <> ' + IntToStr(Abdacod);
sqlTotalBaixas.Close;
sqlTotalBaixas.CommandText := SQL;
sqlTotalBaixas.Open;
Result := sqlTotalBaixasvltotbaixas.Value;
end;
procedure TdmDadosAssinantes.PosicionarAssinante(ACodigoAssinante: Integer; ACodigoAssinatura: Integer);
begin
if not cdsTblass.Active then
exit;
if cdsTblass.RecordCount = 0 then
exit;
// Posicona o registro do Assinante na tela
if not cdsTblass.Locate('asscod', ACodigoAssinante, []) then
begin
cdsTblass.First;
exit;
end;
if not cdsTblada.Active then
exit;
if cdsTblada.RecordCount = 0 then
exit;
// Posicona o registro da Assinatura na tela
if not cdsTblada.Locate('asscod;adacod', VarArrayOf([ACodigoAssinante,ACodigoAssinatura]), []) then
cdsTblada.First;
if cdsTblcpa.Active then
cdsTblcpa.First;
if cdsTblbda.Active then
cdsTblbda.First;
end;
procedure TdmDadosAssinantes.SalvarAssinante(AValidarDados: Boolean);
var
Transaction: TDBXTransaction;
begin
if not cdsTblass.Active then
raise Exception.Create(NENHUM_ASSINANTE_SELECIONADA);
// ---------------------------------------------------------------------------
// Aplica mais uma vez os métodos de validação
// ---------------------------------------------------------------------------
if AValidarDados then
begin
cdsTblasscepcepentValidate(cdsTblasscepcepent);
cdsTblassassnomeValidate(cdsTblassassnome);
cdsTblassasscnpjValidate(cdsTblassasscnpj);
cdsTblassasscpfValidate(cdsTblassasscpf);
cdsTblassassdtinativoValidate(cdsTblassassdtinativo);
cdsTblassrdzcodValidate(cdsTblassrdzcod);
cdsTblass.Tag := 2;
try
cdsTblassassnroentValidate(cdsTblassassnroent);
finally
cdsTblass.Tag := 0;
end;
cdsTblassassemailValidate(cdsTblassassemail);
end;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosAssinante(FOperacao, true);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.SalvarAssinatura(AValidarDados: Boolean);
var
Transaction: TDBXTransaction;
begin
if not cdsTblada.Active then
raise Exception.Create(NENHUMA_ASSINATURA_SELECIONADA);
// ---------------------------------------------------------------------------
// Aplica mais uma vez os métodos de validação da Assinatura
// ---------------------------------------------------------------------------
if AValidarDados then
begin
cdsTbladaadadtvencValidate(cdsTbladaadadtvenc);
cdsTbladaadavlValidate(cdsTbladaadavl);
cdsTbladaadavldescValidate(cdsTbladaadavl);
cdsTbladaadadtcancelValidate(cdsTbladaadadtcancel);
end;
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Procedimento de gravação de Logs do último usuário que alterou o registro.
// ---------------------------------------------------------------------------
if cdsTblada.State in [dsBrowse] then
cdsTblada.Edit;
cdsTbladaadadtalt.AsDateTime := dmDadosGlobal.GetDataHoraBanco;
cdsTbladausucodalt.Value := dmUsuario.cdsUsuariousucod.Value;
// ---------------------------------------------------------------------------
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosAssinatura(FOperacao, True);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.SalvarBaixa(AValidarDados: Boolean);
var
Transaction: TDBXTransaction;
begin
if not cdsTblbda.Active then
raise Exception.Create(NENHUMA_BAIXA_SELECIONADA);
// ---------------------------------------------------------------------------
// Aplica mais uma vez os métodos de validação
// ---------------------------------------------------------------------------
if AValidarDados then
begin
cdsTblbdabdadtValidate(cdsTblbdabdadt);
cdsTblbdabdavlValidate(cdsTblbdabdavl);
end;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosBaixa(FOperacao, true);
// Chamo este método aqui, pois o valor pendente da assinatura pode ter mudado.
AtualizarDadosAssinatura(oUpdate, false);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
procedure TdmDadosAssinantes.SalvarHistorico(AValidarDados: Boolean);
var
Transaction: TDBXTransaction;
begin
if not cdsTblhas.Active then
raise Exception.Create(NENHUM_HISTORICO_SELECIONADO);
// ---------------------------------------------------------------------------
// Aplica mais uma vez os métodos de validação
// ---------------------------------------------------------------------------
if AValidarDados then
begin
cdsTblhashasdtValidate(cdsTblhashasdt);
cdsTblhashasdescrValidate(cdsTblhashasdescr);
end;
if dmConexao.SQLConnection.InTransaction then
raise Exception.Create('Já existe alguma atualização de cadastro em andamento.');
Transaction := nil;
try
Transaction := dmConexao.SQLConnection.BeginTransaction(TDBXIsolations.ReadCommitted);
// Grava os dados nas tabelas do Banco
AtualizarDadosHistorico(FOperacao);
// Finaliza a transação
dmConexao.SQLConnection.CommitFreeAndNil(Transaction);
finally
if Assigned(Transaction) then
if dmConexao.SQLConnection.InTransaction then
dmConexao.SQLConnection.RollbackFreeAndNil(Transaction);
end;
end;
end.
|
unit PageController;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
dcfdes,
dxDockControl, dxDockPanel,
EasyEditState,
LrDockUtils, LrDocument,
PageDocument, PageView,
DesignScrollBox, IEView, InspectorView, ComponentTreeView, DesignView,
PhpEditView, JsEditView, CodeExplorerView, HtmlEditView{, CodeExpert};
type
TPageController = class(TLrController)
private
FDocument: TPageDocument;
FOnSelectionChange: TNotifyEvent;
FOnPropChange: TNotifyEvent;
protected
function GetView: TPageViewForm;
procedure SetDocument(const Value: TPageDocument);
protected
//CodeExpert: TCodeExpert;
JsState: TEasyEditState;
LastFocus: TWinControl;
NameList: TStringList;
PhpState: TEasyEditState;
TabState: TDockTabsState;
protected
procedure BuildNameList;
procedure DesignPagesChange(Sender: TObject);
procedure DesignSelect(Sender: TObject);
procedure PageChange(inSender: TObject);
procedure PropChanged(Sender: TObject);
procedure SelectDesignerClick(Sender: TObject);
procedure SelectComponent(inComponent: TComponent);
public
{ Public declarations }
constructor Create(inDocument: TPageDocument); reintroduce;
destructor Destroy; override;
procedure Activate; override;
procedure CodeExpertUpdate(inSender: TObject);
procedure Deactivate; override;
procedure LazyUpdate; override;
procedure Publish;
procedure ShowOutput;
procedure SyncViewToPage;
procedure UpdateCode;
public
property Document: TPageDocument read FDocument write SetDocument;
property View: TPageViewForm read GetView;
property OnPropChange: TNotifyEvent read FOnPropChange
write FOnPropChange;
property OnSelectionChange: TNotifyEvent read FOnSelectionChange
write FOnSelectionChange;
end;
implementation
uses
LrUtils, LrTagParser,
ThComponentIterator, ThCssStyle, ThJavaScript, ThPageControl,
TpForm,
PhpEventProperty, JsInspector,
Main;
constructor TPageController.Create(inDocument: TPageDocument);
begin
inherited Create(nil);
// CodeExpert := TCodeExpert.Create(View.PhpEditForm.Edit);
NameList := TStringList.Create;
TabState := TDockTabsState.Create(View);
PhpState := TEasyEditState.Create;
JsState := TEasyEditState.Create;
Document := inDocument;
end;
destructor TPageController.Destroy;
begin
// CodeExpert.Free;
NameList.Free;
JsState.Free;
PhpState.Free;
TabState.Free;
inherited;
end;
function TPageController.GetView: TPageViewForm;
begin
Result := MainForm.PageView;
end;
procedure TPageController.SetDocument(const Value: TPageDocument);
begin
FDocument := Value;
InsertForm(Document.DesignForm, View.Scroller, alNone);
Document.DesignForm.DCLiteDesigner.PopupMenu := MainForm.DesignPopup;
Document.DesignForm.OnActivate := MainForm.EditorEnter;
Document.DesignForm.OnSelectionChange := DesignSelect;
Document.Page.OnChange := PageChange;
end;
procedure TPageController.SyncViewToPage;
begin
with Document do
begin
DesignForm.BoundsRect := Page.BoundsRect;
if ThVisibleColor(Page.Style.Color) then
DesignForm.Color := Page.Style.Color
else
DesignForm.Color := clWhite;
View.Scroller.Color := DesignForm.Color;
with DesignForm.DCLiteDesigner do
begin
ShowComponents := Page.ShowComponents;
ShowGrid := Page.ShowGrid;
ShowCaptions := Page.ShowCaptions;
end;
end;
end;
procedure TPageController.Activate;
begin
View.PhpEditForm.OnModified := Document.ChangeEvent;
View.PhpEditForm.OnLazyUpdate := CodeExpertUpdate;
View.PhpEditForm.Strings := Document.Page.PhpSource;
//
View.JsEditForm.OnModified := Document.ChangeEvent;
View.JsEditForm.Strings := Document.Page.JsSource;
//
View.DesignPages.OnChange := DesignPagesChange;
View.OnSelectComponent := SelectComponent;
View.RsRulerCorner.OnClick := SelectDesignerClick;
//
InspectorForm.OnPropChanged := PropChanged;
//
Document.DesignForm.Parent := View.Scroller;
Document.DesignForm.ActivateDesigner;
//
SyncViewToPage;
//
ActivateDock(View.DesignDock);
//
TabState.Restore;
//
if (LastFocus <> nil) and LastFocus.CanFocus then
LastFocus.SetFocus;
//
JsState.SetState(View.JsEditForm.Edit);
PhpState.SetState(View.PhpEditForm.Edit);
end;
procedure TPageController.Deactivate;
begin
View.PhpEditForm.OnModified := nil;
View.PhpEditForm.OnLazyUpdate := nil;
View.JsEditForm.OnModified := nil;
View.DesignPages.OnChange := nil;
View.OnSelectComponent := nil;
View.RsRulerCorner.OnClick := nil;
InspectorForm.OnPropChanged := nil;
//
Document.DesignForm.DeactivateDesigner;
Document.DesignForm.Parent := View.HideSheet;
//
LazyUpdate;
TabState.Capture;
LastFocus := MainForm.LastEditor;
JsState.GetState(View.JsEditForm.Edit);
PhpState.GetState(View.PhpEditForm.Edit);
end;
procedure TPageController.BuildNameList;
var
i: Integer;
begin
NameList.Clear;
with TThComponentIterator.Create(Document.DesignForm) do
try
while Next do
begin
NameList.Add('$' + Component.Name + '=' + Component.ClassName);
if (Component is TTpForm) then
with TTpForm(Component) do
for i := 0 to Pred(Inputs.Count) do
NameList.Add('$' + Inputs[i].WebName + '=' + 'TTpInput');
end;
finally
Free;
end;
end;
procedure TPageController.CodeExpertUpdate(inSender: TObject);
begin
BuildNameList;
View.PhpEditForm.ObjectList := NameList;
end;
procedure TPageController.LazyUpdate;
begin
//BuildNameList;
//CodeExpert.UpdateGlobals(NameList);
UpdateCode;
end;
procedure TPageController.UpdateCode;
begin
View.PhpEditForm.ValidateMethods(Document.DesignForm);
//
Document.Page.PhpSource.Assign(View.PhpEditForm.Source.Strings);
Document.UpdatePageName(View.PhpEditForm.Source.Strings);
//
View.JsEditForm.ValidateMethods(Document.DesignForm);
Document.Page.JsSource.Assign(View.JsEditForm.Source.Strings);
end;
procedure TPageController.PageChange(inSender: TObject);
begin
SyncViewToPage;
end;
procedure TPageController.PropChanged(Sender: TObject);
begin
Document.Modified := true;
View.Refresh;
if Assigned(OnPropChange) then
OnPropChange(Self);
end;
procedure TPageController.DesignSelect(Sender: TObject);
begin
if Document = nil then
begin
View.DesignSelect(nil, nil, nil, nil);
end
else with Document do
begin
View.DesignSelect(DesignForm.SelectedComponents, DesignForm,
DesignForm.Selection, Page);
//
if Assigned(OnSelectionChange) then
OnSelectionChange(Self);
//
// This needs to be moved elsewhere
if (DesignForm.Selection is TThSheet) then
TThSheet(DesignForm.Selection).Select;
end;
end;
procedure TPageController.SelectComponent(inComponent: TComponent);
begin
Document.DesignForm.Selection := inComponent;
end;
procedure TPageController.DesignPagesChange(Sender: TObject);
begin
if View.DesignPages.ActivePage = View.OutputSheet then
ShowOutput;
end;
procedure TPageController.ShowOutput;
var
s: TStringList;
begin
s := Document.GenerateHtml;
with TLrTaggedDocument.Create do
try
Text := s.Text;
s.Clear;
Indent(s);
finally
Free;
end;
View.DesignHtml := s; //Document.GenerateHtml;
end;
procedure TPageController.SelectDesignerClick(Sender: TObject);
begin
Document.DesignForm.SetFocus;
end;
procedure TPageController.Publish;
begin
View.DebugForm.Clear;
View.DebugForm.Parent.Visible := Document.Page.Debug;
PhpState.GetState(View.PhpEditForm.Edit);
Document.Publish;
View.PhpEditForm.Source.Strings.Assign(Document.Page.PhpSource);
PhpState.SetState(View.PhpEditForm.Edit);
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls, Menus, GdipApi, GdipClass, XPMan;
type
TFrmMain = class(TForm)
PaintBoxTop : TPaintBox;
PMRenderProperties : TPopupMenu; // PaintBoxTop popupmenu
MIRenderQuality : TMenuItem;
MIRenderQualityLow : TMenuItem;
MIRenderQualityMedium: TMenuItem;
MIRenderQualityHigh : TMenuItem;
MIRenderSmooth : TMenuItem;
MIRenderSmoothNone : TMenuItem;
MIRenderSmoothAAS : TMenuItem;
MIRenderSmoothHigh : TMenuItem;
PnlBottom : TPanel; // Draw properties panel
LblString : TLabel;
EdtString : TEdit;
GPBFontProperties : TGroupBox;
LblFontNames : TLabel;
CBXFontNames : TComboBox;
LblFontSize : TLabel;
EdtFontSize : TEdit;
UDFontSize : TUpDown;
GPBBorderColor : TGroupBox;
LblBorderAlpha : TLabel;
EdtBorderAlpha : TEdit;
UDBorderAlpha : TUpDown;
LblBorderRed : TLabel;
EdtBorderRed : TEdit;
UDBorderRed : TUpDown;
LblBorderGreen : TLabel;
EdtBorderGreen : TEdit;
UDBorderGreen : TUpDown;
LblBorderBlue : TLabel;
EdtBorderBlue : TEdit;
UDBorderBlue : TUpDown;
GPBInnerColor : TGroupBox;
LblInnerAlpha : TLabel;
EdtInnerAlpha : TEdit;
UDInnerAlpha : TUpDown;
LblInnerRed : TLabel;
EdtInnerRed : TEdit;
UDInnerRed : TUpDown;
LblInnerGreen : TLabel;
EdtInnerGreen : TEdit;
UDInnerGreen : TUpDown;
LblInnerBlue : TLabel;
EdtInnerBlue : TEdit;
UDInnerBlue : TUpDown;
BtnApply : TButton;
XPManifest1 : TXPManifest;
LblBorderSize: TLabel;
EdtBorderSize: TEdit;
UDBorderSize: TUpDown;
procedure PaintBoxTopPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnApplyClick(Sender: TObject);
procedure CompQualityClick(Sender: TObject);
procedure SmoothClick(Sender: TObject);
procedure CBXFontNamesChange(Sender: TObject);
procedure EdtStringChange(Sender: TObject);
private
protected
procedure AddFontName(const FontName: string);
public
vDString : string;
vDFntName : string;
vDFntSize : single;
vDBrdSize : single;
vDBorderCol: TGPColor;
vDInnerCol : TGPColor;
vDCQ : CompositingQuality;
vDSM : SmoothingMode;
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
procedure TFrmMain.FormCreate(Sender: TObject);
begin
// Enregistre quelques polices d'ecriture
AddFontName('Arial');
AddFontName('Arial black');
AddFontName('Comic sans ms');
AddFontName('Courier');
AddFontName('Courier new');
AddFontName('Garamond');
AddFontName('Impact');
AddFontName('Lucida console');
AddFontName('Microsoft sans serif');
AddFontName('Monotype corsiva');
AddFontName('Tahoma');
AddFontName('Times new roman');
AddFontName('Trebuchet ms');
AddFontName('Verdana');
// selectionne la premiere police
CBXFontNames.ItemIndex:=0;
// Propriétés de rendus par defaut
vDCQ:=CompositingQualityHighQuality;
vDSM:=SmoothingModeAntiAlias;
// Redessine
BtnApplyClick(nil);
end;
// Ajoute une fonte existante dans la liste CBXFontNames
procedure TFrmMain.AddFontName(const FontName: string);
begin
if Screen.Fonts.IndexOf(FontName)<>-1
then CBXFontNames.Items.Add(FontName)
end;
// Applique les changements
procedure TFrmMain.BtnApplyClick(Sender: TObject);
begin
// Texte
vDString:=EdtString.Text;
// Taille du contour
vdBrdSize:=UDBorderSize.Position;
// Police d'ecriture
vDFntName:=CBXFontNames.Text;
vdFntSize:=UDFontSize.Position;
// Couleur du contour
vDBorderCol:=ARGBMake(UDBorderAlpha.Position,
UDBorderRed.Position,
UDBorderGreen.Position,
UDBorderBlue.Position);
// Couleur du texte
vdInnerCol :=ARGBMake(UDInnerAlpha.Position,
UDInnerRed.Position,
UDInnerGreen.Position,
UDInnerBlue.Position);
// Redessine
PaintBoxTop.Repaint;
end;
// Definition de la qualité de rendu
procedure TFrmMain.CompQualityClick(Sender: TObject);
begin
case (Sender as TMenuItem).Tag of
1: vDCQ:=CompositingQualityHighSpeed;
2: vDCQ:=CompositingQualityAssumeLinear;
3: vDCQ:=CompositingQualityHighQuality;
else vDCQ:=CompositingQualityHighQuality;
end;
PaintBoxTop.Repaint;
end;
// Definition du lissage du rendu
procedure TFrmMain.SmoothClick(Sender: TObject);
begin
case (Sender as TMenuItem).Tag of
1: vDSM:=SmoothingModeNone;
2: vDSM:=SmoothingModeAntiAlias;
3: vDSM:=SmoothingModeHighQuality;
else vDSM:=SmoothingModeAntiAlias;
end;
PaintBoxTop.Repaint;
end;
// Dessin
procedure TFrmMain.PaintBoxTopPaint(Sender: TObject);
var
DPen: TGPPen;
Layout: TGPRect;
Drawer: TGPGraphics;
DBrush: TGPSolidBrush;
DFntFam: TGPFontFamily;
DPath: TGPGraphicsPath;
DFntFmt: TGPStringFormat;
begin
// Zone de dessin
Layout.X:=0;
Layout.Y:=0;
Layout.Width:=(Sender as TPaintBox).Width-1;
Layout.Height:=(Sender as TPaintBox).Height-1;
// Creation des classes GDI+
Drawer:=TGPGraphics.Create((Sender as TPaintBox).Canvas.Handle);
Drawer.SetCompositingQuality(vDCQ);
Drawer.SetSmoothingMode(vdSM);
DPath:=TGPGraphicsPath.Create;
DPen:=TGPPen.Create(vDBorderCol, vDBrdSize);
DBrush:=TGPSolidBrush.Create(vDInnerCol);
DFntFam:=TGPFontFamily.Create(vDFntName);
DFntFmt:=TGPStringFormat.Create;
DFntFmt.SetAlignment(StringAlignmentCenter);
DFntFmt.SetLineAlignment(StringAlignmentCenter);
// Efface le canvas
Drawer.Clear(aclWhite);
// Remise a zero du Path (facultatif)
DPath.Reset;
// Ajoute un dessin dans le Path
DPath.AddString(vDString, Length(vDString), DFntFam, FontStyleRegular, vDFntSize, Layout, DFntFmt);
// Dessine le countour du path
Drawer.DrawPath(DPen, DPath);
// Remplis le path
Drawer.FillPath(DBrush, DPath);
// Free classes GDI+
DFntFmt.Free;
DFntFam.Free;
DBrush.Free;
DPen.Free;
DPath.Free;
Drawer.Free;
end;
procedure TFrmMain.CBXFontNamesChange(Sender: TObject);
begin
BtnApply.Click;
end;
procedure TFrmMain.EdtStringChange(Sender: TObject);
begin
BtnApply.Click;
end;
end.
|
{------------------------------------------------------------------------------}
{ 单元名称: Wil.pas }
{ }
{ 单元作者: 清清 (QQ:272987775 Email:272987775@QQ.com) }
{ 创建日期: 2007-10-28 20:30:00 }
{ }
{ 功能介绍: }
{ 传奇2 Wil 文件读取单元 }
{ }
{ 使用说明: }
{ }
{ WIL 位图文件: 由 文件头+调色板(256色)+(TImageInfo+位图 Bits)*N项 组成 }
{ WIX 索引文件: 实际上就是一个文件头+指针数组, 指针指向 TImageInfo 结构 }
{ }
{ 更新历史: }
{ }
{ 尚存问题: }
{ }
{ WIL 的调色板是不是都是一样的?如果是,则可以省略 }
{ 注意: WIL 的数据格式定义都是没有 pack 的 record }
{ }
{ Weapon.wix 数据有误: 索引文件头设置的图片数量为 40856, 实际能读出的数量 }
{ 为 40855, 传奇源代码可以正常运行的原因是它没有检测可读出的内容. }
{ 可能需要重建索引. 目前的解决方法是在 LoadIndexFile 中根据读出的实际内 }
{ 容对 FImageCount 进行修正. }
{ }
{------------------------------------------------------------------------------}
unit WIL;
interface
uses
Windows, Classes, Graphics, SysUtils, DXDraws,
DirectX, DIB, wmUtil, HUtil32;
{------------------------------------------------------------------------------}
// WIL 常量定义
{------------------------------------------------------------------------------}
var
g_boUseDIBSurface :Boolean = FALSE;// 是否在创建 WIL Surface 时使用 DIB 绘制
// 如果直接使用 WIL 文件中的位图 Bits 会出现少量颜色
// 显示不正确,在传奇源代码中的结果也是如此。
{------------------------------------------------------------------------------}
// WIL 文件格式定义
{------------------------------------------------------------------------------}
type
// WIL 文件头格式 (56Byte)
TLibType = (ltLoadBmp, ltLoadMemory, ltLoadMunual, ltUseCache);
TBmpImage = record
Bmp :TBitmap;
dwLatestTime :LongWord;
end;
pTBmpImage = ^TBmpImage;
TBmpImageArr = array[0..MaxListSize div 4] of TBmpImage;
TDxImageArr = array[0..MaxListSize div 4] of TDxImage;
PTBmpImageArr = ^TBmpImageArr;
PTDxImageArr = ^TDxImageArr;
{------------------------------------------------------------------------------}
// TWilFile class
{------------------------------------------------------------------------------}
TWMImages = class (TComponent)
private
FFileName: String; //0x24 // WIL 文件名
FImageCount: integer; //0x28 // 图片数量
FLibType: TLibType; //0x2C //图象装载方式
FDxDraw: TDxDraw; //0x30
FDDraw: TDirectDraw; //0x34
//FMaxMemorySize: integer; //0x38
btVersion:Byte; //0x3C
m_bt458 :Byte;
FAppr:Word;
procedure LoadAllData;
procedure LoadIndex (idxfile: string);
procedure LoadDxImage (position: integer; pdximg: PTDxImage);
procedure LoadBmpImage (position: integer; pbmpimg: PTBmpImage);
procedure FreeOldMemorys;
function FGetImageSurface (index: integer): TDirectDrawSurface;
procedure FSetDxDraw (fdd: TDxDraw);
procedure FreeOldBmps;
function FGetImageBitmap (index: integer): TBitmap;
protected
lsDib: TDib; //0x40
m_dwMemChecktTick: LongWord; //0x44
public
m_ImgArr :pTDxImageArr; //0x48
m_BmpArr :pTBmpImageArr; //0x4C
m_IndexList :TList; //0x50
m_FileStream: TFileStream; //0x54
MainPalette: TRgbQuads;
constructor Create (AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize;
procedure Finalize;
procedure ClearCache;
procedure LoadPalette;
procedure FreeBitmap (index: integer);
function GetImage (index: integer; var px, py: integer): TDirectDrawSurface;
function GetCachedImage (index: integer; var px, py: integer): TDirectDrawSurface;
function GetCachedSurface (index: integer): TDirectDrawSurface;
function GetCachedBitmap (index: integer): TBitmap;
property Images[index: integer]: TDirectDrawSurface read FGetImageSurface;
property Bitmaps[Index: Integer]: TBitmap read FGetImageBitmap;
property DDraw: TDirectDraw read FDDraw write FDDraw;
published
property FileName: string read FFileName write FFileName;
property ImageCount: integer read FImageCount;
property DxDraw: TDxDraw read FDxDraw write FSetDxDraw;
property LibType: TLibType read FLibType write FLibType;
//property MaxMemorySize: integer read FMaxMemorySize write FMaxMemorySize;
property Appr:Word read FAppr write FAppr;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MirGame', [TWmImages]);
end;
constructor TWMImages.Create (AOwner: TComponent);
begin
inherited Create (AOwner);
FFileName := '';
FLibType := ltLoadBmp;
FImageCount := 0;
//FMaxMemorySize := 1024*1000; //1M
FDDraw := nil;
FDxDraw := nil;
m_FileStream := nil;
m_ImgArr := nil;
m_BmpArr := nil;
m_IndexList := TList.Create;
lsDib := TDib.Create;
lsDib.BitCount := 8;
m_dwMemChecktTick := GetTickCount;
btVersion:=0;
m_bt458:=0;
end;
destructor TWMImages.Destroy;
begin
m_IndexList.Free;
if m_FileStream <> nil then m_FileStream.Free;
lsDib.Free;
inherited Destroy;
end;
procedure TWMImages.Initialize;
var
Idxfile: String;
Header :TWMImageHeader;
begin
if not (csDesigning in ComponentState) then begin
if FFileName = '' then begin
//raise Exception.Create ('FileName not assigned..');
Exit;
end;
if (LibType <> ltLoadBmp) and (FDDraw = nil) then begin
//raise Exception.Create ('DDraw not assigned..');
Exit;
end;
if FileExists (FFileName) then begin
if m_FileStream = nil then
m_FileStream := TFileStream.Create (FFileName, fmOpenRead or fmShareDenyNone);
m_FileStream.Read (Header, SizeOf(TWMImageHeader));
if header.VerFlag = 0 then begin
btVersion:=1;
m_FileStream.Seek(-4,soFromCurrent);
end;
FImageCount := Header.ImageCount;
if LibType = ltLoadBmp then begin
m_BmpArr := AllocMem (SizeOf(TBmpImage) * FImageCount);
if m_BmpArr = nil then
raise Exception.Create (self.Name + ' BmpArr = nil');
end else begin
m_ImgArr:=AllocMem(SizeOf(TDxImage) * FImageCount);
if m_ImgArr = nil then
raise Exception.Create (self.Name + ' ImgArr = nil');
end;
//索引文件
idxfile := ExtractFilePath(FFileName) + ExtractFileNameOnly(FFileName) + '.WIX';
LoadPalette;
if LibType = ltLoadMemory then
LoadAllData
else begin
LoadIndex (idxfile);
end;
end else begin
// MessageDlg (FFileName + ' Cannot find file.', mtWarning, [mbOk], 0);
end;
end;
end;
procedure TWMImages.Finalize;
var
i: integer;
begin
//释放装载的所有图片
//if FImageCount > 0 then begin//20080629
for i:=0 to FImageCount-1 do begin
if m_ImgArr[i].Surface <> nil then begin
m_ImgArr[i].Surface.Free;
m_ImgArr[i].Surface := nil;
end;
end;
//end;
if m_FileStream <> nil then
FreeAndNil(m_FileStream);
if FImageCount > 0 then begin
if LibType = ltLoadBmp then begin //20080718释放内存
FreeMem(m_BmpArr);
end else begin
FreeMem(m_ImgArr);
end;
end;
end;
//装载图片到内存,需要大量内存!
procedure TWMImages.LoadAllData;
var
i: integer;
imgi: TWMImageInfo;
dib: TDIB;
dximg: TDxImage;
begin
dib := TDIB.Create;
if FImageCount > 0 then begin//20080629
for i:=0 to FImageCount-1 do begin
if btVersion <> 0 then m_FileStream.Read (imgi, sizeof(TWMImageInfo) - 4)
else m_FileStream.Read (imgi, sizeof(TWMImageInfo));
dib.Width := imgi.nWidth;
dib.Height := imgi.nHeight;
dib.ColorTable := MainPalette;
dib.UpdatePalette;
m_FileStream.Read (dib.PBits^, imgi.nWidth * imgi.nHeight);
dximg.nPx := imgi.px;
dximg.nPy := imgi.py;
dximg.surface := TDirectDrawSurface.Create (FDDraw);
dximg.surface.SystemMemory := True;
dximg.surface.SetSize (imgi.nWidth, imgi.nHeight);
dximg.surface.Canvas.Draw (0, 0, dib);
dximg.surface.Canvas.Release;
dib.Clear; //FreeImage;
dximg.surface.TransparentColor := 0;
m_ImgArr[i] := dximg;
FreeAndNil(dximg.surface); //20080719添加
end;
end;
dib.Free;
end;
//从WIL文件中装载调色板
procedure TWMImages.LoadPalette;
{var
Entries: TPaletteEntries; }
begin
if btVersion <> 0 then
m_FileStream.Seek (sizeof(TWMImageHeader) - 4, 0)
else
m_FileStream.Seek (sizeof(TWMImageHeader), 0);
m_FileStream.Read (MainPalette, sizeof(TRgbQuad) * 256); //
end;
procedure TWMImages.LoadIndex (idxfile: string);
var
fhandle, i, value: integer;
header: TWMIndexHeader;
//pidx: PTWMIndexInfo; //20080718注释释放内存
pvalue: PInteger;
begin
m_IndexList.Clear;
if FileExists (idxfile) then begin
fhandle := FileOpen (idxfile, fmOpenRead or fmShareDenyNone);
if fhandle > 0 then begin
if btVersion <> 0 then
FileRead (fhandle, header, sizeof(TWMIndexHeader) - 4)
else
FileRead (fhandle, header, sizeof(TWMIndexHeader));
GetMem (pvalue, 4*header.IndexCount);
FileRead (fhandle, pvalue^, 4*header.IndexCount);
if header.IndexCount > 0 then //20080629
for i:=0 to header.IndexCount-1 do begin
value := PInteger(integer(pvalue) + 4*i)^;
m_IndexList.Add (pointer(value));
end;
FreeMem(pvalue);
FileClose (fhandle);
end;
end;
end;
{----------------- Private Variables ---------------------}
function TWMImages.FGetImageSurface (index: integer): TDirectDrawSurface;
begin
Result := nil;
if LibType = ltUseCache then begin
Result := GetCachedSurface (index);
end else
if LibType = ltLoadMemory then begin
if (index >= 0) and (index < ImageCount) then
Result := m_ImgArr[index].Surface;
end;
end;
function TWMImages.FGetImageBitmap (index: integer): TBitmap;
begin
Result:=nil;
if LibType <> ltLoadBmp then exit;
Result := GetCachedBitmap (index);
end;
procedure TWMImages.FSetDxDraw (fdd: TDxDraw);
begin
FDxDraw := fdd;
end;
// *** DirectDrawSurface Functions
procedure TWMImages.LoadDxImage (position: integer; pdximg: PTDxImage);
var
imginfo: TWMImageInfo;
ddsd: TDDSurfaceDesc;
SBits, PSrc, DBits: PByte;
n, slen: integer;
begin
m_FileStream.Seek (position, 0);
if btVersion <> 0 then m_FileStream.Read (imginfo, SizeOf(TWMImageInfo)-4)
else m_FileStream.Read (imginfo, SizeOf(TWMImageInfo));
if g_boUseDIBSurface then begin //DIB
//非全屏时
try
lsDib.Clear;
lsDib.Width := imginfo.nWidth;
lsDib.Height := imginfo.nHeight;
except
end;
lsDib.ColorTable := MainPalette;
lsDib.UpdatePalette;
DBits := lsDib.PBits;
m_FileStream.Read (DBits^, imginfo.nWidth * imgInfo.nHeight);
pdximg.nPx := imginfo.px;
pdximg.nPy := imginfo.py;
pdximg.surface := TDirectDrawSurface.Create (FDDraw);
pdximg.surface.SystemMemory := TRUE;
pdximg.surface.SetSize (imginfo.nWidth, imginfo.nHeight);
pdximg.surface.Canvas.Draw (0, 0, lsDib);
pdximg.surface.Canvas.Release;
pdximg.surface.TransparentColor := 0;
end else begin //
//全屏时
try
slen := WidthBytes(imginfo.nWidth);
GetMem (PSrc, slen * imgInfo.nHeight);
// SBits := PSrc; //20080718注释释放内存
m_FileStream.Read (PSrc^, slen * imgInfo.nHeight);
pdximg.surface := TDirectDrawSurface.Create (FDDraw);
pdximg.surface.SystemMemory := TRUE;
pdximg.surface.SetSize (slen, imginfo.nHeight);
//pdximg.surface.Palette := MainSurfacePalette;
pdximg.nPx := imginfo.px;
pdximg.nPy := imginfo.py;
ddsd.dwSize := SizeOf(ddsd);
pdximg.surface.Lock (TRect(nil^), ddsd);
DBits := ddsd.lpSurface;
if imginfo.nHeight > 0 then //20080629
for n:=imginfo.nHeight - 1 downto 0 do begin
SBits := PByte (Integer(PSrc) + slen * n);
Move(SBits^, DBits^, slen);
Inc (integer(DBits), ddsd.lPitch);
end;
pdximg.surface.TransparentColor := 0;
finally
pdximg.surface.UnLock();
FreeMem(PSrc); //20080719修改
end;
end;
end;
procedure TWMImages.LoadBmpImage (position: integer; pbmpimg: PTBmpImage);
var
imginfo: TWMImageInfo;
DBits: PByte;
begin
m_FileStream.Seek (position, 0);
m_FileStream.Read (imginfo, sizeof(TWMImageInfo)-4);
lsDib.Width := imginfo.nWidth;
lsDib.Height := imginfo.nHeight;
lsDib.ColorTable := MainPalette;
lsDib.UpdatePalette;
DBits := lsDib.PBits;
m_FileStream.Read (DBits^, imginfo.nWidth * imgInfo.nHeight);
pbmpimg.bmp := TBitmap.Create;
pbmpimg.bmp.Width := lsDib.Width;
pbmpimg.bmp.Height := lsDib.Height;
pbmpimg.bmp.Canvas.Draw (0, 0, lsDib);
lsDib.Clear;
end;
procedure TWMImages.ClearCache;
var
i: integer;
begin
if ImageCount > 0 then //20080629
for i:=0 to ImageCount - 1 do begin
if m_ImgArr[i].Surface <> nil then begin
m_ImgArr[i].Surface.Free;
m_ImgArr[i].Surface := nil;
end;
end;
//MemorySize := 0;
end;
function TWMImages.GetImage (index: integer; var px, py: integer): TDirectDrawSurface;
begin
if (index >= 0) and (index < ImageCount) then begin
px := m_ImgArr[index].nPx;
py := m_ImgArr[index].nPy;
Result := m_ImgArr[index].surface;
end else
Result := nil;
end;
{--------------- BMP functions ----------------}
procedure TWMImages.FreeOldBmps;
var
i, ntime{, curtime}: integer;
begin
ntime := 0;
if ImageCount > 0 then //20080629
for i:=0 to ImageCount-1 do begin
// curtime := GetTickCount;
if m_BmpArr[i].Bmp <> nil then begin
if GetTickCount - m_BmpArr[i].dwLatestTime > 5000 then begin
m_BmpArr[i].Bmp.Free;
m_BmpArr[i].Bmp := nil;
end else begin
if GetTickCount - m_BmpArr[i].dwLatestTime > ntime then begin
ntime := GetTickCount - m_BmpArr[i].dwLatestTime;
end;
end;
end;
end;
end;
procedure TWMImages.FreeBitmap (index: integer);
begin
if (index >= 0) and (index < ImageCount) then begin
if m_BmpArr[index].Bmp <> nil then begin
//MemorySize := MemorySize - BmpArr[index].Bmp.Width * BmpArr[index].Bmp.Height;
//if MemorySize < 0 then MemorySize := 0;
m_BmpArr[index].Bmp.FreeImage;
m_BmpArr[index].Bmp.Free;
m_BmpArr[index].Bmp := nil;
end;
end;
end;
//坷贰等 某矫 瘤框
procedure TWMImages.FreeOldMemorys;
var
i: integer;
begin
if ImageCount > 0 then //20080629
for i:=0 to ImageCount-1 do begin
if m_ImgArr[i].Surface <> nil then begin
if GetTickCount - m_ImgArr[i].dwLatestTime > 5 * 60 * 1000 then begin
m_ImgArr[i].Surface.Free;
m_ImgArr[i].Surface := nil;
//FreeAndNil(m_ImgArr[i].Surface); //20081719修改
end;
end;
end;
end;
//Cache甫 捞侩窃
function TWMImages.GetCachedSurface (index: integer): TDirectDrawSurface;
var
nPosition:Integer;
//nErrCode:Integer;
begin
Result := nil;
//nErrCode:=0;
try
if (index < 0) or (index >= ImageCount) then exit;
if GetTickCount - m_dwMemChecktTick > 10000 then begin
m_dwMemChecktTick := GetTickCount;
//if MemorySize > FMaxMemorySize then begin
FreeOldMemorys;
//end;
end;
//nErrCode:=1;
if m_ImgArr[index].Surface = nil then begin //cache登绢 乐瘤 臼澜. 货肺 佬绢具窃.
if index < m_IndexList.Count then begin
nPosition:= Integer(m_IndexList[index]);
LoadDxImage (nPosition, @m_ImgArr[index]);
m_ImgArr[index].dwLatestTime := GetTickCount;
//nErrCode:=2;
Result := m_ImgArr[index].Surface;
//MemorySize := MemorySize + ImgArr[index].Surface.Width * ImgArr[index].Surface.Height;
end;
end else begin
m_ImgArr[index].dwLatestTime := GetTickCount;
//nErrCode:=3;
Result := m_ImgArr[index].Surface;
end;
except
//DebugOutStr ('GetCachedSurface 3 Index: ' + IntToStr(index) + ' Error Code: ' + IntToStr(nErrCode));
end;
end;
function TWMImages.GetCachedImage (index: integer; var px, py: integer): TDirectDrawSurface;
var
position: integer;
//nErrCode:Integer;
begin
Result := nil;
//nErrCode:=0;
try
if (index < 0) or (index >= ImageCount) then Exit;
if GetTickCount - m_dwMemChecktTick > 10000 then begin
m_dwMemChecktTick := GetTickCount;
//if MemorySize > FMaxMemorySize then begin
FreeOldMemorys;
//end;
end;
//nErrCode:=1;
if m_ImgArr[index].Surface = nil then begin //cache
if index < m_IndexList.Count then begin
position := Integer(m_IndexList[index]);
LoadDxImage (position, @m_ImgArr[index]);
m_ImgArr[index].dwLatestTime := GetTickCount;
px := m_ImgArr[index].nPx;
py := m_ImgArr[index].nPy;
Result := m_ImgArr[index].Surface;
//MemorySize := MemorySize + ImgArr[index].Surface.Width * ImgArr[index].Surface.Height;
end;
end else begin
m_ImgArr[index].dwLatestTime := GetTickCount;
px := m_ImgArr[index].nPx;
py := m_ImgArr[index].nPy;
Result := m_ImgArr[index].Surface;
end;
except
//DebugOutStr ('GetCachedImage 3 Index: ' + IntToStr(index) + ' Error Code: ' + IntToStr(nErrCode));
end;
end;
function TWMImages.GetCachedBitmap (index: integer): TBitmap;
var
position: integer;
begin
Result := nil;
if (index < 0) or (index >= ImageCount) then exit;
if m_BmpArr[index].Bmp = nil then begin //cache登绢 乐瘤 臼澜. 货肺 佬绢具窃.
if index < m_IndexList.Count then begin
position := Integer(m_IndexList[index]);
LoadBmpImage (position, @m_BmpArr[index]);
m_BmpArr[index].dwLatestTime := GetTickCount;
Result := m_BmpArr[index].Bmp;
//MemorySize := MemorySize + BmpArr[index].Bmp.Width * BmpArr[index].Bmp.Height;
//if (MemorySize > FMaxMemorySize) then begin
FreeOldBmps;
//end;
end;
end else begin
m_BmpArr[index].dwLatestTime:=GetTickCount;
Result := m_BmpArr[index].Bmp;
end;
end;
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0089.PAS
Description: Numbers up to 255 digits
Author: ALEKSANDAR DLABAC
Date: 01-02-98 07:35
*)
{ Unit LongNum;}
{
██████████████████████████████████████████████████
███▌▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▐███▒▒
███▌██ ██▐███▒▒
███▌██ Numbers with up to 255 digits ██▐███▒▒
███▌██ -- New functions and bug fixes -- ██▐███▒▒
███▌██ ██▐███▒▒
███▌██ Aleksandar Dlabac ██▐███▒▒
███▌██ (C) 1997. Dlabac Bros. Company ██▐███▒▒
███▌██ ------------------------------ ██▐███▒▒
███▌██ adlabac@urcpg.urc.cg.ac.yu ██▐███▒▒
███▌██ adlabac@urcpg.pmf.cg.ac.yu ██▐███▒▒
███▌██ ██▐███▒▒
███▌▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▐███▒▒
██████████████████████████████████████████████████▒▒
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
}
{
This program enables use of a very long signed integer numbers - up to
255 digits. Numbers are in fact strings, so they can be easily writed on
screen/file/printer.
}
uses crt;
{ Interface }
Function LongNumError : Boolean; forward;
{ Returns the status of last operations performed. If there was an error
in calculations (overflow, for example), since LongNumError previous
call, True will be returned. }
Function MakeLong (Number:longint) : string; forward;
{ Converts longint number to string. }
Function MakeInt (Number:string) : longint; forward;
{ Converts long number to longint, if possible. }
Function FormatLongNumber (Number:string;Digits:byte) : string; forward;
{ Formats long number so it will have given number of digits. If number of
digits is zero the number will be represented with as less as possible
digits. Otherwise, if number of digits is smaller than number size,
LongNumError will return True. }
Function Neg (A:string) : string; forward;
{ Returns -A. }
Function Sgn (A:string) : shortint; forward;
{ Returns Signum (A): 1 if A>0, 0 if A=0, -1 if A<0. }
Function Add (A,B:string) : string; forward;
{ Returns A+B. }
Function Subtract (A,B:string) : string; forward;
{ Returns A-B. }
Function Multiple (A,B:string) : string; forward;
{ Returns A*B. }
Function Divide (A,B:string;var Remainder:string) : string; forward;
{ Returns A/B. Remainder is division remaider. }
Function Power (A:string;B:byte) : string; forward;
{ Returns A^B. }
Function Square (A:string) : string; forward;
{ Returns A^2. }
Function SquareRoot (A:string) : string; forward;
{ Returns Sqrt (A). If negative value is given, square root of absolute
value will be returned, and LongNumError will return True. }
Function LongToHex (A:string) : string; forward;
{ Returns hexadecimal value of A. }
Function HexToLong (A:string) : string; forward;
{ Returns decimal value of A, where A is hexadecimal value. }
Function Equal (A,B:string) : Boolean; forward;
{ Returns True if A=B. }
Function Greater (A,B:string) : Boolean; forward;
{ Returns True if A>B. }
Function GreaterOrEqual (A,B:string) : Boolean; forward;
{ Returns True if A>=B. }
{ Implementation }
Var LongNumErrorFlag : Boolean;
Function LongNumError : Boolean;
Var Temp : Boolean;
Begin
Temp:=LongNumErrorFlag;
LongNumErrorFlag:=False;
LongnumError:=Temp
End;
Function Dgt (C:char) : byte;
Var Temp : byte;
Begin
Temp:=0;
If C in ['1'..'9'] then
Temp:=Ord (C)-48;
If not (C in ['-',' ','0'..'9']) then
LongNumErrorFlag:=True;
Dgt:=Temp
End;
Function MakeLong (Number:longint) : string;
Var Temp : string;
Begin
Str (Number,Temp);
MakeLong:=Temp
End;
Function MakeInt (Number:string) : longint;
Var Temp : longint;
I : byte;
Flag : Boolean;
Begin
Flag:=(Sgn (Subtract (MakeLong (2147483647),Number))=-1) or
(Sgn (Subtract (Number,MakeLong (-2147483647)))=-1) or (Number='');
Temp:=0;
If Flag then
LongNumErrorFlag:=True
else
Begin
For I:=1 to Length (Number) do
Temp:=Temp*10+Dgt (Number [I]);
Temp:=Temp*Sgn (Number);
End;
MakeInt:=Temp
End;
Function FormatLongNumber (Number:string;Digits:byte) : string;
Var I : byte;
Sign, Temp : string;
Begin
Temp:=Number;
I:=1;
Sign:='';
Repeat
While (I<Length (Temp)) and (Temp [I]=' ') do
Inc (I);
While (I<Length (Temp)) and (Temp [I]='0') do
Begin
Temp [I]:=' ';
Inc (I)
End;
If (I<Length (Temp)) and (Temp [I]='-') then
Begin
Sign:='-';
Temp [I]:=' '
End;
Until (I>=Length (Temp)) or (Temp [I] in ['1'..'9','A'..'F']);
While (Length (Temp)>0) and (Temp [1]=' ') do
Temp:=Copy (Temp,2,Length (Temp)-1);
If Temp='' then
Temp:='0';
If Temp<>'0' then
Temp:=Sign+Temp;
If Digits>0 then
Begin
While Length (Temp)<Digits do
Temp:=' '+Temp;
If (Digits<Length (Temp)) and (Temp [Length (Temp)-Digits]<>' ') then
LongNumErrorFlag:=True;
Temp:=Copy (Temp,Length (Temp)-Digits+1,Digits)
End;
FormatLongNumber:=Temp
End;
Function Neg (A:string) : string;
Var Temp : string;
Begin
Temp:=FormatLongNumber (A,0);
If Temp [1]='-' then
Temp:=Copy (Temp,2,Length (Temp)-1)
else
If Length (Temp)<255 then
Temp:='-'+Temp
else
LongNumErrorFlag:=True;
Neg:=Temp
End;
Function Sgn (A:string) : shortint;
Var I : byte;
Temp : shortint;
S : string;
Begin
S:=FormatLongNumber (A,0);
Case S [1] of
'-' : Temp:=-1;
'0' : Temp:=0;
else Temp:=1
End;
Sgn:=Temp
End;
Function Add (A,B:string) : string;
Var Sign, Factor, SgnA, SgnB, N : shortint;
Transf, Sub, I : byte;
N1, N2, Temp : string;
Begin
SgnA:=Sgn (A);
SgnB:=Sgn (B);
If SgnA*SgnB=0 then
Begin
If Sgn (A)=0 then
Temp:=B
else
Temp:=A
End
else
Begin
If SgnA=-1 then
N1:=Neg (A)
else
N1:=A;
If SgnB=-1 then
N2:=Neg (B)
else
N2:=B;
While Length (N1)<Length (N2) do
N1:=' '+N1;
While Length (N2)<Length (N1) do
N2:=' '+N2;
If SgnA*SgnB>0 then
Begin
Sign:=SgnA;
Factor:=1;
End
else
Begin
If N1=N2 then
Sign:=1
else
Begin
If N1>N2 then
Sign:=SgnA
else
Begin
Sign:=SgnB;
Temp:=N1;
N1:=N2;
N2:=Temp
End
End;
Factor:=-1
End;
Temp:='';
Transf:=0;
Sub:=0;
For I:=Length (N1) downto 1 do
Begin
N:=Transf+(10+Dgt (N1 [I])-Sub) mod 10+Factor*Dgt (N2 [I]);
Transf:=0;
If Dgt (N1 [I])-Sub<0 then
Sub:=1
else
Sub:=0;
If N<0 then
Begin
Sub:=1;
Inc (N,10)
End
else
If N>=10 then
Begin
Transf:=1;
Dec (N,10)
End;
Temp:=Chr (N+48)+Temp;
End;
If ((Length (Temp)=255) and (Transf>0)) or (Sub>0) then
LongNumErrorFlag:=True
else
Begin
If Transf>0 then
Temp:=Chr (Transf+48)+Temp;
If Sign=-1 then
Temp:=Neg (Temp)
End
End;
Temp:=FormatLongNumber (Temp,0);
Add:=Temp
End;
Function Subtract (A,B:string) : string;
Var Temp : string;
Begin
Subtract:=Add (A,Neg (B))
End;
Function Multiple (A,B:string) : string;
Var Sign, SgnA, SgnB, N : shortint;
I, J, D, Transf : byte;
N1, N2, Temp, S : string;
Begin
SgnA:=Sgn (A);
SgnB:=Sgn (B);
Sign:=SgnA*SgnB;
If SgnA=-1 then
N1:=Neg (A)
else
N1:=A;
If SgnB=-1 then
N2:=Neg (B)
else
N2:=B;
If Sign=0 then
Temp:='0'
else
Begin
N1:=FormatLongNumber (N1,0);
N2:=FormatLongNumber (N2,0);
Temp:='0';
For J:=Length (N2) downto 1 do
Begin
D:=Dgt (N2 [J]);
Transf:=0;
S:='';
For I:=1 to Length (N2)-J do
S:=S+'0';
For I:=Length (N1) downto 1 do
Begin
N:=Transf+D*Dgt (N1 [I]);
If Length (S)=255 then
LongNumErrorFlag:=True;
S:=Chr (N mod 10+48)+S;
Transf:=N div 10
End;
If Transf>0 then
If Length (S)=255 then
LongNumErrorFlag:=True
else
S:=Chr (Transf+48)+S;
Temp:=Add (Temp,S)
End
End;
If Sign=-1 then
Temp:=Neg (Temp);
Temp:=FormatLongNumber (Temp,0);
Multiple:=Temp
End;
Function Divide (A,B:string;var Remainder:string) : string;
Var Sign, SgnA, SgnB : shortint;
I, J : byte;
N1, N2, Temp, S1, S2 : string;
Begin
SgnA:=Sgn (A);
SgnB:=Sgn (B);
Sign:=SgnA*SgnB;
If SgnA=-1 then
N1:=Neg (A)
else
N1:=A;
If SgnB=-1 then
N2:=Neg (B)
else
N2:=B;
N1:=FormatLongNumber (N1,0);
N2:=FormatLongNumber (N2,0);
If not GreaterOrEqual (N1,N2) then
Begin
Temp:='0';
If SgnA=-1 then
Remainder:=Neg (N1)
else
Remainder:=N1
End
else
Begin
Temp:='';
S1:=N1;
For I:=1 to Length (N1)-Length (N2)+1 do
Begin
S2:=Copy (S1,1,I+Length (N2)-1);
J:=9;
While Greater (Multiple (N2,Chr (J+48)),S2) do
Dec (J);
Temp:=Temp+Chr (J+48);
S1:=Subtract (S2,Multiple (N2,Chr (J+48)))+Copy (S1,I+Length (N2),Length (S1)-I-Length (N2)+1);
While Length (S1)<Length (N1) do
S1:=' '+S1
End;
If SgnA=-1 then
Remainder:=Neg (Subtract (N1,Multiple (N2,Temp)))
else
Remainder:=Subtract (N1,Multiple (N2,Temp));
End;
If Sign=-1 then
Temp:=Neg (Temp);
Temp:=FormatLongNumber (Temp,0);
Divide:=Temp
End;
Function Power (A:string;B:byte) : string;
Var I : byte;
Temp : string;
Error : Boolean;
Begin
Error:=False;
Temp:='1';
For I:=1 to B do
Temp:=Multiple (Temp,A);
Temp:=FormatLongNumber (Temp,0);
Power:=Temp
End;
Function Square (A:string) : string;
Begin
Square:=Multiple (A,A)
End;
Function SquareRoot (A:string) : string;
Var I : byte;
J : char;
N, Temp, S1, S2, Remainder : string;
Begin
N:=FormatLongNumber (A,0);
If Sgn (N)=-1 then
Begin
LongNumErrorFlag:=True;
N:=Neg (A)
End;
If Length (N) mod 2=1 then
Begin
S1:=' '+N [1];
I:=2
End
else
Begin
S1:=N [1]+N [2];
I:=3
End;
Temp:=Chr (Trunc (Sqrt (MakeInt (S1)))+48);
Remainder:=Subtract (S1,Square (Temp));
While I<Length (N) do
Begin
S1:=Remainder+N [I]+N [I+1];
J:='9';
S2:=Multiple (Temp,'2');
While Greater (Multiple (S2+J,J),S1) do
Dec (J);
Temp:=Temp+J;
Remainder:=Subtract (S1,Multiple (S2+J,J));
Inc (I,2)
End;
SquareRoot:=Temp
End;
Function LongToHex (A:string) : string;
Const HexDigit : array [0..15] of char =
('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
Var SgnA : shortint;
Temp, N, Remainder : string;
Begin
Temp:='';
SgnA:=Sgn (A);
If SgnA=-1 then
N:=Neg (A)
else
N:=FormatLongNumber (A,0);
Repeat
N:=Divide (N,'16',Remainder);
Temp:=HexDigit [MakeInt (Remainder)]+Temp;
Until N='0';
If SgnA=-1 then
Temp:='-'+Temp;
LongtoHex:=Temp
End;
Function HexToLong (A:string) : string;
Var SgnA : shortint;
I : byte;
N, Temp, S1, S2 : string;
Begin
Temp:='';
S1:='1';
SgnA:=Sgn (A);
If SgnA=-1 then
N:=Neg (A)
else
N:=FormatLongNumber (A,0);
For I:=Length (N) downto 1 do
Begin
If N [I] in ['0'..'9'] then
S2:=N [I]
else
If UpCase (N [I]) in ['A'..'F'] then
S2:='1'+Chr (Ord (N [I])-17)
else
LongNumErrorFlag:=True;
Temp:=Add (Temp,Multiple (S1,S2));
S1:=Multiple (S1,'16')
End;
If SgnA=-1 then
Temp:='-'+Temp;
HexToLong:=Temp
End;
Function Equal (A,B:string) : Boolean;
Begin
Equal:=Sgn (Subtract (A,B))=0
End;
Function Greater (A,B:string) : Boolean;
Begin
Greater:=Sgn (Subtract (A,B))>0
End;
Function GreaterOrEqual (A,B:string) : Boolean;
Begin
GreaterOrEqual:=Sgn (Subtract (A,B))>=0
End;
{
Begin
LongNumErrorFlag:=False
End.
}
{ ---------------------- Demo program ---------------------- }
{Program LongTest;}
{Uses Crt, LongNum;}
Var L : longint;
S1, S2, Remainder : string;
Begin
ClrScr;
S1:=MakeLong (-198371298);
If LongNumError then
Writeln ('Error in calculations.')
else
Write (S1);
L:=MakeInt (S1);
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln (' = ',L);
Writeln;
S1:=Add ('1234567890','987654321');
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('1234567890 + 987654321 = ',S1);
Writeln;
S1:=Multiple ('-123','456');
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('-123 * 456 = ',S1);
Writeln;
S1:=Divide ('12345','-456',Remainder);
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('12345 / (-456) = ',S1,' [',Remainder,']');
Writeln;
S1:=Power ('-1234567890',5);
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('-1234567890^5 = ',S1);
Writeln;
S1:=Square ('-1234567890');
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('-1234567890^2 = ',S1);
Writeln;
S2:=S1;
S1:=SquareRoot (S1);
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('Sqrt (',S2,') = ',S1);
Writeln;
S1:=LongToHex ('1234567890987654321');
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln ('1234567890987654321 = ',S1,'H');
Writeln;
S2:=S1;
S1:=HexToLong (S1);
If LongNumError then
Writeln ('Error in calculations.')
else
Writeln (S2,'H = ',S1)
End.
|
unit DPM.IDE.ProjectNotifier;
interface
uses
System.Classes,
ToolsApi,
DPM.IDE.Logger;
//not used at the moment, but the plan is to use it to detect active platform changes.
type
TDPMProjectNotifier = class(TInterfacedObject,IOTAProjectNotifier, IOTAModuleNotifier,IOTANotifier )
private
FLogger : IDPMIDELogger;
protected
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
function CheckOverwrite: Boolean;
procedure Modified;
procedure ModuleRemoved(const AFileName: string);
procedure ModuleAdded(const AFileName: string);
procedure ModuleRenamedA(const AOldFileName, ANewFileName: string);
procedure ModuleRenamed(const NewName: string);
procedure IOTAProjectNotifier.ModuleRenamed = ModuleRenamedA;
public
constructor Create(const logger : IDPMIDELogger);
end;
implementation
{ TDPMProjectNotifier }
procedure TDPMProjectNotifier.AfterSave;
begin
end;
procedure TDPMProjectNotifier.BeforeSave;
begin
end;
function TDPMProjectNotifier.CheckOverwrite: Boolean;
begin
result := true;
end;
constructor TDPMProjectNotifier.Create(const logger: IDPMIDELogger);
begin
FLogger := logger;
end;
procedure TDPMProjectNotifier.Destroyed;
begin
end;
procedure TDPMProjectNotifier.Modified;
begin
end;
procedure TDPMProjectNotifier.ModuleAdded(const AFileName: string);
begin
end;
procedure TDPMProjectNotifier.ModuleRemoved(const AFileName: string);
begin
end;
procedure TDPMProjectNotifier.ModuleRenamedA(const AOldFileName, ANewFileName: string);
begin
end;
procedure TDPMProjectNotifier.ModuleRenamed(const NewName: string);
begin
end;
end.
|
unit uWholeOrderOrTradePointDlg;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, DBCtrls, DB, ADODB, UtilsBase, Variants;
type
TWholeOrderOrTPointParams = record
Caption: string;
OrderId: Integer;
TradePointId: Variant;
end;
TWholeOrderOrTradePointDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
rbWholeOrder: TRadioButton;
rbTradePoint: TRadioButton;
dsTradePoint: TDataSource;
cbTradePoint: TDBLookupComboBox;
qrTradePoint: TADOQuery;
procedure OKBtnClick(Sender: TObject);
procedure rbTradePointClick(Sender: TObject);
private
{ Private declarations }
FParams: ^TWholeOrderOrTPointParams;
procedure InitControls;
procedure SaveResults;
function ValidValuesEntered: Boolean;
public
{ Public declarations }
class function Execute(var AParams: TWholeOrderOrTPointParams): Boolean;
end;
var
WholeOrderOrTradePointDlg: TWholeOrderOrTradePointDlg;
implementation
{$R *.dfm}
uses uMain;
class function TWholeOrderOrTradePointDlg.Execute(var AParams: TWholeOrderOrTPointParams): Boolean;
var
B: Boolean;
begin
with TWholeOrderOrTradePointDlg.Create(nil) do
try
FParams := @AParams;
InitControls;
Result := ShowModal = mrOk;
finally
Free;
end;
end;
procedure TWholeOrderOrTradePointDlg.InitControls;
begin
Self.Caption := FParams.Caption;
rbWholeOrder.Checked := true;
cbTradePoint.Enabled := rbTradePoint.Checked;
qrTradePoint.Parameters.ParamByName('OrderId').Value := FParams.OrderId;
if not qrTradePoint.Active then
qrTradePoint.Open
else
qrTradePoint.Refresh;
if qrTradePoint.RecordCount = 1 then
cbTradePoint.KeyValue := qrTradePoint.FieldByName('id').Value;
end;
procedure TWholeOrderOrTradePointDlg.SaveResults;
begin
FParams^.TradePointId := Null;
if rbTradePoint.Checked then
FParams^.TradePointId := cbTradePoint.KeyValue;
end;
function TWholeOrderOrTradePointDlg.ValidValuesEntered: Boolean;
begin
Result := false;
if rbTradePoint.Checked and VarIsNull(cbTradePoint.KeyValue) then
DoError('Не задана аптека');
Result := true;
end;
procedure TWholeOrderOrTradePointDlg.OKBtnClick(Sender: TObject);
begin
if ValidValuesEntered then
begin
SaveResults;
ModalResult := mrOk;
end;
end;
procedure TWholeOrderOrTradePointDlg.rbTradePointClick(Sender: TObject);
begin
cbTradePoint.Enabled := rbTradePoint.Checked;
end;
end.
|
unit SDK;
interface
uses
Windows, Classes, SysUtils;
type
TGList = class(TList)
private
GLock: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
end;
implementation
constructor TGList.Create;
begin
inherited Create;
InitializeCriticalSection(GLock);
end;
destructor TGList.Destroy;
begin
DeleteCriticalSection(GLock);
inherited;
end;
procedure TGList.Lock;
begin
EnterCriticalSection(GLock);
end;
procedure TGList.UnLock;
begin
LeaveCriticalSection(GLock);
end;
end.
|
unit LLevel;
{$mode objfpc}{$H+}{$Define LLEVEL}
interface
uses
Classes, SysUtils, IniFiles, Graphics, LMap, LTypes, LIniFiles, LPosition,
LSize;
type
TLLevel=class(TObject)
private
{types and vars}
var
FIni: TLIniFile;
FMap: TLMap;
FPlayerPosition: TLPlayerPosition;
public
{types and vars}
type
TLLevelArray=array of TLLevel;
public
{functions and procedures}
constructor Create(Aini: TLIniFile);
destructor Destroy; override;
private
{propertyes}
property ini: TLIniFile read FIni write FIni;
property Map: TLMap read FMap write FMap;
public
{propertyes}
procedure setPlayerPosition(Value: TLPlayerPosition);
function isPlayerPosition(Value: TLPlayerPosition): Boolean;
property PlayerPosition: TLPlayerPosition read FPlayerPosition write setPlayerPosition;
function getWidth: Integer;
procedure setWidth(Value: Integer);
property Width: Integer read getWidth write setWidth;
function getHeight: Integer;
procedure setHeight(Value: Integer);
property Height: Integer read getHeight write setHeight;
function getdata: TBitmap;
property data: TBitmap read getdata;
function getViewSize: TL3DSize;
procedure setViewSize(Value: TL3DSize);
property ViewSize: TL3DSize read getViewSize write setViewSize;
function getIsWall(Ax, Ay: Integer): Boolean;
property isWall[Ax, Ay: Integer]: Boolean read getIsWall;
end;
TLLevelArray=TLLevel.TLLevelArray;
function ReadLevelArray(const Ident: String; var ini: TLIniFile): TLLevelArray;
implementation
constructor TLLevel.Create(AIni: TLIniFile);
begin
inherited Create;
Fini:=AIni;
FMap:=TLMap.Create(ini.ReadIni('Map', 'ini'));
FPlayerPosition:=TLPlayerPosition.Create;
PlayerPosition.coords:=ini.ReadPoint('Player', 'coords', Point(round(Width/2), round(Height/2)));
PlayerPosition.direction:=ini.ReadFloat('Player', 'direction', 0);
end;
destructor TLLevel.Destroy;
begin
inherited Destroy;
end;
function TLLevel.isPlayerPosition(Value: TLPlayerPosition):Boolean;
var minx, maxx, miny, maxy: Integer;
begin
minx:=1;
maxx:=Map.Size.Width;
miny:=1;
maxy:=Map.Size.Height;
Result:=(
//((0<=Value.direction) and (Value.direction<=1)) and
((0<=Value.X) and (Value.X<=maxx)) and
((0<=Value.Y) and (Value.Y<=maxy))
);
end;
procedure TLLevel.setPlayerPosition(Value: TLPlayerPosition);
begin
if isPlayerPosition(Value) and (Map.data.Canvas.Pixels[Value.coords.x, Value.coords.y]<>clBlack) then
begin
FPlayerPosition:=Value;
end;
end;
function TLLevel.getWidth: Integer;
begin
Result:=Map.Size.Height;
end;
procedure TLLevel.setWidth(Value: Integer);
begin
Map.Size.Width:=Value;
end;
function TLLevel.getHeight: Integer;
begin
Result:=Map.Size.Height;
end;
procedure TLLevel.setHeight(Value: Integer);
begin
Map.Size.Height:=Value;
end;
function TLLevel.getdata: TBitmap;
begin
Result:=Map.data;
end;
function TLLevel.getViewSize: TL3DSize;
begin
Result:=ini.ReadL3DSize('Player', 'viewsize');
end;
procedure TLLevel.setViewSize(Value:TL3DSize);
begin
ini.WriteL3DSize('Player', 'viewsize', Value);
end;
function TLLevel.getIsWall(Ax, Ay: Integer): Boolean;
begin
Result:=data.Canvas.Pixels[Ax, Ay]=clBlack;
end;
function ReadLevelArray(const Ident: String; var ini: TLIniFile): TLLevelArray;
var inis: TLIniFileArray;
i: Integer;
begin
inis:=ini.ReadIniArray(Ident);
SetLength(Result, Length(inis));
for i:=0 to Length(inis)-1 do
begin
Result[i]:=TLLevel.Create(inis[i]);
end;
end;
end.
|
{: Loading NURBS into a GLScene FreeForm/Actor object<p>
A very simple parametric model of a duck, comprised of 3 NURBS
surfaces. The Nurbs format is essentially the NurbsSurface geometry
type used in VRML. One limitation at the moment is the Control points
must each be on a separate line. Inverted surfaces are handled with
the ccw FALSE statement in the .nurbs file (duck3.nurbs uses this
setting).<p>
Use the resolution slider to increase or decrease the models triangle
count dynamically.<p>
}
unit unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, GLScene, GLVectorFileObjects, GLObjects, GLViewer,
ExtCtrls, ComCtrls, StdCtrls, GLTexture, GLCrossPlatform, GLCoordinates,
GLMaterial, GLState;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
Panel1: TPanel;
GLSceneViewer1: TGLSceneViewer;
TrackBar1: TTrackBar;
Label1: TLabel;
CheckBox1: TCheckBox;
GLActor1: TGLActor;
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure FormCreate(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
mx, my: integer;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses FileUtil, GLFileNurbs, GLParametricSurfaces, VectorGeometry, VectorLists;
procedure TForm1.FormCreate(Sender: TObject);
var
cp: TAffineVectorList;
path: UTF8String;
p: integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p + 5, Length(path));
path := IncludeTrailingPathDelimiter(path) + IncludeTrailingPathDelimiter('media');
SetCurrentDirUTF8(path);
// Load the nurbs data
GLActor1.LoadFromFile('duck1.nurbs');
GLActor1.AddDataFromFile('duck2.nurbs');
GLActor1.AddDataFromFile('duck3.nurbs');
{ Translate Actor based on the first mesh object's average
control point. Quick and dirty ... or maybe just dirty :P }
cp := TMOParametricSurface(GLActor1.MeshObjects[0]).ControlPoints;
GLActor1.Position.Translate(VectorNegate(VectorScale(cp.Sum, 1 / cp.Count)));
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mx := x;
my := y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - y, mx - x);
mx := x;
my := y;
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
var
i: integer;
begin
if Assigned(GLActor1) then
begin
for i := 0 to 2 do
TMOParametricSurface(GLActor1.MeshObjects[i]).Resolution := TrackBar1.Position;
GLActor1.StructureChanged;
end;
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
with GLActor1.Material do
begin
if Checkbox1.Checked then
begin
PolygonMode := pmLines;
FaceCulling := fcNoCull;
end
else
begin
PolygonMode := pmFill;
FaceCulling := fcBufferDefault;
end;
end;
end;
end.
|
unit Documents;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
JvTabBar,
Desktop;
const
CM_CLOSE = WM_APP + $02;
type
TDocumentsForm = class(TForm)
DocumentTabs: TJvTabBar;
DocumentPanel: TPanel;
procedure FormCreate(Sender: TObject);
procedure DocumentTabsTabClosing(Sender: TObject; Item: TJvTabBarItem;
var AllowClose: Boolean);
procedure DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
procedure DocumentTabsTabClosed(Sender: TObject; Item: TJvTabBarItem);
private
{ Private declarations }
procedure CMClose(var Message: TMessage); message CM_Close;
procedure CurrentChanged(Sender: TObject);
procedure DocumentChanged(Sender: TObject);
procedure DocumentsChanged(Sender: TObject);
public
{ Public declarations }
procedure UpdateDocumentTabs;
end;
var
DocumentsForm: TDocumentsForm;
Desktop: TDesktop;
implementation
uses
LrUtils, TurboDocumentHost, LiteBrowser, PhpEdit, ImageView;
{$R *.dfm}
procedure TDocumentsForm.FormCreate(Sender: TObject);
begin
AddForm(TurboDocumentHostForm, TTurboDocumentHostForm, DocumentPanel);
AddForm(LiteBrowserForm, TLiteBrowserForm, DocumentPanel);
AddForm(PhpEditForm, TPhpEditForm, DocumentPanel);
AddForm(ImageViewForm, TImageViewForm, DocumentPanel);
//
Desktop := TDesktop.Create;
Desktop.OnDocumentsChanged := DocumentsChanged;
Desktop.OnCurrentChanged := CurrentChanged;
Desktop.AddDocumentObserver(DocumentChanged);
end;
procedure TDocumentsForm.UpdateDocumentTabs;
var
i: Integer;
begin
DocumentPanel.Visible := Desktop.Count > 0;
with DocumentTabs do
try
OnTabSelected := nil;
Tabs.BeginUpdate;
Tabs.Clear;
for i := 0 to Pred(Desktop.Count) do
with Desktop.Documents[i] do
AddTab(DisplayName).Modified := Modified;
if (Desktop.Index >= 0) and (Desktop.Index < Tabs.Count) then
SelectedTab := Tabs[Desktop.Index];
//SelectedTab := nil;
finally
Tabs.EndUpdate;
OnTabSelected := DocumentTabsTabSelected;
end;
end;
procedure TDocumentsForm.DocumentsChanged(Sender: TObject);
begin
CurrentChanged(Sender);
//UpdateDocumentTabs;
end;
procedure TDocumentsForm.CurrentChanged(Sender: TObject);
procedure SilentTabSelect(inIndex: Integer);
begin
with DocumentTabs do
try
OnTabSelected := nil;
SelectedTab := Tabs[inIndex];
finally
OnTabSelected := DocumentTabsTabSelected;
end;
end;
begin
UpdateDocumentTabs;
if Desktop.Index >= 0 then
SilentTabSelect(Desktop.Index);
end;
procedure TDocumentsForm.DocumentChanged(Sender: TObject);
begin
UpdateDocumentTabs;
end;
procedure TDocumentsForm.DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
begin
Desktop.Index := Item.Index;
end;
procedure TDocumentsForm.DocumentTabsTabClosing(Sender: TObject;
Item: TJvTabBarItem; var AllowClose: Boolean);
begin
AllowClose := true;
end;
procedure TDocumentsForm.DocumentTabsTabClosed(Sender: TObject;
Item: TJvTabBarItem);
begin
if Desktop.StartCloseCurrent then
PostMessage(Handle, CM_CLOSE, 0, 0);
end;
procedure TDocumentsForm.CMClose(var Message: TMessage);
begin
Desktop.FinishCloseCurrent;
end;
end.
|
{
Bicubic Interpolation for Image Scaling
http://paulbourke.net/texture_colour/imageprocess/
Original C code Written by Paul Bourke
http://paulbourke.net/libraries/bitmaplib.c
Pascal version by Cirec 2012
add: Callback methode to step a ProgressBar
}
unit Bicubics;
interface
uses Windows, Graphics;
type
TObjectProc = procedure of object;
procedure BiCubicScale(const bm_in: TBitmap; const nx, ny: Integer;
const bm_out: TBitmap; const nnx, nny: Integer; const ProgressCallBack: TObjectProc = nil);
implementation
function BiCubicR(const x: Extended): Extended;
var
xp2,xp1,xm1: Extended;
r: Extended;
begin
R := 0;
xp2 := x + 2;
xp1 := x + 1;
xm1 := x - 1;
if xp2 > 0 then
r := r + xp2 * xp2 * xp2;
if xp1 > 0 then
r := r - 4 * xp1 * xp1 * xp1;
if x > 0 then
r := r + 6 * x * x * x;
if xm1 > 0 then
r := r - 4 * xm1 * xm1 * xm1;
Result := r / 6.0;
end;
{
Scale an image using bicubic interpolation
}
procedure BiCubicScale(const bm_in: TBitmap; const nx, ny: Integer;
const bm_out: TBitmap; const nnx, nny: Integer; const ProgressCallBack: TObjectProc = nil);
var
i_out,j_out,i_in,j_in,ii,jj: Integer;
n,m: Integer;
index: Integer;
cx,cy,dx,dy,weight,
red,green,blue,alpha: Extended;
col: RGBQuad;
Pbm_In, Pbm_Out: Cardinal;
begin
bm_In.PixelFormat := pf32bit;
bm_Out.PixelFormat := pf32bit;
Pbm_In := Cardinal(bm_In.ScanLine[ny-1]);
Pbm_Out := Cardinal(bm_Out.ScanLine[nny-1]);
for j_out := 0 to nny-1 do
begin
for i_out := 0 to nnx-1 do
begin
i_in := (i_out * nx) div nnx;
j_in := (j_out * ny) div nny;
cx := i_out * nx / nnx;
cy := j_out * ny / nny;
dx := cx - i_in;
dy := cy - j_in;
red := 0;
green := 0;
blue := 0;
alpha := 0;
for m := -1 to 2 do
for n := -1 to 2 do
begin
ii := i_in + m;
jj := j_in + n;
if ii < 0 then ii := 0;
if ii >= nx then ii := nx-1;
if jj < 0 then jj := 0;
if jj >= ny then jj := ny-1;
index := jj * nx + ii;
weight := BiCubicR(m-dx) * BiCubicR(n-dy);
// weight := BiCubicR(dx-m) * BiCubicR(dy-n);
with PRGBQuad(index * 4 + Pbm_In)^ do
begin
red := red + weight * rgbRed;
green := green + weight * rgbGreen;
blue := blue + weight * rgbBlue;
alpha := alpha + weight * rgbReserved;
end;
end;
col.rgbRed := Trunc(red);
col.rgbGreen := Trunc(green);
col.rgbBlue := Trunc(blue);
col.rgbReserved := Trunc(alpha);
PRGBQuad((j_out * nnx + i_out) * 4 + Pbm_Out)^ := col;
end;
if Assigned(ProgressCallBack) then
ProgressCallBack;
end;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
// Exporter for the "Laz-Model XML" format
unit uEmxExport;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs,
uIntegrator, uModelEntity, uModel, uFeedback;
type
TEmxExporter = class(TExportIntegrator)
private
Ids : TStringList;
Output : TMemoryStream;
NextId : integer;
Feedback : IEldeanFeedback;
procedure WritePackage(P : TAbstractPackage);
procedure WriteLogicPackage(L : TLogicPackage);
procedure WriteUnitPackage(U : TUnitPackage);
procedure WriteClass(C : TClass);
procedure WriteInterface(I : TInterface);
procedure WriteEntityHeader(E : TModelEntity; const AName : string);
procedure WriteFeatures(C : TClassifier);
procedure WriteDataType(T : TDataType);
function MakeTypeRef(C : TClassifier) : string;
function MakeId(const S : string) : string;
function XmlClose(const S : string) : string;
function XmlOpen(const S : string) : string;
function Xml(const S : string) : string;
procedure Write(const S : string);
public
constructor Create(om: TObjectModel; AFeedback : IEldeanFeedback = nil); reintroduce;
destructor Destroy; override;
procedure InitFromModel; override;
procedure ShowSaveDialog;
procedure SaveTo(const FileName : string);
function GetText : string;
end;
implementation
{ TEmxExporter }
constructor TEmxExporter.Create(om: TObjectModel; AFeedback : IEldeanFeedback = nil);
begin
inherited Create(om);
Output := TMemoryStream.Create;
Ids := TStringList.Create;
Ids.Sorted := True;
Ids.Duplicates := dupIgnore;
NextId := 0;
Self.Feedback := AFeedback;
if Feedback=nil then
Self.Feedback := NilFeedback;
end;
destructor TEmxExporter.Destroy;
begin
FreeAndNil(Output);
FreeAndNil(Ids);
inherited;
end;
procedure TEmxExporter.InitFromModel;
begin
//Write(XmiHeader);
//Write( XmlOpen('Model_Management.Model') );
WritePackage(Model.ModelRoot);
//Write( XmlClose('Model_Management.Model') );
//Write(XmiFooter);
Feedback.Message('Laz-Model xmi export finished.');
end;
function TEmxExporter.MakeId(const S : string): string;
var
I : integer;
begin
I := Ids.IndexOf(S);
if I=-1 then
begin
Inc(NextId);
I := Ids.Add(S);
end;
Result := 'emx_' + IntToStr(I);
end;
procedure TEmxExporter.ShowSaveDialog;
var
D : TSaveDialog;
Dir : string;
begin
D := TSaveDialog.Create(nil);
try
Dir := ExtractFilePath( Model.ModelRoot.GetConfigFile );
D.DefaultExt := 'emx';
D.InitialDir := Dir;
D.Filter := 'Laz-Model xml files (*.emx)|*.emx|All files (*.*)|*.*';
D.Options := D.Options + [ofOverwritePrompt];
if D.Execute then
SaveTo( D.FileName );
finally
D.Free;
end;
end;
procedure TEmxExporter.Write(const S: string);
begin
Output.Write(S[1],Length(S));
Output.Write(#13#10,2);
end;
procedure TEmxExporter.WriteClass(C: TClass);
var
Mi : IModelIterator;
begin
WriteEntityHeader(C, 'Class');
WriteFeatures(C);
if Assigned(C.Ancestor) then
begin
Write( XmlOpen( 'Class.Ancestor') );
// MakeGeneral(C,C.Ancestor);
Write( XmlClose( 'Class.Ancestor') );
end;
//Implements
Mi := C.GetImplements;
if Mi.HasNext then
begin
Write( XmlOpen( 'Class.Implements') );
// while Mi.HasNext do
// MakeAbstract(C, Mi.Next as TClassifier);
Write( XmlClose( 'Class.Implements') );
end;
Mi := C.GetDescendants;
if Mi.HasNext then
begin
Write( XmlOpen( 'Class.Descendant') );
// while Mi.HasNext do
// MakeGeneral( Mi.Next as TClassifier, C);
Write( XmlClose( 'Class.Descendant') );
end;
Write( XmlClose('Class') );
end;
procedure TEmxExporter.WriteFeatures(C: TClassifier);
var
Mi : IModelIterator;
F : TModelEntity;
procedure WriteAttribute(A : TAttribute);
begin
WriteEntityHeader(A, 'Attribute');
if Assigned(A.TypeClassifier) then
begin
Write( XmlOpen('TypeClassifier') );
Write( MakeTypeRef(A.TypeClassifier) );
Write( XmlClose('TypeClassifier') );
end;
Write( XmlClose('Attribute') );
end;
procedure WriteOperation(O : TOperation);
var
Mio : IModelIterator;
P : TParameter;
begin
WriteEntityHeader(O, 'Operation');
Write( XmlOpen('Parameters') );
if Assigned(O.ReturnValue) then
begin
Write( XmlOpen('ReturnParameter') );
Write( '<' + 'Parameter.kind value="return"/>');
Write( MakeTypeRef( O.ReturnValue ) );
Write( XmlClose('ReturnParameter') );
end;
Mio := O.GetParameters;
while Mio.HasNext do
begin
P := Mio.Next as TParameter;
WriteEntityHeader(P, 'Parameter');
if Assigned(P.TypeClassifier) then
begin
Write( XmlOpen('Parameter.type') );
Write( MakeTypeRef(P.TypeClassifier) );
Write( XmlClose('Parameter.type') );
end;
Write( XmlClose('Parameter') );
end;
Write( XmlClose('Parameters') );
Write( XmlClose('Operation') );
end;
begin
Mi := C.GetFeatures;
if Mi.HasNext then
begin
Write( XmlOpen('Feature') );
while Mi.HasNext do
begin
F := Mi.Next;
if F is TAttribute then
WriteAttribute(F as TAttribute)
else if F is TOperation then
WriteOperation(F as TOperation);
end;
Write( XmlClose('Feature') );
end;
end;
procedure TEmxExporter.WriteEntityHeader(E: TModelEntity; const AName: string);
const
VisibilityMap: array[TVisibility] of string = ('private', 'protected', 'public', 'public');
//(viPrivate,viProtected,viPublic,viPublished);
begin
{
<UnitPackage id="emx_17" name="LogWriter" visibility="private">
}
Write( '<' + AName + ' id="' + MakeId(E.FullName) + '" name="' + Xml(E.Name) +
'" visibility="' + VisibilityMap[E.Visibility] + '">' );
end;
procedure TEmxExporter.WritePackage(P: TAbstractPackage);
begin
Feedback.Message('EMX generating package ' + P.Name + '...');
//WriteEntityHeader(P,'Package');
if P is TLogicPackage then
WriteLogicPackage(P as TLogicPackage)
else if P is TUnitPackage then
WriteUnitPackage(P as TUnitPackage);
//Write( XmlClose('Package') );
end;
procedure TEmxExporter.WriteLogicPackage(L: TLogicPackage);
var
Mi : IModelIterator;
begin
WriteEntityHeader(L,'LogicPackage');
Mi := L.GetPackages;
while Mi.HasNext do
WritePackage( Mi.Next as TAbstractPackage );
Write( XmlClose('LogicPackage') );
end;
procedure TEmxExporter.WriteUnitPackage(U: TUnitPackage);
var
Mi : IModelIterator;
C : TModelEntity;
begin
WriteEntityHeader(U,'UnitPackage');
Mi := U.GetClassifiers;
while Mi.HasNext do
begin
C := Mi.Next;
if C is TClass then
WriteClass(C as TClass)
else if C is TInterface then
WriteInterface(C as TInterface)
else if C is TDataType then
WriteDataType(C as TDataType);
end;
Write( XmlClose('UnitPackage') );
end;
function TEmxExporter.XmlClose(const S: string): string;
begin
Result := '</' + S + '>';
end;
function TEmxExporter.XmlOpen(const S: string): string;
begin
Result := '<' + S + '>';
end;
//Writes a reference to a classifier
function TEmxExporter.MakeTypeRef(C: TClassifier) : string;
var
S : string;
begin
if C is TClass then
S := 'Class'
else if C is TDataType then
S := 'DataType'
else if C is TInterface then
S := 'Interface';
Result := '<' + S +' idref="' + MakeId(C.FullName) + '"/>';
end;
//Check that string does not contain xml-chars like < and >
function TEmxExporter.Xml(const S: string): string;
var
I : integer;
begin
Result := S;
for I:=1 to Length(Result) do
case Result[I] of
'<' : Result[I]:='(';
'>' : Result[I]:=')';
end;
end;
procedure TEmxExporter.WriteInterface(I: TInterface);
{
<Foundation.Core.ModelElement.supplierDependency>
<Foundation.Core.Abstraction xmi.idref="xmi.37"/>
</Foundation.Core.ModelElement.supplierDependency>
}
var
Mi : IModelIterator;
begin
WriteEntityHeader(I, 'Interface');
WriteFeatures(I);
//Implementing classes
Mi := I.GetImplementingClasses;
if Mi.HasNext then
begin
Write( XmlOpen( 'Interface.ImplementingClass') );
// while Mi.HasNext do
// MakeAbstract(Mi.Next as TClassifier,I);
Write( XmlClose( 'Interface.ImplementingClass') );
end;
Write( XmlClose('Interface') );
end;
procedure TEmxExporter.WriteDataType(T: TDataType);
begin
WriteEntityHeader(T, 'DataType');
Write( XmlClose('DataType') );
end;
procedure TEmxExporter.SaveTo(const FileName: string);
var
F : TFileStream;
begin
F := TFileStream.Create( FileName ,fmCreate);
try
F.CopyFrom(Output, 0);
finally
F.Free;
end;
end;
//Returns the whole emx-file as a string.
function TEmxExporter.GetText: string;
begin
SetLength(Result,Output.Size);
Move(Output.Memory^,Result[1],Output.Size);
end;
end.
|
unit Glass;
interface
uses
Winapi.Windows,
System.SysUtils, System.Classes, FMX.Types, FMX.Controls,
FMX.Graphics, FMX.Effects;
type
TGlass = class(TControl)
private
FParentScreenshotBitmap: TBitmap;
FParentWidth: Single;
FParentHeight: Single;
FBitmapCRC: Integer;
FCachedBitmap: TBitmap;
FPainted: Boolean;
procedure DefineParentSize;
function IsBitmapSizeChanged(ABitmap: TBitmap;
const ANewWidth, ANewHeight: Single): Boolean;
procedure MakeParentScreenshot;
protected
procedure Paint; override;
procedure ProcessChildEffect(const AParentScreenshotBitmap: TBitmap); virtual; abstract;
public
property Painted: Boolean read FPainted;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Position;
property Width;
property Height;
end;
implementation
uses
FMX.Forms, System.Math, System.Types, IdHashCRC, IdGlobal;
{ TOverlay }
constructor TGlass.Create(AOwner: TComponent);
begin
inherited;
// Create parent background
FParentScreenshotBitmap := TBitmap.Create(0, 0);
FCachedBitmap := TBitmap.Create(0, 0);
end;
destructor TGlass.Destroy;
begin
FParentScreenshotBitmap.Free;
FCachedBitmap.Free;
inherited;
end;
procedure TGlass.DefineParentSize;
begin
FParentWidth := 0;
FParentHeight := 0;
if Parent is TCustomForm then
begin
FParentWidth := (Parent as TCustomForm).ClientWidth;
FParentHeight := (Parent as TCustomForm).ClientHeight;
end;
if Parent is TControl then
begin
FParentWidth := (Parent as TControl).Width;
FParentHeight := (Parent as TControl).Height;
end;
end;
function TGlass.IsBitmapSizeChanged(ABitmap: TBitmap;
const ANewWidth, ANewHeight: Single): Boolean;
begin
Result := not SameValue(ANewWidth * ABitmap.BitmapScale, ABitmap.Width) or
not SameValue(ANewHeight * ABitmap.BitmapScale, ABitmap.Height);
end;
function IsSameBitmap(Bitmap1, Bitmap2: TBitmap): Boolean;
var
Stream1, Stream2: TMemoryStream;
begin
Assert((Bitmap1 <> nil) and (Bitmap2 <> nil), 'Params can''t be nil');
Result:= False;
if (Bitmap1.Height <> Bitmap2.Height) or (Bitmap1.Width <> Bitmap2.Width) then
Exit;
Stream1:= TMemoryStream.Create;
try
Bitmap1.SaveToStream(Stream1);
Stream2:= TMemoryStream.Create;
try
Bitmap2.SaveToStream(Stream2);
if Stream1.Size = Stream2.Size Then
Result:= CompareMem(Stream1.Memory, Stream2.Memory, Stream1.Size);
finally
Stream2.Free;
end;
finally
Stream1.Free;
end;
end;
procedure TGlass.MakeParentScreenshot;
var
Form: TCommonCustomForm;
Child: TFmxObject;
ParentControl: TControl;
begin
if FParentScreenshotBitmap.Canvas.BeginScene then
try
FDisablePaint := True;
if Parent is TCommonCustomForm then
begin
Form := Parent as TCommonCustomForm;
for Child in Form.Children do
if (Child is TControl) and (Child as TControl).Visible then
begin
if not (Child is TGlass) or TGlass(Child).Painted then
begin
ParentControl := Child as TControl;
ParentControl.PaintTo(FParentScreenshotBitmap.Canvas,
ParentControl.ParentedRect);
end;
end;
end
else
(Parent as TControl).PaintTo(FParentScreenshotBitmap.Canvas,
RectF(0, 0, FParentWidth, FParentHeight));
finally
FDisablePaint := False;
FParentScreenshotBitmap.Canvas.EndScene;
end;
end;
function HashBitmap(const ABitmap: TBitmap): Integer;
var
stream: TMemoryStream;
hash: TIdHashCRC32;
begin
stream := nil;
hash := nil;
try
stream := TMemoryStream.Create;
hash := TIdHashCRC32.Create;
ABitmap.SaveToStream(stream);
//Stream.Seek(0, soBeginning);
Result := BytesToLongWord(hash.HashStream(stream, 0, -1));
finally
stream.Free;
hash.Free;
end;
end;
procedure TGlass.Paint;
var
NewCRC: Integer;
begin
inherited;
// Make screenshot of Parent control
DefineParentSize;
if IsBitmapSizeChanged(FParentScreenshotBitmap, FParentWidth, FParentHeight) then
FParentScreenshotBitmap.SetSize(Round(FParentWidth), Round(FParentHeight));
MakeParentScreenshot;
NewCRC := HashBitmap(FParentScreenshotBitmap);
OutputDebugString(Pchar(IntToHex(NewCRC, 8)));
// Apply glass effect
Canvas.BeginScene;
try
if NewCRC <> FBitmapCRC then
begin
ProcessChildEffect(FParentScreenshotBitmap);
FCachedBitmap.Assign(FParentScreenshotBitmap);
end;
Canvas.DrawBitmap(FCachedBitmap, ParentedRect, LocalRect, 1, True);
finally
Canvas.EndScene;
end;
FBitmapCRC := NewCRC;
FPainted := True;
end;
end.
|
unit API_MVC_VCL;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls,
API_MVC;
type
TViewVCLBase = class(TForm, IViewAbstract)
private
{ Private declarations }
FController: TControllerAbstract;
FControllerClass: TControllerClass;
FDoNotFreeAfterClose: Boolean;
FIsMainView: Boolean;
FOnViewMessage: TViewMessageProc;
function GetCloseMessage: string;
procedure FormFree(Sender: TObject; var Action: TCloseAction);
protected
//function AssignPicFromFile(aImage: TImage; const aPath: string): Boolean;
//function AssignPicFromStream(aImage: TImage; var aMIMEType: TMIMEType; const aPictureStream: TStream; aDefType: Boolean = False): Boolean;
/// <summary>
/// Override this procedure for assign FControllerClass in the main Application View(Form).
/// </summary>
procedure InitMVC(var aControllerClass: TControllerClass); virtual;
procedure SendMessage(aMsg: string);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CloseMessage: string read GetCloseMessage;
property OnViewMessage: TViewMessageProc read FOnViewMessage write FOnViewMessage;
end;
TVCLSupport = class(TPlatformSupport)
public
function CreateView<T: TViewVCLBase>(aInstantShow: Boolean = False): T;
end;
TControllerVCLBase = class(TControllerAbstract)
private
FVCL: TVCLSupport;
public
constructor Create; override;
destructor Destroy; override;
property VCL: TVCLSupport read FVCL;
end;
implementation
{$R *.dfm}
//uses
//API_Files,
//Vcl.Imaging.jpeg,
//Vcl.Imaging.pngimage;
{function TViewVCLBase.AssignPicFromStream(aImage: TImage; var aMIMEType: TMIMEType; const aPictureStream: TStream; aDefType: Boolean = False): Boolean;
var
JPEGPicture: TJPEGImage;
PNGPicture: TPNGImage;
begin
Result := False;
if aDefType then
aMIMEType := mtUnknown;
if aDefType or
(aMIMEType = mtJPEG)
then
begin
JPEGPicture := TJPEGImage.Create;
try
try
aPictureStream.Position := 0;
JPEGPicture.LoadFromStream(aPictureStream);
JPEGPicture.DIBNeeded;
aImage.Picture.Assign(JPEGPicture);
aDefType := False;
aMIMEType := mtJPEG;
Result := True;
except
end;
finally
JPEGPicture.Free;
end;
end;
if aDefType or
(aMIMEType = mtPNG)
then
begin
PNGPicture := TPNGImage.Create;
try
try
aPictureStream.Position := 0;
PNGPicture.LoadFromStream(aPictureStream);
aImage.Picture.Assign(PNGPicture);
aDefType := False;
aMIMEType := mtPNG;
Result := True;
except
end;
finally
PNGPicture.Free;
end;
end;
if aDefType or
(aMIMEType = mtBMP)
then
begin
try
aPictureStream.Seek(0, soFromBeginning);
aImage.Picture.Bitmap.LoadFromStream(aPictureStream);
aDefType := False;
aMIMEType := mtBMP;
Result := True;
except
end;
end;
end;
function TViewVCLBase.AssignPicFromFile(aImage: TImage; const aPath: string): Boolean;
var
FileStream: TFileStream;
MIMEType: TMIMEType;
begin
FileStream := TFilesEngine.CreateFileStream(aPath);
try
MIMEType := TFilesEngine.GetMIMEType(aPath);
if MIMEType <> mtUnknown then
Result := AssignPicFromStream(aImage, MIMEType, FileStream);
finally
FileStream.Free;
end;
end; }
function TViewVCLBase.GetCloseMessage: string;
begin
Result := 'On' + Self.Name + 'Closed';
end;
destructor TControllerVCLBase.Destroy;
begin
FVCL.Free;
inherited;
end;
constructor TControllerVCLBase.Create;
begin
inherited;
FVCL := TVCLSupport.Create(Self);
end;
procedure TViewVCLBase.InitMVC(var aControllerClass: TControllerClass);
begin
end;
procedure TViewVCLBase.FormFree(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
SendMessage(CloseMessage);
end;
function TVCLSupport.CreateView<T>(aInstantShow: Boolean = False): T;
begin
Result := T.Create(nil);
Result.OnViewMessage := FController.ViewListener;
if aInstantShow then
Result.Show;
end;
destructor TViewVCLBase.Destroy;
begin
SendMessage(Self.Name + 'Closed');
if FIsMainView then
FController.Free;
inherited;
end;
constructor TViewVCLBase.Create(AOwner: TComponent);
begin
inherited;
InitMVC(FControllerClass);
if Assigned(FControllerClass) and not Assigned(FController) then
begin
FIsMainView := True;
FController := FControllerClass.Create;
FOnViewMessage := FController.ViewListener;
end;
if not FDoNotFreeAfterClose then
OnClose := FormFree;
end;
procedure TViewVCLBase.SendMessage(aMsg: string);
begin
FOnViewMessage(aMsg);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Utils.XML;
interface
uses
DPM.Core.MSXML;
type
TXMLUtils = class
//we are using this to preserve the formatting of the dproj file.
class procedure PrettyFormatXML(const node : IXMLDOMNode; const indentSize : integer);
end;
implementation
procedure DoPrettyFormatXML(const node : IXMLDOMNode; const indentSize : integer; var indentLen : integer);
const
CRLF = #13#10;
TAB = #9;
var
i : integer;
newnode : IXMLDOMNode;
childNode : IXMLDOMNode;
siblingNode : IXMLDOMNode;
stmp : string;
sDebug : string;
function SpaceString(stringLen : integer) : string;
begin
result := StringOfChar(' ', stringLen);
end;
function hasChildElements(const anode : IXMLDOMNode) : boolean;
var
j : integer;
cnode : IXMLDOMNode;
begin
result := False;
for j := 0 to anode.childNodes.length - 1 do
begin
cnode := anode.childNodes.item[j];
if (cnode.nodeType = NODE_ELEMENT) or (cnode.nodeType = NODE_CDATA_SECTION) then
begin
result := True;
break;
end;
end;
end;
function GetNextElement(const anode : IXMLDOMNode) : IXMLDOMNode;
begin
result := anode.nextSibling;
while result <> nil do
begin
if result.nodeType = NODE_ELEMENT then
break;
result := result.nextSibling;
end;
end;
begin
if node.nodeType = NODE_TEXT then
exit;
if node.childNodes.length > 0 then
begin
sDebug := node.nodeName;
if hasChildElements(node) then
begin
Inc(indentLen, indentSize);
i := 0;
while i < node.childNodes.length do
begin
childNode := node.childNodes.item[i];
sDebug := childNode.nodeName;
case childNode.nodeType of //
NODE_ELEMENT, NODE_CDATA_SECTION :
begin
stmp := CRLF + SpaceString(indentLen);
newnode := node.ownerDocument.createTextNode(stmp);
node.insertBefore(newnode, childNode);
if hasChildElements(childNode) then
DoPrettyFormatXML(childNode, indentSize, indentLen);
siblingNode := GetNextElement(childNode);
stmp := CRLF + SpaceString(indentLen);
newnode := node.ownerDocument.createTextNode(stmp);
if siblingNode <> nil then
node.insertBefore(newnode, siblingNode);
Inc(i);
end;
NODE_TEXT :
begin
// remove any old formatting nodes.
node.removeChild(childNode);
continue;
end
end;
Inc(i);
end;
Dec(indentLen, indentSize);
stmp := CRLF + SpaceString(indentLen);
newnode := node.ownerDocument.createTextNode(stmp);
node.appendChild(newnode);
end;
end;
end;
class procedure TXMLUtils.PrettyFormatXML(const node : IXMLDOMNode; const indentSize : integer);
var
indentLen : integer;
begin
indentLen := 0;
DoPrettyFormatXML(node, indentSize, indentLen);
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fHistory;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ImgList, ActnList, ComCtrls, uMultiLanguage, TB2MRU,
Registry, uCommon, uCommonClass, TB2Item, SpTBXItem, TB2Dock, TB2Toolbar;
type
TfmHistory = class(TForm)
lv: TListView;
acHistory: TActionList;
acRemove: TAction;
acOpen: TAction;
acShowPath: TAction;
acRemoveAll: TAction;
TBXDock1: TSpTBXDock;
TBXToolbar1: TSpTBXToolbar;
TBItemContainer1: TTBItemContainer;
TBXSubmenuItem1: TSpTBXSubmenuItem;
TBXItem3: TSpTBXItem;
TBXItem2: TSpTBXItem;
TBXItem1: TSpTBXItem;
TBXSeparatorItem1: TSpTBXSeparatorItem;
TBXItem4: TSpTBXItem;
TBXPopupMenu1: TSpTBXPopupMenu;
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure acHistoryUpdate(Action: TBasicAction; var Handled: Boolean);
procedure acOpenExecute(Sender: TObject);
procedure acRemoveExecute(Sender: TObject);
procedure acShowPathExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure acRemoveAllExecute(Sender: TObject);
procedure lvStartDrag(Sender: TObject; var DragObject: TDragObject);
private
FPathVisible: boolean;
FLockUpdate: boolean;
FFilesMRU: TTBMRUList;
procedure SetPathVisible(const Value: boolean);
procedure SetLockUpdate(const Value: boolean);
procedure ClearList;
procedure SetFilesMRU(const Value: TStrings);
procedure LoadConfig;
procedure SaveConfig;
public
procedure UpdateList;
property FilesMRU: TStrings write SetFilesMRU;
property LockUpdate: boolean read FLockUpdate write SetLockUpdate;
property PathVisible: boolean read FPathVisible write SetPathVisible;
end;
implementation
{$R *.DFM}
uses
fFilePane, fMain;
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHistory.SetFilesMRU(const Value: TStrings);
begin
FFilesMRU.Items := value;
UpdateList;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.SetPathVisible(const Value: boolean);
var
i: integer;
rec: TFileData;
begin
if (FPathVisible <> Value) then
begin
FPathVisible := Value;
lv.Items.BeginUpdate;
try
for i := 0 to lv.Items.Count - 1 do
begin
rec := TFileData(lv.Items[i].Data);
if Value then
lv.Items[i].Caption := rec.FileName
else
lv.Items[i].Caption := ExtractFileName(rec.FileName);
end;
finally
lv.Items.EndUpdate;
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.SetLockUpdate(const Value: boolean);
begin
if (FLockUpdate <> Value) then
begin
FLockUpdate := Value;
if not Value then
UpdateList;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHistory.ClearList;
var
i: integer;
begin
lv.Items.BeginUpdate;
try
lv.Items.Clear;
for i := 0 to lv.Items.Count - 1 do
if Assigned(lv.Items[i].Data) then
TFileData(lv.Items[i].Data).Free;
finally
lv.Items.EndUpdate;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.UpdateList;
var
SelectedFile: string;
rec: TFileData;
i: integer;
Item: TListItem;
begin
if LockUpdate then
EXIT;
if Assigned(lv.Selected) then
SelectedFile := UpperCase(TFileData(lv.Selected.Data).FileName)
else
SelectedFile := '';
lv.Items.BeginUpdate;
ClearList;
for i := 0 to FFilesMRU.Items.Count - 1 do
begin
rec := TFileData.Create(FFilesMRU.Items[i]);
Item := lv.Items.Add;
with Item do
begin
if PathVisible then
Caption := rec.FileName
else
Caption := ExtractFileName(rec.FileName);
ImageIndex := rec.IconIndex;
Data := rec;
end;
if (UpperCase(rec.FileName) = SelectedFile) then
lv.Selected := Item;
end;
lv.Items.EndUpdate;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.LoadConfig;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
with reg do
begin
OpenKey(CONTEXT_REG_KEY + 'FileHistory', TRUE);
PathVisible := ReadRegistryBool(reg, 'ShowPath', TRUE);
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.SaveConfig;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
with reg do
begin
OpenKey(CONTEXT_REG_KEY + 'FileHistory', TRUE);
WriteBool('ShowPath', PathVisible);
Free;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHistory.acHistoryUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
acOpen.Enabled := Assigned(lv.Selected);
acRemove.Enabled := Assigned(lv.Selected);
acRemoveAll.Enabled := lv.Items.Count > 0;
acShowPath.Checked := fPathVisible;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.acOpenExecute(Sender: TObject);
var
i: integer;
str: TStringList;
rec: TFileData;
begin
str := TStringList.Create;
try
for i := 0 to lv.Items.Count - 1 do
if (lv.Items[i].Selected) then
begin
rec := TFileData(lv.Items[i].Data);
if Assigned(rec) then
str.Add(rec.FileName);
end;
fmMain.OpenMultipleFiles(str);
finally
str.Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.acRemoveExecute(Sender: TObject);
var
i: integer;
begin
for i := 0 to lv.Items.Count - 1 do
if lv.Items[i].Selected then
FFilesMRU.Remove(TFileData(lv.Items[i].Data).FileName);
UpdateList;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.acRemoveAllExecute(Sender: TObject);
var
i: integer;
begin
for i := 0 to lv.Items.Count - 1 do
FFilesMRU.Remove(TFileData(lv.Items[i].Data).FileName);
ClearList;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.acShowPathExecute(Sender: TObject);
begin
PathVisible := not PathVisible;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// lv events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHistory.lvStartDrag(Sender: TObject;
var DragObject: TDragObject);
var
str: TStringList;
rec: TFileData;
i: integer;
begin
with lv do
begin
if (SelCount > 1) then
DragCursor := crMultiDrag
else
DragCursor := crDrag;
end;
str := TStringList.Create;
for i := 0 to lv.Items.Count - 1 do
if lv.Items[i].Selected then
begin
rec := TFileData(lv.Items[i].Data);
if not rec.IsDirectory then
str.Add(rec.FileName);
end;
TFilePanelDragFiles.Create(fmMain.FilePanel, lv, str);
str.Free;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHistory.FormCreate(Sender: TObject);
begin
lv.SmallImages := fmMain.FileIconPool.ImageList;
LoadConfig;
acOpen.Hint := mlStr(ML_EXPL_HINT_OPEN, 'Open selected files');
acRemove.Hint := mlStr(ML_EXPL_HINT_REMOVE,
'Remove selected files from list');
acRemoveAll.Hint := mlStr(ML_EXPL_HINT_REMOVE_ALL,
'Remove all files from list');
acShowPath.Hint := mlStr(ML_EXPL_HINT_TOGGLEPATH, 'Toggle show/hide path');
acOpen.Caption := mlStr(ML_FAV_OPEN, '&Open');
acRemove.Caption := mlStr(ML_FAV_REMOVE, '&Remove');
acRemoveAll.Caption := mlStr(ML_FAV_REMOVE_ALL, 'Remove A&ll');
acShowPath.Caption := mlStr(ML_FAV_SHOW_PATH, '&Show Path');
FFilesMRU := TTBMRUList.Create(self);
FFilesMRU.MaxItems := 99; // will only be loaded with maxitems from main screen
FFilesMRU.AddFullPath := true;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.FormActivate(Sender: TObject);
begin
acHistory.State := asNormal;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.FormDeactivate(Sender: TObject);
begin
acHistory.State := asSuspended;
end;
//------------------------------------------------------------------------------------------
procedure TfmHistory.FormDestroy(Sender: TObject);
begin
SaveConfig;
ClearList;
end;
//------------------------------------------------------------------------------------------
end.
|
//------------------------------------------------------------------------------
//LoginServer UNIT
//------------------------------------------------------------------------------
// What it does-
// The Login Server Class.
// An object type that contains all information about a login server
// This unit is to help for future design of multi server communication IF
// the user were to want to do so. Else, it would act as an all-in-one.
// Only one type in this unit for the time being.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength
// in various calls
//
//------------------------------------------------------------------------------
unit LoginServer;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IdContext,
PacketTypes,
List32,
SysUtils,
Account,
Server,
LoginOptions;
type
//------------------------------------------------------------------------------
//TLoginServer CLASS
//------------------------------------------------------------------------------
TLoginServer = class(TServer)
protected
fCharaServerList : TIntList32;
fAccountList : TIntList32;
Procedure OnConnect(AConnection: TIdContext);override;
Procedure OnDisconnect(AConnection: TIdContext); override;
Procedure OnExecute(AConnection: TIdContext);override;
Procedure OnException(AConnection: TIdContext;
AException: Exception);override;
Procedure LoadOptions;
Procedure SendLoginError(var AClient: TIdContext; const Error : byte; const Error_Message : String='');
procedure SendDCError(var AClient: TIdContext; const Error : byte);
Procedure SendCharacterServers(AnAccount : TAccount; AClient: TIdContext);
Procedure ParseMF(AClient : TIdContext; var Username : string; Password : string);
Procedure ValidateLogin(
AClient: TIdContext;
InBuffer : TBuffer;
Username : String;
Password : String
);
procedure VerifyCharaServer(
AClient: TIdContext;
InBuffer : TBuffer;
Password : String
);
procedure UpdateToAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
procedure RemoveFromAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
public
Options : TLoginOptions;
Constructor Create();
Destructor Destroy();override;
Procedure Start();override;
Procedure Stop();override;
end;
//------------------------------------------------------------------------------
implementation
uses
//Delphi
StrUtils,
//Helios
BufferIO,
CharaLoginCommunication,
CharacterServerInfo,
Globals,
LoginAccountInfo,
Main,
TCPServerRoutines
;
//Subclasses the TThreadlink, designed to store a MD5 Key to for use
//with MD5 client connections
type TLoginThreadLink = class(TThreadLink)
MD5Key : string;
end;
const
//ERROR REPLY CONSTANTS
LOGIN_UNREGISTERED = 0;
LOGIN_INVALIDPASSWORD = 1;
LOGIN_TIMEUP = 2;
LOGIN_REJECTED = 3;
LOGIN_BANNED = 4;
LOGIN_TEMPORARYBAN = 6;
//LOGIN_SERVERFULL = ;
//------------------------------------------------------------------------------
//Create() CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Initializes our Login Server
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Constructor TLoginServer.Create();
begin
Inherited;
fCharaServerList := TIntList32.Create;
fAccountList := TIntList32.Create;
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy() DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Destroys our Login Server
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Destructor TLoginServer.Destroy();
begin
fCharaServerList.Free;
fAccountList.Free;
Inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Start() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Enables the login server to accept incoming connections
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TLoginServer.Start();
begin
if NOT Started then
begin
inherited;
LoadOptions;
Port := Options.Port;
ActivateServer('Login',TCPServer, Options.IndySchedulerType, Options.IndyThreadPoolSize);
end else
begin
Console.Message('Cannot start():: Login server is already running.', 'Login Server', MS_ALERT);
end;
end;{Start}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Stop() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Stops the login server from accepting incoming connections
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
// May 1st, 2007 - Tsusai - Reversed the free'ing for loop to go backwards.
//
//------------------------------------------------------------------------------
Procedure TLoginServer.Stop();
var
Index : Integer;
begin
if Started then
begin
DeActivateServer('Login', TCPServer);
//Free up our existing server info objects
for Index := fCharaServerList.Count - 1 downto 0 do
begin
fCharaServerList.Objects[Index].Free;
fCharaServerList.Delete(Index);
end;
Options.Save;
Options.Free;
inherited;
end else
begin
Console.Message('Cannot Stop():: Login server is not running.', 'Login Server', MS_ALERT);
end;
end;{Start}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnConnect() EVENT
//------------------------------------------------------------------------------
// What it does-
// Event which is fired when a user attempts to connect to the login
// server. It writes information about the connection to the console.
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
// December 26th, 2007 - Tsusai - Resets the MD5 key on TLoginThreadLink just
// incase
//
//------------------------------------------------------------------------------
procedure TLoginServer.OnConnect(AConnection: TIdContext);
begin
AConnection.Data := TLoginThreadLink.Create(AConnection);
TLoginThreadLink(AConnection.Data).DatabaseLink := Database;
TLoginThreadLink(AConnection.Data).MD5Key := ''; //blank just incase.
//Console.Message('Connection from ' + AConnection.Connection.Socket.Binding.PeerIP. 'Login Server', MS_INFO);
end;{LoginServerConnect}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnDisconnect() EVENT
//------------------------------------------------------------------------------
// What it does-
// Executes when a client disconnects from the login server. Removes
// disconnected character servers from the list.
//
// Changes -
// January 4th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TLoginServer.OnDisconnect(AConnection: TIdContext);
var
idx : integer;
ACharaServInfo : TCharaServerInfo;
begin
if AConnection.Data is TCharaServerLink then
begin
ACharaServInfo := TCharaServerLink(AConnection.Data).Info;
idx := fCharaServerList.IndexOfObject(ACharaServInfo);
if not (idx = -1) then
begin
fCharaServerList.Delete(idx);
end;
end;
AConnection.Data.Free;
AConnection.Data:=nil;
end;{OnDisconnect}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnException EVENT
//------------------------------------------------------------------------------
// What it does-
// Handles Socket exceptions gracefully by outputting the exception message
// and then disconnecting the client.
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginServer.OnException(AConnection: TIdContext;
AException: Exception);
begin
if AnsiContainsStr(AException.Message, '10053') or
AnsiContainsStr(AException.Message, '10054')
then begin
AConnection.Connection.Disconnect;
end;
end;{OnException}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SendLoginError PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// If some detail was wrong with login, this sends the reply with the
// constant Error number (look at constants) to the client.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginServer.SendLoginError(var AClient: TIdContext; const Error : byte; const Error_Message : String='');
var
Buffer : TBuffer;
begin
WriteBufferWord( 0, $006a, Buffer);
WriteBufferByte( 2, Error, Buffer);
WriteBufferString(3, Error_Message, 20, Buffer);
SendBuffer(AClient, Buffer,PacketDB.GetLength($006a));
end; // proc SendLoginError
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SendDCError PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Send connection error code to client
//
// Changes -
// April 11th, 2007 - Aeomin - Created header
//
//------------------------------------------------------------------------------
procedure TLoginServer.SendDCError(var AClient: TIdContext; const Error : byte);
var
Buffer : TBuffer;
begin
WriteBufferWord( 0, $0081, Buffer);
WriteBufferByte( 2, Error, Buffer);
SendBuffer(AClient, Buffer ,PacketDB.GetLength($0081));
end; // proc SendDCError
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SendCharacterServers PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Upon successful authentication, this procedure sends the list of
// character servers to the client.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// January 20th, 2007 - Tsusai - Wrapped the console messages, now using
// IdContext.Binding shortcut.
// April 11th, 2007 - Aeomin - Changed packet 0x0081 to SendDcError
//
//------------------------------------------------------------------------------
procedure TLoginServer.SendCharacterServers(AnAccount : TAccount; AClient: TIdContext);
var
Buffer : TBuffer;
Index : integer;
Size : Word;
begin
//Packet Format...
//R 0069 <len>.w <login ID1>.l <account ID>.l <login ID2>.l ?.32B <sex>.B (47 total)
//{<IP>.l <port>.w <server name>.20B <login users>.w <maintenance>.w <new>.w}.32B*
if fCharaServerList.Count > 0 then
begin
Size := 47 + (fCharaServerList.Count * 32);
WriteBufferWord(0,$0069,Buffer);
WriteBufferWord(2,Size,Buffer);
WriteBufferLongWord(4,AnAccount.LoginKey[1],Buffer);
WriteBufferLongWord(8,AnAccount.ID,Buffer);
WriteBufferLongWord(12,AnAccount.LoginKey[2],Buffer);
WriteBufferLongWord(16, 0, Buffer);
WriteBufferString(20, FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz'#0, AnAccount.LastLoginTime), 24, Buffer);
WriteBufferWord(44, 0, Buffer);
WriteBufferByte(46,AnAccount.GenderNum,Buffer);
for Index := 0 to fCharaServerList.Count - 1 do begin
WriteBufferLongWord(
47+(index*32)+0,
TCharaServerInfo(fCharaServerList.Objects[Index]).Address(
AClient.Binding.PeerIP
),
Buffer
);
WriteBufferWord(47+(index*32)+4,TCharaServerInfo(fCharaServerList.Objects[Index]).Port,Buffer);
WriteBufferString(47+(index*32)+6,TCharaServerInfo(fCharaServerList.Objects[Index]).ServerName,20,Buffer);
WriteBufferWord(47+(index*32)+26,TCharaServerInfo(fCharaServerList.Objects[Index]).OnlineUsers,Buffer);
WriteBufferWord(47+(index*32)+28,0,Buffer);
WriteBufferWord(47+(index*32)+30,0,Buffer);
end;
SendBuffer(AClient, Buffer, Size);
end else
begin
SendDcError(AClient, 1); //01 Server Closed
end;
end; // Proc SendCharacterServers
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//ParseMF() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Parses a client's login for _M/_F registration.
//
// Changes -
// January 4th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginServer.ParseMF(AClient : TIdContext; var Username : string; Password : string);
var
GenderStr : string;
AnAccount : TAccount;
begin
GenderStr := Uppercase(RightStr(Username,2)); {get _M or _F and cap it}
if (GenderStr = '_M') or
(GenderStr = '_F') then
begin
//Trim the MF off because people forget to take it off.
Username := LeftStr(Username,Length(Username)-2);
AnAccount := TAccount.Create(AClient);
try
AnAccount.Name := UserName;
AnAccount.Password := Password;
AnAccount.Gender := GenderStr[2];
//Check to see if the account already exists.
if NOT TLoginThreadLink(AClient.Data).DatabaseLink.Account.Exists(AnAccount) then
begin
AnAccount.StorageID := TLoginThreadLink(AClient.Data).DatabaseLink.Character.CreateStorage;
//Create the account.
TLoginThreadLink(AClient.Data).DatabaseLink.Account.New(
AnAccount
);
end;
finally
AnAccount.Free;
end;
end;
end;{ParseMF}
//----------------------------------------------------------------------------
//------------------------------------------------------------------------------
//ValidateLogin PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Checks a clients authentication information against the database. On
// authentication success, it sends the client a list of character servers.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// January 3rd, 2007 - Tsusai - Added console messages.
// January 20th, 2007 - Tsusai - Wrapped the console messages, now using
// IdContext.Binding shortcut
// December 26th, 2007 - Tsusai - Fixed up MD5 client checking.
//
//------------------------------------------------------------------------------
procedure TLoginServer.ValidateLogin(
AClient: TIdContext;
InBuffer : TBuffer;
Username : String;
Password : String
);
var
AnAccount : TAccount;
AccountPassword : string;
MD5Key : string;
Idx : Integer;
CharSrvIdx: Integer;
AccountInfo : TLoginAccountInfo;
begin
Console.Message(
'RO Client connection from ' +
AClient.Binding.PeerIP, 'Login Server', MS_NOTICE
);
MD5Key := '';
if (TLoginThreadLink(AClient.Data).MD5Key <> '') then
begin
MD5Key := TLoginThreadLink(AClient.Data).MD5Key;
end;
//If MF enabled, and NO MD5KEY LOGIN, parse _M/_F
if Options.EnableMF and
(MD5Key = '') then
begin
ParseMF(AClient, Username, Password);
end;
AnAccount := TAccount.Create(AClient);
AnAccount.Name := UserName;
TLoginThreadLink(AClient.Data).DatabaseLink.Account.Load(AnAccount);
if AnAccount.ID > 0 then
begin
AccountPassword := AnAccount.Password;
if ( not (MD5Key = '') and //If key isn't blank AND if one of the combinations
( (Password = GetMD5(MD5Key + AccountPassword)) or
(Password = GetMD5(AccountPassword+ MD5Key))
)
) or //or plain text to text compare
(AccountPassword = Password) then
begin
// if not AnAccount.IsBanned then
if AnAccount.State = 0 then
begin
if AnAccount.BannedUntil <= Now then
begin
if not AnAccount.GameTimeUp then
begin
Idx := fAccountList.IndexOf(AnAccount.ID);
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[idx] as TLoginAccountInfo;
if AccountInfo.OnCharSrvList then
begin
fAccountList.Delete(Idx);
SendDcError(AClient, 8); //Server still recognizes your last login
end else
begin
if AccountInfo.UnderKickQuery then
begin
SendDcError(AClient, 8); //Server still recognizes your last login
end else
begin
CharSrvIdx := fCharaServerList.IndexOf(AccountInfo.CharServerID);
if CharSrvIdx > -1 then
begin
AccountInfo.UnderKickQuery := True;
SendKickAccountChara(TCharaServerInfo(fCharaServerList.Objects[CharSrvIdx]).Connection, AnAccount.ID);
SendDcError(AClient, 8); //Server still recognizes your last login
end else
begin
SendLoginError(AClient, LOGIN_REJECTED);
end;
end;
end;
end else
begin
AnAccount.LoginKey[1] := Random($7FFFFFFF) + 1;
AnAccount.LoginKey[2] := Random($7FFFFFFF) + 1;
AnAccount.LastIP := AClient.Binding.PeerIP;
AnAccount.LastLoginTime := Now;
Inc(AnAccount.LoginCount);
TLoginThreadLink(AClient.Data).DatabaseLink.Account.Save(AnAccount);
AccountInfo := TLoginAccountInfo.Create(AnAccount.ID);
AccountInfo.OnCharSrvList := True;
fAccountList.AddObject(AnAccount.ID,AccountInfo);
SendCharacterServers(AnAccount,AClient);
end;
end else
begin
SendLoginError(AClient,LOGIN_TIMEUP);
end;
end else
begin
SendLoginError(AClient, LOGIN_TEMPORARYBAN, AnAccount.GetBanUntilTimeString);
end;
end else
begin
SendLoginError(AClient, AnAccount.State-1);
end;
end else
begin
SendLoginError(AClient,LOGIN_INVALIDPASSWORD);
end;
end else
begin
SendLoginError(AClient,LOGIN_UNREGISTERED);
end;
AnAccount.Free;
end;//ValidateLogin
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//VerifyCharaServer() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Makes sure a character server is allowed to be added to the character
// server list by verifying it's password.
//
// Changes -
// January 3rd, 2007 - Tsusai - Added console messages.
// January 4th, 2007 - RaX - Created Header. Tsusai lazy =)
// January 14th, 2007 - Tsusai - Updated error response
// January 20th, 2007 - Tsusai - Wrapped the console messages, now using
// IdContext.Binding shortcut
//
//------------------------------------------------------------------------------
procedure TLoginServer.VerifyCharaServer(
AClient: TIdContext;
InBuffer : TBuffer;
Password : String
);
var
Servername : String;
Port : word;
CServerInfo : TCharaServerInfo;
ID : LongWord;
Validated : byte;
begin
Console.Message(
'Reading Character Server connection from ' +
AClient.Binding.PeerIP, 'Login Server', MS_NOTICE
);
Validated := 0; //Assume true
ID := BufferReadLongWord(2,InBuffer);
if (fCharaServerList.IndexOf(ID) > -1) then
begin
Console.Message('Character Server failed verification. ID already in use.', 'Login Server', MS_WARNING);
Validated := 1;
end;
if Password <> GetMD5(Options.Key) then
begin
Console.Message('Character Server failed verification: Invalid Security Key.',
'Login Server',
MS_INFO);
Validated := 2;
end;
if Validated = 0 then
begin
Console.Message('Character Server connection validated.', 'Login Server', MS_INFO);
Servername := BufferReadString(22, 24, InBuffer);
Port := BufferReadWord(46, InBuffer);
CServerInfo := TCharaServerInfo.Create;
CServerInfo.ServerID := ID;
CServerInfo.ServerName := ServerName;
CServerInfo.Port := Port;
CServerInfo.Connection := AClient;
AClient.Data := TCharaServerLink.Create(AClient);
TCharaServerLink(AClient.Data).DatabaseLink := Database;
TCharaServerLink(AClient.Data).Info := CServerInfo;
fCharaServerList.AddObject(ID, CServerInfo);
end;
SendValidateFlagToChara(AClient,Validated);
end;{VerifyCharaServer}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//UpdateToAccountList PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Parse the data send by Char server.
// Update account's data in account list
//
// Changes -
// April 12th, 2007 - Aeomin - header created
//
//------------------------------------------------------------------------------
procedure TLoginServer.UpdateToAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
var
AccountID: LongWord;
Idx : Integer;
AccountInfo : TLoginAccountInfo;
begin
AccountID := BufferReadLongWord(2, InBuffer);
Idx := fAccountList.IndexOf(AccountID);
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[Idx] as TLoginAccountInfo;
AccountInfo.CharServerID := BufferReadLongWord(6, InBuffer);
AccountInfo.OnCharSrvList := False;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//RemoveFromAccountList PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Parse the data send by Char server.
// Remove account from account list (Logged off)
//
// Changes -
// April 12th, 2007 - Aeomin - header created
// April 12th, 2007 - Aeomin - Reset login keys to 0 after DC
// May 1st, 2007 - Tsusai - Commented out the key reset. Causes issues with
// multiexe zone usage.
//
//------------------------------------------------------------------------------
procedure TLoginServer.RemoveFromAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
var
AccountID : LongWord;
Idx : Integer;
AnAccount : TAccount;
begin
AccountID := BufferReadLongWord(2, InBuffer);
Idx := fAccountList.IndexOf(AccountID);
if Idx > -1 then
begin
AnAccount := TAccount.Create(AClient);
AnAccount.ID := AccountID;
TLoginThreadLink(AClient.Data).DatabaseLink.Account.Load(AnAccount);
if Assigned(AnAccount) then begin
fAccountList.Delete(Idx);
TLoginThreadLink(AClient.Data).DatabaseLink.Account.Save(AnAccount);
end;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//ParseLogin PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Accepts incoming connections to the Login server and verifies the login
// data.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// January 3rd, 2007 - Tsusai - Added console messages.
// April 10th, 2007 - Aeomin - Changed index from 2 to 6 to support Char server ID.
// December 26th, 2007 - Tsusai - Fixed up MD5 client preping.
//
//------------------------------------------------------------------------------
procedure TLoginServer.OnExecute(AConnection: TIdContext);
var
Buffer : TBuffer;
UserName : String;
Password : String;
ID : Word;
MD5Len : Integer;
MD5Key : String;
Size : Word;
begin
//Get ID
RecvBuffer(AConnection,Buffer,2);
ID := BufferReadWord(0,Buffer);
Case ID of
$0064: //Basic login
begin
//Read the rest of the packet
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($0064)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadString(30,24,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$01DB: //Client connected asking for md5 key to send a secure password
begin
MD5Key := MakeRNDString( Random(10)+1 );
MD5Len := Length(MD5Key);
TLoginThreadLink(AConnection.Data).MD5Key := MD5Key;
WriteBufferWord(0,$01DC,Buffer);
WriteBufferWord(2,MD5Len+4,Buffer);
WriteBufferString(4,MD5Key,MD5Len,Buffer);
SendBuffer(AConnection,Buffer,MD5Len+4);
end;
$01DD: //Recieve secure login details
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($01DD)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadMD5(30,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$01fa: //Another MD5 based login
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($01fa)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadMD5(30,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$027c: //Yet another one
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($027c)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadMD5(30,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$0277:// New login packet (kRO 2006-04-24aSakexe langtype 0)
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($0277,6)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadString(30,24,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$02b0:// New login packet (kRO 2007-05-14aSakexe langtype 0)
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($02b0,8)-2);
UserName := BufferReadString(6,24,Buffer);
Password := BufferReadString(30,24,Buffer);
ValidateLogin(AConnection,Buffer,Username,Password);
end;
$0200: //Account name?
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($0200)-2);
end;
$0204://Receive MD5 of client...
begin
// Do nothing...
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($0204)-2);
end;
$2000:
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($2000)-2);
Password := BufferReadMD5(6,Buffer);
VerifyCharaServer(AConnection,Buffer,Password);
end;
$2002:
begin
if AConnection.Data is TCharaServerLink then
begin
RecvBuffer(AConnection,Buffer[2],2);
Size := BufferReadWord(2,Buffer);
RecvBuffer(AConnection,Buffer[4],Size-4);
TCharaServerLink(AConnection.Data).Info.WAN := BufferReadString(4,Size-4,Buffer);
Console.Message('Received updated Character Server WANIP.', 'Login Server', MS_NOTICE);
end;
end;
$2003:
begin
if AConnection.Data is TCharaServerLink then
begin
RecvBuffer(AConnection,Buffer[2],2);
Size := BufferReadWord(2,Buffer);
RecvBuffer(AConnection,Buffer[4],Size-4);
TCharaServerLink(AConnection.Data).Info.LAN := BufferReadString(4,Size-4,Buffer);
Console.Message('Received updated Character Server LANIP.', 'Login Server', MS_NOTICE);
end;
end;
$2004:
begin
if AConnection.Data is TCharaServerLink then
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($2004)-2);
TCharaServerLink(AConnection.Data).Info.OnlineUsers := BufferReadWord(2,Buffer);
Console.Message('Received updated Character Server Online Users.', 'Login Server', MS_DEBUG);
end;
end;
$2005:
begin
if AConnection.Data is TCharaServerLink then
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($2005)-2);
UpdateToAccountList(AConnection,Buffer);
end;
end;
$2006:
begin
if AConnection.Data is TCharaServerLink then
begin
RecvBuffer(AConnection,Buffer[2],PacketDB.GetLength($2006)-2);
RemoveFromAccountList(AConnection,Buffer);
end;
end;
else
begin
Console.Message('Unknown Login Packet : ' + IntToHex(ID,4), 'Login Server', MS_WARNING);
end;
end;
end; // Proc SendCharacterServers
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadOptions PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Creates and Loads the inifile.
//
// Changes -
// January 4th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TLoginServer.LoadOptions;
begin
Options := TLoginOptions.Create(MainProc.Options.ConfigDirectory+'/Login.ini');
Options.Load;
Options.Save;
end;{LoadOptions}
//------------------------------------------------------------------------------
end.
|
program MultiLogger;
{$IFDEF MSWINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
{$MODE DELPHI}
{$R *.res}
uses
{$IFDEF UNIX}
CThreads,
{$ENDIF}
Classes,
SysUtils,
Quick.Console,
Quick.Logger,
Quick.Logger.Provider.Console,
Quick.Logger.Provider.Files,
Quick.Logger.Provider.Email,
Quick.Logger.Provider.Events,
Quick.Logger.Provider.Rest,
Quick.Logger.Provider.Redis,
{$IFDEF MSWINDOWS}
Quick.Logger.Provider.IDEDebug,
Quick.Logger.Provider.EventLog,
{$ENDIF}
Quick.Logger.Provider.Memory,
Quick.Logger.Provider.Telegram,
Quick.Logger.Provider.Slack,
Quick.Logger.UnhandledExceptionHook,
Quick.Logger.Provider.InfluxDB,
Quick.Logger.Provider.Logstash,
Quick.Logger.Provider.ElasticSearch,
Quick.Logger.Provider.GrayLog,
Quick.Logger.Provider.Sentry,
Quick.Logger.Provider.Twilio;
var
a : Integer;
procedure Test;
var
x : Integer;
threadnum : Integer;
begin
Inc(a);
threadnum := a;
Sleep(Random(50));
for x := 1 to 10000 do
begin
Log('Thread %d - Item %d (%s)',[threadnum,x,DateTimeToStr(Now,GlobalLogConsoleProvider.FormatSettings)],etWarning);
end;
Log('Thread %d - (Finished) (%s)',[threadnum,DateTimeToStr(Now,GlobalLogConsoleProvider.FormatSettings)],etWarning);
end;
procedure MultiThreadWriteTest;
var
i : Integer;
begin
a := 0;
for i := 1 to 30 do
begin
Log('Launch Thread %d',[i],etInfo);
TThread.CreateAnonymousThread(Test).Start;
end;
Sleep(1000);
Log('Process finished. Press <Enter> to Exit',etInfo);
end;
type
TMyEvent = class
procedure Critical(logItem : TLogItem);
end;
procedure TMyEvent.Critical(logItem : TLogItem);
begin
Writeln(Format('OnCritical Event received: %s',[logitem.Msg]));
end;
begin
//wait for 60 seconds to flush pending logs in queue on program finishes
Logger.WaitForFlushBeforeExit := 60;
//configure Console Log provider
Logger.Providers.Add(GlobalLogConsoleProvider);
with GlobalLogConsoleProvider do
begin
LogLevel := LOG_ALL;
ShowEventColors := True;
ShowTimeStamp := True;
TimePrecission := True;
Enabled := True;
end;
//configure File log provider
Logger.Providers.Add(GlobalLogFileProvider);
with GlobalLogFileProvider do
begin
FileName := './LoggerDemo.log';
LogLevel := LOG_ALL;
TimePrecission := True;
MaxRotateFiles := 3;
MaxFileSizeInMB := 5;
RotatedFilesPath := './RotatedLogs';
CompressRotatedFiles := False;
Enabled := True;
end;
//configure Email log provider
Logger.Providers.Add(GlobalLogEmailProvider);
with GlobalLogEmailProvider do
begin
LogLevel := [etCritical];
SMTP.Host := 'smtp.domain.com';
SMTP.Username := 'myemail@domain.com';
SMTP.Password := '1234';
Mail.SenderName := 'Quick.Logger Alert';
Mail.From := 'myemail@domain.com';
Mail.Recipient := 'otheremail@domain.com';
Mail.CC := '';
Enabled := False; //enable when you have a stmp server to connect
end;
//configure Events log provider
Logger.Providers.Add(GlobalLogEventsProvider);
with GlobalLogEventsProvider do
begin
LogLevel := [etWarning,etCritical];
SendLimits.TimeRange := slByMinute;
SendLimits.LimitEventTypes := [etWarning];
SendLimits.MaxSent := 2;
OnCritical := TMyEvent.Critical;
Enabled := True;
end;
{$IFDEF MSWINDOWS}
//configure IDEDebug provider
Logger.Providers.Add(GlobalLogIDEDebugProvider);
with GlobalLogIDEDebugProvider do
begin
LogLevel := [etCritical];
Enabled := True;
end;
//configure EventLog provider
Logger.Providers.Add(GlobalLogEventLogProvider);
with GlobalLogEventLogProvider do
begin
LogLevel := [etSuccess,etError,etCritical,etException];
Source := 'QuickLogger';
Enabled := True;
end;
{$ENDIF}
//configure Rest log provider
Logger.Providers.Add(GlobalLogRestProvider);
with GlobalLogRestProvider do
begin
URL := 'http://localhost/event';
LogLevel := [etError,etCritical,etException];
Enabled := False; //enable when you have a http server server to connect
end;
//configure Redis log provider
Logger.Providers.Add(GlobalLogRedisProvider);
with GlobalLogRedisProvider do
begin
Host := '192.168.1.133';
LogKey := 'Log';
MaxSize := 1000;
Password := 'pass123';
LogLevel := LOG_ALL;// [etError,etCritical,etException];
Enabled := True; //enable when you have a redis to connect
end;
//configure Mem log provider
Logger.Providers.Add(GlobalLogMemoryProvider);
with GlobalLogMemoryProvider do
begin
LogLevel := [etError,etCritical,etException];
Enabled := True;
end;
//configure Telegram log provider
Logger.Providers.Add(GlobalLogTelegramProvider);
with GlobalLogTelegramProvider do
begin
ChannelName := 'YourChannel';
ChannelType := TTelegramChannelType.tcPrivate;
BotToken := 'yourbottoken';
Environment := 'Test';
PlatformInfo := 'App';
IncludedInfo := [iiAppName,iiHost,iiEnvironment,iiPlatform];
LogLevel := [etError,etCritical,etException];
Enabled := False;
end;
//configure Slack log provider
Logger.Providers.Add(GlobalLogSlackProvider);
with GlobalLogSlackProvider do
begin
ChannelName := 'alerts';
UserName := 'yourbot';
WebHookURL := 'https://hooks.slack.com/services/TXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX';
LogLevel := [etError,etCritical,etException];
Enabled := False;
end;
//configure Logstash log provider
Logger.Providers.Add(GlobalLogLogstashProvider);
with GlobalLogLogstashProvider do
begin
URL := 'http://192.168.1.133:5011';
IndexName := 'logger';
LogLevel := [etError,etCritical,etException];
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedInfo := [iiAppName,iiHost,iiEnvironment,iiPlatform];
Enabled := False; //enable when you have a logstash service to connect
end;
//configure ElasticSearch log provider
Logger.Providers.Add(GlobalLogElasticSearchProvider);
with GlobalLogElasticSearchProvider do
begin
URL := 'http://192.168.1.133:9200';
IndexName := 'logger';
LogLevel := [etError,etCritical,etException];
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedInfo := [iiAppName,iiHost,iiEnvironment,iiPlatform];
Enabled := False; //enable when you have a ElasticSearch service to connect
end;
//configure InfluxDB log provider
Logger.Providers.Add(GlobalLogInfluxDBProvider);
with GlobalLogInfluxDBProvider do
begin
URL := 'http://192.168.1.133:8086';
DataBase := 'logger';
CreateDataBaseIfNotExists := True;
LogLevel := LOG_DEBUG;
MaxFailsToRestart := 5;
MaxFailsToStop := 0;
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedTags := [iiAppName,iiHost,iiEnvironment,iiPlatform];
IncludedInfo := [iiAppName,iiHost,iiEnvironment,iiPlatform];
Enabled := False; //enable when you have a InfluxDB server to connect
end;
//configure GrayLog log provider
Logger.Providers.Add(GlobalLogGrayLogProvider);
with GlobalLogGrayLogProvider do
begin
URL := 'http://192.168.1.133:12201';
LogLevel := LOG_DEBUG;
MaxFailsToRestart := 5;
MaxFailsToStop := 0;
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedInfo := [iiAppName,iiEnvironment,iiPlatform];
Enabled := False; //enable when you have a GrayLog server to connect
end;
//configure Sentry log provider
Logger.Providers.Add(GlobalLogSentryProvider);
with GlobalLogSentryProvider do
begin
DSNKey := 'https://xxxxxxxxxxx@999999.ingest.sentry.io/999999';
LogLevel := LOG_DEBUG;
MaxFailsToRestart := 5;
MaxFailsToStop := 0;
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedInfo := [iiAppName,iiEnvironment,iiPlatform,iiOSVersion,iiUserName];
Enabled := False; //enable when you have a Sentry server to connect
end;
//configure Twilio log provider
Logger.Providers.Add(GlobalLogTwilioProvider);
with GlobalLogTwilioProvider do
begin
AccountSID := 'ACxxxxxxxxx';
AuthToken := 'xxxx';
SendFrom := '+123123123';
SendTo := '+123123123';
LogLevel := LOG_DEBUG;
MaxFailsToRestart := 5;
MaxFailsToStop := 0;
Environment := 'Production';
PlatformInfo := 'Desktop';
IncludedInfo := [iiAppName,iiEnvironment,iiPlatform,iiOSVersion,iiUserName];
Enabled := False; //enable when you have a Twilio account to connect
end;
Log('Quick.Logger Demo 1 [Event types]',etHeader);
Log('Hello world!',etInfo);
Log('An error msg!',etError);
Log('A warning msg!',etWarning);
Log('A critical error!',etCritical);
Log('Successfully process',etSuccess);
Log('Quick.Logger Demo 2 [Exception Hook]',etHeader);
Log('Press <Enter> to begin Thread collision Test',etInfo);
//ConsoleWaitForEnterKey;
Log('Quick.Logger Demo 3 [Thread collision]',etHeader);
MultiThreadWriteTest;
ConsoleWaitForEnterKey;
//check if you press the key before all items are flushed to console/disk
if Logger.QueueCount > 0 then
begin
Writeln(Format('There are %d log items in queue. Waiting %d seconds max to flush...',[Logger.QueueCount,Logger.WaitForFlushBeforeExit]));
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, DDetours;
type
TMain = class(TForm)
MemLog: TMemo;
BtnEnableHook1: TButton;
BtnEnableHook2: TButton;
BtnEnableHook3: TButton;
BtnRemoveHook1: TButton;
BtnRemoveHook2: TButton;
BtnRemoveHook3: TButton;
BtnTest: TButton;
procedure BtnEnableHook1Click(Sender: TObject);
procedure BtnEnableHook2Click(Sender: TObject);
procedure BtnEnableHook3Click(Sender: TObject);
procedure BtnRemoveHook1Click(Sender: TObject);
procedure BtnRemoveHook2Click(Sender: TObject);
procedure BtnRemoveHook3Click(Sender: TObject);
procedure BtnTestClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Main: TMain;
implementation
{$R *.dfm}
type
TMsgBoxNextHookProc = function(hWnd: hWnd; lpText, lpCaption: LPCWSTR; uType: UINT): Integer; stdcall;
var
NextHook1: TMsgBoxNextHookProc = nil;
NextHook2: TMsgBoxNextHookProc = nil;
NextHook3: TMsgBoxNextHookProc = nil;
function MessageBox_Hook1(hWnd: hWnd; lpText, lpCaption: LPCWSTR; uType: UINT): Integer; stdcall;
begin
Main.MemLog.Lines.Add('Hook 1 executed successfully.');
Result := NextHook1(hWnd, 'Hook1', lpCaption, uType);
end;
function MessageBox_Hook2(hWnd: hWnd; lpText, lpCaption: LPCWSTR; uType: UINT): Integer; stdcall;
begin
Main.MemLog.Lines.Add('Hook 2 executed successfully.');
Result := NextHook2(hWnd, lpText, 'Hook2', uType);
end;
function MessageBox_Hook3(hWnd: hWnd; lpText, lpCaption: LPCWSTR; uType: UINT): Integer; stdcall;
begin
Main.MemLog.Lines.Add('Hook 3 executed successfully.');
Result := NextHook3(hWnd, lpText, lpText, uType);
end;
procedure TMain.BtnEnableHook1Click(Sender: TObject);
begin
if not Assigned(NextHook1) then
@NextHook1 := InterceptCreate(@MessageBox, @MessageBox_Hook1);
end;
procedure TMain.BtnEnableHook2Click(Sender: TObject);
begin
if not Assigned(NextHook2) then
@NextHook2 := InterceptCreate(@MessageBox, @MessageBox_Hook2);
end;
procedure TMain.BtnEnableHook3Click(Sender: TObject);
begin
if not Assigned(NextHook3) then
@NextHook3 := InterceptCreate(@MessageBox, @MessageBox_Hook3);
end;
procedure TMain.BtnRemoveHook1Click(Sender: TObject);
begin
if Assigned(NextHook1) then
begin
InterceptRemove(@NextHook1);
NextHook1 := nil;
end;
end;
procedure TMain.BtnRemoveHook2Click(Sender: TObject);
begin
if Assigned(NextHook2) then
begin
InterceptRemove(@NextHook2);
NextHook2 := nil;
end;
end;
procedure TMain.BtnRemoveHook3Click(Sender: TObject);
begin
if Assigned(NextHook3) then
begin
InterceptRemove(@NextHook3);
NextHook3 := nil;
end;
end;
procedure TMain.BtnTestClick(Sender: TObject);
begin
MemLog.Lines.Add('----------------------------');
MessageBox(Handle, 'Msg Text', 'Msg Caption', MB_OK);
end;
procedure TMain.FormCreate(Sender: TObject);
begin
MemLog.Clear;
end;
end.
|
(*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 具现化的大小写不敏感的WideString类型的声明
// Create by HouSisong, 2006.10.21
//------------------------------------------------------------------------------
unit DGL_WideStringCaseInsensitive;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
const
_NULL_Value:WideString='';
type
_ValueType = WideString; //大小写不敏感的String
function _HashValue(const Key: _ValueType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$define _DGL_Compare} //比较函数
function _IsEqual(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b);
function _IsLess(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
{$I DGL.inc_h}
type
TCIWStrAlgorithms = _TAlgorithms;
ICIWStrIterator = _IIterator;
ICIWStrContainer = _IContainer;
ICIWStrSerialContainer = _ISerialContainer;
ICIWStrVector = _IVector;
ICIWStrList = _IList;
ICIWStrDeque = _IDeque;
ICIWStrStack = _IStack;
ICIWStrQueue = _IQueue;
ICIWStrPriorityQueue = _IPriorityQueue;
TCIWStrVector = _TVector;
TCIWStrDeque = _TDeque;
TCIWStrList = _TList;
ICIWStrVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
ICIWStrDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
ICIWStrListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TCIWStrStack = _TStack;
TCIWStrQueue = _TQueue;
TCIWStrPriorityQueue = _TPriorityQueue;
//
ICIWStrMapIterator = _IMapIterator;
ICIWStrMap = _IMap;
ICIWStrMultiMap = _IMultiMap;
TCIWStrSet = _TSet;
TCIWStrMultiSet = _TMultiSet;
TCIWStrMap = _TMap;
TCIWStrMultiMap = _TMultiMap;
TCIWStrHashSet = _THashSet;
TCIWStrHashMultiSet = _THashMultiSet;
TCIWStrHashMap = _THashMap;
TCIWStrHashMultiMap = _THashMultiMap;
implementation
uses
HashFunctions;
function _HashValue(const Key :_ValueType):Cardinal; overload;
begin
result:=HashValue_WideStrCaseInsensitive(Key);
end;
function _IsEqual(const a,b :_ValueType):boolean; //result:=(a=b);
begin
result:=IsEqual_WideStrCaseInsensitive(a,b);
end;
function _IsLess(const a,b :_ValueType):boolean; //result:=(a<b); 默认排序准则
begin
result:=IsLess_WideStrCaseInsensitive(a,b);
end;
{$I DGL.inc_pas}
end.
|
unit dmNationalityMain;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase;
type
TMainDM = class(TDataModule)
Database: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
ReportDataSet: TpFIBDataSet;
ReportDataSource: TDataSource;
NationalityDataSet: TpFIBDataSet;
NationalityDataSetID_NATIONALITY: TFIBIntegerField;
NationalityDataSetNAME_NATIONALITY: TFIBStringField;
NationalityDataSource: TDataSource;
ReportDataSetDEPARTMENT_NAME: TFIBStringField;
ReportDataSetFIO: TFIBStringField;
ReportDataSetPOST_NAME: TFIBStringField;
ReportDataSetBIRTH_DATE: TFIBDateField;
ReportDataSetDEPARTMENT_NAME_UPPER: TFIBStringField;
ReportDataSetHOME_ADR: TFIBStringField;
ReportDataSetHOME_PHONE: TFIBStringField;
ConstsQuery: TpFIBDataSet;
ConstsQueryUSE_END: TFIBDateTimeField;
ConstsQueryDATE_END: TFIBDateField;
ConstsQueryFIRM_NAME: TFIBStringField;
ConstsQueryDATE_BEG: TFIBDateField;
ConstsQueryFIRM_EDRPOU: TFIBStringField;
ConstsQueryFIRM_UKUD: TFIBStringField;
ConstsQueryPASS_AGE: TFIBIntegerField;
ConstsQueryEDUC_AGE: TFIBIntegerField;
ConstsQueryCURRENT_DEPARTMENT: TFIBIntegerField;
ConstsQueryCURRENT_BUHG_DEPARTMENT: TFIBIntegerField;
ConstsQueryLAST_BEG_LOG_DATE: TFIBDateTimeField;
ConstsQueryLAST_END_LOG_DATE: TFIBDateTimeField;
ConstsQueryMAN_PENS_AGE: TFIBIntegerField;
ConstsQueryWOMAN_PENS_AGE: TFIBIntegerField;
ConstsQueryDEFAULT_NIGHT_BEG: TFIBTimeField;
ConstsQueryDEFAULT_NIGHT_END: TFIBTimeField;
ConstsQuerySHIFT_BEGIN: TFIBDateField;
ConstsQueryBONUS1: TFIBIntegerField;
ConstsQueryBONUS2: TFIBIntegerField;
ConstsQueryBONUS1_ABBR: TFIBStringField;
ConstsQueryBONUS2_ABBR: TFIBStringField;
ConstsQueryCITY: TFIBStringField;
ConstsQueryCONT_STAJ_MONTH: TFIBIntegerField;
ConstsQueryLOCAL_DEPARTMENT: TFIBIntegerField;
ConstsQueryORDERS_HEADER: TFIBStringField;
ConstsQueryDB_VERSION: TFIBIntegerField;
ConstsQueryDEFAULT_PAY_FORM: TFIBIntegerField;
ConstsQueryDEFAULT_WORK_COND: TFIBIntegerField;
ConstsQueryDEFAULT_WORK_MODE: TFIBIntegerField;
ConstsQueryRAISE_TYPE_FOR_OKLAD: TFIBIntegerField;
ConstsQueryBONUS_CALC: TFIBIntegerField;
ConstsQueryNEW_ORDERS: TFIBStringField;
ConstsQueryUSE_MOVING_SMET: TFIBIntegerField;
ConstsQueryVIZA_REQUIRED_IN_ORDERS: TFIBStringField;
ConstsQueryID_VIDOPL: TFIBIntegerField;
ConstsQueryDEFAULT_SMETA: TFIBIntegerField;
ConstsQueryAPPRENTICE_MOVING_TYPE: TFIBIntegerField;
ConstsQueryHIDDEN_ID_POST: TFIBIntegerField;
ConstsQueryID_DOG_FOR_COMAND: TFIBIntegerField;
ConstsQueryTABLE_WORK_DAYS_SMENA: TFIBIntegerField;
ConstsQueryGLOBAL_ROOT: TFIBIntegerField;
ConstsQueryALLOW_EMPTY_SMETS_IN_ORDERS: TFIBStringField;
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainDM: TMainDM;
implementation
{$R *.dfm}
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2008 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: Tools for read sound info
// Last update: 9 mar 2008
unit SoundReader;
interface
Uses Windows, Classes, SysUtils, mmSystem, SWFTools, MPEGAudio;
const { Constants for wave format identifier }
WAVE_FORMAT_PCM = $0001; { Windows PCM }
WAVE_FORMAT_G723_ADPCM = $0014; { Antex ADPCM }
WAVE_FORMAT_ANTEX_ADPCME = $0033; { Antex ADPCME }
WAVE_FORMAT_G721_ADPCM = $0040; { Antex ADPCM }
WAVE_FORMAT_APTX = $0025; { Audio Processing Technology }
WAVE_FORMAT_AUDIOFILE_AF36 = $0024; { Audiofile, Inc. }
WAVE_FORMAT_AUDIOFILE_AF10 = $0026; { Audiofile, Inc. }
WAVE_FORMAT_CONTROL_RES_VQLPC = $0034; { Control Resources Limited }
WAVE_FORMAT_CONTROL_RES_CR10 = $0037; { Control Resources Limited }
WAVE_FORMAT_CREATIVE_ADPCM = $0200; { Creative ADPCM }
WAVE_FORMAT_DOLBY_AC2 = $0030; { Dolby Laboratories }
WAVE_FORMAT_DSPGROUP_TRUESPEECH = $0022; { DSP Group, Inc }
WAVE_FORMAT_DIGISTD = $0015; { DSP Solutions, Inc. }
WAVE_FORMAT_DIGIFIX = $0016; { DSP Solutions, Inc. }
WAVE_FORMAT_DIGIREAL = $0035; { DSP Solutions, Inc. }
WAVE_FORMAT_DIGIADPCM = $0036; { DSP Solutions ADPCM }
WAVE_FORMAT_ECHOSC1 = $0023; { Echo Speech Corporation }
WAVE_FORMAT_FM_TOWNS_SND = $0300; { Fujitsu Corp. }
WAVE_FORMAT_IBM_CVSD = $0005; { IBM Corporation }
WAVE_FORMAT_OLIGSM = $1000; { Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLIADPCM = $1001; { Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLICELP = $1002; { Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLISBC = $1003; { Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLIOPR = $1004; { Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_IMA_ADPCM = $0011; { Intel ADPCM }
WAVE_FORMAT_DVI_ADPCM = $0011; { Intel ADPCM }
WAVE_FORMAT_UNKNOWN = $0000;
WAVE_FORMAT_ADPCM = $0002; { Microsoft ADPCM }
WAVE_FORMAT_ALAW = $0006; { Microsoft Corporation }
WAVE_FORMAT_MULAW = $0007; { Microsoft Corporation }
WAVE_FORMAT_GSM610 = $0031; { Microsoft Corporation }
WAVE_FORMAT_MPEG = $0050; { Microsoft Corporation }
WAVE_FORMAT_MPEG_L3 = $0055;
WAVE_FORMAT_NMS_VBXADPCM = $0038; { Natural MicroSystems ADPCM }
WAVE_FORMAT_OKI_ADPCM = $0010; { OKI ADPCM }
WAVE_FORMAT_SIERRA_ADPCM = $0013; { Sierra ADPCM }
WAVE_FORMAT_SONARC = $0021; { Speech Compression }
WAVE_FORMAT_MEDIASPACE_ADPCM = $0012; { Videologic ADPCM }
WAVE_FORMAT_YAMAHA_ADPCM = $0020; { Yamaha ADPCM }
WAVE_FORMAT_MP3 = $0150;
MSADPCM_NUM_COEF = 7;
type
TADPCMCoef = packed record
Coef1, Coef2: SmallInt;
end;
TADPCMCoefSet = Array[0..MSADPCM_NUM_COEF-1] of TADPCMCoef;
PADPCMCoefSet = ^TADPCMCoefSet;
type
TChunkInfo= record
Start, Len: longint;
end;
TWaveHeader = record
WaveFormat: Word; { format type }
Channels: Word; { number of channels (i.e. mono, stereo, etc.) }
SamplesPerSec: DWORD; { sample rate }
BitsPerSample: Word; { number of bits per sample of mono data }
Samples : longint;
end;
TWaveFormat_ADPCM = packed record
wFormatTag: Word; { format type }
nChannels: Word; { number of channels (i.e. mono, stereo,
etc.) }
nSamplesPerSec: Longint; { sample rate }
nAvgBytesPerSec: Longint; { for buffer estimation }
nBlockAlign: Word; { block size of data }
{ --- Addition for TWaveFormat --- }
wBitsPerSample: Word;
cbSize: Word; { SizeOf(wSamplesPerBlock..Predictors. For PCM
factorial }
{ --- Additional data for ADPCM ------- }
wSamplesPerBlock: SmallInt;
wNumCoef: SmallInt; { const 7 }
CoefSet: TADPCMCoefSet; { Also for Mono Coef1,Coef2 }
end;
TMP3Info = record
SamplesPerFrame: word; // samples per frame
FrameLength: word; // byte per frame
FrameCount: word;
BitsPerSec: word;
end;
TWaveReader = class (TObject)
private
FMP3: TMPEGAudio;
FDuration: double;
FWaveData: TStream;
function GetMPEGAudio: TMPEGAudio;
procedure SetMPEGAudio(const Value: TMPEGAudio);
procedure SetWaveData(const Value: TStream);
protected
FFileName: string;
ADInfo: TWaveFormat_ADPCM;
UnCompressBuf: TMemoryStream;
ReadSeek, SkipSample: longint;
procedure ReadFormatInfo(H: THandle);
procedure CheckMP3(nativ: boolean);
procedure CheckMP3Stream(Src: TStream; nativ: boolean);
property MP3: TMPEGAudio read GetMPEGAudio write SetMPEGAudio;
public
WaveHeader: TWaveHeader;
FormatInfo, DataInfo: TChunkInfo;
MP3Info: TMP3Info;
constructor Create (fn: string);
constructor CreateFromStream(Src: TMemoryStream; isMP3: boolean);
destructor Destroy; override;
function WriteMP3Block(Dest: TBitsEngine; Start: longint; Count: word; loop: boolean): longint; //return new frame number
procedure WriteBlock(Dest: TBitsEngine; SamplesCount: longint; bits: byte; loop: boolean);
function WriteReCompress(Dest: TBitsEngine; Src: TStream; Size: longint; bits: byte; isContine: boolean): boolean;
procedure WriteToStream(Dest: TBitsEngine; bits: byte);
procedure WriteUncompressBlock(Dest: TBitsEngine; Size: longint; bits: byte; loop: boolean);
property Duration: double read FDuration write FDuration; // sec
property WaveData: TStream read FWaveData write SetWaveData;
end;
Function isSupportSoundFormat(fn: string):boolean;
procedure WriteCompressWave(dest: TBitsEngine; src: TStream; Size: longint; bits: byte; src16, stereo,
continue, single: boolean);
const
SndRates: array [0..3] of word = (5512, 11025, 22050, 44100);
{ Table for samples per frame}
MPEG_SAMPLES_FRAME: array [0..3, 0..2] of Word =
((576, 1152, 384), { For MPEG 2.5 }
(0, 0, 0), { Reserved }
(576, 1152, 384), { For MPEG 2 }
(1152, 1152, 384)); { For MPEG 1 }
// 384, 1152, 1152}, /* MPEG-1 */
// 384, 1152, 576} /* MPEG-2(.5) */
(*
Sample Rate | 48000 24000 12000
| 44100 22050 11025
| 32000 16000 8000
-------------+-----------------------
Layer I | 384 384 384
Layer II | 1152 1152 1152
Layer III | 1152 576 576
*)
implementation
//Uses MPEGaudio{, MPGTools};
const
IndexTable2: array[0..1] of integer = (-1, 2);
IndexTable3: array[0..3] of integer = (-1, -1, 2, 4);
IndexTable4: array[0..7] of integer = (-1, -1, -1, -1, 2, 4, 6, 8);
IndexTable5: array[0..15] of integer =(-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16);
StepSizeTable: array[0..88] of Integer = (
7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
);
MSADPCM_adapt : array[0..15] of Word = (230, 230, 230, 230,
307, 409, 512, 614,
768, 614, 512, 409,
307, 230, 230, 230);
type
TWaveFormat_MPEG = packed record
wf: tWAVEFORMATEX;
fwHeadLayer: WORD;
dwHeadBitrate: DWORD;
fwHeadMode: WORD ;
fwHeadModeExt: WORD ;
wHeadEmphasis: WORD ;
fwHeadFlags: WORD ;
dwPTSLow: DWORD ;
dwPTSHigh: DWORD ;
end;
function isSupportSoundFormat(fn: string):boolean;
var f_ext: string[5];
MP3: TMPEGAudio;
FS: tFileStream;
W: word;
begin
Result := false;
f_ext := UpperCase(ExtractfileExt(fn));
// f_ext := '.MP3';
if f_ext = '.MP3' then
begin
MP3:= TMPEGAudio.Create;
Result := MP3.isMP3File(fn);
// MP3.Free;
end else
if f_ext = '.WAV' then
begin
FS:=tFileStream.Create(fn, fmOpenRead + fmShareDenyWrite);
FS.Position := 20;
FS.Read(W, 2);
FS.Free;
case W of
WAVE_FORMAT_PCM,
WAVE_FORMAT_ADPCM: Result := true;
WAVE_FORMAT_MPEG,
WAVE_FORMAT_MPEG_L3:
begin
MP3:= TMPEGAudio.Create;
MP3.ReadFromFile(fn);
Result := MP3.FirstFrame.Found;
// MP3.FileName := fn;
// MP3.IsValid;
// MP3.Free;
end;
else Result := false;
end;
end;
end;
constructor TWaveReader.Create (fn: string);
var
H: THandle;
f_ext: string[5];
begin
FFileName := fn;
if FFileName = '' then Exit;
f_ext := UpperCase(ExtractfileExt(fn));
if f_ext = '.MP3' then
begin
WaveData := TFileStream.Create(FN, fmOpenRead + fmShareDenyWrite);
CheckMP3Stream(WaveData, true);
end else
if f_ext = '.WAV' then
begin
H := mmioOpen(PChar(fn), nil, MMIO_READ);
if H > 0 then
begin
ReadFormatInfo(H);
mmioClose(H, 0);
if WaveHeader.WaveFormat in [WAVE_FORMAT_PCM, WAVE_FORMAT_ADPCM] then
begin
ReadSeek := 0;
SkipSample := 0;
UnCompressBuf := TMemoryStream.Create;
WaveData := TFileStream.Create(FN, fmOpenRead + fmShareDenyWrite);
WaveData.Position := DataInfo.Start;
end;
end;
end;
end;
constructor TWaveReader.CreateFromStream(Src: TMemoryStream; isMP3: boolean);
var H: THandle;
Info: TMMIOInfo;
begin
if isMP3 then
begin
CheckMP3Stream(Src, true);
end else
begin
FillChar(Info, SizeOf(Info), 0);
Info.pchBuffer := Src.Memory;
Info.cchBuffer := Src.Size;
info.fccIOProc := FOURCC_MEM;
H := mmioOpen(nil, @Info, MMIO_READWRITE);
if H > 0 then
begin
ReadFormatInfo(H);
mmioClose(H, 0);
if WaveHeader.WaveFormat in [WAVE_FORMAT_PCM, WAVE_FORMAT_ADPCM] then
begin
ReadSeek := 0;
SkipSample := 0;
UnCompressBuf := TMemoryStream.Create;
WaveData := Src;
WaveData.Position := DataInfo.Start;
end;
end;
end;
end;
procedure TWaveReader.ReadFormatInfo(H: THandle);
var
mmckinfoParent: TMMCKInfo;
mmckinfoSubchunk: TMMCKInfo;
Buff: array [0..255] of byte;
VF1: TPCMWaveFormat absolute Buff;
VF2: TWaveFormat_ADPCM absolute Buff;
VF4: TWaveFormatEx absolute Buff;
begin
mmckinfoParent.fccType := mmioStringToFOURCC('WAVE', MMIO_TOUPPER);
if (mmioDescend(H, PMMCKINFO(@mmckinfoParent), nil, MMIO_FINDRIFF) <> 0) then Exit;
mmckinfoSubchunk.ckid := mmioStringToFOURCC('fmt ', 0);
mmioDescend(H, @mmckinfoSubchunk, @mmckinfoParent, MMIO_FINDCHUNK);
// WaveHeader.Fixed1 := mmckinfoSubchunk.cksize;
FormatInfo.Start := mmckinfoSubchunk.dwDataOffset;
FormatInfo.Len := mmckinfoSubchunk.cksize;
mmioAscend(H, @mmckinfoSubchunk, 0);
mmckinfoSubchunk.ckid := mmioStringToFOURCC('data', 0);
mmioDescend(H, @mmckinfoSubchunk, @mmckinfoParent, MMIO_FINDCHUNK);
DataInfo.Start := mmckinfoSubchunk.dwDataOffset;
DataInfo.Len := mmckinfoSubchunk.cksize;
mmioSeek(H, FormatInfo.Start, 0);
mmioRead(H, @Buff, FormatInfo.Len);
Move(Buff, WaveHeader.WaveFormat, 2);
case WaveHeader.WaveFormat of
WAVE_FORMAT_PCM:
begin
WaveHeader.Channels := VF1.wf.nChannels;
WaveHeader.SamplesPerSec := VF1.wf.nSamplesPerSec;
WaveHeader.BitsPerSample := VF1.wBitsPerSample;
WaveHeader.Samples := (DataInfo.Len * 8) div (WaveHeader.BitsPerSample * WaveHeader.Channels);
end;
WAVE_FORMAT_ADPCM:
begin
ADInfo := VF2;
WaveHeader.Channels := VF2.nChannels;
WaveHeader.SamplesPerSec := VF2.nSamplesPerSec;
WaveHeader.BitsPerSample := VF2.wBitsPerSample;
WaveHeader.Samples := Trunc(VF2.wSamplesPerBlock * DataInfo.Len / VF2.nBlockAlign) - 2;
end;
WAVE_FORMAT_MPEG,
WAVE_FORMAT_MPEG_L3:
begin
if FFileName <> '' then CheckMP3(false);
end;
else
begin
WaveHeader.Channels := VF4.nChannels;
WaveHeader.SamplesPerSec := VF4.nSamplesPerSec;
WaveHeader.BitsPerSample := VF4.wBitsPerSample;
WaveHeader.Samples := (DataInfo.Len * 8) div (WaveHeader.BitsPerSample * WaveHeader.Channels);
end;
end;
if Duration = 0 then
Duration := WaveHeader.Samples / WaveHeader.SamplesPerSec;
end;
procedure TWaveReader.SetMPEGAudio(const Value: TMPEGAudio);
begin
if Assigned(FMP3) then FMP3.Free;
FMP3 := Value;
end;
procedure TWaveReader.SetWaveData(const Value: TStream);
begin
if Assigned(FWaveData) then FWaveData.Free;
FWaveData := Value;
end;
destructor TWaveReader.Destroy;
begin
// mmioClose(FHandle, 0);
if Assigned(FMP3) then FMP3.Free;
if Assigned(FWaveData) and (FWaveData is TFileStream) then FWaveData.Free;
if Assigned(UnCompressBuf) then UnCompressBuf.Free;
inherited;
end;
function TWaveReader.GetMPEGAudio: TMPEGAudio;
begin
if not Assigned(FMP3) then FMP3 := TMPEGAudio.Create;
result := FMP3;
end;
procedure TWaveReader.CheckMP3(nativ:boolean);
var
F: TFileStream;
begin
F := TFileStream.Create(FFileName, fmOpenRead + fmShareDenyWrite);
CheckMP3Stream(F, nativ);
F.Free;
end;
procedure TWaveReader.CheckMP3Stream(Src: TStream; nativ: boolean);
begin
MP3 := TMPEGAudio.Create;
MP3.ReadFromStream(Src);
if Nativ then
begin
WaveHeader.WaveFormat := WAVE_FORMAT_MP3;
DataInfo.Start := MP3.FirstFrame.Position + MP3.ID3v2.Size;
DataInfo.Len := MP3.FileLength - DataInfo.Start - MP3.ID3v1.Size;
end;
WaveHeader.Channels := byte(not (MP3.FirstFrame.ModeID = MPEG_CM_MONO)) + 1;
WaveHeader.SamplesPerSec := MP3.SampleRate;
WaveHeader.BitsPerSample := 16;
WaveHeader.Samples := Round(MP3.SampleRate * MP3.Duration);
MP3Info.FrameLength := MP3.FirstFrame.Size;
MP3Info.FrameCount := MP3.FrameCount;
MP3Info.BitsPerSec := MP3.BitRate;
MP3Info.SamplesPerFrame := MPEG_SAMPLES_FRAME[MP3.FirstFrame.VersionID, MP3.FirstFrame.SampleRateID];
if (MP3Info.FrameLength * MP3Info.FrameCount ) > MP3.FileLength then
MP3Info.FrameCount := MP3.FileLength div MP3Info.FrameLength;
Duration := MP3.Duration;
// MP3.Free;
end;
procedure CheckSmallInt(var value: longint);
begin
if value > 32767 then value := 32767 else
if value < -32768 then value := -32768;
end;
{$IFDEF VER130}
type
TIntegerArray = array of integer;
PIntegerArray = ^TIntegerArray;
{$ENDIF}
procedure WriteCompressWave(dest: TBitsEngine; src: TStream; Size: longint; bits: byte; src16, stereo,
continue, single: boolean);
var sign, step, delta, vpdiff: integer;
PArray: PIntegerArray;
bSize, iDiff, k: longint;
nSamples: longint;
iChn, cChn: byte;
ValPred, Val: array [0..1] of longint;
Index: array [0..1] of smallint;
function ReadSample: SmallInt;
var W: word;
B: Byte;
begin
if src16 then
begin
src.Read(W, 2);
Result := smallint(W);
Dec(bSize, 2);
end else
begin
src.Read(B, 1);
Result := smallint((B - 128) shl 8);
Dec(bSize);
end;
end;
begin
if not continue then
dest.WriteBits(bits - 2, 2);
case bits of
2: PArray := @IndexTable2;
3: PArray := @IndexTable3;
4: PArray := @IndexTable4;
5: PArray := @IndexTable5;
end;
nSamples := 0;
cChn := 1 + byte(Stereo);
bSize := Size;
while bSize > 0 do
begin
if (nSamples and $fff) = 0 then
begin
ValPred[0] := ReadSample;
if Stereo then ValPred[1] := ReadSample;
Val[0] := ReadSample;
if Stereo then Val[1] := ReadSample;
for iChn := 0 to cChn - 1 do
begin
dest.WriteBits(ValPred[iChn], 16);
iDiff := abs(Val[iChn] - ValPred[iChn]);
Index[iChn] := 0;
while ((Index[iChn] < 63) and (StepSizeTable[Index[iChn]] < iDiff)) do Inc(Index[iChn]);
dest.WriteBits(Index[iChn], 6);
end;
ValPred[0] := Val[0];
if Stereo then ValPred[1] := Val[1];
end else
begin
if ((nSamples-1) and $fff) > 0 then
begin
Val[0] := ReadSample;
if Stereo then Val[1] := ReadSample;
end;
for iChn := 0 to cChn - 1 do
begin
iDiff := Val[iChn] - ValPred[iChn];
if (iDiff < 0) then
begin
sign := 1 shl (bits - 1);
iDiff := -iDiff;
end
else sign := 0;
delta := 0;
step := StepSizeTable[Index[iChn]];
VPDiff := step shr (bits-1);
k := bits - 2;
while k >= 0 do
begin
if (iDiff >= step) then
begin
delta := delta or (1 shl k);
VPDiff := VPDiff + step;
iDiff := iDiff - step;
end;
dec(k);
step := step shr 1;
end;
if (sign = 0)
then Inc(ValPred[iChn], vpdiff)
else Dec(ValPred[iChn], vpdiff);
CheckSmallInt(ValPred[iChn]);
inc(Index[iChn], PArray^[delta]);
if (Index[iChn] < 0 ) then Index[iChn] := 0
else if (index[iChn] > 88) then index[iChn] := 88;
delta := delta or sign;
dest.WriteBits(delta, bits);
end;
end;
inc(nSamples);
end;
if single then dest.FlushLastByte();
end;
procedure TWaveReader.WriteBlock(Dest: TBitsEngine; SamplesCount: Integer; bits: byte; loop: boolean);
var
Decoded, dSize, UnSize, il, Unclaimed, SavedSamples: longint;
buffer: TMemoryStream;
isContine, NoLastBlock: boolean;
sBits, Zero: Byte;
begin
if (bits = 0) or (bits > ADInfo.wBitsPerSample)
then sBits := ADInfo.wBitsPerSample
else sBits := bits;
buffer := TMemoryStream.Create;
buffer.SetSize(ADInfo.nBlockAlign);
Decoded := SkipSample;
SavedSamples := 0;
isContine := false;
NoLastBlock := true;
while (Decoded <= SamplesCount) and (ReadSeek < (DataInfo.Start + DataInfo.Len)) do
begin
if (ReadSeek + ADInfo.nBlockAlign) > (DataInfo.Start + DataInfo.Len) then
begin
dSize := (DataInfo.Len + DataInfo.Start) - ReadSeek;
inc(Decoded, trunc(dSize * ADInfo.wSamplesPerBlock / ADInfo.nBlockAlign));
NoLastBlock := false;
// last block contain bad saplases :|
end else
begin
dSize := ADInfo.nBlockAlign;
inc(Decoded, ADInfo.wSamplesPerBlock);
end;
if NoLastBlock then
begin
buffer.Position := 0;
//mmioRead(FHandle, buffer.Memory, dSize);
buffer.CopyFrom(WaveData, dSize);
buffer.Position := 0;
if WriteReCompress(Dest, buffer, dSize, sBits, isContine) then
begin
inc(SavedSamples, $1000);
isContine := true;
end;
end;
inc(ReadSeek, dSize);
end;
Unclaimed := 0;
UnSize := 0;
if (UnCompressBuf.Position > 0) or (not isContine) then
begin
UnSize := (SamplesCount - SavedSamples) * 2 * ADInfo.nChannels {- 2 - 2 * (ADInfo.nChannels -1)};
Unclaimed := UnCompressBuf.Position - UnSize;
if Unclaimed < 0 then
begin
if loop then
begin
ReadSeek := DataInfo.Start;
WaveData.Seek(ReadSeek, 0);
//mmioSeek(FHandle, ReadSeek, 0);
SkipSample := UnCompressBuf.Position div (2 * ADInfo.nChannels);
WriteBlock(Dest, SamplesCount - SkipSample, bits, loop)
end else
begin
Zero := 0;
for il := 1 to -Unclaimed do UnCompressBuf.Write(Zero, 1);
end;
end;
if (Unclaimed >= 0) or ((Unclaimed < 0) and (not loop)) then
begin
UnCompressBuf.Position := 0;
WriteCompressWave(Dest, UnCompressBuf, UnSize, sBits, true, ADInfo.nChannels=2, isContine, true);
end;
end;
if Unclaimed > 0 then
begin
SkipSample := Decoded - SamplesCount;
buffer.SetSize(Unclaimed);
buffer.Position := 0;
UnCompressBuf.Position := UnSize;
buffer.CopyFrom(UnCompressBuf, Unclaimed);
UnCompressBuf.LoadFromStream(buffer);
end else
if not loop then
begin
SkipSample := 0;
UnCompressBuf.Position := 0;
end;
buffer.Free;
end;
function TWaveReader.WriteMP3Block(Dest: TBitsEngine; Start: longint; Count: word; loop: boolean): longint;
var il, i0, delta: word;
begin
Result := Start;
il := 0;
while il < Count do
begin
if Result < MP3.FrameCount then
begin
if MP3.FrameInfo[Result].isSound then
begin
WaveData.Position := MP3.FrameInfo[Result].Position;
with MP3.FrameInfo[Result] do
if (Position + Size) < WaveData.Size
then
Dest.BitsStream.CopyFrom(WaveData, Size)
else
begin
Dest.BitsStream.CopyFrom(WaveData, WaveData.Size - Position);
delta := Size - (WaveData.Size - Position);
for i0 := 1 to delta do Dest.WriteByte(0);
end;
inc(il);
end;
Inc(Result);
end else
begin
if loop then Result := 0
else
begin
delta := (Count - il) * MP3Info.FrameLength;
for i0 := 1 to delta do Dest.WriteByte(0);
il := Count;
end;
end;
end;
end;
function TWaveReader.WriteReCompress(Dest: TBitsEngine; Src: TStream; Size: Integer;
bits: byte; isContine: boolean): boolean;
var
aiSamp1, aiSamp2,
aiCoef1, aiCoef2,
aiDelta: array[0..1] of Smallint;
iInput, iNextInput: Smallint;
iChn, nChn, n: byte;
be: TBitsEngine;
isFirst: boolean;
il, UnSize, decSample, sSize: longint;
begin
Result := false;
be := TBitsEngine.Create(Src);
UnSize := $2000 * ADInfo.nChannels;
nChn := ADInfo.nChannels;
if Size = 0 then sSize := Src.Size else sSize := Size;
for iChn := 0 to nChn - 1 do
begin
n := be.ReadByte;
aiCoef1[iChn] := ADInfo.CoefSet[n].Coef1;
aiCoef2[iChn] := ADInfo.CoefSet[n].Coef2;
end;
for iChn := 0 to nChn - 1 do aiDelta[iChn]:= smallint(be.ReadWord);
for iChn := 0 to nChn - 1 do aiSamp1[iChn]:= smallint(be.ReadWord);
for iChn := 0 to nChn - 1 do aiSamp2[iChn]:= smallint(be.ReadWord);
for iChn := 0 to nChn - 1 do UnCompressBuf.Write(aiSamp2[iChn], 2);
for iChn := 0 to nChn - 1 do UnCompressBuf.Write(aiSamp1[iChn], 2);
isFirst := True;
il := 1;
while il <= (ADInfo.wSamplesPerBlock - 2) do
begin
inc(il);
for iChn := 0 to nChn - 1 do
begin
if isFirst then
begin
if (Src.Size > Src.Position) then
begin
iNextInput := be.ReadByte;
// iInput := iNextInput shr 4;
// iNextInput := byte(iNextInput) shl 12 shr 12;
asm
mov ax, iNextInput
cbw
sar ax,4
mov iInput, ax
mov ax, iNextInput
sal ax, 12
sar ax, 12
mov iNextInput, ax
end;
end;
isFirst := False;
end else
begin
iInput := iNextInput;
isFirst := True;
end;
decSample := aiDelta[iChn];
aiDelta[iChn] := (decSample * MSADPCM_adapt[iInput and $0f]) div 256;
if aiDelta[iChn] < 16 then aiDelta[iChn] := 16;
decSample := (decSample * iInput) +
((LongInt(aiSamp1[iChn])*aiCoef1[iChn])+
(LongInt(aiSamp2[iChn])*aiCoef2[iChn])) div 256;
CheckSmallInt(decSample);
aiSamp2[iChn] := aiSamp1[iChn];
aiSamp1[iChn] := decSample;
UnCompressBuf.Write(smallint(decSample), 2);
if (UnCompressBuf.Position = UnSize) then
begin
UnCompressBuf.Position := 0;
WriteCompressWave(Dest, UnCompressBuf, UnSize, bits, true, ADInfo.nChannels=2,
isContine, false);
isContine := true;
Result := true;
UnCompressBuf.Position := 0;
end;
end;
if (Src.Position = sSize) and isFirst then
il := ADInfo.wSamplesPerBlock; // for break
end;
be.Free;
end;
procedure TWaveReader.WriteToStream(Dest: TBitsEngine; bits: byte);
var
buffer: TMemoryStream;
bSize, dSize, UnSize: longint;
sBits: byte;
isContine: boolean;
begin
if (bits = 0) or (bits > ADInfo.wBitsPerSample)
then sBits := ADInfo.wBitsPerSample
else sBits := bits;
buffer := TMemoryStream.Create;
buffer.SetSize(ADInfo.nBlockAlign);
UnSize := $2000 * ADInfo.nChannels;
UnCompressBuf.SetSize(UnSize);
bSize := DataInfo.Len;
isContine := false;
while bSize > 0 do
begin
if bSize >= ADInfo.nBlockAlign then dSize := ADInfo.nBlockAlign
else
begin
dSize := bSize;
buffer.SetSize(dSize);
end;
buffer.Position := 0;
// mmioRead(FHandle, buffer.Memory, dSize);
buffer.CopyFrom(WaveData, dSize);
buffer.Position := 0;
isContine := WriteReCompress(Dest, buffer, 0{dSize}, sBits, isContine) or isContine;
Dec(bSize, dSize);
end;
if UnCompressBuf.Position > 0 then
begin
UnSize := UnCompressBuf.Position;
UnCompressBuf.Position := 0;
WriteCompressWave(Dest, UnCompressBuf, UnSize, sBits, true, ADInfo.nChannels=2, isContine, true);
end;
buffer.Free;
end;
procedure TWaveReader.WriteUncompressBlock;
var sSize, il: longint;
Zero: byte;
begin
sSize := 0;
while sSize < Size do
begin
if (WaveData.Position + Size) > (DataInfo.Start + DataInfo.Len) then
begin
sSize := (DataInfo.Start + DataInfo.Len) - WaveData.Position;
end else
begin
sSize := Size;
end;
if bits = 0
then Dest.BitsStream.CopyFrom(WaveData, sSize)
else
begin
if sSize = Size then
WriteCompressWave(Dest, WaveData, Size, bits, WaveHeader.BitsPerSample = 16,
WaveHeader.Channels = 2, false, true);
end;
if sSize < Size then
begin
if bits = 0 then
begin
if Loop then
begin
WaveData.Position := DataInfo.Start;
Dest.BitsStream.CopyFrom(WaveData, Size - sSize);
end else
begin
for il := 1 to Size - sSize do
Dest.WriteByte(0);
end;
end else
begin
UnCompressBuf.SetSize(Size);
UnCompressBuf.Position := 0;
UnCompressBuf.CopyFrom(WaveData, sSize);
if loop then
begin
WaveData.Position := DataInfo.Start;
UnCompressBuf.CopyFrom(WaveData, Size - sSize);
end else
begin
for il := 1 to Size - sSize do
UnCompressBuf.Write(Zero, 1);
end;
UnCompressBuf.Position := 0;
WriteCompressWave(Dest, UnCompressBuf, UnCompressBuf.Size, bits, WaveHeader.BitsPerSample = 16,
WaveHeader.Channels = 2, false, true);
end;
sSize := Size;
end;
end;
end;
end.
|
{циклический сдвиг при помощи нод,
используя одну переменную для запоминания последущей перестановки}
program displacement3;
uses crt;
const N=6;
type arr=array[1..N] of integer;
function max(a,b:integer):integer;
begin
if (a>=b) then max:=a
else max:=b
end;
function min(a,b:integer):integer;
begin
if (a<b) then min:=a
else min:=b
end;
function nod(max,min:integer):integer;
var modulj:integer;
begin
modulj:=max mod min;
if (max=0) or (min=0) then nod:=max
else if (modulj=0) then nod:=min
else nod:=nod(min,modulj);
end;
procedure invert(var a:arr;k,position,memory,head,nodcounter,nodnumbers:integer;bool:boolean);
var tmp:integer;
begin
tmp:=a[position];
a[position]:=memory;
memory:=tmp;
position:=position+k;
if (position>N) then
begin
position:=position-N;
inc(nodcounter);
end;
if (bool=true) and (head=position-k) then
begin
inc(head);
position:=head+k;
memory:=a[head];
end;
if (nodnumbers<>nodcounter) or ((nodnumbers=nodcounter) and (head<>position-k))
then invert(a,k,position,memory,head,nodcounter,nodnumbers,bool);
end;
var matrix:arr;
i,k,nodnumbers:integer;
bool:boolean;
begin
writeln('vvedite massiv');
for i:=1 to N do
begin
readln(matrix[i]);
end;
writeln('vvedite dlinu smeshenija');
readln(k);
nodnumbers:=Nod(N,k);
if nodnumbers=1 then
begin
bool:=false;
nodnumbers:=k;
end
else bool:=true;
if (k>=1) and (k<N)
then invert(matrix,k,1+k,matrix[1],matrix[1],0,nodnumbers,bool);
for i:=1 to N do
begin
write(matrix[i]);
end;
readkey;
end. |
unit uMainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, OleCtrls, SHDocVw,
ExtCtrls;
type
TfrmMain = class(TForm)
pnlTop: TPanel;
lblScanURL: TLabel;
edtScanURL: TEdit;
btnLoadPage: TButton;
btnScan: TButton;
pnlBottom: TPanel;
wbBrowser: TWebBrowser;
pnlMiddle: TPanel;
mmoLog: TMemo;
procedure btnScanClick(Sender: TObject);
procedure btnLoadPageClick(Sender: TObject);
procedure wbBrowserNavigateError(ASender: TObject; const pDisp: IDispatch;
const URL, Frame, StatusCode: OleVariant; var Cancel: WordBool);
private
{ Private declarations }
// Web page has loaded Flag
// isPageLoaded : Boolean;
// Load Web page and return result of load
function LoadPage(aURL: WideString): integer;
procedure ScanPage(aWebBrowser: TWebBrowser);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses MSHTML;
const // name of class wich contains lotto name
cCNlottoName: WideString = 'lotto_name';
// name of class wich contains block result N
cCNresult_block_result : WideString = 'result_block result';
// Name of class containing results
cCNaccount_content : WideString = 'account-content';
{$R *.dfm}
procedure TfrmMain.btnLoadPageClick(Sender: TObject);
var iLoadResult: integer;
begin
btnLoadPage.Enabled := false;
btnScan.Enabled := false;
// isPageLoaded := False;
try
iLoadResult := LoadPage(edtScanURL.Text);
finally
btnLoadPage.Enabled := True;
btnScan.Enabled := True;
end;
end;
procedure TfrmMain.btnScanClick(Sender: TObject);
begin
btnLoadPage.Enabled := false;
btnScan.Enabled := false;
try
ScanPage(wbBrowser);
finally
btnLoadPage.Enabled := True;
btnScan.Enabled := True;
end;
end;
function TfrmMain.LoadPage(aURL: WideString): integer;
begin
// isPageLoaded := False;
Result := READYSTATE_UNINITIALIZED;
wbBrowser.Navigate(edtScanURL.Text);
{
while wbBrowser.ReadyState = READYSTATE_LOADING do
begin
Sleep(100);
Application.ProcessMessages;
end;
}
repeat
Application.ProcessMessages;
until wbBrowser.ReadyState >= READYSTATE_COMPLETE;
Result := wbBrowser.ReadyState;
end;
procedure TfrmMain.ScanPage(aWebBrowser: TWebBrowser);
var
HtmlDocument: IHtmlDocument2;
HtmlCollection, HtmlResBlockCollection, HtmlOneResCollection: IHtmlElementCollection;
HtmlElement, HtmlResElement: IHtmlElement;
I, j: Integer;
begin
if wbBrowser.Document = nil then Exit;
mmoLog.Lines.Clear;
HtmlDocument := aWebBrowser.Document as IHtmlDocument2;
// HtmlCollection := HtmlDocument.All;
// HtmlCollection := HtmlDocument.All.tags('<div class="account-content">') as IHTMLElementCollection;
HtmlCollection := HtmlDocument.All.tags('div') as IHTMLElementCollection;
for i := 0 to HtmlCollection.Length - 1 do
begin
HtmlElement := HtmlCollection.Item(i, 0) as IHtmlElement;
if CompareStr(HtmlElement.className, cCNaccount_content) = 0 then
begin
HtmlResBlockCollection := HtmlElement.children as IHtmlElementCollection;
// mmoLog.Lines.Add(HtmlElement.TagName + #09 + HtmlElement.InnerText);
break;
end;
// if CompareStr(HtmlElement.className, cCNlottoName) = 0 then
{
if Pos(cCNresult_block_result, HtmlElement.className) > 0 then
begin
// mmoLog.Lines.Add(HtmlElement.className + ' --- ' + HtmlElement.InnerText);
HtmlResCollection := HtmlElement.children as IHtmlElementCollection;
for j := 0 to HtmlResCollection.length - 1 do
begin
HtmlResElement := HtmlResCollection.Item(j, 0) as IHtmlElement;
mmoLog.Lines.Add(HtmlResElement.className +
' --- ' + HtmlResElement.InnerText +
' +++ ' + HtmlResElement.outerText +
' *** ' + HtmlResElement.outerHTML);
end;
end;
}
end; // for
// Check result existance
if Assigned (HtmlResBlockCollection) then
begin
for i := 0 to HtmlResBlockCollection.Length - 1 do
begin
HtmlElement := HtmlResBlockCollection.Item(i, 0) as IHtmlElement;
mmoLog.Lines.Add(HtmlElement.className + ' --- ' + HtmlElement.InnerText);
if Pos(cCNresult_block_result, HtmlElement.className) > 0 then
begin
// mmoLog.Lines.Add(HtmlElement.className + ' --- ' + HtmlElement.InnerText);
HtmlOneResCollection := HtmlElement.children as IHtmlElementCollection;
for j := 0 to HtmlOneResCollection.length - 1 do
begin
HtmlResElement := HtmlOneResCollection.Item(j, 0) as IHtmlElement;
mmoLog.Lines.Add(HtmlResElement.className +
' --- ' + HtmlResElement.InnerText +
' +++ ' + HtmlResElement.outerText +
' *** ' + HtmlResElement.outerHTML);
end;
end;
end;
end;
end;
procedure TfrmMain.wbBrowserNavigateError(ASender: TObject;
const pDisp: IDispatch; const URL, Frame, StatusCode: OleVariant;
var Cancel: WordBool);
begin
MessageDlg('Navigate Error, status code = ' + IntToStr(StatusCode), mtError, [mbOK], 0);
end;
end.
|
unit HCSocket;
interface
uses
System.Classes, System.Generics.Collections, Net.CrossSocket, Net.CrossSocket.Base,
utils_buffer;
type
THCRDataEvent = procedure(const AConnection: ICrossConnection; const ADataStream: TBytesStream) of object;
THCRErrorEvent = procedure(const AError: string) of object;
IHCRSocket = interface(ICrossSocket)
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
function GetGraceful: Boolean;
procedure SetGraceful(const Value: Boolean);
function GetPort: Integer;
procedure SetPort(const Value: Integer);
function GetHost: string;
procedure SetHost(const Value: string);
function GetOnReceivedData: THCRDataEvent;
procedure SetOnReceivedData(const Value: THCRDataEvent);
function GetOnError: THCRErrorEvent;
procedure SetOnError(const Value: THCRErrorEvent);
procedure PostStream(var AStream: TBytesStream; const AConnectionIndex: Integer = 0); overload;
procedure PostStream(var AStream: TBytesStream; const AConnection: ICrossConnection); overload;
property Active: Boolean read GetActive write SetActive;
property Graceful: Boolean read GetGraceful write SetGraceful;
property Port: Integer read GetPort write SetPort;
property Host: string read GetHost write SetHost;
property OnReceiveData: THCRDataEvent read GetOnReceivedData write SetOnReceivedData;
property OnError: THCRErrorEvent read GetOnError write SetOnError;
end;
THCRSocket = class(TCrossSocket, IHCRSocket)
strict private
FHost: string;
FPort: Integer;
FGraceful: Boolean;
FOnReceivedData, FOnSentData: THCRDataEvent;
FOnError: THCRErrorEvent;
function DecodeRecvBuffer(const ABuffer: TBufferLink): TObject;
protected
function GetActive: Boolean; virtual;
procedure SetActive(const Value: Boolean); virtual;
procedure LogicConnected(AConnection: ICrossConnection); override;
procedure LogicDisconnected(AConnection: ICrossConnection); override;
procedure LogicReceived(AConnection: ICrossConnection; ABuf: Pointer; ALen: Integer); override;
function GetHost: string;
procedure SetHost(const Value: string);
function GetPort: Integer;
procedure SetPort(const Value: Integer);
function GetGraceful: Boolean;
procedure SetGraceful(const Value: Boolean);
function GetOnReceivedData: THCRDataEvent;
procedure SetOnReceivedData(const Value: THCRDataEvent);
function GetOnError: THCRErrorEvent;
procedure SetOnError(const Value: THCRErrorEvent);
public
constructor Create; virtual;
destructor Destroy; override;
procedure PostStream(var AStream: TBytesStream; const AConnectionIndex: Integer = 0); overload;
procedure PostStream(var AStream: TBytesStream; const AConnection: ICrossConnection); overload;
property Active: Boolean read GetActive write SetActive;
property Graceful: Boolean read GetGraceful write SetGraceful;
property Host: string read GetHost write SetHost;
property Port: Integer read GetPort write SetPort;
property OnReceiveData: THCRDataEvent read GetOnReceivedData write SetOnReceivedData;
property OnError: THCRErrorEvent read GetOnError write SetOnError;
end;
THCRServer = class(THCRSocket)
private
FActive: Boolean;
protected
function GetActive: Boolean; override;
procedure SetActive(const Value: Boolean); override;
public
constructor Create; override;
end;
THCRClient = class(THCRSocket)
private
FActive: Boolean;
protected
function GetActive: Boolean; override;
procedure SetActive(const Value: Boolean); override;
public
constructor Create; override;
end;
function LocalIP: String;
function IsLegalIP(const AIP: string): Boolean;
function GetIPSection(const AIP: string): string;
implementation
uses
System.SysUtils, Winapi.Winsock2;
function LocalIP: String;
type
TaPInAddr = Array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: Array[0..63] of AnsiChar;
i: Integer;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
try
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
i := 0;
while pPtr^[i] <> nil do
begin
Result := inet_ntoa(pptr^[i]^);
Inc(i);
end;
finally
WSACleanup;
end;
end;
{ 检查IP地址是否合法 }
function IsLegalIP(const AIP: string): Boolean;
{ 获得子字符串在父字符串中出现的次数 }
function GetSubStrCount(ASubStr, AParentStr: string): integer;
begin
Result := 0;
while Pos(UpperCase(ASubStr), UpperCase(AParentStr)) <> 0 do
begin
AParentStr := Copy(AParentStr, Pos(ASubStr, AParentStr) + 1, Length(AParentStr)); //假设s2最大长度为9999个字符
Result := Result + 1;
end;
end;
begin
{if inet_addr(PAnsiChar(AIP))=INADDR_NONE then
Result := False
else}
if (GetSubStrCount('.', AIP) = 3) and (Longword(inet_addr(PAnsiChar(AnsiString(AIP)))) <> INADDR_NONE) then
Result := True
else
Result := False;
end;
function GetIPSection(const AIP: string): string;
var
i: Integer;
begin
Result := '';
for i := Length(AIP) downto 1 do
begin
if AIP[i] = '.' then
begin
Result := Copy(AIP, 1, i) + '1';
Break;
end;
end;
end;
{ THCRSocket }
constructor THCRSocket.Create;
begin
inherited Create(0);
FHost := '0.0.0.0';
FPort := 0;
FGraceful := True;
end;
function THCRSocket.DecodeRecvBuffer(const ABuffer: TBufferLink): TObject;
var
vDataSize, vLen: Cardinal;
vDataProtoVer: Byte;
begin
Result := nil;
if ABuffer.validCount < SizeOf(Cardinal) then Exit; // 缓存中的数据长度不够表示数据长度
ABuffer.MarkReaderIndex; // 记录读取位置
ABuffer.ReadBuffer(@vDataSize, SizeOf(vDataSize)); // 数据长度
if vDataSize > 0 then
begin
if ABuffer.ValidCount < vDataSize - SizeOf(vDataSize) then // 不够完整的数据
begin
ABuffer.restoreReaderIndex;
Exit;
end;
ABuffer.ReadBuffer(@vDataProtoVer, SizeOf(vDataProtoVer)); // 读数据协议
vLen := vDataSize - SizeOf(vDataSize) - SizeOf(vDataProtoVer);
Result := TBytesStream.Create;
TBytesStream(Result).SetSize(vLen);
ABuffer.ReadBuffer(TMemoryStream(Result).Memory, vLen);
TBytesStream(Result).Position := 0;
{if FVerifyData then // 校验
begin
vActVerifyValue := VerifyData(TMemoryStream(Result).Memory^, vDataLen);
if vVerifyValue <> vActVerifyValue then
begin
sfLogger.logMessage(IntToHex(vVerifyValue) + '-' + IntToHex(vActVerifyValue));
raise Exception.Create(strRecvException_VerifyErr);
end;
end;}
//清理缓存<如果没有可用的内存块>清理
if ABuffer.ValidCount = 0 then
ABuffer.ClearBuffer
else
ABuffer.ClearHaveReadBuffer;
end
else // 不够完整
begin
Result := nil;
ABuffer.restoreReaderIndex;
end;
end;
destructor THCRSocket.Destroy;
begin
Active := False;
Self.StopLoop;
inherited Destroy;
end;
function THCRSocket.GetActive: Boolean;
begin
Result := False;
end;
function THCRSocket.GetGraceful: Boolean;
begin
Result := FGraceful;
end;
function THCRSocket.GetHost: string;
begin
Result := FHost;
end;
function THCRSocket.GetOnError: THCRErrorEvent;
begin
Result := FOnError;
end;
function THCRSocket.GetOnReceivedData: THCRDataEvent;
begin
Result := FOnReceivedData;
end;
function THCRSocket.GetPort: Integer;
begin
Result := FPort;
end;
procedure THCRSocket.LogicConnected(AConnection: ICrossConnection);
begin
inherited LogicConnected(AConnection);
AConnection.UserObject := TBufferLink.Create;
end;
procedure THCRSocket.LogicDisconnected(AConnection: ICrossConnection);
begin
inherited LogicDisconnected(AConnection);
Active := False;
if Assigned(AConnection.UserObject) then
TBufferLink(AConnection.UserObject).Free;
end;
procedure THCRSocket.LogicReceived(AConnection: ICrossConnection; ABuf: Pointer; ALen: Integer);
var
vRecvBuffer: TBufferLink;
vDecodeObj: TObject;
begin
inherited LogicReceived(AConnection, ABuf, ALen);
vRecvBuffer := AConnection.UserObject as TBufferLink;
vRecvBuffer.AddBuffer(ABuf, ALen);
vDecodeObj := DecodeRecvBuffer(vRecvBuffer);
if Integer(vDecodeObj) = -1 then // 错误的包格式, 关闭连接
begin
Active := False;
Exit;
end
else
if vDecodeObj <> nil then
begin
try
if Assigned(FOnReceivedData) then
FOnReceivedData(AConnection, TBytesStream(vDecodeObj));
finally
TBytesStream(vDecodeObj).Free;
end;
end;
end;
procedure THCRSocket.PostStream(var AStream: TBytesStream; const AConnectionIndex: Integer = 0);
var
vConns: TArray<ICrossConnection>;
begin
if AStream.Size = 0 then Exit;
vConns := LockConnections.Values.ToArray;
try
if Assigned(vConns) then
begin
if (AConnectionIndex >= 0) and (AConnectionIndex <= Length(vConns)) then
PostStream(AStream, vConns[AConnectionIndex]);
end;
finally
UnlockConnections;
end;
end;
procedure THCRSocket.PostStream(var AStream: TBytesStream;
const AConnection: ICrossConnection);
var
vStream: TBytesStream;
begin
if AStream.Size = 0 then Exit;
vStream := AStream;
AConnection.SendStream(AStream, procedure(AConnection: ICrossConnection; ASuccess: Boolean)
begin
vStream.Free;
end);
end;
procedure THCRSocket.SetActive(const Value: Boolean);
begin
end;
procedure THCRSocket.SetGraceful(const Value: Boolean);
begin
FGraceful := Value;
end;
procedure THCRSocket.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure THCRSocket.SetOnError(const Value: THCRErrorEvent);
begin
FOnError := Value;
end;
procedure THCRSocket.SetOnReceivedData(const Value: THCRDataEvent);
begin
FOnReceivedData := Value;
end;
procedure THCRSocket.SetPort(const Value: Integer);
begin
FPort := Value;
end;
{ THCRServer }
constructor THCRServer.Create;
begin
inherited Create;
FActive := False;
end;
function THCRServer.GetActive: Boolean;
begin
Result := FActive;
end;
procedure THCRServer.SetActive(const Value: Boolean);
begin
if FActive <> Value then
begin
FActive := Value;
if FActive then
begin
Self.Listen('0.0.0.0', Port, procedure(AListen: ICrossListen; ASuccess: Boolean)
begin
FActive := ASuccess;
if not FActive then
begin
if Assigned(OnError) then
OnError('服务端启动失败!');
end;
end);
end
else
begin
if Graceful then
DisconnectAll
else
CloseAllConnections;
end;
inherited SetActive(FActive);
end;
end;
{ THCRClient }
constructor THCRClient.Create;
begin
inherited Create;
FActive := False;
end;
function THCRClient.GetActive: Boolean;
begin
Result := FActive;
end;
procedure THCRClient.SetActive(const Value: Boolean);
begin
if FActive <> Value then
begin
FActive := Value;
if FActive then
begin
Self.Connect(Host, Port, procedure(AConnection: ICrossConnection; ASuccess: Boolean)
begin
FActive := ASuccess;
if not FActive then
begin
if Assigned(OnError) then
OnError('连接失败!');
end;
end);
end
else
begin
if Graceful then
DisconnectAll
else
CloseAllConnections;
end;
inherited SetActive(FActive);
end;
end;
{ TRecvData }
//constructor TRecvData.Create;
//begin
// inherited Create;
// Size := 0;
// Offset := 0;
// Stream := TBytesStream.Create;
//end;
//
//destructor TRecvData.Destroy;
//begin
// Stream.Free;
// inherited Destroy;
//end;
end.
|
unit ini_Group_unitM_Form;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, ToolWin, ComCtrls, Db, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery,
pFIBStoredProc, Menus, ActnList, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGridLevel,
cxGrid, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, cxDBData, cxTextEdit, ib_externals,
FIBDatabase, pFIBDatabase, Variants, pUtils;
type
Tini_Group_unitM_Form1 = class(TForm)
ToolBar1: TToolBar;
AddButton: TSpeedButton;
DelButton: TSpeedButton;
EditButton: TSpeedButton;
RefreshButton: TSpeedButton;
CloseButton: TSpeedButton;
DataSet: TpFIBDataSet;
StoredProc: TpFIBStoredProc;
SelectButton: TSpeedButton;
DataSource1: TDataSource;
PopupMenu: TPopupMenu;
AddPopup: TMenuItem;
EditPopup: TMenuItem;
DelPopup: TMenuItem;
N4: TMenuItem;
RefreshPopup: TMenuItem;
SelectPopup: TMenuItem;
ToolButton1: TToolButton;
ActionList: TActionList;
ActionMod: TAction;
ActionDel: TAction;
ActionAdd: TAction;
ActionSel: TAction;
ActionRefresh: TAction;
ActionExit: TAction;
DBGrid1: TcxGrid;
DBGrid1Level1: TcxGridLevel;
TableView: TcxGridDBTableView;
ID_GROUP_UNITM_Column: TcxGridDBColumn;
NAME_GROUP_UNITM_Column: TcxGridDBColumn;
Database: TpFIBDatabase;
pFIBTransaction1: TpFIBTransaction;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
pFIBTransaction2: TpFIBTransaction;
procedure RefreshButtonClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DelButtonClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
procedure DBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure DBGrid1DblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure AddPopupClick(Sender: TObject);
procedure EditPopupClick(Sender: TObject);
procedure DelPopupClick(Sender: TObject);
procedure RefreshPopupClick(Sender: TObject);
procedure SelectPopupClick(Sender: TObject);
procedure DBGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ActionModExecute(Sender: TObject);
procedure ActionDelExecute(Sender: TObject);
procedure ActionAddExecute(Sender: TObject);
procedure ActionSelExecute(Sender: TObject);
procedure ActionRefreshExecute(Sender: TObject);
procedure ActionExitExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
id_Group_unitM_Add : Integer;
id_pos : integer;
destructor Destroy; override;
end;
function ShowSprav(AOwner : TComponent; DBHandle : PVoid; fs : TFormStyle; id_unit_meas : int64) : Variant; stdcall;
exports ShowSprav;
implementation
uses ini_Group_UnitM_Form_Add;
{$R *.DFM}
function ShowSprav(AOwner : TComponent; DBHandle : PVoid; fs : TFormStyle; id_unit_meas : int64) : Variant; stdcall;
var
SpravForm : Tini_Group_unitM_Form1;
res : TResultArray;
begin
SpravForm := Tini_Group_unitM_Form1.Create(AOwner);
SpravForm.Database.Handle := DBHandle;
SpravForm.FormStyle := fs;
SpravForm.id_pos := id_unit_meas;
Result := NULL;
if fs = fsNormal then begin
if SpravForm.ShowModal = mrOK then begin
Result := VarArrayOf([SpravForm.DataSet.Fields[0].Value, SpravForm.DataSet.Fields[1].Value]);
end;
end;
end;
destructor Tini_Group_unitM_Form1.Destroy;
begin
inherited;
end;
procedure Tini_Group_unitM_Form1.RefreshButtonClick(Sender: TObject);
var
id_Key : integer;
begin
id_Key := DataSet['ID_GROUP_UNITM'];
DataSet.Active := False;
DataSet.Active := True;
DataSet.Locate('ID_GROUP_UNITM', id_Key, []);
end;
procedure Tini_Group_unitM_Form1.CloseButtonClick(Sender: TObject);
begin
if FormStyle = fsNormal then ModalResult := mrCancel
else Close;
end;
procedure Tini_Group_unitM_Form1.AddButtonClick(Sender: TObject);
var
AddForm : Tini_Group_UnitM_Form_Add1;
begin
AddForm := Tini_Group_UnitM_Form_Add1.Create(Self);
AddForm.Caption := 'Додати групу одиниць вимірювання';
AddForm.ShowModal;
if AddForm.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_ADD', [AddForm.Name_Group_unitM.Text]);
id_Group_unitM_Add := StoredProc.Fields[0].AsInteger;
StoredProc.Transaction.Commit;
RefreshButtonClick(Sender);
end;
AddForm.Free;
end;
procedure Tini_Group_unitM_Form1.EditButtonClick(Sender: TObject);
var
AddForm : Tini_Group_unitM_Form_Add1;
begin
if DataSet.Fields[0].AsString = '' then Exit;
AddForm := Tini_Group_UnitM_Form_Add1.Create(Self);
AddForm.Caption := 'Змінити групу одиниць вимірювання';
AddForm.Name_Group_unitM.Text := DataSet.Fields[1].AsString;
ini_Group_unitM_Form_Add.id_Group_unitM := DataSet.Fields[0].AsInteger;
AddForm.ShowModal;
if AddForm.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_MODIFY', [ini_Group_unitM_Form_Add.id_Group_unitM,
AddForm.Name_Group_unitM.Text]);
StoredProc.Transaction.Commit;
RefreshButtonClick(Sender);
end;
AddForm.Free;
end;
procedure Tini_Group_unitM_Form1.DelButtonClick(Sender: TObject);
begin
if DataSet.Fields[0].AsString = '' then Exit;
case MessageDlg('Ви дійсно бажаєте знищити цей запис?', mtConfirmation, [mbYes, mbNo], 0) of
mrYes :
begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_DEL', [DataSet.Fields[0].AsInteger]);
StoredProc.Transaction.Commit;
RefreshButtonClick(Sender);
end;
mrNo : Exit;
end;
end;
procedure Tini_Group_unitM_Form1.SelectButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure Tini_Group_unitM_Form1.DBGrid1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #27 then CloseButtonClick(Sender);
if SelectButton.Visible and (Key = #13) then SelectButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.DBGrid1DblClick(Sender: TObject);
begin
if SelectButton.Visible then SelectButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure Tini_Group_unitM_Form1.AddPopupClick(Sender: TObject);
begin
AddButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.EditPopupClick(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.DelPopupClick(Sender: TObject);
begin
DelButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.RefreshPopupClick(Sender: TObject);
begin
RefreshButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.SelectPopupClick(Sender: TObject);
begin
SelectButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.DBGrid1KeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_F5 then RefreshButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionModExecute(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionDelExecute(Sender: TObject);
begin
DelButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionAddExecute(Sender: TObject);
begin
AddButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionSelExecute(Sender: TObject);
begin
DBGrid1DblClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionRefreshExecute(Sender: TObject);
begin
RefreshButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.ActionExitExecute(Sender: TObject);
begin
CloseButtonClick(Sender);
end;
procedure Tini_Group_unitM_Form1.FormShow(Sender: TObject);
begin
DataSet.Active := False;
DataSet.SQLs.SelectSQL.Text := 'select * from PUB_SP_GROUP_UNITM_VIEW';
DataSet.Active := True;
if id_pos <> -1 then begin
id_pos := -1;
DataSet.Locate('ID_GROUP_UNITM', id_pos, []);
end;
end;
procedure Tini_Group_unitM_Form1.FormCreate(Sender: TObject);
begin
id_pos := -1;
end;
end.
|
program HowToUseVectorToDetermineAPath;
uses
SwinGame, sgTypes;
procedure Main();
var
origin: Point2D;
planetVector, ufoVector, resultant: Vector;
distance: LineSegment;
begin
OpenGraphicsWindow('Determine Vector Path', 800, 600);
ClearScreen(ColorWhite);
origin := PointAt(0, 0);
planetVector := VectorTo(700, 100);
ufoVector := VectorTo(150, 520);
LoadBitmapNamed('planet', 'planet.png');
LoadBitmapNamed('ufo', 'ufo.png');
repeat
ProcessEvents();
ClearScreen(ColorWhite);
resultant := SubtractVectors(planetVector, ufoVector);
distance := LineFromVector(ufoVector, resultant);
DrawBitmap ('planet', planetVector);
DrawBitmap ('ufo', ufoVector);
DrawLine(ColorBlue, origin, planetVector);
DrawLine(ColorRed, origin, ufoVector);
DrawLine(ColorGreen, distance);
RefreshScreen();
until WindowcloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit LogNTest;
interface
uses
DUnitX.TestFramework,
Math,
uIntX;
type
[TestFixture]
TLogNTest = class(TObject)
public
[Test]
procedure LogNBase10();
[Test]
procedure LogNBase2();
end;
implementation
[Test]
procedure TLogNTest.LogNBase10();
var
based, numberd, ans: Double;
number: TIntX;
begin
based := 10;
number := 100;
numberd := 100;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 10;
numberd := 10;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 500;
numberd := 500;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 1000;
numberd := 1000;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
end;
[Test]
procedure TLogNTest.LogNBase2();
var
based, numberd, ans: Double;
number: TIntX;
begin
based := 2;
number := 100;
numberd := 100;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 10;
numberd := 10;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 500;
numberd := 500;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := 1000;
numberd := 1000;
ans := Math.LogN(based, numberd);
Assert.IsTrue(TIntX.LogN(based, number) = ans);
number := TIntX.One shl 64 shl High(Int32);
Assert.IsTrue(TIntX.LogN(based, number) = 2147483711);
end;
initialization
TDUnitX.RegisterTestFixture(TLogNTest);
end.
|
unit EditVideo;
interface
uses
Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Objects,
FMX.Edit, FMX.ListBox,
EditVideoController,
Video;
type
TfrmEditVideo = class(TForm)
TopLabel: TLabel;
ButtonLayout: TLayout;
btCancel: TButton;
btSave: TButton;
BottomLayout: TLayout;
CenterLayout: TLayout;
NameLayout: TLayout;
edName: TEdit;
lbName: TLabel;
CenterLayout2: TLayout;
edFileLocation: TEdit;
lbFileLocation: TLabel;
btFile: TSpeedButton;
Image1: TImage;
Layout1: TLayout;
cbFormat: TComboBox;
lbFormat: TLabel;
btNewFormat: TSpeedButton;
Layout2: TLayout;
cbAlbum: TComboBox;
lbAlbum: TLabel;
btNewAlbum: TSpeedButton;
Layout3: TLayout;
cbArtist: TComboBox;
lbArtist: TLabel;
btNewArtist: TSpeedButton;
Layout4: TLayout;
edDurationMinutes: TEdit;
lbDuration: TLabel;
edDurationSeconds: TEdit;
Label1: TLabel;
procedure btSaveClick(Sender: TObject);
procedure btFileClick(Sender: TObject);
procedure btNewFormatClick(Sender: TObject);
procedure btNewArtistClick(Sender: TObject);
procedure btNewAlbumClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btCancelClick(Sender: TObject);
private
FController: TEditVideoController;
public
procedure LoadVideoFormats;
procedure LoadArtists;
procedure LoadAlbums;
procedure SetVideo(VideoId: Variant);
end;
implementation
uses
Aurelius.Engine.ObjectManager,
Artist, DBConnection, VideoFormat,
EditVideoFormat, EditArtist, EditAlbum,
MediaFile;
{$R *.fmx}
procedure TfrmEditVideo.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmEditVideo.btFileClick(Sender: TObject);
var
OpenDlg: TOpenDialog;
begin
OpenDlg := TOpenDialog.Create(Self);
try
OpenDlg.Options := [TOpenOption.ofFileMustExist];
if OpenDlg.Execute then
edFileLocation.Text := OpenDlg.FileName;
finally
OpenDlg.Free;
end;
end;
procedure TfrmEditVideo.btNewAlbumClick(Sender: TObject);
var
frmEditAlbum: TfrmEditAlbum;
begin
frmEditAlbum := TfrmEditAlbum.Create(Self);
try
frmEditAlbum.ShowModal;
if frmEditAlbum.ModalResult = mrOk then
begin
LoadAlbums;
CbAlbum.ItemIndex := CbAlbum.Items.Count - 1;
end;
finally
frmEditAlbum.Free;
end;
end;
procedure TfrmEditVideo.btNewArtistClick(Sender: TObject);
var
frmEditArtist: TfrmEditArtist;
begin
frmEditArtist := TfrmEditArtist.Create(Self);
try
frmEditArtist.ShowModal;
if frmEditArtist.ModalResult = mrOk then
begin
LoadArtists;
cbArtist.ItemIndex := cbArtist.Items.Count - 1;
end;
finally
frmEditArtist.Free;
end;
end;
procedure TfrmEditVideo.btNewFormatClick(Sender: TObject);
var
frmEditVideoFormat: TfrmEditVideoFormat;
begin
frmEditVideoFormat := TfrmEditVideoFormat.Create(Self);
try
frmEditVideoFormat.ShowModal;
if frmEditVideoFormat.ModalResult = mrOk then
begin
LoadVideoFormats;
cbFormat.ItemIndex := cbFormat.Items.Count - 1;
end;
finally
frmEditVideoFormat.Free;
end;
end;
procedure TfrmEditVideo.btSaveClick(Sender: TObject);
var
Video: TVideo;
Album: TAlbum;
Min, Sec: Word;
begin
Video := FController.Video;
Video.MediaName := edName.Text;
Video.FileLocation := edFileLocation.Text;
if cbFormat.ItemIndex >= 0 then
Video.VideoFormat := TVideoFormat(cbFormat.Items.Objects[cbFormat.ItemIndex]);
if cbArtist.ItemIndex >= 0 then
Video.Artist := TArtist(cbArtist.Items.Objects[cbArtist.ItemIndex]);
if CbAlbum.ItemIndex >= 0 then
begin
Album := TAlbum(CbAlbum.Items.Objects[CbAlbum.ItemIndex]);
Video.Album := Album;
end;
if (edDurationMinutes.Text <> '') and (edDurationSeconds.Text <> '') then
begin
Min := StrToInt(edDurationMinutes.Text);
Sec := StrToInt(edDurationSeconds.Text);
Video.Duration := Min * 60 + Sec;
end;
FController.SaveVideo(Video);
ModalResult := mrOk;
end;
procedure TfrmEditVideo.FormCreate(Sender: TObject);
begin
FController := TEditVideoController.Create;
LoadVideoFormats;
LoadArtists;
LoadAlbums;
end;
procedure TfrmEditVideo.FormDestroy(Sender: TObject);
begin
FController.Free;
end;
procedure TfrmEditVideo.LoadAlbums;
var
Albums: TList<TAlbum>;
Al: TAlbum;
begin
cbAlbum.Items.Clear;
Albums := FController.GetAlbums;
try
for Al in Albums do
CbAlbum.Items.AddObject(Al.AlbumName, Al);
finally
Albums.Free;
end;
end;
procedure TfrmEditVideo.LoadArtists;
var
Artists: TList<TArtist>;
A: TArtist;
begin
cbArtist.Items.Clear;
Artists := FController.GetArtists;
try
for A in Artists do
cbArtist.Items.AddObject(A.ArtistName, A);
finally
Artists.Free;
end;
end;
procedure TfrmEditVideo.LoadVideoFormats;
var
VideoFormats: TList<TVideoFormat>;
F: TVideoFormat;
begin
cbFormat.Items.Clear;
VideoFormats := FController.GetVideoFormats;
try
for F in VideoFormats do
cbFormat.Items.AddObject(F.FormatName, F);
finally
VideoFormats.Free;
end;
end;
procedure TfrmEditVideo.SetVideo(VideoId: Variant);
var
Video: TVideo;
begin
FController.Load(VideoId);
Video := FController.Video;
edName.Text := Video.MediaName;
edFileLocation.Text := Video.FileLocation;
cbFormat.ItemIndex := cbFormat.Items.IndexOfObject(Video.VideoFormat);
cbArtist.ItemIndex := cbArtist.Items.IndexOfObject(Video.Artist);
CbAlbum.ItemIndex := CbAlbum.Items.IndexOfObject(Video.Album);
if Video.Duration.HasValue then
begin
edDurationMinutes.Text := FormatFloat('#0', Video.Duration.Value div 60);
edDurationSeconds.Text := FormatFloat('00', Video.Duration.Value mod 60);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.