text stringlengths 14 6.51M |
|---|
unit TestBreakConditionalCompilation;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestBreakConditionalCompilation, released May 2005.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ AFS 26 April 03
test the linebreaking around $IFDEF options }
uses
{ delphi }
Classes,
{ DUnit }
BaseTestProcess,
{ local }
Converter, SettingsTypes, SetReturns;
type
TTestBreakConditionalCompilation = class(TBaseTestProcess)
private
{ the input file }
fsFileIn: string;
{ the saved settings }
feSaveRebreakLines: TWhenToRebreakLines;
fbPreProcessorEnabled: boolean;
feSaveBeforeCompilerDirectUses: TTriOptionStyle;
feSaveBeforeCompilerDirectStatements: TTriOptionStyle;
feSaveBeforeCompilerDirectGeneral: TTriOptionStyle;
feSaveAfterCompilerDirectUses: TTriOptionStyle;
feSaveAfterCompilerDirectStatements: TTriOptionStyle;
feSaveAfterCompilerDirectGeneral: TTriOptionStyle;
procedure CheckReplace(var ps: string; const psFind, psReplace: string);
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNoChange;
procedure TestUsesBreakBeforeAdd;
procedure TestUsesBreakBeforeRemove;
procedure TestUsesBreakAfterAdd;
procedure TestUsesBreakAfterRemove;
procedure TestCodeBreakBeforeAdd;
procedure TestCodeBreakBeforeRemove;
procedure TestCodeBreakAfterAdd;
procedure TestCodeBreakAfterRemove;
procedure TestGeneralBreakBeforeAdd;
procedure TestGeneralBreakBeforeRemove;
procedure TestGeneralBreakAfterAdd;
procedure TestGeneralBreakAfterRemove;
end;
implementation
uses
{ delphi }
SysUtils,
{ DUnit }
TestFramework,
{ local }
JcfStringUtils,
JcfUnicodeFiles,
JCFSettings;
procedure TTestBreakConditionalCompilation.Setup;
const
IN_FILE_NAME = '..\..\Test\TestCases\TestCondCompBreaks.pas';
var
leContentType: TFileContentType;
lsFileContents: WideString;
begin
inherited;
if FileExists(IN_FILE_NAME) then
begin
ReadTextFile(IN_FILE_NAME, lsFileContents, leContentType);
fsFileIn := string(lsFileContents);
end
else
begin
fsFileIn := '';
end;
{ store settings }
feSaveRebreakLines := JcfFormatSettings.Returns.RebreakLines;
JcfFormatSettings.Returns.RebreakLines := rbOff;
fbPreProcessorEnabled := JcfFormatSettings.PreProcessor.Enabled;
JcfFormatSettings.PreProcessor.Enabled := False;
feSaveBeforeCompilerDirectUses := JcfFormatSettings.Returns.BeforeCompilerDirectUses;
feSaveBeforeCompilerDirectStatements := JcfFormatSettings.Returns.BeforeCompilerDirectStatements;
feSaveBeforeCompilerDirectGeneral := JcfFormatSettings.Returns.BeforeCompilerDirectGeneral;
feSaveAfterCompilerDirectUses := JcfFormatSettings.Returns.AfterCompilerDirectUses;
feSaveAfterCompilerDirectStatements := JcfFormatSettings.Returns.AfterCompilerDirectStatements;
feSaveAfterCompilerDirectGeneral := JcfFormatSettings.Returns.AfterCompilerDirectGeneral;
end;
procedure TTestBreakConditionalCompilation.TearDown;
begin
{ restore settings }
JcfFormatSettings.Returns.RebreakLines := feSaveRebreakLines;
JcfFormatSettings.PreProcessor.Enabled := fbPreProcessorEnabled;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := feSaveBeforeCompilerDirectUses;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := feSaveBeforeCompilerDirectStatements;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := feSaveBeforeCompilerDirectGeneral;
JcfFormatSettings.Returns.AfterCompilerDirectUses := feSaveAfterCompilerDirectUses;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := feSaveAfterCompilerDirectStatements;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := feSaveAfterCompilerDirectGeneral;
inherited;
end;
procedure TTestBreakConditionalCompilation.CheckReplace(var ps: string;
const psFind, psReplace: string);
begin
Check(Pos(psFind, ps) > 0, string('String not found: ' + psFind));
StrReplace(ps, psFind, psReplace, [rfIgnoreCase]);
if Pos(psFind, psReplace) = 0 then
Check(Pos(psFind, ps) = 0, string('String still found' + psFind));
end;
procedure TTestBreakConditionalCompilation.TestNoChange;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
TestFormatResult(string(fsFileIn), string(fsFileIn));
end;
procedure TTestBreakConditionalCompilation.TestUsesBreakBeforeAdd;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
CheckReplace(lsFileOut, ' {$IFDEF BAR_RAISED}', NativeLineBreak + '{$IFDEF BAR_RAISED}');
CheckReplace(lsFileOut, ' {$ENDIF} Dialogs', NativeLineBreak + '{$ENDIF} Dialogs');
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestUsesBreakBeforeRemove;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
CheckReplace(fsFileIn, '{$IFDEF BAR_RAISED}', NativeLineBreak + '{$IFDEF BAR_RAISED}');
CheckReplace(fsFileIn, '{$ENDIF} Dialogs', NativeLineBreak + '{$ENDIF} Dialogs');
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestUsesBreakAfterAdd;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectUses := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
CheckReplace(lsFileOut, '{$IFDEF BAR_RAISED}', '{$IFDEF BAR_RAISED}' + NativeLineBreak + ' ');
CheckReplace(lsFileOut, 'Classes, {$ENDIF}', 'Classes, {$ENDIF}' + NativeLineBreak + ' ');
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestUsesBreakAfterRemove;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectUses := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := string(fsFileIn);
CheckReplace(fsFileIn, '{$IFDEF BAR_RAISED} ', '{$IFDEF BAR_RAISED}' + NativeLineBreak + ' ');
CheckReplace(fsFileIn, 'Classes, {$ENDIF} ', 'Classes, {$ENDIF}' + NativeLineBreak + ' ');
TestFormatResult(string(fsFileIn), lsFileOut);
end;
procedure TTestBreakConditionalCompilation.TestCodeBreakBeforeAdd;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
CheckReplace(fsFileIn, NativeLineBreak + ' {$IFDEF HAS_STUFF}', '{$IFDEF HAS_STUFF}');
CheckReplace(fsFileIn, NativeLineBreak + ' {$ENDIF}', '{$ENDIF}');
CheckReplace(lsFileOut, ' {$IFDEF HAS_STUFF}', '{$IFDEF HAS_STUFF}');
CheckReplace(lsFileOut, ' {$ENDIF}', '{$ENDIF}');
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestCodeBreakBeforeRemove;
var
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
CheckReplace(lsFileOut, NativeLineBreak + ' {$IFDEF HAS_STUFF}', ' {$IFDEF HAS_STUFF}');
CheckReplace(lsFileOut, NativeLineBreak + ' {$ENDIF}', ' {$ENDIF}');
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestCodeBreakAfterAdd;
var
lsPrefix: string;
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := string(fsFileIn);
lsPrefix := '{$IFDEF HAS_STUFF}';
CheckReplace(fsFileIn, lsPrefix + NativeLineBreak, lsPrefix);
lsPrefix := 'SomeStuff;' + NativeLineBreak + ' {$ENDIF}';
CheckReplace(fsFileIn, lsPrefix + NativeLineBreak, lsPrefix);
TestFormatResult(string(fsFileIn), lsFileOut);
end;
procedure TTestBreakConditionalCompilation.TestCodeBreakAfterRemove;
var
lsFileOut: string;
lsPrefix: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
lsFileOut := fsFileIn;
lsPrefix := '{$IFDEF HAS_STUFF}';
CheckReplace(lsFileOut, lsPrefix + NativeLineBreak, lsPrefix);
lsPrefix := 'SomeStuff;' + NativeLineBreak + ' {$ENDIF}';
CheckReplace(lsFileOut, lsPrefix + NativeLineBreak, lsPrefix);
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestGeneralBreakBeforeAdd;
var
lsFind, lsReplace: string;
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
lsFileOut := fsFileIn;
lsFind := NativeLineBreak + NativeLineBreak + '{$IFDEF SYM2}';
lsReplace := '{$IFDEF SYM2}';
CheckReplace(fsFileIn, lsFind, lsReplace);
lsFind := '''Black socks''; {$ENDIF}';
lsReplace := '''Black socks'';' + NativeLineBreak + NativeLineBreak + '{$ENDIF}';
CheckReplace(lsFileOut, lsFind, lsReplace);
lsFind := '{$IFDEF SYM2} ';
lsReplace := '{$IFDEF SYM2}' + NativeLineBreak + NativeLineBreak;
CheckReplace(lsFileOut, lsFind, lsReplace);
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestGeneralBreakAfterRemove;
var
lsFind, lsReplace: string;
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
lsFileOut := string(fsFileIn);
lsFind := '{$IFDEF SYM2}';
lsReplace := '{$IFDEF SYM2}' + NativeLineBreak + NativeLineBreak;
CheckReplace(fsFileIn, lsFind, lsReplace);
(*
lsReplace := '''Black socks'';' + NativeLineBreak + '{$ENDIF}';
lsFind := '''Black socks''; {$ENDIF}';
CheckReplace(fsFileIn, lsFind, lsReplace);
*)
TestFormatResult(string(fsFileIn), lsFileOut);
end;
procedure TTestBreakConditionalCompilation.TestGeneralBreakAfterAdd;
var
lsFind, lsReplace: string;
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eAlways;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
lsFileOut := fsFileIn;
lsFind := '{$IFDEF SYM2} ';
lsReplace := '{$IFDEF SYM2}' + NativeLineBreak;
CheckReplace(lsFileOut, lsFind, lsReplace);
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
procedure TTestBreakConditionalCompilation.TestGeneralBreakBeforeRemove;
var
lsFind, lsReplace: string;
lsFileOut: string;
begin
Check(fsFileIn <> '', 'No input file');
JcfFormatSettings.Returns.AfterCompilerDirectGeneral := eNever;
JcfFormatSettings.Returns.BeforeCompilerDirectGeneral := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectStatements := eLeave;
JcfFormatSettings.Returns.BeforeCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectUses := eLeave;
JcfFormatSettings.Returns.AfterCompilerDirectStatements := eLeave;
lsFileOut := fsFileIn;
lsFind := '{$IFDEF SYM2} ';
lsReplace := '{$IFDEF SYM2} ' + NativeLineBreak;
CheckReplace(fsFileIn, lsFind, lsReplace);
TestFormatResult(string(fsFileIn), string(lsFileOut));
end;
initialization
TestFramework.RegisterTest('Processes', TTestBreakConditionalCompilation.Suite);
end.
|
(**
This module contains a form for configuring the parts of the process that
are to be enabled.
@Author David Hoyle
@Version 1.0
@Date 04 Jan 2018
**)
Unit ITHelper.EnabledOptions;
Interface
Uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Buttons,
ITHelper.GlobalOptions,
ITHelper.Types;
{$INCLUDE 'CompilerDefinitions.inc'}
Type
(** A form to represent the form interface. **)
TfrmITHEnabledOptions = Class(TForm)
chkEnable: TCheckBox;
gbxOptions: TGroupBox;
btnOK: TBitBtn;
btnCancel: TBitBtn;
chkBefore: TCheckBox;
chkAfter: TCheckBox;
chkZip: TCheckBox;
chkIncBuild: TCheckBox;
chkBuildRes: TCheckBox;
chkCopyVerInfo: TCheckBox;
btnHelp: TBitBtn;
Procedure EnabledClick(Sender: TObject);
Procedure btnHelpClick(Sender: TObject);
Private
Public
{ Public declarations }
Class Function Execute(Const strProjectGroup: String; Var Options: TITHEnabledOptions) : Boolean;
End;
Implementation
{$R *.dfm}
Uses
ITHelper.TestingHelperUtils;
{ TForm2 }
(**
This is an on click event handler for the Help button.
@precon None.
@postcon Displays the Enabled Options help page.
@param Sender as a TObject
**)
Procedure TfrmITHEnabledOptions.btnHelpClick(Sender: TObject);
Const
strEnabledOptions = 'EnabledOptions';
Begin
HtmlHelp(0, PChar(ITHHTMLHelpFile(strEnabledOptions)), HH_DISPLAY_TOPIC, 0);
End;
(**
This is an on click event handler for the Enabled check box.
@precon None.
@postcon Enabled or disables the
@param Sender as a TObject
**)
Procedure TfrmITHEnabledOptions.EnabledClick(Sender: TObject);
Begin
gbxOptions.Enabled := chkEnable.Checked;
chkBefore.Enabled := chkEnable.Checked;
chkAfter.Enabled := chkEnable.Checked;
chkZip.Enabled := chkEnable.Checked;
chkIncBuild.Enabled := chkEnable.Checked;
chkCopyVerInfo.Enabled := chkEnable.Checked;
chkBuildRes.Enabled := chkEnable.Checked;
End;
(**
This is the forms main interface method for invoking the dialogue.
@precon None.
@postcon Invokes the dialogue with parameters passed as var parameters.
@param strProjectGroup as a String as a constant
@param Options as a TITHEnabledOptions as a reference
@return a Boolean
**)
Class Function TfrmITHEnabledOptions.Execute(Const strProjectGroup: String;
Var Options: TITHEnabledOptions): Boolean;
Const
strOptions = ' Options';
var
frm: TfrmITHEnabledOptions;
Begin
Result := False;
frm := TfrmITHEnabledOptions.Create(Nil);
Try
frm.Caption := strProjectGroup + strOptions;
frm.chkEnable.Checked := eoGroupEnabled In Options;
frm.EnabledClick(Nil);
frm.chkBefore.Checked := eoBefore In Options;
frm.chkAfter.Checked := eoAfter In Options;
frm.chkZip.Checked := eoZip In Options;
frm.chkIncBuild.Checked := eoIncrementBuild In Options;
frm.chkCopyVerInfo.Checked := eoCopyVersionInfo In Options;
frm.chkBuildRes.Checked := eoBuildVersionResource In Options;
If frm.ShowModal = mrOK Then
Begin
Options := [];
If frm.chkEnable.Checked Then
Include(Options, eoGroupEnabled);
If frm.chkBefore.Checked Then
Include(Options, eoBefore);
If frm.chkAfter.Checked Then
Include(Options, eoAfter);
If frm.chkZip.Checked Then
Include(Options, eoZip);
If frm.chkIncBuild.Checked Then
Include(Options, eoIncrementBuild);
If frm.chkBuildRes.Checked Then
Include(Options, eoBuildVersionResource);
If frm.chkCopyVerInfo.Checked Then
Include(Options, eoCopyVersionInfo);
Result := True;
End;
Finally
frm.Free;
End;
End;
End.
|
unit FIToolkit.Reports.Builder.Exceptions;
interface
uses
FIToolkit.Commons.Exceptions;
type
EReportsBuilderCommonException = class abstract (ECustomException);
{ Report builder exceptions }
EReportBuilderException = class abstract (EReportsBuilderCommonException);
{ Report template exceptions }
EReportTemplateException = class abstract (EReportsBuilderCommonException);
EInvalidReportTemplate = class (EReportTemplateException);
EReportTemplateLoadError = class (EReportTemplateException);
EReportTemplateParseError = class (EReportTemplateException);
implementation
uses
FIToolkit.Reports.Builder.Consts;
initialization
RegisterExceptionMessage(EInvalidReportTemplate, RSInvalidReportTemplate);
RegisterExceptionMessage(EReportTemplateLoadError, RSReportTemplateLoadError);
RegisterExceptionMessage(EReportTemplateParseError, RSReportTemplateParseError);
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
hrc: HGLRC;
mode : Boolean;
end;
const
Vertex1 : Array [0..9, 0..1] of GLFloat =
((-0.23678, 0.35118), (-0.23678, 0.7764),
(-0.37966, 0.7764), (-0.55, 0.60606),
(-0.55, -0.4), (-0.23576, -0.4),
(-0.23678, 0.35118), (-0.23576, -0.4),
(0.1375, -0.4), (0.13678, 0.35118));
Colors1 : Array [0..9, 0..2] of GLFloat =
((0.66, 0.3, 0.5), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.4), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.3), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.2), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.8), (0.55, 0.30, 0.8));
Edge1 : Array [0..9] of Boolean =
(True, True, True, True, True, False, False, True, False, True);
Vertex2 : Array [0..5, 0..1] of GLFloat =
((0.1375, -0.4), (0.45, -0.4),
(0.45, 0.60606), (0.27966, 0.7764),
(0.13678, 0.7764), (0.13678, 0.35118));
Colors2 : Array [0..5, 0..2] of GLFloat =
((0.66, 0.3, 0.8), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.8), (0.55, 0.30, 0.8),
(0.66, 0.3, 0.8), (0.55, 0.30, 0.8));
Edge2 : Array [0..5] of Boolean =
(True, True, True, True, True, False);
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
procedure glVertexPointer (size: GLint; atype: GLenum;
stride: GLsizei; data: pointer); stdcall; external OpenGL32;
procedure glColorPointer (size: GLint; atype: GLenum; stride: GLsizei;
data: pointer); stdcall; external OpenGL32;
procedure glDrawArrays (mode: GLenum; first: GLint; count: GLsizei);
stdcall; external OpenGL32;
procedure glEnableClientState (aarray: GLenum); stdcall; external OpenGL32;
procedure glDisableClientState (aarray: GLenum); stdcall; external OpenGL32;
procedure glEdgeFlagPointer (stride: GLsizei; data: pointer); stdcall; external OpenGL32;
const
GL_VERTEX_ARRAY = $8074;
GL_COLOR_ARRAY = $8076;
GL_EDGE_FLAG_ARRAY = $8079;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight);
// устанавливаем режим в зависимости от значения mode
If mode
then glPolygonMode (GL_FRONT_AND_BACK, GL_LINE)
else glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_EDGE_FLAG_ARRAY);
// glEnable (GL_EDGE_FLAG_ARRAY_EXT); // - согласно документации
glVertexPointer(2, GL_FLOAT, 0, @Vertex1);
glColorPointer(3, GL_FLOAT, 0, @Colors1);
glEdgeFlagPointer(1, @Edge1);
glDrawArrays(GL_POLYGON, 0, 10);
glVertexPointer(2, GL_FLOAT, 0, @Vertex2);
glColorPointer(3, GL_FLOAT, 0, @Colors2);
glEdgeFlagPointer(1, @Edge2);
glDrawArrays(GL_POLYGON, 0, 6);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_EDGE_FLAG_ARRAY);
SwapBuffers(Canvas.Handle);
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
mode := True;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_SPACE then begin
mode := not mode;
Refresh;
end;
end;
end.
|
unit WithdrawalDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzDBEdit,
RzEdit, Vcl.Mask, RzBtnEdt, Vcl.DBCtrls, RzDBCmbo;
type
TfrmWithdrawalDetail = class(TfrmBasePopupDetail)
dteWithdrawalDate: TRzDBDateTimeEdit;
edWithdrawn: TRzDBNumericEdit;
edCardNo: TRzEdit;
bteClient: TRzButtonEdit;
dbluAccount: TRzDBLookupComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure bteClientButtonClick(Sender: TObject);
private
{ Private declarations }
procedure GetClientBankAccounts;
public
{ Public declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
var
frmWithdrawalDetail: TfrmWithdrawalDetail;
implementation
{$R *.dfm}
{ TfrmWithdrawalDetail }
uses
PaymentData, IFinanceDialogs, Withdrawal, ActiveClientsSearch, ActiveClient;
procedure TfrmWithdrawalDetail.BindToObject;
begin
inherited;
end;
procedure TfrmWithdrawalDetail.bteClientButtonClick(Sender: TObject);
begin
with TfrmActiveClientsSearch.Create(self) do
begin
try
try
ShowModal;
if ModalResult = mrOK then
begin
wd.Client := activeCln;
bteClient.Text := activeCln.Name;
GetClientBankAccounts;
end;
except
on e: Exception do ShowErrorBox(e.Message);
end;
finally
Free;
end;
end;
end;
procedure TfrmWithdrawalDetail.Cancel;
begin
inherited;
end;
procedure TfrmWithdrawalDetail.GetClientBankAccounts;
begin
dbluAccount.ListSource.DataSet.Close;
dbluAccount.ListSource.DataSet.Open;
dbluAccount.Enabled := true;
end;
procedure TfrmWithdrawalDetail.Save;
begin
inherited;
wd.Save;
end;
function TfrmWithdrawalDetail.ValidEntry: boolean;
var
error: string;
begin
if dteWithdrawalDate.Text = '' then error := 'Please select a date.'
else if not Assigned(wd.Client) then error := 'No client selected.'
else if dbluAccount.Text = '' then error := 'Please select an account.'
else if edWithdrawn.Value <= 0 then error := 'Invalid value for amount.';
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
end.
|
{
unit Lang
ES: unidad para facilitar el cambio de idioma en los errores
EN: unit to facilitate the change of language of the errors
=========================================================================
History:
ver 1.3.2
ES:
mejora: se mejora la traducción al francés (gracias Fred)
EN:
improvement: best translation for French language (thanks Fred)
ver 1.3.1
ES:
error: la traducción al ruso estaba mal codificada (GC: issue 35)
EN:
bug: Russian translation is not read, incorrect encoding of the language resources file. (GC: issue 35)
ver 1.2.0
ES:
nuevo: añadido el idioma Húngaro (gracias Bógáncs Sándor)
nuevo: añadido el idioma italiano (gracias Vincenzo Scarpellino)
EN:
new: added Hungarian language (thanks Bógáncs Sándor)
new: added Italian language (thanks Vincenzo Scarpellino)
ver 1.0.0
ES:
nuevo: (issue GC4) añadido el idioma alemán (gracias Sascha)
error: corregido error en función GetTranslateText
nuevo: añadido el idioma ruso (gracias Teltikov Aleksandr)
EN:
new: (issue GC4) added German language (thanks Sascha)
bug: bug fixed in function GetTranslateText
new: added russian language (thanks Teltikov Aleksandr)
ver 0.1.9
ES:
nuevo: documentación
nuevo: añadido el idioma danés (gracias Hugo Pedersen)
EN:
new: documentation
new: added danish language (thanks Hugo Pedersen)
ver 0.1.7
ES:
nuevo: añadido el idioma portugués (gracias Moacir Fortes)
EN:
new: added portuguese language (thanks Moacir Fortes)
ver 0.1.6
ES:
nuevo: añadido el idioma francés (gracias Stéphane)
EN:
new: added french language (thanks Stéphane)
ver 0.1:
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
Lang unit contains strings messages error displayed by the components and a function to do the translation.
To add a new language you must be to do these steps:
- create a new constant array with all translations
- add the new language to set GMConstants.TLang
- change the GetTranslateText function by adding new language
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit Lang contiene las cadenas de los mensajes de error mostrados por los componentes y una función para realizar la traducción.
Para añadir un nuevo idioma se tendrán que hacer estos pasos:
- crear una nueva constante de tipo array con todas las traducciones
- añadir el nuevo idioma al conjunto GMConstants.TLang
- modificar la función GetTranslateText añadiendo el nuevo idioma del conjunto
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit Lang;
interface
uses
GMConstants;
const
{*------------------------------------------------------------------------------
Array with messages in Spanish
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en español
-------------------------------------------------------------------------------}
Lang_ESP: array[0..15] of string = (
'No se ha especificado el objeto WebBrowser', // 0
'Página inicial aun no cargada', // 1
'El mapa todavía no ha sido creado', // 2
'No está activo', // 3
'No se ha podido cargar el recurso', // 4
'Este objeto no tiene relación en JavaScript', // 5
'Id de JavaScript incorrecto', // 6
'Id de JavaScript inexistente', // 7
'Número de parámetros incorrecto', // 8
'Tipo de parámetro incorrecto', // 9
'Valor de parámetro incorrecto', // 10
'Índice fuera de rango', // 11
'Mapa no asignado', // 12
'El fichero no existe', // 13
'El número de columna es incorrecto', // 14
'Campo "%s" no encontrado en la tabla.' // 15
);
{*------------------------------------------------------------------------------
Array with messages in English
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en inglés
-------------------------------------------------------------------------------}
Lang_ENG: array[0..15] of string = (
'WebBrowser not defined', // 0
'Initial page not loaded', // 1
'The map is not yet created', // 2
'Not active', // 3
'Can''t load resource', // 4
'This object has no relation in JavaScript', // 5
'Id from JavaScript incorrect', // 6
'JavaScript Id does not exist', // 7
'Incorrect number of parameters', // 8
'Incorrect type parameter', // 9
'Incorrect value parameter', // 10
'Index out of range', // 11
'Map not assigned', // 12
'File does not exist', // 13
'The col number is incorrect', // 14
'Field "%s" not found into table.' // 15
);
{*------------------------------------------------------------------------------
Array with messages in French
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en francés
-------------------------------------------------------------------------------}
Lang_FRE: array[0..15] of string = (
'Navigateur Web non défini', // 0
'Page initiale non chargée', // 1
'La carte n''est pas encore créée', // 2
'Inactif', // 3
'Impossible de charger la ressource', // 4
'Cet object n''a pas de relation dans JavaScript', // 5
'Id JavaScript incorrect', // 6
'Id JavaScript inexistant', // 7
'Nombre incorrecte de paramètres', // 8
'Type de paramètre incorrect', // 9
'Valeur de paramètre incorrecte', // 10
'Indice hors limites', // 11
'Carte non attribuée', // 12
'Le fichier n''existe pas', // 13
'Le numéro de colonne est incorrect', // 14
'Champ "%s" introuvable dans la table.'// 15
);
{*------------------------------------------------------------------------------
Array with messages in Brazilian Portuguese
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en portugués de Brasil
-------------------------------------------------------------------------------}
Lang_PTBR: array[0..15] of string = (
'Navegador Web não definido', // 0
'Página inicial não foi carregada', // 1
'O mapa ainda não foi criado', // 2
'Inativo', // 3
'Não é possível carregar recursos', // 4
'Este objeto não tem relação em JavaScript', // 5
'Id do JavaScript incorreto', // 6
'Id do JavaScript não existe', // 7
'Número incorreto de parâmetros', // 8
'Tipo de parâmetro incorreto', // 9
'Valor do parâmetro incorreto', // 10
'Índice fora do intervalo', // 11
'Mapa não atribuído', // 12
'O arquivo não existe', // 13
'O número da coluna está errado', // 14
''
);
{*------------------------------------------------------------------------------
Array with messages in Danish
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en danés
-------------------------------------------------------------------------------}
Lang_DAN: array[0..15] of string = (
'WebBrowser ikke defineret', // 0
'Første side er ikke hentet', // 1
'Kortet er ikke dannet endnu', // 2
'Ikke aktiv', // 3
'Kan ikke hente ressource', // 4
'Dette object har ingen relation i JavaScript', // 5
'Id fra JavaScript er forkert', // 6
'JavaScript Id findes ikke', // 7
'Forkert antal parametre', // 8
'Forkert parameter type', // 9
'Forkert værdi parameter', // 10
'Index uden for område', // 11
'Kort ikke angivet', // 12
'Filen findes ikke', // 13
'Antal kolonner er forkert', // 14
''
);
{*------------------------------------------------------------------------------
Array with messages in German
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en alemán
-------------------------------------------------------------------------------}
Lang_GER: array[0..15] of string = (
'Webbrowser nicht definiert', // 0
'Initialisierungswebseite nicht geladen', // 1
'Die Karte wurde noch nicht erzeugt', // 2
'Nicht aktiv', // 3
'Kann die Resourcen nicht laden', // 4
'Dieses Objekt hat in JavaScript keine Zuordnung', // 5
'ID in JavaScript ungültig', // 6
'JavaScript ID existiert nicht', // 7
'Anzahl der Parameter ungültig', // 8
'Nicht korrketer Parametertyp', // 9
'Ungültiger Wert im Parameter', // 10
'Index ausserhalb des zulässigen Bereichs', // 11
'Karte nich zugewiesen', // 12
'Datei existiert nicht', // 13
'Die Spaltennummer ist ungültig', // 14
''
);
{*------------------------------------------------------------------------------
Array with messages in Russian
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en ruso
-------------------------------------------------------------------------------}
Lang_RUS: array[0..15] of string = (
'WebBrowser не определен', // 0
'Начальная страница не загружается', // 1
'Карта еще не создана', // 2
'Не активно', // 3
'Не могу загрузить ресурс', // 4
'Этот объект не JavaScript', // 5
'Id из JavaScript неверно', // 6
'JavaScript Id не существует', // 7
'Неверное количество параметров', // 8
'Неверный Тип параметра', // 9
'Неверное значение параметра', // 10
'Выход за границы индекса', // 11
'Карта не присвоен на уровне', // 12
'Файл не существует', // 13
'Неверный номер столбца', // 14
'Поле "%s" не найден в таблице.' // 15
);
{*------------------------------------------------------------------------------
Array with messages in Hungarian
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en Húngaro
-------------------------------------------------------------------------------}
Lang_HUN: array[0..15] of string = (
'WebBrowser nincs definiálva', // 0
'A kezdő oldal nincs betöltve', // 1
'A térkép még nem jött létre', // 2
'Nem aktív', // 3
'Nem lehet betölteni az erőforrást', // 4
'Ennek az objektumnak nincs JavaScript hivatkozása', // 5
'Érvénytelen JavaScript Id', // 6
'A JavaScript Id nem létezik', // 7
'Érvénytelen számú paraméter', // 8
'Érvénytelen paraméter típus', // 9
'Érvénytelen paraméter érték', // 10
'Tartományon kívüli index érték', // 11
'Nincs térkép kapcsolva', // 12
'A fájl nem létezik', // 13
'Hibás oszlop szám', // 14
''
);
{*------------------------------------------------------------------------------
Array with messages in Italian
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con los mensajes en Italiano
-------------------------------------------------------------------------------}
Lang_ITA: array[0..15] of string = (
'WebBrowser non definito', // 0
'La pagina iniziziale non è stata caricata', // 1
'La mappa non è ancora creata', // 2
'Non attivo', // 3
'Impossibile caricare la risorsa', // 4
'Questo oggetto non ha alcuna relazione in JavaScript', // 5
'Id da JavaScript non corretto', // 6
'Id da JavaScript inesistente', // 7
'Numero errato di parametri', // 8
'Tipo di parametro errato', // 9
'Valore del parametro errato', // 10
'Indice fuori intervallo', // 11
'Mappa non assegnata', // 12
'Il file non esiste', // 13
'Il numero di colonna è errato', // 14
''
);
{*------------------------------------------------------------------------------
GetTranslateText fucntion retrieves a translated string into the Lang language
@param Text string to translate
@param Lang destination language
@return translated string
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función GetTranslateText devuelve una cadena traducida al idioma Lang
@param Text cadena a traducir
@param Lang lenguaje destino
@return cadena traducida
-------------------------------------------------------------------------------}
function GetTranslateText(Text: string; Lang: TLang): string;
implementation
{ TLanguage }
function GetTranslateText(Text: string; Lang: TLang): string;
function GetIndex(Text: string): Integer;
begin
Result := 0;
while Result <= High(Lang_ESP) do
begin
if Text = Lang_ESP[Result] then Break;
Inc(Result);
end;
if Result > High(Lang_ESP) then Result := -1;
end;
var
Idx: Integer;
begin
Idx := GetIndex(Text);
if Idx = -1 then Result := Text
else
begin
case Lang of
English: Result := Lang_ENG[Idx];
French: Result := Lang_FRE[Idx];
PortuguesBR: Result := Lang_PTBR[Idx];
Danish: Result := Lang_DAN[Idx];
German: Result := Lang_GER[Idx];
Russian: Result := Lang_RUS[GetIndex(Text)];
Hungarian: Result := Lang_HUN[GetIndex(Text)];
Italian: Result := Lang_ITA[GetIndex(Text)];
else Result := Text;
end;
if Result = '' then Result := Text;
end;
end;
end.
|
unit CodeGenerator.IBX.Test;
interface
uses
DUnitX.TestFramework,
Base.Test;
{$M+}
type
[TestFixture]
TTestCodeGeneratorIBX = class(TTestBaseORM)
public
[Test]
procedure Test_InterfaceWithIBX();
[Test]
procedure Test_StartingIBXImpl();
[Test]
procedure Test_StartingIBXImplEx();
[Test]
procedure Test_IBXImpl_SaveTo();
end;
{$M-}
implementation
uses
System.Classes,
System.SysUtils,
IBX.IBDatabase,
IBX.IBCustomDataSet,
Persistence.CodeGenerator.Abstract,
Persistence.CodeGenerator.IBX,
Spring.Persistence.Mapping.CodeGenerator.Abstract;
procedure TTestCodeGeneratorIBX.Test_InterfaceWithIBX;
var
Actual: ICodeGenerator<TObject>;
begin
Actual := TCodeGenerator<TObject>.Create;
Actual.Database := Database;
Assert.IsNotNull(Actual);
Assert.IsNotNull(Actual.TablesWithField);
end;
procedure TTestCodeGeneratorIBX.Test_StartingIBXImpl;
var
Actual: ICodeGenerator<TIBDataBase>;
Code: string;
begin
Actual := TCodeGeneratorIBX.Create();
Actual.Database := Database;
Actual.Generate;
Assert.IsNotNull(Actual);
Assert.IsNotNull(Actual.TablesWithField);
Assert.AreEqual(10, Actual.TablesWithField.Count);
Code := Actual.TablesWithField.Items['CUSTOMER'];
Assert.IsTrue(Code.Length > 0);
Assert.IsTrue(Code.Contains('[Table(''CUSTOMER'', '''')]'));
Assert.IsTrue(Code.Contains('TCUSTOMER = class'));
Assert.IsTrue(Code.Contains('FCUST_NO: INTEGER;'));
Assert.IsTrue(Code.Contains('[AutoGenerated]'));
Assert.IsTrue(Code.Contains('[Column(''CUST_NO'',[cpRequired,cpPrimaryKey,cpNotNull])]'));
Assert.IsTrue(Code.Contains('property CUST_NO: INTEGER read FCUST_NO write FCUST_NO;'));
Assert.IsTrue(Code.Contains('[Column(''CONTACT_FIRST'',[],15)]'));
Assert.IsTrue(Code.Contains('property CONTACT_FIRST: VARCHAR read FCONTACT_FIRST write FCONTACT_FIRST;'));
end;
procedure TTestCodeGeneratorIBX.Test_StartingIBXImplEx;
var
Actual: ICodeGenerator<TIBDataBase>;
begin
Actual := TCodeGeneratorIBX.Create();
Assert.WillRaise(
procedure
begin
Actual.Generate;
end,
EArgumentNilException);
end;
procedure TTestCodeGeneratorIBX.Test_IBXImpl_SaveTo;
var
Actual: ICodeGenerator<TIBDataBase>;
begin
Actual := TCodeGeneratorIBX.Create();
Actual.Database := Database;
Actual.Generate;
Actual.SaveTo(
procedure(x: string)
begin
Assert.IsTrue(x.Contains('[Column('''), x);
Assert.IsTrue(x.Contains('property '), x);
end);
end;
initialization
TDUnitX.RegisterTestFixture(TTestCodeGeneratorIBX);
end.
|
unit GridSystem;
interface
uses
FMX.Dialogs, System.SysUtils, System.Types, FMX.Graphics, System.Classes, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Layouts,
GridSystem.Types,
System.TypInfo;
type
TGSLayout = class(TLayout)
private
{ private declarations }
FMinHeight: Single;
FAutoHeight: Boolean;
FFill: TBrush;
FSides: TSides;
FXRadius: Single;
FYRadius: Single;
FCorners: TCorners;
FCornerType: TCornerType;
function IsSidesStored: Boolean;
procedure SetMinHeight(const Value: Single);
function GetMinHeight: Single;
procedure SetAutoHeight(const Value: Boolean);
procedure SetFill(const Value: TBrush);
procedure SetSides(const Value: TSides);
procedure SetXRadius(const Value: Single);
procedure SetYRadius(const Value: Single);
procedure SetCorners(const Value: TCorners);
procedure SetCornerType(const Value: TCornerType);
protected
{ protected declarations }
procedure DoFillChange(Sender: TObject);
procedure Paint; override;
function CalcNewHeight: Single;
procedure DoRealign; override;
procedure Resize; override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ published declarations }
property MinHeight: Single read GetMinHeight write FMinHeight;
property AutoHeight: Boolean read FAutoHeight write SetAutoHeight;
property Fill: TBrush read FFill write SetFill;
property Sides: TSides read FSides write SetSides stored IsSidesStored;
property XRadius: Single read FXRadius write SetXRadius;
property YRadius: Single read FYRadius write SetYRadius;
property Corners: TCorners read FCorners write SetCorners;
property CornerType: TCornerType read FCornerType write SetCornerType default TCornerType.Round;
end;
TGSFlowLayout = class(TFlowLayout)
private
{ private declarations }
FMinHeight: Single;
FAutoHeight: Boolean;
FFill: TBrush;
FCornerType: TCornerType;
FCorners: TCorners;
FSides: TSides;
FXRadius: Single;
FYRadius: Single;
function IsSidesStored: Boolean;
procedure SetMinHeight(const Value: Single);
function GetMinHeight: Single;
procedure SetAutoHeight(const Value: Boolean);
procedure SetFill(const Value: TBrush);
procedure SetCorners(const Value: TCorners);
procedure SetCornerType(const Value: TCornerType);
procedure SetSides(const Value: TSides);
procedure SetXRadius(const Value: Single);
procedure SetYRadius(const Value: Single);
protected
{ protected declarations }
procedure Paint; override;
function CalcNewHeight: Single;
procedure DoRealign; override;
procedure Resize; override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ published declarations }
property MinHeight: Single read GetMinHeight write FMinHeight;
property AutoHeight: Boolean read FAutoHeight write SetAutoHeight;
property Fill: TBrush read FFill write SetFill;
property Sides: TSides read FSides write SetSides stored IsSidesStored;
property XRadius: Single read FXRadius write SetXRadius;
property YRadius: Single read FYRadius write SetYRadius;
property Corners: TCorners read FCorners write SetCorners;
property CornerType: TCornerType read FCornerType write SetCornerType default TCornerType.Round;
end;
TGSContainer = class(TGSLayout, IGSContainer)
private
{ private declarations }
protected
{ protected declarations }
function GetScreenType: TScreenType;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ published declarations }
property ScreenType: TScreenType read GetScreenType;
end;
TGSRow = class(TGSFlowLayout, IGSRow)
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
published
{ published declarations }
end;
TGSCol = class(TGSLayout, IGSCol)
private
{ private declarations }
FColumns: TGSColumnsDictionary;
FOnColumnsChanged: TNotifyEvent;
procedure SetColumns(const Value: TGSColumnsDictionary);
function GetColumns: TGSColumnsDictionary;
procedure DoValueNotify(Sender: TObject; const Item: GSColumnWidth; Action: TCollectionNotification);
protected
{ protected declarations }
procedure DoRealign; override;
procedure SetWidthByColumn;
procedure LoadCompProperty(Stream: TStream);
procedure StoreCompProperty(Stream: TStream);
procedure DefineProperties(Filer: TFiler); override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ published declarations }
property Columns: TGSColumnsDictionary read GetColumns write SetColumns;
end;
implementation
{ TGSContainer }
constructor TGSContainer.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TGSContainer.Destroy;
begin
inherited;
end;
function TGSContainer.GetScreenType: TScreenType;
begin
Result := TScreenType.ScreenExtraSmall;
if Width >= 576 then
Result := TScreenType.ScreenSmall;
if Width >= 768 then
Result := TScreenType.ScreenMedium;
if Width >= 992 then
Result := TScreenType.ScreenLarge;
if Width >= 1200 then
Result := TScreenType.ScreenExtraLarge;
end;
{ TGSCol }
constructor TGSCol.Create(AOwner: TComponent);
begin
inherited;
FColumns := TGSColumnsDictionary.Create;
FColumns.OnValueNotify := DoValueNotify;
end;
procedure TGSCol.DefineProperties(Filer: TFiler);
function DoWrite: Boolean;
begin
if Filer.Ancestor <> nil then
begin
Result := True;
if Filer.Ancestor is TGSCol then
begin
Result := True; // not Equals(TGSCol(Filer.Ancestor));
end
end
else
Result := Columns.Count > 0;
end;
begin
inherited;
Filer.DefineBinaryProperty('DataColumns', LoadCompProperty, StoreCompProperty, DoWrite);
end;
destructor TGSCol.Destroy;
begin
FColumns.Clear;
FColumns.Free;
inherited;
end;
procedure TGSCol.DoRealign;
begin
inherited;
SetWidthByColumn;
end;
procedure TGSCol.DoValueNotify(Sender: TObject; const Item: GSColumnWidth; Action: TCollectionNotification);
begin
SetWidthByColumn;
Realign;
end;
function TGSCol.GetColumns: TGSColumnsDictionary;
begin
Result := FColumns;
end;
procedure TGSCol.LoadCompProperty(Stream: TStream);
var
LStringList: TStringList;
LStrCount: Integer;
begin
LStringList := TStringList.Create;
try
LStringList.LoadFromStream(Stream);
Columns.Clear;
for LStrCount := 0 to LStringList.Count - 1 do
begin
Columns.Add(TScreenType(GetEnumValue(TypeInfo(TScreenType), LStringList.Names[LStrCount])),
LStringList.Values[LStringList.Names[LStrCount]].ToInteger);
end;
SetWidthByColumn;
Realign;
finally
FreeAndNil(LStringList);
end;
end;
procedure TGSCol.SetColumns(const Value: TGSColumnsDictionary);
begin
FColumns := Value;
end;
procedure TGSCol.SetWidthByColumn;
var
LGSRow: TGSRow;
LGSContainer: TGSContainer;
LColumnsCount: Integer;
LNewWidth: Single;
LColumnWidth: GSColumnWidth;
begin
if Supports(Parent, IGSRow) then
begin
LGSRow := Parent as TGSRow;
if Supports(LGSRow.Parent, IGSContainer) then
begin
LGSContainer := LGSRow.Parent as TGSContainer;
LNewWidth := TControl(LGSContainer).Width - Margins.Left - Margins.Right - 0.001;
if Columns.ContainsKey(LGSContainer.ScreenType) then
begin
LNewWidth := TControl(LGSContainer).Width * Columns.Items[LGSContainer.ScreenType] / High(GSColumnWidth) - Margins.Left -
Margins.Right - 0.001;
end
else
begin
for LColumnsCount := 0 to Integer(High(TScreenType)) do
begin
if Columns.TryGetValue(TScreenType(LColumnsCount), LColumnWidth) then
begin
LNewWidth := TControl(LGSContainer).Width * LColumnWidth / High(GSColumnWidth) - Margins.Left - Margins.Right - 0.001;
end;
if LGSContainer.ScreenType < TScreenType(LColumnsCount) then
Break;
end;
end;
Width := LNewWidth;
end;
end;
end;
procedure TGSCol.StoreCompProperty(Stream: TStream);
var
LKey: TScreenType;
LStrList: TStringList;
begin
if Columns <> nil then
begin
LStrList := TStringList.Create;
try
for LKey in FColumns.Keys do
begin
LStrList.AddPair(GetEnumName(TypeInfo(TScreenType), Integer(LKey)), IntToStr(Columns.Items[LKey]));
end;
finally
LStrList.SaveToStream(Stream);
FreeAndNil(LStrList);
SetWidthByColumn;
Realign;
end;
end;
end;
{ TGSLayout }
function TGSLayout.CalcNewHeight: Single;
function MaxBottomControl(Control: TControl): Single;
begin
if Control.Visible then
Result := Control.Position.Y + Control.Height + Control.Margins.Bottom + TControl(Control.Parent).Padding.Bottom
else
Result := 0;
end;
var
LControlsCount: Integer;
LNewHeight: Single;
begin
LNewHeight := FMinHeight;
for LControlsCount := 0 to ControlsCount - 1 do
begin
if MaxBottomControl(Controls[LControlsCount]) > LNewHeight then
LNewHeight := MaxBottomControl(Controls[LControlsCount]);
end;
Result := LNewHeight;
end;
constructor TGSLayout.Create(AOwner: TComponent);
begin
inherited;
CanParentFocus := True;
HitTest := False;
FMinHeight := 50;
FFill := TBrush.Create(TBrushKind.None, $FFFFFFFF);
FFill.OnChanged:= DoFillChange;
end;
destructor TGSLayout.Destroy;
begin
FreeAndNil(FFill);
inherited;
end;
procedure TGSLayout.DoFillChange(Sender: TObject);
begin
Repaint;
end;
procedure TGSLayout.DoRealign;
begin
inherited;
if FAutoHeight then
Self.Height := CalcNewHeight;
end;
function TGSLayout.GetMinHeight: Single;
begin
Result := FMinHeight;
end;
function TGSLayout.IsSidesStored: Boolean;
begin
Result := FSides * AllSides <> AllSides
end;
procedure TGSLayout.Paint;
var
LShapeRect: TRectF;
LOff: Single;
begin
inherited;
try
LShapeRect := TRectF.Create(0, 0, Width, Height);
if Sides <> AllSides then
begin
LOff := LShapeRect.Left;
if not(TSide.Top in FSides) then
LShapeRect.Top := LShapeRect.Top - LOff;
if not(TSide.Left in FSides) then
LShapeRect.Left := LShapeRect.Left - LOff;
if not(TSide.Bottom in FSides) then
LShapeRect.Bottom := LShapeRect.Bottom + LOff;
if not(TSide.Right in FSides) then
LShapeRect.Right := LShapeRect.Right + LOff;
Canvas.FillRect(LShapeRect, XRadius, YRadius, FCorners, AbsoluteOpacity, FFill, CornerType);
end
else
begin
Canvas.FillRect(LShapeRect, XRadius, YRadius, FCorners, AbsoluteOpacity, FFill, CornerType);
end;
finally
end;
end;
procedure TGSLayout.Resize;
begin
inherited;
Realign;
end;
procedure TGSLayout.SetAutoHeight(const Value: Boolean);
begin
FAutoHeight := Value;
end;
procedure TGSLayout.SetCorners(const Value: TCorners);
begin
FCorners := Value;
end;
procedure TGSLayout.SetCornerType(const Value: TCornerType);
begin
FCornerType := Value;
end;
procedure TGSLayout.SetFill(const Value: TBrush);
begin
FFill := Value;
end;
procedure TGSLayout.SetMinHeight(const Value: Single);
begin
FMinHeight := Value;
end;
procedure TGSLayout.SetSides(const Value: TSides);
begin
FSides := Value;
end;
procedure TGSLayout.SetXRadius(const Value: Single);
begin
FXRadius := Value;
end;
procedure TGSLayout.SetYRadius(const Value: Single);
begin
FYRadius := Value;
end;
{ TGSFlowLayout }
function TGSFlowLayout.CalcNewHeight: Single;
function MaxBottomControl(Control: TControl): Single;
begin
if Control.Visible then
Result := Control.Position.Y + Control.Height + Control.Margins.Bottom + TControl(Control.Parent).Padding.Bottom
else
Result := 0;
end;
var
LControlsCount: Integer;
LNewHeight: Single;
begin
LNewHeight := FMinHeight;
for LControlsCount := 0 to ControlsCount - 1 do
begin
if MaxBottomControl(Controls[LControlsCount]) > LNewHeight then
LNewHeight := MaxBottomControl(Controls[LControlsCount]);
end;
Result := LNewHeight;
end;
constructor TGSFlowLayout.Create(AOwner: TComponent);
begin
inherited;
CanParentFocus := True;
HitTest := False;
FMinHeight := 50;
FFill := TBrush.Create(TBrushKind.None, $FFFFFFFF);
end;
destructor TGSFlowLayout.Destroy;
begin
FreeAndNil(FFill);
inherited;
end;
procedure TGSFlowLayout.DoRealign;
begin
inherited;
if FAutoHeight then
Height := CalcNewHeight;
end;
function TGSFlowLayout.GetMinHeight: Single;
begin
Result := FMinHeight
end;
function TGSFlowLayout.IsSidesStored: Boolean;
begin
Result := FSides * AllSides <> AllSides
end;
procedure TGSFlowLayout.Paint;
var
LShapeRect: TRectF;
LOff: Single;
begin
inherited;
try
LShapeRect := TRectF.Create(0, 0, Width, Height);
if Sides <> AllSides then
begin
LOff := LShapeRect.Left;
if not(TSide.Top in FSides) then
LShapeRect.Top := LShapeRect.Top - LOff;
if not(TSide.Left in FSides) then
LShapeRect.Left := LShapeRect.Left - LOff;
if not(TSide.Bottom in FSides) then
LShapeRect.Bottom := LShapeRect.Bottom + LOff;
if not(TSide.Right in FSides) then
LShapeRect.Right := LShapeRect.Right + LOff;
Canvas.FillRect(LShapeRect, XRadius, YRadius, FCorners, AbsoluteOpacity, FFill, CornerType);
end
else
begin
Canvas.FillRect(LShapeRect, XRadius, YRadius, FCorners, AbsoluteOpacity, FFill, CornerType);
end;
finally
end;
end;
procedure TGSFlowLayout.Resize;
var
LControlsCount: Integer;
begin
inherited;
for LControlsCount := 0 to ControlsCount - 1 do
begin
if Supports(Controls[LControlsCount], IGSCol) then
begin
TGSCol(Controls[LControlsCount]).Realign;
end;
end;
Realign;
end;
procedure TGSFlowLayout.SetAutoHeight(const Value: Boolean);
begin
FAutoHeight := Value;
end;
procedure TGSFlowLayout.SetCorners(const Value: TCorners);
begin
FCorners := Value;
end;
procedure TGSFlowLayout.SetCornerType(const Value: TCornerType);
begin
FCornerType := Value;
end;
procedure TGSFlowLayout.SetFill(const Value: TBrush);
begin
FFill := Value;
end;
procedure TGSFlowLayout.SetMinHeight(const Value: Single);
begin
FMinHeight := Value;
end;
procedure TGSFlowLayout.SetSides(const Value: TSides);
begin
FSides := Value;
end;
procedure TGSFlowLayout.SetXRadius(const Value: Single);
begin
FXRadius := Value;
end;
procedure TGSFlowLayout.SetYRadius(const Value: Single);
begin
FYRadius := Value;
end;
end.
|
{***************************************************************
DESCRIPTION : Search and display CRC-16 Rocksoft Parameters
REQUIREMENTS : D3-D7/D9-D10/D12/D255
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODUS : Graphic
REFERENCES : [1] Ross Williams' public domain C sources crcmodel.c, crcmodel.h
in "A Painless Guide to CRC Error Detection Algorithms"
http://www.ross.net/crc/download/crc_v3.txt
[2] Greg Cook's Catalogue of Parameterised CRC Algorithms
http://reveng.sourceforge.net/crc-catalogue/
REMARK : - For Delphi2 ignore/remove all unsupported properties
- D25 tested with Tokyo Starter/Win32
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00 21.08.08 W.Ehrhardt Initial version
1.01 21.08.08 we Added ResMemo
1.02 21.08.08 we Reordered loops, bailout/running
1.03 21.08.08 we Fix logic for second data stet
1.04 21.08.08 we Stop button
1.05 09.09.08 we Clear/Load/Save buttons and actions
1.06 10.09.08 we Checkbox "List only verified"
1.07 10.09.08 we Test CRC1/CRC2 swap logic
1.08 10.09.08 we Check known algorithms
1.09 12.09.08 we Display checked data sets in memo
1.10 25.04.09 we Clear speed button
1.11 11.09.09 we Three data sets
1.12 01.10.09 we CRC-16/MAXIM, CRC-16/T10-DIF
1.13 01.10.09 we Swap 1/2 entries
1.14 04.10.09 we Full xorout loop if (polymin=polymax) and (initmin=initmax)
1.15 10.10.09 we Renamed to SRP16, info button, impoved initial directories logic
1.16 11.10.09 we Code clean up, D12 compatibility
1.17 11.10.09 we Bugfix "clear parameters": remove error color
1.18 13.03.10 we Added CRC16_DDS110, CRC16_TELEDISK to known algorithms
1.20 03.01.14 we CRC16_CDMA2000, CRC16_DECTX, CRC16_TMS37157
1.21 17.05.17 we 8 more known algorithms
1.21.1 12.06.18 we Lazarus adjustments
****************************************************************}
(*-------------------------------------------------------------------------
(C) Copyright 2008-2018 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
unit srp16u_l;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
{$i std.inc}
uses
{$IFnDEF FPC}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Buttons,
inifiles, mem_util, base2n, crc_sick, crcmodel, crcm_cat, ExtCtrls, Menus;
const
TB_Version = 'LazSRP16 V1.21';
type
TForm1 = class(TForm)
Button_Start: TBitBtn;
Button_Stop: TBitBtn;
CB_Format1: TComboBox;
CB_Format2: TComboBox;
CB_Format3: TComboBox;
CB_Poly: TComboBox;
CB_Verified: TCheckBox;
ECRC1: TEdit;
ECRC2: TEdit;
ECRC3: TEdit;
ECStr1: TEdit;
ECStr2: TEdit;
ECStr3: TEdit;
EInitMax: TEdit;
EInitMin: TEdit;
EPolyMax: TEdit;
EPolyMin: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Lab_Hdr: TLabel;
Lab_maxinit: TLabel;
Lab_maxpoly: TLabel;
Lab_mininit: TLabel;
Lab_minpoly: TLabel;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
PopupMenu1: TPopupMenu;
ResMemo: TMemo;
RE_Clear: TMenuItem;
RE_Insert: TMenuItem;
SaveDialog1: TSaveDialog;
SB_CheckKnown: TSpeedButton;
SB_Info: TSpeedButton;
SB_Load: TSpeedButton;
SB_New: TSpeedButton;
SB_RemSpaces: TSpeedButton;
SB_Save: TSpeedButton;
SB_Swap: TSpeedButton;
procedure FormCreate(Sender: TObject);
{-One-time initialization}
procedure ECStr1Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
procedure ECStr2Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
procedure ECStr3Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
procedure CB_Format1Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
procedure CB_Format2Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
procedure CB_Format3Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
procedure Button_StartClick(Sender: TObject);
{-Prepare data/parameters and start search loop}
procedure Button_StopClick(Sender: TObject);
{-Setup bailout and indicate search loop exit}
procedure SB_NewClick(Sender: TObject);
{-Clear search parameters/data}
procedure SB_LoadClick(Sender: TObject);
{-Load parameters from file}
procedure SB_SaveClick(Sender: TObject);
{-Save parameters to file}
procedure SB_CheckKnownClick(Sender: TObject);
{-Prepare data and check known algortithms}
procedure RE_InsertClick(Sender: TObject);
{-Insert data/CRC sets into text}
procedure RE_ClearClick(Sender: TObject);
{-Clear richedit result text}
procedure SB_RemSpacesClick(Sender: TObject);
{-Remove spaces from Hex data, add $ to Hex CRC}
procedure CB_PolyChange(Sender: TObject);
{-Fill min/max Poly from Poly combo box change}
procedure SB_SwapClick(Sender: TObject);
{-Swap sets 1 and 2}
procedure SB_InfoClick(Sender: TObject);
{-Show info}
private
{ Private declarations }
buf1,buf2,buf3: array[0..1023] of byte;
blen1,blen2,blen3: word;
initmin, initmax: word;
polymin, polymax: word;
tcrc1, tcrc1s: word;
tcrc2, tcrc2s: word;
tcrc3, tcrc3s: word;
bailout, running: boolean;
public
{ Public declarations }
procedure Check1;
{-Check input1, color warning if inv. Hex}
procedure Check2;
{-Check input2, color warning if inv. Hex}
procedure Check3;
{-Check input3, color warning if inv. Hex}
procedure SearchPara;
{-Main routine: search Rocksoft parameters for data/CRC sets}
procedure LoadBSF(const FName: string);
{-Load parameters from file}
procedure SaveBSF(const FName: string);
{-Save parameters to file}
procedure Chk1Known(const para: TCRCParam);
{-Check a single known algo given by TCRCParam}
procedure CheckSick;
{-Check CRC-16/Sick}
procedure CheckAllKnown;
{-Calculate and display CRCs for all crcm_cat 16 bit algorithms}
procedure DisplayData;
{-Insert data/CRC sets into text}
end;
var
Form1: TForm1;
implementation
{$IFnDEF FPC}
{$R *.dfm}
{$ELSE}
{$R *.lfm}
{$ENDIF}
var
CRCPara: TCRCParam = (poly : $0;
init : $ffff;
xorout: $ffff;
check : $0;
width : 16;
refin : true;
refout: true;
name : 'TEST');
{---------------------------------------------------------------------------}
function bool2str(b: boolean): string;
{-boolean to 'true'/'false'}
begin
if b then result:='true ' else result:='false';
end;
{---------------------------------------------------------------------------}
procedure TForm1.DisplayData;
{-Insert data/CRC sets into text}
var
l1,l2,l3: integer;
begin
l1 := length(ECStr1.Text);
l2 := length(ECStr2.Text);
l3 := length(ECStr3.Text);
if l1 or l2 or l3 > 0 then ResMemo.Lines.Append('Checked data sets');
if l1>0 then ResMemo.Lines.Append('CRC1: '+ECRC1.Text+', Data1: '+ECStr1.Text);
if l2>0 then ResMemo.Lines.Append('CRC2: '+ECRC2.Text+', Data2: '+ECStr2.Text);
if l3>0 then ResMemo.Lines.Append('CRC3: '+ECRC3.Text+', Data3: '+ECStr3.Text);
end;
{---------------------------------------------------------------------------}
procedure TForm1.Chk1Known(const para: TCRCParam);
{-Check a single known algo given by TCRCParam}
var
CRC1, CRC2, CRC3: longint;
ctx: TCRC_ctx;
s: string;
found: boolean;
begin
cm_Create(para,nil,ctx);
cm_Full(ctx, CRC1, @buf1, blen1);
found := false;
if (CRC1=tcrc1) or (CRC1=tcrc1s) then begin
ResMemo.Lines.Append('Found known algorithm: '+string(para.Name));
s := 'CRC=$'+string(HexWord(CRC1))+
' Poly=$'+string(HexWord(para.poly))+
' init=$'+string(HexWord(para.init))+
' xorout=$'+string(HexWord(para.xorout))+
' refin='+bool2str(para.refin)+
' refout='+bool2str(para.refout);
if (blen2>0) or (blen3>0) then begin
cm_Full(ctx, CRC2, @buf2, blen2);
cm_Full(ctx, CRC3, @buf3, blen3);
if ((CRC1=tcrc1) and (CRC2=tcrc2)) or ((CRC1=tcrc1s) and (CRC2=tcrc2s)) then begin
ResMemo.Lines.Append(s);
ResMemo.Lines.Append(' *** Second data set verified');
ResMemo.Update;
found := true;
end;
if (blen3>0) and (((CRC1=tcrc1) and (CRC3=tcrc3)) or ((CRC1=tcrc1s) and (CRC3=tcrc3s))) then begin
if not found then ResMemo.Lines.Append(s);
found := true;
ResMemo.Lines.Append(' *** Third data set verified');
ResMemo.Update;
end;
if (not CB_Verified.Checked) and (not found) then begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
end
else begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
Application.ProcessMessages;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CheckSick;
{-Check CRC-16/Sick}
var
CRC1, CRC2, CRC3: word;
s: string;
found: boolean;
begin
CRC_Sick_Full(CRC1, @buf1, blen1);
found := false;
if (CRC1=tcrc1) or (CRC1=tcrc1s) then begin
s := 'Found known algorithm: CRC-16/Sick. CRC=$'+string(HexWord(CRC1));
if (blen2>0) or (blen3>0) then begin
CRC_Sick_Full(CRC2, @buf2, blen2);
CRC_Sick_Full(CRC3, @buf3, blen3);
if ((CRC1=tcrc1) and (CRC2=tcrc2)) or ((CRC1=tcrc1s) and (CRC2=tcrc2s)) then begin
ResMemo.Lines.Append(s);
ResMemo.Lines.Append(' *** Second data set verified');
ResMemo.Update;
found := true;
end;
if (blen3>0) and (((CRC1=tcrc1) and (CRC3=tcrc3)) or ((CRC1=tcrc1s) and (CRC3=tcrc3s))) then begin
if not found then ResMemo.Lines.Append(s);
found := true;
ResMemo.Lines.Append(' *** Third data set verified');
ResMemo.Update;
end;
if (not CB_Verified.Checked) and (not found) then begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
end
else begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
Application.ProcessMessages;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CheckAllKnown;
{-Calculate and display CRCs for all crcm_cat 16 bit algorithms}
begin
ResMemo.Lines.Append('===== Checking for known algorithms =====');
DisplayData;
Chk1Known(CRC16_ARC);
Chk1Known(CRC16_ATOM);
Chk1Known(CRC16_AUG2_CITT);
Chk1Known(CRC16_AUG_CITT);
Chk1Known(CRC16_BT_CHIP);
Chk1Known(CRC16_BUYPASS);
Chk1Known(CRC16_CITT);
Chk1Known(CRC16_DNP);
Chk1Known(CRC16_EN_13757);
Chk1Known(CRC16_RIELLO);
Chk1Known(CRC16_ICODE);
Chk1Known(CRC16_KERMIT);
Chk1Known(CRC16_MCRF4XX);
Chk1Known(CRC16_MODBUS);
Chk1Known(CRC16_R);
Chk1Known(CRC16_USB);
Chk1Known(CRC16_X25);
Chk1Known(CRC16_XKERMIT);
Chk1Known(CRC16_ZMODEM);
Chk1Known(CRC16_MAXIM);
Chk1Known(CRC16_T10_DIF);
Chk1Known(CRC16_DDS110);
Chk1Known(CRC16_TELEDISK);
Chk1Known(CRC16_CDMA2000);
Chk1Known(CRC16_DECTX);
Chk1Known(CRC16_TMS37157);
Chk1Known(CRC16_A);
Chk1Known(CRC16_CMS);
Chk1Known(CRC16_GENIBUS);
Chk1Known(CRC16_GSM);
Chk1Known(CRC16_LJ1200);
Chk1Known(CRC16_OPENSAFETY_A);
Chk1Known(CRC16_OPENSAFETY_B);
Chk1Known(CRC16_PROFIBUS);
CheckSick;
ResMemo.Lines.Append('===== done =====');
ResMemo.Lines.Append('');
ResMemo.Update;
ResMemo.SetFocus;
ResMemo.SelStart := length(ResMemo.text);
end;
{---------------------------------------------------------------------------}
procedure TForm1.SearchPara;
{-Main routine: search Rocksoft parameters for data/CRC sets}
var
CRC1, CRC2, CRC3: longint;
p: word;
listall, found: boolean;
ref, tinit, txout, txmax: word;
s: string;
var
ctx: TCRC_ctx;
begin
ResMemo.Clear;
ResMemo.Lines.Add('===== Result parameter sets =====');
ResMemo.Update;
listall := not CB_Verified.Checked;
if (polymin=polymax) and (initmin=initmax) then txmax:=$FFFF else txmax:=1;
//TestKnown;
try
for p:=polymin to polymax do begin
CRCpara.poly := p;
for tinit:=initmin to initmax do begin
CRCpara.init := tinit;
for ref:=0 to 3 do begin
case ref of
0: begin CRCpara.refin := false; CRCpara.refout := false; end;
1: begin CRCpara.refin := true; CRCpara.refout := true; end;
2: begin CRCpara.refin := false; CRCpara.refout := true; end;
3: begin CRCpara.refin := true; CRCpara.refout := false; end;
end;
for txout:=0 to txmax do begin
if bailout then exit;
if txmax=1 then CRCpara.xorout := txout*$FFFF
else CRCpara.xorout := txout;
cm_Create(CRCPara,nil,ctx);
cm_Full(ctx, CRC1, @buf1, blen1);
found := false;
if (CRC1=tcrc1) or (CRC1=tcrc1s) then begin
s := 'CRC=$'+string(HexWord(CRC1))+
' Poly=$'+string(HexWord(CRCpara.poly))+
' init=$'+string(HexWord(CRCpara.init))+
' xorout=$'+string(HexWord(CRCpara.xorout))+
' refin='+bool2str(CRCpara.refin)+
' refout='+bool2str(CRCpara.refout);
if (blen2>0) or (blen3>0) then begin
cm_Full(ctx, CRC2, @buf2, blen2);
cm_Full(ctx, CRC3, @buf3, blen3);
if (blen2>0) and (((CRC1=tcrc1) and (CRC2=tcrc2)) or ((CRC1=tcrc1s) and (CRC2=tcrc2s))) then begin
found := true;
ResMemo.Lines.Append(s);
ResMemo.Lines.Append(' *** Second data set verified');
ResMemo.Update;
end;
if (blen3>0) and (((CRC1=tcrc1) and (CRC3=tcrc3)) or ((CRC1=tcrc1s) and (CRC3=tcrc3s))) then begin
if not found then ResMemo.Lines.Append(s);
found := true;
ResMemo.Lines.Append(' *** Third data set verified');
ResMemo.Update;
end;
if listall and (not found) then begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
end
else begin
ResMemo.Lines.Append(s);
ResMemo.Update;
end;
Application.ProcessMessages;
end;
end; {for txout}
end; {for ref}
end; {for tinit}
end; {for poly}
finally
ResMemo.Lines.Append('===== done =====');
ResMemo.Lines.Append('');
ResMemo.Update;
ResMemo.SetFocus;
ResMemo.SelStart := length(ResMemo.text);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.Check1;
{-Check input1, color warning if inv. Hex}
var
s: string;
i: integer;
HOK: boolean;
begin
s := ECStr1.Text;
if length(s)>sizeof(buf1) then SetLength(s,sizeof(buf1));
blen1 := length(s);
if CB_Format1.Itemindex=1 then begin
{string input, copy char to buf bytes}
for i:=1 to blen1 do buf1[i-1] := byte(s[i]);
ECstr1.Color := clWindow;
end
else begin
{Hex input, first check for invalid chars}
HOK := true;
for i:=1 to blen1 do begin
if pos(upcase(s[i]),'0123456789ABCDEF')=0 then begin
HOK := false;
break;
end;
end;
if HOK then begin
ECstr1.Color := clWindow;
end
else begin
ECstr1.Color := clYellow;
end;
{Convert hex string to memory at buf, stops at first invalid}
DecodeBase16AStr({$ifdef D12Plus} ansistring {$endif}(s), @buf1, sizeof(buf1),blen1);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.Check2;
{-Check input2, color warning if inv. Hex}
var
s: string;
i: integer;
HOK: boolean;
begin
s := ECStr2.Text;
if length(s)>sizeof(buf2) then SetLength(s,sizeof(buf2));
blen2 := length(s);
if CB_Format2.Itemindex=1 then begin
{string input, copy char to buf bytes}
for i:=1 to blen2 do buf2[i-1] := byte(s[i]);
ECstr2.Color := clWindow;
end
else begin
{Hex input, first check for invalid chars}
HOK := true;
for i:=1 to blen2 do begin
if pos(upcase(s[i]),'0123456789ABCDEF')=0 then begin
HOK := false;
break;
end;
end;
if HOK then begin
ECstr2.Color := clWindow;
end
else begin
ECstr2.Color := clYellow;
end;
{Convert hex string to memory at buf, stops at first invalid}
DecodeBase16AStr({$ifdef D12Plus} ansistring {$endif}(s), @buf2, sizeof(buf2),blen2);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.Check3;
{-Check input3, color warning if inv. Hex}
var
s: string;
i: integer;
HOK: boolean;
begin
s := ECStr3.Text;
if length(s)>sizeof(buf3) then SetLength(s,sizeof(buf3));
blen3 := length(s);
if CB_Format3.Itemindex=1 then begin
{string input, copy char to buf bytes}
for i:=1 to blen3 do buf3[i-1] := byte(s[i]);
ECstr3.Color := clWindow;
end
else begin
{Hex input, first check for invalid chars}
HOK := true;
for i:=1 to blen3 do begin
if pos(upcase(s[i]),'0123456789ABCDEF')=0 then begin
HOK := false;
break;
end;
end;
if HOK then begin
ECstr3.Color := clWindow;
end
else begin
ECstr3.Color := clYellow;
end;
{Convert hex string to memory at buf, stops at first invalid}
DecodeBase16AStr({$ifdef D12Plus} ansistring {$endif}(s), @buf3, sizeof(buf3),blen3);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.LoadBSF(const FName: string);
{-Load parameters from file}
var
IniFile: TIniFile;
i1,i2,i3: integer;
begin
IniFile := TIniFile.Create(Fname);
try
ECRC1.Text := IniFile.ReadString('SRP-Para','CRC1_Value','');
ECRC2.Text := IniFile.ReadString('SRP-Para','CRC2_Value','');
ECRC3.Text := IniFile.ReadString('SRP-Para','CRC3_Value','');
ECStr1.Text := IniFile.ReadString('SRP-Para','CRC1_String','');
ECStr2.Text := IniFile.ReadString('SRP-Para','CRC2_String','');
ECStr3.Text := IniFile.ReadString('SRP-Para','CRC3_String','');
i1 := IniFile.ReadInteger('SRP-Para','CRC1_Format',0);
i2 := IniFile.ReadInteger('SRP-Para','CRC2_Format',0);
i3 := IniFile.ReadInteger('SRP-Para','CRC3_Format',0);
if i1 in [0,1] then CB_Format1.Itemindex := i1;
if i2 in [0,1] then CB_Format2.Itemindex := i2;
if i3 in [0,1] then CB_Format3.Itemindex := i2;
CB_Poly.Text := IniFile.ReadString('SRP-Para','Poly','');
EPolyMin.Text := IniFile.ReadString('SRP-Para','PolyMin','');
EPolyMax.Text := IniFile.ReadString('SRP-Para','PolyMax','');
EInitMin.Text := IniFile.ReadString('SRP-Para','InitMin','');
EInitMax.Text := IniFile.ReadString('SRP-Para','InitMax','');
Check1;
Check2;
Check3;
finally
IniFile.Free;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SaveBSF(const FName: string);
{-Save parameters to file}
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(Fname);
try
IniFile.EraseSection('SRP-Para');
IniFile.WriteString ('SRP-Para','CRC1_Value',ECRC1.Text);
IniFile.WriteString ('SRP-Para','CRC2_Value',ECRC2.Text);
IniFile.WriteString ('SRP-Para','CRC3_Value',ECRC3.Text);
IniFile.WriteInteger('SRP-Para','CRC1_Format',CB_Format1.Itemindex);
IniFile.WriteInteger('SRP-Para','CRC2_Format',CB_Format2.Itemindex);
IniFile.WriteInteger('SRP-Para','CRC3_Format',CB_Format3.Itemindex);
IniFile.WriteString ('SRP-Para','CRC1_String',ECStr1.Text);
IniFile.WriteString ('SRP-Para','CRC2_String',ECStr2.Text);
IniFile.WriteString ('SRP-Para','CRC3_String',ECStr3.Text);
IniFile.WriteString ('SRP-Para','Poly', CB_Poly.Text);
IniFile.WriteString ('SRP-Para','PolyMin',EPolyMin.Text);
IniFile.WriteString ('SRP-Para','PolyMax',EPolyMax.Text);
IniFile.WriteString ('SRP-Para','InitMin',EInitMin.Text);
IniFile.WriteString ('SRP-Para','InitMax',EInitMax.Text);
finally
IniFile.Free;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.FormCreate(Sender: TObject);
{-One-time initialization}
begin
CB_Format1.Itemindex := 0;
CB_Format2.Itemindex := 0;
CB_Format3.Itemindex := 0;
CB_Poly.Itemindex := 0;
Lab_Hdr.Caption := TB_Version + ' | Search and display CRC16 Rocksoft parameters';
end;
{---------------------------------------------------------------------------}
procedure TForm1.ECStr1Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
begin
if ECStr1.Modified then Check1;
end;
{---------------------------------------------------------------------------}
procedure TForm1.ECStr2Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
begin
if ECStr2.Modified then Check2;
end;
{---------------------------------------------------------------------------}
procedure TForm1.ECStr3Change(Sender: TObject);
{-(Re)calculate and display CRCs if input changed}
begin
if ECStr3.Modified then Check3;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CB_Format1Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
begin
Check1;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CB_Format2Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
begin
Check2;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CB_Format3Change(Sender: TObject);
{-(Re)calculate and display CRCs if input format changed}
begin
Check2;
end;
{---------------------------------------------------------------------------}
procedure TForm1.Button_StartClick(Sender: TObject);
{-Prepare data/parameters and start search loop}
begin
Check1;
Check2;
Check3;
if blen1 > 0 then begin
tcrc1 := StrToInt(ECRC1.Text);
tcrc1s := swap(tcrc1);
if blen2>0 then begin
tcrc2 := StrToInt(ECRC2.Text);
tcrc2s := swap(tcrc2);
end;
if blen3>0 then begin
tcrc3 := StrToInt(ECRC3.Text);
tcrc3s := swap(tcrc3);
end;
initmin := StrToIntDef(EInitMin.Text,0);
initmax := StrToIntDef(EInitMax.Text,$FFFF);
polymin := StrToIntDef(EPolyMin.Text,1);
polymax := StrToIntDef(EPolyMax.Text,$FFFF);
Button_Start.Enabled := false;
Button_Stop.Enabled := true;
bailout := false;
running := true;
SearchPara;
running := false;
Button_Stop.Enabled := false;
Button_Start.Enabled := true;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.Button_StopClick(Sender: TObject);
{-Setup bailout and indicate search loop exit}
begin
bailout := true;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_NewClick(Sender: TObject);
{-Clear search parameters/data}
begin
if MessageDlg('Clear parameters?', mtConfirmation, [mbYes, mbNo], 0)=mrYes then begin
ECRC1.Text := '';
ECRC2.Text := '';
ECRC3.Text := '';
ECStr1.Text := '';
ECStr2.Text := '';
ECStr3.Text := '';
CB_Format1.Itemindex := 0;
CB_Format2.Itemindex := 0;
CB_Format3.Itemindex := 0;
CB_Poly.Itemindex := 0;
EPolyMin.Text := '';
EPolyMax.Text := '';
EInitMin.Text := '';
EInitMax.Text := '';
ECstr1.Color := clWindow;
ECstr2.Color := clWindow;
ECstr3.Color := clWindow;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_LoadClick(Sender: TObject);
{-Load parameters from file}
begin
if Opendialog1.InitialDir='' then Opendialog1.InitialDir := Savedialog1.InitialDir;
if Opendialog1.InitialDir='' then Opendialog1.InitialDir := ExtractFilePath(Application.ExeName);
if Opendialog1.Execute then begin
LoadBSF(Opendialog1.Filename);
Opendialog1.InitialDir := ExtractFilePath(Opendialog1.Filename);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_SaveClick(Sender: TObject);
{-Save parameters to file}
begin
if Savedialog1.InitialDir='' then Savedialog1.InitialDir := Opendialog1.InitialDir;
if Savedialog1.InitialDir='' then Savedialog1.InitialDir := ExtractFilePath(Application.ExeName);
if Savedialog1.Execute then begin
SaveBSF(Savedialog1.Filename);
Savedialog1.InitialDir := ExtractFilePath(Savedialog1.Filename);
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_CheckKnownClick(Sender: TObject);
{-Prepare data and check known algortithms}
begin
Check1;
Check2;
Check3;
if blen1 > 0 then begin
tcrc1 := StrToInt(ECRC1.Text);
tcrc1s := swap(tcrc1);
if blen2>0 then begin
tcrc2 := StrToInt(ECRC2.Text);
tcrc2s := swap(tcrc2);
end;
if blen3>0 then begin
tcrc3 := StrToInt(ECRC3.Text);
tcrc3s := swap(tcrc3);
end;
CheckAllKnown;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.RE_InsertClick(Sender: TObject);
{-Insert data/CRC sets into text}
begin
DisplayData;
end;
{---------------------------------------------------------------------------}
procedure TForm1.RE_ClearClick(Sender: TObject);
{-Clear richedit result text}
begin
ResMemo.Clear;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_RemSpacesClick(Sender: TObject);
{-Remove spaces from Hex data, add $ to Hex CRC}
var
s: string;
i: integer;
begin
{Remove spaces if HEX format}
if CB_Format1.Itemindex=0 then begin
s := ECStr1.Text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
ECStr1.Text := s;
end;
{Remove spaces if HEX format}
if CB_Format2.Itemindex=0 then begin
s := ECStr2.Text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
ECStr2.Text := s;
end;
{Remove spaces if HEX format}
if CB_Format3.Itemindex=0 then begin
s := ECStr3.Text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
ECStr3.Text := s;
end;
Check1;
Check2;
Check3;
{Insert $ if CRC contains HEX char}
s := ECRC1.text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
if (s<>'') and (s[1]<>'$') then begin
for i:=1 to length(s) do begin
if pos(upcase(s[i]),'ABCDEF')>0 then begin
s := '$'+s;
ECRC1.text := s;
break;
end;
end;
end;
{Insert $ if CRC contains HEX char}
s := ECRC2.text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
if (s<>'') and (s[1]<>'$') then begin
for i:=1 to length(s) do begin
if pos(upcase(s[i]),'ABCDEF')>0 then begin
s := '$'+s;
ECRC2.text := s;
break;
end;
end;
end;
{Insert $ if CRC contains HEX char}
s := ECRC3.text;
i := pos(' ',s);
while i>0 do begin
delete(s,i,1);
i := pos(' ',s);
end;
if (s<>'') and (s[1]<>'$') then begin
for i:=1 to length(s) do begin
if pos(upcase(s[i]),'ABCDEF')>0 then begin
s := '$'+s;
ECRC3.text := s;
break;
end;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.CB_PolyChange(Sender: TObject);
{-Fill min/max Poly from Poly combo box change}
begin
EPolyMin.Text := CB_Poly.Text;
EPolyMax.Text := CB_Poly.Text;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_SwapClick(Sender: TObject);
{-Swap sets 1 and 2}
var
t: string;
i : integer;
begin
if (ECRC2.Text<>'') and (ECStr2.Text<>'') then begin
t := ECRC2.Text;
ECRC2.Text := ECRC1.Text;
ECRC1.Text := t;
t := ECStr2.Text;
ECStr2.Text := ECStr1.Text;
ECStr1.Text := t;
i := CB_Format2.Itemindex;
CB_Format2.Itemindex := CB_Format1.Itemindex;
CB_Format1.Itemindex := i;
Check1;
Check2;
end;
end;
{---------------------------------------------------------------------------}
procedure TForm1.SB_InfoClick(Sender: TObject);
{-Show info}
begin
MessageDlg( TB_Version+' (c) 2008-2018 W.Ehrhardt'+#13+#10
+'Open source freeware demo for searching CRC16 Rocksoft parameters'+#13+#10
+''+#13+#10
+'Search and display logic:'+#13+#10
+''+#13+#10
+'1. Enter up to three CRC/Data pairs'+#13+#10
+'2a. If you know the poly, enter it into Min.poly and Max.poly'+#13+#10
+'2b. If you know the init value, enter it into Min.init and Max.init'+#13+#10
+'2c. If only verified parameters shall be listed, check "List if double match"'+#13+#10
+'3. Click Search! button'+#13+#10
+''+#13+#10
+'LazSRP16 searches the ranges Min.poly .. Max.poly and Min.init .. Max.init, with all'+#13+#10
+'additional combinations of refin/refout and xorout=$0000/$FFFF and swapped'+#13+#10
+'CRC bytes. Normally one of the Poly or Init range is set to just one fixed value;'+#13+#10
+'if Min.poly=Max.poly and Min.init=Max.init, a special xorout search routine is used.'+#13+#10
+''+#13+#10
+'This software is provided "as-is", without any express or implied'+#13+#10
+'warranty. In no event will the authors be held liable for any'+#13+#10
+'damages arising from the use of this software.',
mtInformation, [mbOK], 0);
end;
end.
|
unit dmConnection;
interface
uses
SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdCmdTCPClient, IdIRC, IdContext, ComCtrls, Contnrs,
fChat;
type
TConnectionData = class(TDataModule)
IdIRC: TIdIRC;
procedure DataModuleDestroy(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure IdIRCChannelMode(ASender: TIdContext; const ANickname, AHost, AChannel, AMode, AParams: string);
procedure IdIRCConnected(Sender: TObject);
procedure IdIRCCTCPQuery(ASender: TIdContext; const ANickname, AHost, ATarget, ACommand, AParams: string);
procedure IdIRCCTCPReply(ASender: TIdContext; const ANickname, AHost, ATarget, ACommand, AParams: string);
procedure IdIRCDisconnected(Sender: TObject);
procedure IdIRCJoin(ASender: TIdContext; const ANickname, AHost, AChannel: string);
procedure IdIRCKick(ASender: TIdContext; const ANickname, AHost, AChannel, ATarget, AReason: string);
procedure IdIRCMOTD(ASender: TIdContext; AMOTD: TStrings);
procedure IdIRCNicknameChange(ASender: TIdContext; const AOldNickname, AHost, ANewNickname: string);
procedure IdIRCNicknamesListReceived(ASender: TIdContext; const AChannel: string; ANicknameList: TStrings);
procedure IdIRCNotice(ASender: TIdContext; const ANickname, AHost, ATarget, ANotice: string);
procedure IdIRCPrivateMessage(ASender: TIdContext; const ANicknameFrom, AHost, ANicknameTo, AMessage: string);
procedure IdIRCRaw(ASender: TIdContext; AIn: Boolean; const AMessage: string);
procedure IdIRCServerError(ASender: TIdContext; AErrorCode: Integer; const AErrorMessage: string);
procedure IdIRCServerUsersListReceived(ASender: TIdContext; AUsers: TStrings);
procedure IdIRCServerVersion(ASender: TIdContext; const AVersion, AHost, AComments: string);
procedure IdIRCTopic(ASender: TIdContext; const ANickname, AHost, AChannel, ATopic: string);
procedure IdIRCPart(ASender: TIdContext; const ANickname, AHost, AChannel, APartMessage: string);
procedure IdIRCQuit(ASender: TIdContext; const ANickname, AHost, AReason: string);
procedure IdIRCServerWelcome(ASender: TIdContext; const AMsg: string);
procedure IdIRCUserMode(ASender: TIdContext; const ANickname, AHost, AMode: string);
procedure IdIRCISupport(ASender: TIdContext; AParameters: TStrings);
procedure IdIRCMyInfo(ASender: TIdContext; const AServer, AVersion, AUserModes, AChanModes, AExtra: string);
procedure IdIRCNicknameError(ASender: TIdContext; AError: Integer);
private
FLastNick: string;
FServerNode: TTreeNode;
FServerChat: TChatFrame;
FChatTargets: TStrings;
FChatFrames: TObjectList;
FCycling: Boolean;
FPort: Integer;
FPassword: string;
FJoinTopics: TStrings;
FActiveChat: TChatFrame;
FNetwork: string;
FUsedServer: string;
FServer: string;
FNickHost: string;
procedure AddNickToList(const ANewNick: string);
procedure HandleCustomRawCommands(const ARawMessage: string);
procedure SetPassword(const Value: string);
procedure SetPort(const Value: Integer);
procedure SetupReplies;
function GetNicknameChannelSign(const AChannelChat: TChatFrame; const ANickname: string): string;
procedure RemoveNickFromChannel(const AChatFrame: TChatFrame; const ANickname: string);
procedure SetActiveChat(const Value: TChatFrame);
procedure UpdateNicksFromModeChange(const AChannel, AModes: string);
function GetUsedNickname: string;
procedure RefreshTopicForChannel(const AChannel: string);
function GetConnected: Boolean;
procedure SetServer(const Value: string);
procedure LoadSettings;
procedure RemoveNickFromList(const ANickname: string);
public
procedure HandleChannelJoined(const AChannel: string; const AFocusChannel: Boolean);
procedure HandleNickNamesList(const AChannel, ANickNames: string);
function OpenChatWithTarget(const ATarget: string; const AFocusTarget: Boolean): TChatFrame;
procedure Connect;
procedure Disconnect(const AReason: string = '');
procedure Say(const ATarget, AText: string);
procedure Notice(const ATarget, AText: string);
procedure Whois(const AMask: string; const ATarget: string = '');
procedure Join(const AChannel: string; const AKey: string = '');
procedure ListChannelNicknames(const AChannel: string; const ATarget: string = '');
procedure Part(const AChannel: string; const AReason: string = '');
procedure Cycle(const AChannel: string; const AReason: string = '');
procedure CTCPQuery(const ATarget, ACommand, AParameters: string);
procedure SendRaw(const ALine: string);
procedure Action(const ATarget, AMessage: string);
procedure Query(const ATarget: string; const AMessage: string = '');
procedure CloseWindow(const ATarget: string);
procedure SetNickname(const ANickname: string);
procedure Quit(const AReason: string);
property ServerChat: TChatFrame read FServerChat;
property ActiveChat: TChatFrame read FActiveChat write SetActiveChat;
property ServerNode: TTreeNode read FServerNode;
property Server: string read FServer write SetServer;
property Port: Integer read FPort write SetPort;
property Password: string read FPassword write SetPassword;
property UsedNickname: string read GetUsedNickname;
property Connected: Boolean read GetConnected;
property Network: string read FNetwork;
property UsedServer: string read FServer;
property NickHost: string read FNickHost;
function IsOp(const AChannelChat: TChatFrame; const ANickname: string): Boolean;
function IsVoice(const AChannelChat: TChatFrame; const ANickname: string): Boolean;
end;
implementation
uses fMain, Windows, Dialogs, Forms, uNickNamesListParam, uTokenizer, IniFiles,
uStringUtils, uDateUtils, IdGlobal, StrUtils, uConst;
{$R *.dfm}
{ TConnectionData }
procedure TConnectionData.DataModuleDestroy(Sender: TObject);
begin
if IdIRC.Connected then
try
IdIRC.Disconnect;
except
end;
FJoinTopics.Free;
FChatFrames.Free;
FChatTargets.Free;
TTreeView(FServerNode.TreeView).Items.Delete(FServerNode);
end;
procedure TConnectionData.Disconnect(const AReason: string = '');
begin
IdIRC.Disconnect;
end;
procedure TConnectionData.HandleChannelJoined(const AChannel: string; const AFocusChannel: Boolean);
var
ChannelChat: TChatFrame;
begin
ChannelChat := OpenChatWithTarget(AChannel, AFocusChannel);
ChannelChat.AddIRCLine('JOIN', IdIRC.UsedNickname, FNickHost, AChannel, '', True);
if FJoinTopics.IndexOfName(AChannel) >= 0 then
ChannelChat.Topic := FJoinTopics.Values[AChannel];
if ChannelChat.Topic <> '' then
MainForm.TopicEdit.SetIRCText(ChannelChat.Topic);
FJoinTopics.Values[AChannel] := '';
end;
function TConnectionData.OpenChatWithTarget(const ATarget: string; const AFocusTarget: Boolean): TChatFrame;
var
Index: Integer;
ChannelNode: TTreeNode;
begin
Index := FChatTargets.IndexOf(ATarget);
if Index = - 1 then
begin
ChannelNode := MainForm.CreateChatNode(Self, ATarget);
Result := MainForm.CreateChatFrame(ChannelNode);
ActiveChat := Result;
ChannelNode.Selected := True;
FChatTargets.Add(ATarget);
FChatFrames.Add(Result);
end
else
begin
Result := TChatFrame(FChatFrames[Index]);
if AFocusTarget then
MainForm.FindChatNode(Self, ATarget).Selected := True;
end;
end;
procedure TConnectionData.Query(const ATarget: string; const AMessage: string = '');
begin
OpenChatWithTarget(ATarget, True);
if AMessage <> '' then
Say(ATarget, AMessage);
end;
procedure TConnectionData.Quit(const AReason: string);
begin
IdIRC.Disconnect(AReason);
end;
procedure TConnectionData.CloseWindow(const ATarget: string);
var
Index: Integer;
ChatFrame: TChatFrame;
begin
if ATarget = '' then
begin
if MainForm.Connections.Count > 1 then
begin
MainForm.Connections.Remove(Self);
end;
end else
begin
Index := FChatTargets.IndexOf(ATarget);
if Index >= 0 then
begin
ChatFrame := TChatFrame(FChatFrames[Index]);
FChatFrames.Extract(ChatFrame);
FChatTargets.Delete(Index);
ChatFrame.TreeNode.Free;
if ActiveChat = ChatFrame then
ActiveChat := FServerChat;
ChatFrame.Free;
end;
end;
end;
procedure TConnectionData.HandleNickNamesList(const AChannel, ANickNames: string);
var
Index: Integer;
begin
Index := FChatTargets.IndexOf(AChannel);
if Index >= 0 then
begin
TChatFrame(FChatFrames[Index]).Nicknames.Text := ANickNames;
MainForm.PopulateNickList;
MainForm.PopulateTopic; //update read-only property
end;
end;
procedure TConnectionData.CTCPQuery(const ATarget, ACommand, AParameters: string);
begin
IdIRC.CTCPQuery(ATarget, ACommand, AParameters);
ActiveChat.AddIRCLine('CTCPQUERY', IdIRC.UsedNickname, '', ATarget, ACommand, True, AParameters);
end;
procedure TConnectionData.Cycle(const AChannel: string; const AReason: string = '');
begin
FCycling := True;
Part(AChannel, AReason);
Join(AChannel);
end;
procedure TConnectionData.DataModuleCreate(Sender: TObject);
begin
Randomize;
FServer := 'irc.efnet.org';
FChatFrames := TObjectList.Create;
FChatTargets := TStringList.Create;
FJoinTopics := TStringList.Create;
Port := 6667;
SetupReplies;
FServerNode := MainForm.CreateServerNode(Self);
FServerChat := MainForm.CreateChatFrame(FServerNode);
FServerNode.Selected := True;
ActiveChat := FServerChat;
end;
procedure TConnectionData.LoadSettings;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(SettingsFilePath);
try
IdIRC.Nickname := IniFile.ReadString(IdentificationSection, NickNameIdent, 'User' + IntToStr(Random(100)));
IdIRC.AltNickname := IniFile.ReadString(IdentificationSection, AltNickIdent, 'User' + IntToStr(Random(100)));
IdIRC.RealName := IniFile.ReadString(IdentificationSection, RealNameIdent, IdIRC.Nickname);
IdIRC.Username := IniFile.ReadString(IdentificationSection, UserNameIdent, IdIRC.Nickname);
finally
IniFile.Free;
end;
end;
procedure TConnectionData.Notice(const ATarget, AText: string);
begin
IdIRC.Notice(ATarget, AText);
MainForm.ActiveChatFrame.AddIRCLine('MYNOTICE', IdIRC.UsedNickname, '', ATarget, AText, True);
end;
procedure TConnectionData.SetupReplies;
var
Theme: TStrings;
begin
Theme := TStringList.Create;
try
Theme.LoadFromFile(ExtractFilePath(Application.ExeName) + MainForm.CurrentTheme + '.theme');
IdIRC.Replies.Finger := '';
IdIRC.Replies.Version := Theme.Values['VERSION'];
IdIRC.Replies.UserInfo := IdIRC.Username;
IdIRC.Replies.ClientInfo := '';
finally
Theme.Free;
end;
end;
procedure TConnectionData.Action(const ATarget, AMessage: string);
var
Index: Integer;
ChannelChat: TChatFrame;
Sign: string;
begin
IdIRC.Action(ATarget, AMessage);
Index := FChatTargets.IndexOf(ATarget);
if Index >= 0 then
begin
ChannelChat := TChatFrame(FChatFrames[Index]);
Sign := GetNicknameChannelSign(ChannelChat, IdIRC.UsedNickname);
if Sign = '' then
Sign := ' '; //for padding
MainForm.ActiveChatFrame.AddIRCLine('ACTION', IdIRC.UsedNickname, '', ATarget, AMessage, True, '', Sign);
end else
MainForm.ActiveChatFrame.AddIRCLine('ACTION', IdIRC.UsedNickname, '', ATarget, AMessage, True);
end;
procedure TConnectionData.Connect;
begin
try
PostMessage(MainForm.Handle, WM_ENABLEIDENT, 0, 0);
except
on E:Exception do
FServerChat.AddText(E.Message);
end;
FServerNode.Text := Server;
FLastNick := '';
LoadSettings;
IdIRC.Password := Password;
IdIRC.Host := Server;
IdIRC.Port := Port;
IdIRC.Connect;
end;
procedure TConnectionData.IdIRCChannelMode(ASender: TIdContext; const
ANickname, AHost, AChannel, AMode, AParams: string);
var
Index: Integer;
ChannelChat: TChatFrame;
begin
Index := FChatTargets.IndexOf(AChannel);
ChannelChat := TChatFrame(FChatFrames[Index]);
UpdateNicksFromModeChange(AChannel, AMode);
RefreshTopicForChannel(AChannel); //update read-only property
ChannelChat.AddIRCLine('CHANMODE', ANickname, AHost, AChannel, Trim(AMode + ' ' + AParams),
ANickname = IdIRC.UsedNickname, AParams);
end;
procedure TConnectionData.RefreshTopicForChannel(const AChannel: string);
var
Index: Integer;
ChannelChat: TChatFrame;
begin
Index := FChatTargets.IndexOf(AChannel);
ChannelChat := TChatFrame(FChatFrames[Index]);
if MainForm.ActiveChatFrame = ChannelChat then
MainForm.PopulateTopic;
end;
procedure TConnectionData.UpdateNicksFromModeChange(const AChannel, AModes: string);
const
Modes: array[0..1] of Char = ('o', 'v');
Signs: array[0..1] of Char = ('@', '+');
var
I, NickIndex, ModeIndex: Integer;
NickSigns: TStrings;
Nicks: TStrings;
Index: Integer;
ChannelChat: TChatFrame;
Tokenizer: TTokenizer;
ModeFlags, ModeFlag, NickName, NewNick: string;
IsPlus, IsUserMode: Boolean;
begin
Index := FChatTargets.IndexOf(AChannel);
if Index >= 0 then
begin
ChannelChat := TChatFrame(FChatFrames[Index]);
NickSigns := TStringList.Create;
Nicks := TStringList.Create;
Tokenizer := TTokenizer.Create(AModes, ' ');
try
ModeFlags := Tokenizer.NextToken;
if Tokenizer.HasMoreTokens then
begin
while Tokenizer.HasMoreTokens do
Nicks.Add(Tokenizer.NextToken);
for I := 0 to Nicks.Count - 1 do
NickSigns.Values[Nicks[I]] := GetNicknameChannelSign(ChannelChat, Nicks[I]);
NickIndex := 0;
IsPlus := True;
for I := 1 to Length(ModeFlags) do
begin
if ModeFlags[I] = '+' then
IsPlus := True
else if ModeFlags[I] = '-' then
IsPlus := False
else
begin
ModeFlag := ModeFlags[I];
IsUserMode := False;
for ModeIndex := Low(Modes) to High(Modes) do
begin
if SameText(ModeFlag, Modes[ModeIndex]) then
begin
NickName := Nicks[NickIndex];
Inc(NickIndex);
if IsPlus then
begin
if Pos(Signs[ModeIndex], NickSigns.Values[NickName]) = 0 then
NickSigns.Values[NickName] := Signs[ModeIndex]
end
else if Pos(Signs[ModeIndex], NickSigns.Values[NickName]) > 0 then
NickSigns.Values[NickName] := StringReplace(NickSigns.Values[NickName], '@', '', []);
IsUserMode := True;
Break;
end;
end;
if not IsUserMode then
Nicks.Delete(NickIndex);
end;
end;
for I := 0 to Nicks.Count - 1 do
begin
NickName := Nicks[I];
if NickName = '' then
Continue;
if Pos('@', NickSigns.Values[NickName]) > 0 then
NewNick := '@' + NickName
else if Pos('+', NickSigns.Values[NickName]) > 0 then
NewNick := '+' + NickName
else
NewNick := NickName;
RemoveNickFromChannel(ChannelChat, NickName);
ChannelChat.Nicknames.Add(NewNick);
if ChannelChat = MainForm.ActiveChatFrame then
begin
RemoveNickFromList(Nickname);
AddNickToList(NewNick);
end;
end;
end;
finally
NickSigns.Free;
Nicks.Free;
Tokenizer.Free;
end;
end;
end;
procedure TConnectionData.IdIRCDisconnected(Sender: TObject);
begin
FServerChat.AddText('Disconnected from server.');
PostMessage(MainForm.Handle, WM_DISABLEIDENT, 0, 0);
end;
procedure TConnectionData.IdIRCJoin(ASender: TIdContext; const ANickname, AHost, AChannel: string);
var
Index: Integer;
ChannelChat: TChatFrame;
begin
if (ANickname = IdIRC.UsedNickname) and not FCycling then
begin
//prevent deadlock
FNickHost := AHost;
PostMessage(MainForm.Handle, WM_CHANNELJOINED, Integer(Self), GlobalAddAtom(PChar(AChannel)));
end else
begin
Index := FChatTargets.IndexOf(AChannel);
if Index = -1 then
Exit;
ChannelChat := TChatFrame(FChatFrames[Index]);
ChannelChat.AddIRCLine('JOIN', ANickname, AHost, ACHannel, '', ANickname = IdIRC.UsedNickname);
ChannelChat.Nicknames.Add(ANickname);
if MainForm.ActiveChatFrame = ChannelChat then
AddNickToList(ANickname);
end;
FCycling := False;
end;
procedure TConnectionData.IdIRCKick(ASender: TIdContext; const ANickname,
AHost, AChannel, ATarget, AReason: string);
var
Index: Integer;
begin
Index := FChatTargets.IndexOf(AChannel);
if Index = -1 then
Exit;
TChatFrame(FChatFrames[Index]).AddIRCLine('KICK', ANickname, AHost, AChannel, AReason,
ANickname = IdIRC.UsedNickname, '', '@', ATarget);
end;
procedure TConnectionData.IdIRCMOTD(ASender: TIdContext; AMOTD: TStrings);
begin
FServerChat.AddStrings(AMOTD);
end;
procedure TConnectionData.IdIRCNicknamesListReceived(ASender: TIdContext; const
AChannel: string; ANicknameList: TStrings);
var
Param: TNickNamesListParam;
begin
Param := TNickNamesListParam.Create;
Param.Connection := Self;
Param.Channel := AChannel;
Param.NickNames := ANicknameList.Text;
PostMessage(MainForm.Handle, WM_NICKNAMESLIST, Cardinal(Param), 0);
end;
procedure TConnectionData.IdIRCNotice(ASender: TIdContext; const ANickname,
AHost, ATarget, ANotice: string);
var
Nick: string;
begin
if AHost = '' then
begin
//efnet doesn't send a "nick" with this
if ANickname = '' then
Nick := Server
else
Nick := ANickname;
ServerChat.AddIRCLine('SERVERNOTICE', Nick, AHost, ATarget, ANotice, False);
end else
ActiveChat.AddIRCLine('NOTICE', ANickname, AHost, ATarget, ANotice, False);
end;
procedure TConnectionData.IdIRCPart(ASender: TIdContext; const ANickname,
AHost, AChannel, APartMessage: string);
var
Index: Integer;
ChannelChat: TChatFrame;
begin
Index := FChatTargets.IndexOf(AChannel);
if Index = -1 then
Exit;
ChannelChat := TChatFrame(FChatFrames[Index]);
ChannelChat.AddIRCLine('PART', ANickname, AHost, ACHannel, '', ANickname = IdIRC.UsedNickname);
RemoveNickFromChannel(ChannelChat, ANickname);
if ChannelChat = MainForm.ActiveChatFrame then
RemoveNickFromList(ANickname);
end;
procedure TConnectionData.IdIRCPrivateMessage(ASender: TIdContext; const
ANicknameFrom, AHost, ANicknameTo, AMessage: string);
var
Sign: string;
Index: Integer;
ChannelChat: TChatFrame;
begin
if ANicknameTo = IdIRC.UsedNickname then
begin
Index := FChatTargets.IndexOf(ANicknameFrom);
if Index >= 0 then
begin
ChannelChat := TChatFrame(FChatFrames[Index]);
ChannelChat.AddIRCLine('CHANMSG', ANicknameFrom, AHost, ANicknameTo, AMessage,
ANicknameFrom = IdIRC.UsedNickname, '', Sign);
end else
ActiveChat.AddIRCLine('PRIVMSG', ANicknameFrom, AHost, ANicknameTo, AMessage, False);
end else
begin
Index := FChatTargets.IndexOf(ANicknameTo);
if Index = -1 then
Exit;
ChannelChat := TChatFrame(FChatFrames[Index]);
Sign := GetNicknameChannelSign(ChannelChat, ANicknameFrom);
ChannelChat.AddIRCLine('CHANMSG', ANicknameFrom, AHost, ANicknameTo, AMessage,
ANicknameFrom = IdIRC.UsedNickname, '', Sign);
end;
end;
function TConnectionData.GetConnected: Boolean;
begin
Result := IdIRC.Connected;
end;
function TConnectionData.GetNicknameChannelSign(const AChannelChat: TChatFrame; const ANickname: string): string;
begin
if IsOp(AChannelChat, ANickname) then
Result := '@'
else if IsVoice(AChannelChat, ANickname) then
Result := '+'
else
Result := '';
end;
function TConnectionData.GetUsedNickname: string;
begin
Result := IdIRC.UsedNickname;
end;
function TConnectionData.IsOp(const AChannelChat: TChatFrame; const ANickname: string): Boolean;
begin
Result := AChannelChat.Nicknames.IndexOf('@' + ANickname) >= 0;
end;
function TConnectionData.IsVoice(const AChannelChat: TChatFrame; const ANickname: string): Boolean;
begin
Result := AChannelChat.Nicknames.IndexOf('+' + ANickname) >= 0;
end;
procedure TConnectionData.IdIRCQuit(ASender: TIdContext; const ANickname,
AHost, AReason: string);
var
I: Integer;
ChannelChat: TChatFrame;
begin
if ANickname = IdIRC.UsedNickname then
begin
end else
begin
for I := 0 to FChatFrames.Count - 1 do
begin
ChannelChat := TChatFrame(FChatFrames[I]);
if (ChannelChat.Nicknames.IndexOf(ANickname) >= 0) or
(ChannelChat.Nicknames.IndexOf('@' + ANickname) >= 0) or
(ChannelChat.Nicknames.IndexOf('+' + ANickname) >= 0) then
begin
ChannelChat.AddIRCLine('QUIT', ANickname, AHost, '', AReason, ANickname = IdIRC.UsedNickname);
RemoveNickFromChannel(ChannelChat, ANickname);
if ChannelChat = MainForm.ActiveChatFrame then
RemoveNickFromList(ANickname);
end;
end;
end;
end;
procedure TConnectionData.IdIRCCTCPQuery(ASender: TIdContext; const ANickname,
AHost, ATarget, ACommand, AParams: string);
var
Sign: string;
Index: Integer;
ChannelChat: TChatFrame;
begin
if SameText(ACommand, 'ACTION') then
begin
if ATarget = IdIRC.UsedNickname then
begin
ActiveChat.AddIRCLine('ACTION', ANickname, AHost, ATarget, AParams, ANickname = IdIRC.UsedNickname);
end else
begin
Index := FChatTargets.IndexOf(ATarget);
if Index = -1 then
Exit;
ChannelChat := TChatFrame(FChatFrames[Index]);
Sign := GetNicknameChannelSign(ChannelChat, ANickname);
ChannelChat.AddIRCLine('ACTION', ANickname, AHost, ATarget, AParams, ANickname = IdIRC.UsedNickname, '', Sign);
end;
end else
ActiveChat.AddIRCLine('CTCPQUERY', ANickname, AHost, ATarget, ACommand, False, AParams);
end;
procedure TConnectionData.IdIRCCTCPReply(ASender: TIdContext; const ANickname,
AHost, ATarget, ACommand, AParams: string);
begin
ActiveChat.AddIRCLine('CTCPREPLY', ANickname, AHost, ATarget, ACommand, True, AParams);
end;
procedure TConnectionData.IdIRCRaw(ASender: TIdContext; AIn: Boolean; const AMessage: string);
var
Prefix, Text: string;
begin
Prefix := '';
if IdIRC.SenderNick <> '' then
Prefix := Format(':%s', [IdIRC.SenderNick]);
if IdIRC.SenderHost <> '' then
Prefix := Prefix + Format('!%s', [IdIRC.SenderHost]);
if Prefix <> '' then
Prefix := Prefix + ' ';
Text := Prefix + AMessage;
if AIn then
FServerChat.AddIRCLine('RAWIN', '', '', '', Text, False)
else
FServerChat.AddIRCLine('RAWOUT', '', '', '', Text, False);
HandleCustomRawCommands(AMessage);
end;
procedure TConnectionData.HandleCustomRawCommands(const ARawMessage: string);
var
RawCmd, Target, Nick, Host, Text, Text2: string;
Tokenizer: TTokenizer;
begin
Tokenizer := TTokenizer.Create(ARawMessage, ' ');
RawCmd := Tokenizer.NextToken;
if SameText(RawCmd, '307') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
Text := Tokenizer.NextToken;
Delete(Text, 1, 1);
while Tokenizer.HasMoreTokens do
Text := Text + ' '+ Tokenizer.NextToken;
ActiveChat.AddIRCLine(RawCmd, Nick, '', Target, Text, Target = Nick);
end
else if SameText(RawCmd, '311') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
Host := Tokenizer.NextToken + '@'+ Tokenizer.NextToken;
Tokenizer.NextToken;
Text := Tokenizer.NextToken;
Delete(Text, 1, 1);
ActiveChat.AddIRCLine(RawCmd, Nick, Host, Target, Text, Target = Nick);
end
else if SameText(RawCmd, '312') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
Text := Tokenizer.NextToken;
Text2 := Tokenizer.NextToken;
Delete(Text2, 1, 1);
while Tokenizer.HasMoreTokens do
Text2 := Text2 + ' '+ Tokenizer.NextToken;
ActiveChat.AddIRCLine(RawCmd, Nick, '', Target, Text, Target = Nick, Text2);
end
else if SameText(RawCmd, '317') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
Text := DurationToStr(StrToInt(Tokenizer.NextToken) * 1000);
Text2 := DateToStr(UnixToDateTime(StrToInt(Tokenizer.NextToken)));
ActiveChat.AddIRCLine(RawCmd, Nick, '', Target, Text, Target = Nick, Text2);
end
else if SameText(RawCmd, '318') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
ActiveChat.AddIRCLine(RawCmd, Nick, '', Target, '', Target = Nick);
end
else if SameText(RawCmd, '319') then
begin
Target := Tokenizer.NextToken;
Nick := Tokenizer.NextToken;
Text := Tokenizer.NextToken;
Delete(Text, 1, 1);
while Tokenizer.HasMoreTokens do
Text := Text + ' '+ Tokenizer.NextToken;
ActiveChat.AddIRCLine(RawCmd, Nick, '', Target, Text, Target = Nick);
end;
end;
procedure TConnectionData.AddNickToList(const ANewNick: string);
begin
PostMessage(MainForm.Handle, WM_ADDNICK, GlobalAddAtom(PChar(ANewNick)), 0);
end;
procedure TConnectionData.IdIRCConnected(Sender: TObject);
begin
FServerChat.AddText('Connected to server...');
end;
procedure TConnectionData.IdIRCNicknameChange(ASender: TIdContext; const
AOldNickname, AHost, ANewNickname: string);
var
I: Integer;
ChannelChat: TChatFrame;
NewNick: string;
begin
for I := 0 to FChatFrames.Count - 1 do
begin
ChannelChat := TChatFrame(FChatFrames[I]);
if (ChannelChat.Nicknames.IndexOf(AOldNickname) >= 0) or
(ChannelChat.Nicknames.IndexOf('@' + AOldNickname) >= 0) or
(ChannelChat.Nicknames.IndexOf('+' + AOldNickname) >= 0) then
begin
ChannelChat.AddIRCLine('NICK', AOldNickname, '', '', '', ANewNickname = IdIRC.UsedNickname,
'', '', ANewNickname);
NewNick := GetNicknameChannelSign(ChannelChat, AOldNickname) + ANewNickname;
RemoveNickFromChannel(ChannelChat, AOldNickname);
ChannelChat.Nicknames.Add(NewNick);
if ChannelChat = MainForm.ActiveChatFrame then
begin
RemoveNickFromList(AOldNickname);
AddNickToList(NewNick);
end;
end;
end;
if ANewNickname = IdIRC.UsedNickname then
MainForm.PopulateAppCaption;
end;
procedure TConnectionData.RemoveNickFromList(const ANickname: string);
begin
PostMessage(MainForm.Handle, WM_REMOVENICK, GlobalAddAtom(PChar(ANickname)), 0);
end;
procedure TConnectionData.RemoveNickFromChannel(const AChatFrame: TChatFrame; const ANickname: string);
var
Index: Integer;
begin
Index := AChatFrame.Nicknames.IndexOf('@' + ANickname);
if Index >= 0 then
AChatFrame.Nicknames.Delete(Index)
else
begin
Index := AChatFrame.Nicknames.IndexOf('+' + ANickname);
if Index >= 0 then
AChatFrame.Nicknames.Delete(Index)
else
begin
Index := AChatFrame.Nicknames.IndexOf(ANickname);
if Index >= 0 then
AChatFrame.Nicknames.Delete(Index)
end;
end;
end;
procedure TConnectionData.IdIRCServerError(ASender: TIdContext; AErrorCode:
Integer; const AErrorMessage: string);
begin
FServerChat.AddText(AErrorMessage);
end;
procedure TConnectionData.IdIRCServerUsersListReceived(ASender: TIdContext;
AUsers: TStrings);
begin
FServerChat.AddStrings(AUsers);
end;
procedure TConnectionData.IdIRCServerVersion(ASender: TIdContext; const
AVersion, AHost, AComments: string);
begin
FServerChat.AddText(AVersion + #9 + AHost + #9 + AComments);
end;
procedure TConnectionData.IdIRCServerWelcome(ASender: TIdContext; const AMsg: string);
begin
PostMessage(MainForm.Handle, WM_DISABLEIDENT, 0, 0);
FServerChat.AddText(AMsg);
MainForm.PopulateAppCaption;
PostMessage(MainForm.Handle, WM_AUTOJOIN, Integer(Self), 0);
end;
procedure TConnectionData.IdIRCTopic(ASender: TIdContext; const ANickname,
AHost, AChannel, ATopic: string);
var
Index: Integer;
begin
Index := FChatTargets.IndexOf(AChannel);
if Index >= 0 then
begin
if AHost <> '' then // not an On-Join topic
TChatFrame(FChatFrames[Index]).AddIRCLine('TOPIC', ANickname, AHost, AChannel, ATopic,
ANickname = IdIRC.UsedNickname);
TChatFrame(FChatFrames[Index]).Topic := ATopic;
if SameText(MainForm.ActiveTarget, AChannel) then
PostMessage(MainForm.Handle, WM_SETTOPICTEXT, GlobalAddAtom(PChar(ATopic)), 0);
end else if AHost = '' then // this is an On-Join topic, haven't created channel frame yet (threaded)
begin
FJoinTopics.Values[AChannel] := ATopic;
end;
end;
procedure TConnectionData.IdIRCUserMode(ASender: TIdContext; const ANickname,
AHost, AMode: string);
var
RealMode: string;
begin
RealMode := AMode;
if RealMode[1] = ':' then
Delete(RealMode, 1, 1);
ActiveChat.AddIRCLine('USERMODE', ANickname, AHost, '', RealMode, ANickname = IdIRC.UsedNickname);
end;
procedure TConnectionData.IdIRCISupport(ASender: TIdContext; AParameters: TStrings);
const
NetworkDelim = 'NETWORK=';
var
I: Integer;
begin
for I := 0 to AParameters.Count - 1 do
begin
if StartsText(NetworkDelim, AParameters[I]) then
begin
FNetwork := Copy(AParameters[I], Length(NetworkDelim) + 1, Length(AParameters[I]));
MainForm.PopulateAppCaption;
Break;
end;
end;
end;
procedure TConnectionData.IdIRCMyInfo(ASender: TIdContext; const AServer,
AVersion, AUserModes, AChanModes, AExtra: string);
begin
FUsedServer := AServer;
ServerNode.Text := AServer;
end;
procedure TConnectionData.IdIRCNicknameError(ASender: TIdContext; AError: Integer);
begin
if (AError = 433) and (IdIRC.UsedNickname = IdIRC.AltNickname) then
begin
FServerChat.AddText('Nickname and alternate are already in use.');
PostMessage(MainForm.Handle, WM_NICKSINUSE, 0, 0);
end;
end;
procedure TConnectionData.Join(const AChannel: string; const AKey: string = '');
begin
IdIRC.Join(AChannel, AKey);
end;
procedure TConnectionData.ListChannelNicknames(const AChannel: string; const ATarget: string = '');
begin
IdIRC.ListChannelNicknames(AChannel, ATarget);
end;
procedure TConnectionData.Part(const AChannel: string; const AReason: string = '');
begin
IdIRC.Part(AChannel, AReason);
end;
procedure TConnectionData.Say(const ATarget, AText: string);
var
Index: Integer;
ChannelChat: TChatFrame;
Sign: string;
begin
IdIRC.Say(ATarget, AText);
Index := FChatTargets.IndexOf(ATarget);
if Index >= 0 then
begin
ChannelChat := TChatFrame(FChatFrames[Index]);
Sign := GetNicknameChannelSign(ChannelChat, IdIRC.UsedNickname);
ChannelChat.AddIRCLine('CHANMSG', IdIRC.UsedNickname, '', ATarget, AText, True, '', Sign);
end else
MainForm.ActiveChatFrame.AddIRCLine('PRIVMSG', IdIRC.UsedNickname, '', ATarget, AText, True);
end;
procedure TConnectionData.SendRaw(const ALine: string);
begin
IdIRC.Raw(ALine);
end;
procedure TConnectionData.SetActiveChat(const Value: TChatFrame);
begin
FActiveChat := Value;
end;
procedure TConnectionData.SetNickname(const ANickname: string);
begin
IdIRC.Nickname := ANickname;
end;
procedure TConnectionData.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TConnectionData.SetPort(const Value: Integer);
begin
FPort := Value;
end;
procedure TConnectionData.SetServer(const Value: string);
begin
FServer := Value;
if Assigned(FServerNode) then
FServerNode.Text := Value;
end;
procedure TConnectionData.Whois(const AMask: string; const ATarget: string = '');
begin
IdIRC.Whois(AMask, ATarget);
end;
end.
|
{*******************************************************}
{ }
{ Copyright (C) 1999-2000 Inprise Corporation }
{ }
{*******************************************************}
unit DMPooler;
interface
uses SysUtils, Classes, Forms, SyncObjs, Windows;
type
TDataModuleClass = class of TDataModule; // "class" reference
TPooledModule = record
Module: TDataModule; // Point to a TDataModule descendant instance
InUse: Boolean; // Indicates, whether Module is in use or not
end;
TModulePooler = class
private
FCSect: TCriticalSection; // Enables thread safe changes to FModules
FModuleClass: TDataModuleClass; // "class" for TDataModule to pool
FModules: array of TPooledModule; // array of pooled TDataModules
FSemaphore: THandle; // Limits the number of simultaneous
public // pool users.
property ModuleClass: TDataModuleClass read FModuleClass write FModuleClass;
constructor Create;
destructor Destroy; override;
function GetModule: TDataModule; // Get TDataModule from the pool
procedure FreeModule(DataModule: TDataModule); // Return TDataModule back
end; // to the pool
const
PoolSize = 5; //Number of DM's in pool. Might want to pass this from command-line
var
ModulePooler: TModulePooler = nil;
implementation
uses Dialogs;
{ TModulePool }
constructor TModulePooler.Create;
begin
IsMultiThread := True;
FCSect := TCriticalSection.Create;
FSemaphore := CreateSemaphore(nil, PoolSize, PoolSize, nil);
// ShowMessage('Pool created!');
end;
destructor TModulePooler.Destroy;
begin
FCSect.Free;
CloseHandle(FSemaphore);
end;
//Loop through array of Datamodules and free each one.
procedure TModulePooler.FreeModule(DataModule: TDataModule);
var
I: Integer;
begin
FCSect.Enter;
try
for I := 0 to Length(FModules) - 1 do
if FModules[I].Module = DataModule then
FModules[I].InUse := False;
ReleaseSemaphore(FSemaphore, 1, nil);
finally
FCSect.Leave;
end;
end;
function TModulePooler.GetModule: TDataModule;
var
I: Integer;
begin
Result := nil;
if WaitForSingleObject(FSemaphore, 5000) = WAIT_TIMEOUT then
raise Exception.Create('Server too busy');
FCSect.Enter;
try
if Length(FModules) = 0 then
begin
SetLength(FModules, PoolSize);
for I := 0 to PoolSize - 1 do
begin
FModules[I].InUse := False;
FModules[I].Module := FModuleClass.Create(Application);
end;
end;
for I := 0 to Length(FModules) - 1 do
if not FModules[I].InUse then
begin
FModules[I].InUse := True;
Result := FModules[I].Module;
Break;
end;
finally
FCSect.Leave;
end;
//Check if we ran out of connections
if not Assigned(Result) then
raise Exception.Create('Pool is out of capacity');
end;
initialization
ModulePooler := TModulePooler.Create;
finalization
ModulePooler.Free;
end.
|
unit uFlash;
interface
uses
windows, ShockwaveFlashObjects_TLB,SysUtils,strutils;
type
TFlash = class
private
swf: TShockwaveFlash;
class function EncodeData(Func: String;args: array of const): WideString;overload;
class function EncodeData(args: TVarRec): WideString;overload;
public
constructor Create(swfFileName : ansiString);
destructor Destroy; //override;
function getNewData(const priceData,oldData,clientId,priceCode:ansistring):ansistring;
function replaceRequest(const priceData,oldData,clientId:ansistring):ansistring;
function decryptData(const data:ansistring):ansistring;
function cryptData(const data:ansistring):ansistring;
function CryptTimeData(const data:ansistring):ansistring;
function deCryptTimeData(const data:ansistring):ansistring;
function getPriceCode(const data:ansistring):ansistring;
end;
implementation
{ TFlash }
constructor TFlash.Create(swfFileName : ansiString);
begin
if not assigned(swf) then begin
swf:=TShockwaveFlash.Create(nil);
swf.AllowScriptAccess:='always';
swf.AllowNetworking:='all';
swf.Movie:=swfFileName;
end;
end;
destructor TFlash.Destroy;
begin
//inherited;
if assigned(swf) then begin
swf.Free;
swf:=nil;
end;
end;
function TFlash.getPriceCode(const data:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
tmp := EncodeData('getPriceCode', [data]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.replaceRequest(const priceData,oldData,clientId:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
//tmp := TXMLParase.EncodeData('decrptData', [ansistring(trim(edtInput.Text))]);
tmp := EncodeData('replaceRequest', [priceData,oldData,clientId]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.getNewData(const priceData,oldData,clientId,priceCode:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
//tmp := TXMLParase.EncodeData('decrptData', [ansistring(trim(edtInput.Text))]);
tmp := EncodeData('getNewData', [priceData,oldData,clientId,priceCode]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.deCryptTimeData(const data:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
tmp := EncodeData('decryptTimeData', [data]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.cryptTimeData(const data:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
tmp := EncodeData('cryptTimeData', [data]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.cryptData(const data:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
tmp := EncodeData('cryptData', [data]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
function TFlash.decryptData(const data:ansistring):ansistring;
var
tmp: WideString;
Response:ansiString;
begin
tmp := EncodeData('decryptData', [data]);
tmp:=swf.CallFunction(tmp);
Response:=tmp; //<string></string>
Response:=midstr(Response,9,length(Response)-17);
Response:=replaceStr(Response,'"','"');
result:=Response;
end;
//------------------------------------------------------------------------------------
class function TFlash.EncodeData(Func: String;args: array of const): WideString;
var
i:Integer;
tempstr:String;
begin
tempstr:='<arguments>';
i:=args[0].VType;
for i:=Low(args) to High(args) do
begin
if (args[i].VType=vtInteger) or (args[i].VType=VtExtended) or
(args[i].VType=VtBoolean) or (args[i].VType=vtAnsiString) or
(args[i].VType=vtWideString) or (args[i].VType=vtUnicodeString) then
begin
tempstr:=tempstr+EncodeData(args[i]);
end
else
begin
// tempstr:=tempstr+EncodeData(TVarRec(^args[i]));
end;
end;
tempstr:=tempstr+'</arguments>';
Result:='<invoke name="'+Func+'" returntype="xml">'+tempstr+'</invoke>';
end;
class function TFlash.EncodeData(args: TVarRec): WideString;
var
temp:string;
arrtemp:array of Integer;
begin
if (args.VType=vtInteger) then
begin
Result:=Format('<number>%d</number>',[args.VInteger]);
end
else if args.VType=VtExtended then
begin
Result:=Format('<number>%f</number>',[args.VExtended]);
end
else if args.VType=VtBoolean then
begin
Result:=Format('<%s/>',[BoolToStr(args.VBoolean,True)]);
end
else if args.VType=vtAnsiString then
begin
temp:=args.VPChar;
Result:=Format('<string>%s</string>',[temp]);
end
else if args.VType=vtWideString then
begin
temp:=pchar(args.VWideString);
Result:=Format('<string>%s</string>',[temp]);
end
else if args.VType=vtUnicodeString then
begin
temp:=pchar(args.VUnicodeString);
Result:=Format('<string>%s</string>',[temp]);
end
else
begin
Result:='';
end;
end;
end.
|
{------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2009 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
// EasyComponents是HhfComponents的升级版本,当前主版本号为2.0
------------------------------------------------------------------------------}
{
2011-04-09 22:27:29
* TEasyCustomDropDownEdit的基类从TEasyCustomLabelEdit开始,具有Label、BorderColor等属性
并增加右侧的下拉按钮
}
unit untEasyCustomDropDownEdit;
interface
uses
Windows, Messages, StdCtrls, Classes, Graphics, Controls, SysUtils, Forms,
Math, ComObj, untEasyAbout, untEasyEdit, unEasyComboBox;
type
TEasyCustomDropDownEdit = class(TEasyCustomLabelEdit)
private
FAutoFocus : boolean;
FOnMouseEnter : TNotifyEvent;
FOnMouseLeave : TNotifyEvent;
FOnButtonClick : TNotifyEvent;
FMouseInControl : Boolean;
FFlat : Boolean;
FButton : TDgrComboBtn; //下拉按钮
FOldCursor : TCursor; //鼠标状态
FAppereanceStyle: TEasyComboStyle;
FSelectionColor : TColor;
FSelectionColorTo : TColor;
FSelectionGradient : TSelectionGradient;
function GetButtonRect: TRect;
procedure DrawButton(DC: HDC); overload;
procedure DrawButton; overload;
procedure DrawBorders(DC: HDC); overload;
procedure DrawBorders; overload;
procedure ButtonOnChange(Sender: TObject);
procedure WMMouseMove(var Msg: TWMMouse); message WM_MOUSEMOVE;
procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
procedure WMLButtonDown(var Msg: TWMMouse); message WM_LBUTTONDOWN;
procedure SetFlat(const Value: Boolean);
procedure SetAppereanceStyle(const Value: TEasyComboStyle);
procedure SetButton(const Value: TDgrComboBtn);
procedure SetSelectionColor(const Value: TColor);
procedure SetSelectionColorTo(const Value: TColor);
procedure SetSelectionGradient(const Value: TSelectionGradient);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure SetEditRect;
procedure Loaded; override;
procedure DoEnter; override;
procedure DrawArrow(ArP: TPoint; ArClr: TColor); virtual;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
property About;
property Anchors;
property EnterTAB;
property Color;
property BorderColor;
property FocusColor;
property AutoFocus: boolean read FAutoFocus write fAutoFocus default false;
property AppereanceStyle: TEasyComboStyle read FAppereanceStyle write SetAppereanceStyle;
property Button: TDgrComboBtn read FButton write SetButton;
property Flat: Boolean read FFlat write SetFlat;
property TextRightAlign;
property EditLabel;
property LabelPosition;
property LabelSpacing;
property SelectionColor: TColor read FSelectionColor write SetSelectionColor;
property SelectionColorTo: TColor read FSelectionColorTo write SetSelectionColorTo default clNone;
property SelectionGradient: TSelectionGradient read FSelectionGradient write SetSelectionGradient default sgVerticalInOut;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
property OnButtonClick: TNotifyEvent read FOnButtonClick write FOnButtonClick;
end;
TEasyDropDownEdit = class(TEasyCustomDropDownEdit)
published
property Anchors;
property EnterTAB;
property BorderColor;
property Color;
property FocusColor;
property AutoFocus;
property AppereanceStyle;
property Button;
property Flat;
property TextRightAlign;
property EditLabel;
property LabelPosition;
property LabelSpacing;
property SelectionColor;
property SelectionColorTo;
property SelectionGradient;
property OnMouseEnter;
property OnMouseLeave;
property OnButtonClick;
end;
implementation
{ TEasyCustomDropDownEdit }
procedure TEasyCustomDropDownEdit.CMMouseEnter(var Msg: TMessage);
var
DC: HDC;
begin
inherited;
if (csDesigning in ComponentState) then
Exit;
if FAutoFocus then
SetFocus;
if not FMouseInControl and Enabled then
begin
FMouseInControl := True;
DC := GetDC(Handle);
DrawButton(DC);
DrawBorders(DC);
ReleaseDC(Handle, DC);
end;
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
end;
procedure TEasyCustomDropDownEdit.CMMouseLeave(var Message: TMessage);
begin
if FMouseInControl and Enabled then
begin
FMouseInControl := False;
Invalidate;
end;
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self);
end;
constructor TEasyCustomDropDownEdit.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FButton := TDgrComboBtn.Create;
FButton.OnChange := ButtonOnChange;
FMouseInControl := false;
FFlat := true;
FSelectionColor := clHighlight;
FSelectionColorTo := clNone;
FSelectionGradient := sgVerticalInOut;
AppereanceStyle := esOffice2003Classic;//esOffice2003Blue;
FOldCursor := Cursor;
end;
destructor TEasyCustomDropDownEdit.Destroy;
begin
FButton.Free;
inherited Destroy;
end;
procedure TEasyCustomDropDownEdit.DrawButton(DC: HDC);
var
Canvas: TCanvas;
BtnR: TRect;
P: TPoint;
l, t: integer;
// procedure DrawArrow(ArP: TPoint; ArClr: TColor);
// begin
// Canvas.Pen.Color := ArClr;
// Canvas.MoveTo(ArP.X, ArP.Y);
// Canvas.LineTo(ArP.X + 5, ArP.Y);
// Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
// Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
// Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
// end;
begin
Canvas := TCanvas.Create;
Canvas.Handle := DC;
BtnR := GetButtonRect;
P.X := BtnR.Left + ((BtnR.Right - BtnR.Left - 5) div 2) + 1;
P.Y := BtnR.Top + ((BtnR.Bottom - BtnR.Top - 3) div 2) + 1;
if Flat then
begin
if (FMouseInControl or self.Focused) and not (csDesigning in ComponentState) then
begin
if FButton.ColorHot <> clNone then
DrawGradient(Canvas, FButton.ColorHot, FButton.ColorHotTo, 16, BtnR, false);
if not FButton.GlyphHot.Empty then
begin
t := ((BtnR.Bottom - BtnR.Top) - FButton.GlyphHot.Height) div 2 + 1;
l := ((BtnR.Right - BtnR.Left) - FButton.GlyphHot.Width) div 2;
FButton.GlyphHot.Transparent := true;
Canvas.Draw(BtnR.Left + l, BtnR.Top + t, FButton.GlyphHot);
end
else
DrawArrow(P, FButton.HotArrowColor);
end
else
begin
if FButton.Color <> clNone then
DrawGradient(Canvas, FButton.Color, FButton.ColorTo, 16, BtnR, false);
if not FButton.Glyph.Empty then
begin
t := ((BtnR.Bottom - BtnR.Top) - FButton.Glyph.Height) div 2 + 1;
l := ((BtnR.Right - BtnR.Left) - FButton.Glyph.Width) div 2;
FButton.Glyph.Transparent := true;
Canvas.Draw(BtnR.Left + l, BtnR.Top + t, FButton.Glyph);
end
else
DrawArrow(P, FButton.ArrowColor);
end;
end
else
begin
end;
Canvas.Free;
end;
procedure TEasyCustomDropDownEdit.DrawBorders(DC: HDC);
var
Canvas: TCanvas;
R, BtnR: TRect;
begin
Canvas := TCanvas.Create;
Canvas.Handle := DC;
R := ClientRect;
BtnR := GetButtonRect;
if Flat then
begin
// if 1 = 2 then
// begin
// Canvas.Pen.Color := BorderColor;
// Canvas.Brush.Style := bsClear;
// Canvas.Rectangle(R);
// end
// else
begin
if (BorderColor <> clNone) then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := self.Color;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(R);
end;
Canvas.MoveTo(BtnR.Left - 1, BtnR.Top);
Canvas.LineTo(BtnR.Left - 1, BtnR.Bottom + 2);
end;
Canvas.Free;
end;
procedure TEasyCustomDropDownEdit.DrawBorders;
var
DC: HDC;
begin
DC := GetDC(Handle);
DrawBorders(DC);
ReleaseDC(Handle, DC);
end;
procedure TEasyCustomDropDownEdit.DrawButton;
var
DC: HDC;
begin
DC := GetDC(Handle);
DrawButton(DC);
ReleaseDC(Handle, DC);
end;
function TEasyCustomDropDownEdit.GetButtonRect: TRect;
var
R: TRect;
begin
R := ClientRect;
Result := Rect(R.Right - FButton.Width - 1, R.Top + 1, R.Right - 1, R.Bottom - 2);
end;
procedure TEasyCustomDropDownEdit.SetFlat(const Value: Boolean);
begin
if (csLoading in ComponentState) then
begin
FFlat := Value;
Exit;
end;
if FFlat <> Value then
begin
FFlat := Value;
Invalidate;
end;
end;
procedure TEasyCustomDropDownEdit.WMPaint(var Msg: TWMPaint);
var
R, BtnR: TRect;
begin
inherited;
R := ClientRect;
BtnR := GetButtonRect;
if Flat then
begin
// Button Painting
DrawButton;
// Control and Button Border
DrawBorders();
end;
end;
procedure TEasyCustomDropDownEdit.SetAppereanceStyle(
const Value: TEasyComboStyle);
begin
if (FAppereanceStyle <> Value) or (1 > 0) then
begin
FAppereanceStyle := Value;
case FAppereanceStyle of
esOffice2003Blue:
begin
FButton.Color := $FCE1CB;
FButton.ColorTo := $E0A57D;
FButton.ColorDown := $087FE8;
FButton.ColorDownTo := $7CDAF7;
FButton.ColorHot := $DCFFFF;
FButton.ColorHotTo := $5BC0F7;
FSelectionColor := $E0A57D;
BorderColor := $00E0A57D;
end;
esOffice2003Olive:
begin
FButton.Color := $CFF0EA;
FButton.ColorTo := $8CC0B1;
FButton.ColorDown := $087FE8;
FButton.ColorDownTo := $7CDAF7;
FButton.ColorHot := $DCFFFF;
FButton.ColorHotTo := $5BC0F7;
FSelectionColor := $8CC0B1;
//BorderColor := $588060;
BorderColor := $8CC0B1;
end;
esOffice2003Silver:
begin
FButton.Color := $ECE2E1;
FButton.ColorTo := $B39698;
FButton.ColorDown := $087FE8;
FButton.ColorDownTo := $7CDAF7;
FButton.ColorHot := $DCFFFF;
FButton.ColorHotTo := $5BC0F7;
FSelectionColor := $B39698;
BorderColor := $B39698;
end;
esOffice2003Classic:
begin
FButton.Color := clWhite;
FButton.ColorTo := $C9D1D5;
FButton.ColorDown := $B59285;
FButton.ColorDownTo := $B59285;
FButton.ColorHot := $D2BDB6;
FButton.ColorHotTo := $D2BDB6;
FSelectionColor := $B59285;
BorderColor := $C9D1D5;
end;
end;
end;
end;
procedure TEasyCustomDropDownEdit.SetButton(const Value: TDgrComboBtn);
begin
if assigned(Value) then
FButton.Assign(Value);
end;
procedure TEasyCustomDropDownEdit.SetSelectionColor(const Value: TColor);
begin
if FSelectionColor <> Value then
begin
FSelectionColor := Value;
end;
end;
procedure TEasyCustomDropDownEdit.SetSelectionColorTo(const Value: TColor);
begin
FSelectionColorTo := Value;
end;
procedure TEasyCustomDropDownEdit.SetSelectionGradient(
const Value: TSelectionGradient);
begin
FSelectionGradient := Value;
end;
procedure TEasyCustomDropDownEdit.ButtonOnChange(Sender: TObject);
begin
Invalidate;
end;
procedure TEasyCustomDropDownEdit.WMLButtonDown(var Msg: TWMMouse);
begin
inherited;
if csDesigning in ComponentState then
Exit;
if PtInRect(GetButtonRect, point(msg.xpos, msg.ypos)) then
begin
if Assigned(FOnButtonClick) then
FOnButtonClick(Self);
end;
end;
procedure TEasyCustomDropDownEdit.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or (ES_MULTILINE);
end;
procedure TEasyCustomDropDownEdit.SetEditRect;
var
Loc: TRect;
begin
if csDesigning in ComponentState then
Exit;
SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc));
Loc.Bottom := ClientHeight + 1; {+1 is workaround for windows paint bug}
Loc.Right := ClientWidth - FButton.Width - 4;
if (BorderStyle = bsNone) then
begin
Loc.Top := 4;
Loc.Left := 2;
end
else
begin
Loc.Top := 1;
Loc.Left := 1;
end;
SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc));
end;
procedure TEasyCustomDropDownEdit.DoEnter;
begin
inherited;
SetEditRect;
end;
procedure TEasyCustomDropDownEdit.Loaded;
begin
inherited Loaded;
SetEditRect;
end;
procedure TEasyCustomDropDownEdit.DrawArrow(ArP: TPoint; ArClr: TColor);
begin
Canvas.Pen.Color := ArClr;
Canvas.MoveTo(ArP.X, ArP.Y);
Canvas.LineTo(ArP.X + 5, ArP.Y);
Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
end;
procedure TEasyCustomDropDownEdit.WMMouseMove(var Msg: TWMMouse);
begin
inherited;
if PtInRect(GetButtonRect, point(msg.xpos, msg.ypos)) then
begin
if (Cursor <> crArrow) then
begin
FOldCursor := Cursor;
Cursor := crArrow;
end;
end
else if (Cursor = crArrow) then
Cursor := FOldCursor;
end;
end.
|
UNIT globalFormHandler;
INTERFACE
USES
Classes, sysutils,Forms,math;
CONST SLOT_SIZE:longint=32;
FREE_INDEX=255;
DESKTOP_INDEX=254;
MIN_FORM_WIDTH=4;
MIN_FORM_HEIGHT=4;
TYPE
T_slotRange=record
x0,x1,y0,y1:longint;
end;
T_direction=(d_left,d_right,d_up,d_down);
{ T_slotMap }
T_slotMap=object
mapWidth,mapHeight:longint;
occupied:array of byte;
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE clear;
FUNCTION occupy(CONST r:T_slotRange; CONST occupyIndex:byte):byte;
FUNCTION isFree(CONST r:T_slotRange):boolean;
FUNCTION windowPositionToSlotRange(CONST Left,top,height,width:longint):T_slotRange;
PROCEDURE slotRangeToWindowPosition(CONST r:T_slotRange; OUT Left,top,height,width:longint);
end;
P_formMeta=^T_formMeta;
{ T_formMeta }
T_formMeta=object
form:TForm;
sizable:boolean;
slotRange:T_slotRange;
myIndex:byte;
callbacks:record
resize,changeBounds,Show,Hide:TNotifyEvent;
end;
CONSTRUCTOR create(CONST form_:TForm; CONST sizable_:boolean; CONST index:byte);
DESTRUCTOR destroy;
PROCEDURE fetchPosition(VAR map:T_slotMap);
PROCEDURE trimToDesktop(VAR map:T_slotMap);
PROCEDURE applyPosition(VAR map:T_slotMap);
FUNCTION shrinks(CONST dir:T_direction; VAR map:T_slotMap):boolean;
FUNCTION moves(CONST dir:T_direction; VAR map:T_slotMap):boolean;
FUNCTION grows(VAR map:T_slotMap):boolean;
FUNCTION visible: boolean;
FUNCTION requiredSlotSize:T_slotRange;
PROCEDURE FormResize(Sender: TObject);
PROCEDURE FormChangeBounds(Sender: TObject);
PROCEDURE FormShow(Sender: TObject);
PROCEDURE FormHide(Sender: TObject);
end;
PROCEDURE registerForm(CONST f:TForm; CONST canResize:boolean);
PROCEDURE unregisterForm(CONST f:TForm);
PROCEDURE arrangeForms(CONST triggeredBy:longint);
VAR autoarrangeForms:boolean=true;
IMPLEMENTATION
VAR formMeta:array of P_formMeta;
arranging:boolean=false;
arrangementPending:longint=-1;
PROCEDURE finalizeUnit;
VAR i:longint;
begin
for i:=0 to length(formMeta)-1 do dispose(formMeta[i],destroy);
setLength(formMeta,0);
end;
FUNCTION indexOfForm(CONST f:TForm):longint;
VAR i:longint;
begin
for i:=0 to length(formMeta)-1 do if formMeta[i]^.form=f then exit(i);
result:=-1;
end;
PROCEDURE arrangeForms(CONST triggeredBy:longint);
VAR i:longint;
conflictIndex:byte;
conflictForm1,conflictForm2:byte;
growing,
changedInThisLoop:boolean;
changed:boolean=false;
map:T_slotMap;
safeguardCounter:longint=100;
FUNCTION slotCenterX(CONST r:T_slotRange):longint;
begin
result:=r.x0+r.x1;
end;
FUNCTION slotCenterY(CONST r:T_slotRange):longint;
begin
result:=r.y0+r.y1;
end;
PROCEDURE resolveUnbiasedConflict(CONST meta1,meta2:P_formMeta);
VAR dx,dy:longint;
begin
dx:=slotCenterX(meta1^.slotRange)-slotCenterX(meta2^.slotRange);
dy:=slotCenterY(meta1^.slotRange)-slotCenterY(meta2^.slotRange);
map.clear;
if abs(dx)>=abs(dy) then begin
if dx>0 then begin
meta1^.shrinks(d_right,map);
meta2^.shrinks(d_left,map);
end else begin
meta1^.shrinks(d_left,map);
meta2^.shrinks(d_right,map);
end
end else if dy<0 then begin
meta1^.shrinks(d_up,map);
meta2^.shrinks(d_down,map);
end else if dy>0 then begin
meta1^.shrinks(d_down,map);
meta2^.shrinks(d_up,map);
end;
end;
PROCEDURE resolveBiasedConflict(CONST other:P_formMeta);
VAR triggeringMeta:P_formMeta;
dx,dy:longint;
begin
triggeringMeta:=formMeta[triggeredBy];
dx:=slotCenterX(other^.slotRange)-slotCenterX(triggeringMeta^.slotRange);
dy:=slotCenterY(other^.slotRange)-slotCenterY(triggeringMeta^.slotRange);
map.clear;
if abs(dx)>=abs(dy) then begin
if dx<0 then begin
//other is left of triggering -> shrink leftwards, triggering shrinks rightwards as fallback
if not(other^.shrinks(d_left,map)) then triggeringMeta^.shrinks(d_right,map);
end else begin
if not(other^.shrinks(d_right,map)) then triggeringMeta^.shrinks(d_left,map);
end;
end else if dy<0 then begin
if not(other^.shrinks(d_up,map)) then triggeringMeta^.shrinks(d_down,map);
end else if dy>0 then begin
if not(other^.shrinks(d_down,map)) then triggeringMeta^.shrinks(d_up,map);
end;
end;
begin
if arranging then exit;
arranging:=true;
map.create;
for i:=0 to length(formMeta)-1 do formMeta[i]^.fetchPosition(map);
repeat
changedInThisLoop:=false;
//collect conflicts
map.clear;
conflictForm1:=FREE_INDEX;
conflictForm2:=FREE_INDEX;
for i:=0 to length(formMeta)-1 do if formMeta[i]^.visible then begin
conflictIndex:=map.occupy(formMeta[i]^.slotRange,i);
if (conflictForm1=FREE_INDEX) and (conflictIndex<>FREE_INDEX) then begin
conflictForm1:=conflictIndex;
conflictForm2:=i;
end;
end;
//resolve conflicts
if (conflictForm1<>FREE_INDEX) then begin
if conflictForm1=DESKTOP_INDEX then formMeta[conflictForm2]^.trimToDesktop(map)
else if conflictForm1=triggeredBy then resolveBiasedConflict(formMeta[conflictForm2])
else if conflictForm2=triggeredBy then resolveBiasedConflict(formMeta[conflictForm1])
else resolveUnbiasedConflict(formMeta[conflictForm1],formMeta[conflictForm2]);
changedInThisLoop:=true;
end else begin
//grow
repeat
growing:=false;
for i:=0 to length(formMeta)-1 do if i<>triggeredBy then growing:=growing or formMeta[i]^.grows(map);
changedInThisLoop:=changedInThisLoop or growing;
until not(growing);
if (triggeredBy>=0) and (triggeredBy<length(formMeta)) then repeat
growing:=formMeta[triggeredBy]^.grows(map);
changedInThisLoop:=changedInThisLoop or growing;
until not(growing);
end;
changed:=changed or changedInThisLoop;
dec(safeguardCounter)
until not(changedInThisLoop) or (safeguardCounter<=0);
if changed then for i:=0 to length(formMeta)-1 do formMeta[i]^.applyPosition(map);
map.destroy;
Application.ProcessMessages;
arranging:=false;
end;
PROCEDURE registerForm(CONST f: TForm; CONST canResize: boolean);
VAR i:longint;
begin
i:=indexOfForm(f);
if i<0 then begin
i:=length(formMeta);
setLength(formMeta,i+1);
new(formMeta[i],create(f,canResize,i));
end;
end;
PROCEDURE unregisterForm(CONST f: TForm);
VAR i:longint;
begin
i:=indexOfForm(f);
if i<0 then exit;
dispose(formMeta[i],destroy);
while i<length(formMeta)-1 do begin
formMeta[i]:=formMeta[i+1];
inc(i);
end;
setLength(formMeta,length(formMeta)-1);
end;
PROCEDURE formStatusChange(CONST f: TForm);
VAR i:longint;
begin
if not(autoarrangeForms) then exit;
if not(f.showing) then begin
arrangeForms(-1);
exit;
end;
i:=indexOfForm(f);
if i<0 then exit;
arrangeForms(i);
end;
{ T_slotMap }
CONSTRUCTOR T_slotMap.create;
begin
clear;
end;
DESTRUCTOR T_slotMap.destroy;
begin
setLength(occupied,0);
end;
PROCEDURE T_slotMap.clear;
VAR i:longint;
begin
mapWidth:=screen.WorkAreaWidth div SLOT_SIZE;
mapHeight:=screen.WorkAreaHeight div SLOT_SIZE;
setLength(occupied,mapWidth*mapHeight);
for i:=0 to length(occupied)-1 do occupied[i]:=FREE_INDEX;
end;
FUNCTION T_slotMap.occupy(CONST r: T_slotRange; CONST occupyIndex: byte): byte;
VAR x,y:longint;
begin
if (r.x0<0) or (r.y0<0) or (r.x1>=mapWidth) or (r.y1>=mapHeight)
then result:=DESKTOP_INDEX
else result:=FREE_INDEX;
for y:=max(0,r.y0) to min(mapHeight-1,r.y1) do
for x:=max(0,r.x0) to min(mapWidth -1,r.x1) do begin
if result=FREE_INDEX then result:=occupied[x+y*mapWidth];
occupied[x+y*mapWidth]:=occupyIndex;
end;
end;
FUNCTION T_slotMap.isFree(CONST r: T_slotRange): boolean;
VAR x,y:longint;
begin
result:=(r.y0>=0) and (r.x0>=0) and (r.y1<mapHeight) and (r.x1<mapWidth);
if not(result) then exit(result);
for y:=max(0,r.y0) to min(mapHeight-1,r.y1) do
for x:=max(0,r.x0) to min(mapWidth-1 ,r.x1) do result:=result and (occupied[x+y*mapWidth]=FREE_INDEX);
end;
FUNCTION T_slotMap.windowPositionToSlotRange(CONST Left, top, height, width: longint): T_slotRange;
begin
result.x0:=(Left-screen.WorkAreaLeft) div SLOT_SIZE;
if Left+width-screen.WorkAreaLeft=screen.WorkAreaWidth
then result.x1:=mapWidth-1
else result.x1:=(Left-screen.WorkAreaLeft+width-1) div SLOT_SIZE;
result.y0:=(top-screen.WorkAreaTop) div SLOT_SIZE;
if top+height-screen.WorkAreaTop=screen.WorkAreaHeight
then result.y1:=mapHeight-1
else result.y1:=(top-screen.WorkAreaTop+height-1) div SLOT_SIZE;
end;
PROCEDURE T_slotMap.slotRangeToWindowPosition(CONST r: T_slotRange; OUT Left, top, height, width: longint);
begin
Left:=r.x0*SLOT_SIZE+screen.WorkAreaLeft;
if r.x1=mapWidth-1
then width:=screen.WorkAreaWidth-Left
else width:=(r.x1-r.x0+1)*SLOT_SIZE-1;
top:=r.y0*SLOT_SIZE+screen.WorkAreaTop;
if r.y1=mapHeight-1
then height:=screen.WorkAreaHeight-top
else height:=(r.y1-r.y0+1)*SLOT_SIZE-1;
end;
{ T_formMeta }
CONSTRUCTOR T_formMeta.create(CONST form_: TForm; CONST sizable_: boolean;
CONST index: byte);
begin
form:=form_;
sizable:=(sizable_) and (form_<>nil);
myIndex:=index;
callbacks.resize :=form.OnResize; form.OnResize :=@FormResize;
callbacks.changeBounds:=form.OnChangeBounds; form.OnChangeBounds:=@FormChangeBounds;
callbacks.Hide :=form.OnHide; form.OnHide :=@FormHide;
callbacks.Show :=form.OnShow; form.OnShow :=@FormShow;
end;
DESTRUCTOR T_formMeta.destroy;
begin
form.OnResize:=callbacks.resize;
form.OnChangeBounds:=callbacks.changeBounds;
form.OnHide:=callbacks.Hide;
form.OnShow:=callbacks.Show;
end;
PROCEDURE T_formMeta.fetchPosition(VAR map: T_slotMap);
begin
if not(visible) then exit;
slotRange:=map.windowPositionToSlotRange(form.Left,form.top,form.height,form.width);
end;
PROCEDURE T_formMeta.trimToDesktop(VAR map: T_slotMap);
VAR required:T_slotRange;
begin
required:=requiredSlotSize;
if slotRange.x0<0 then begin
slotRange.x0:=0;
if slotRange.x1-slotRange.x0<required.x1 then begin
slotRange.x1:=slotRange.x0+required.x1;
map.occupy(slotRange,myIndex);
end;
end;
if slotRange.y0<0 then begin
slotRange.y0:=0;
if slotRange.y1-slotRange.y0<required.y1 then begin
slotRange.y1:=slotRange.y0+required.y1;
map.occupy(slotRange,myIndex);
end;
end;
if slotRange.x1>=map.mapWidth then begin
slotRange.x1:=map.mapWidth-1;
if slotRange.x1-slotRange.x0<required.x1 then begin
slotRange.x0:=slotRange.x1-required.x1;
map.occupy(slotRange,myIndex);
end;
end;
if slotRange.y1>=map.mapHeight then begin
slotRange.y1:=map.mapHeight-1;
if slotRange.y1-slotRange.y0<required.y1 then begin
slotRange.y0:=slotRange.y1-required.y1;
map.occupy(slotRange,myIndex);
end;
end;
end;
PROCEDURE T_formMeta.applyPosition(VAR map: T_slotMap);
VAR Left,width,top,height:longint;
begin
if not(visible) then exit;
map.slotRangeToWindowPosition(slotRange,Left,top,height,width);
form.Left:=Left;
form.width:=width;
form.top:=top;
form.height:=height;
with slotRange do writeln(form.toString,' apply position ',x0,'..',x1,'x',y0,'..',y1);
end;
FUNCTION vStrip(CONST x,y0,y1:longint):T_slotRange;
begin
result.x0:=x; result.x1:=x;
result.y0:=y0; result.y1:=y1;
end;
FUNCTION hStrip(CONST x0,x1,y:longint):T_slotRange;
begin
result.x0:=x0; result.x1:=x1;
result.y0:=y; result.y1:=y;
end;
FUNCTION T_formMeta.shrinks(CONST dir: T_direction; VAR map: T_slotMap): boolean;
begin
result:=false;
case dir of
d_left: if (slotRange.x1-slotRange.x0)<=requiredSlotSize.x1 then result:=moves(d_left,map) else begin
map.occupy(vStrip(slotRange.x1,slotRange.y0,slotRange.y1),FREE_INDEX);
dec(slotRange.x1);
result:=true;
end;
d_right: if (slotRange.x1-slotRange.x0)<=requiredSlotSize.x1 then result:=moves(d_right,map) else begin
map.occupy(vStrip(slotRange.x0,slotRange.y0,slotRange.y1),FREE_INDEX);
inc(slotRange.x0);
result:=true;
end;
d_up: if (slotRange.y1-slotRange.y0)<=requiredSlotSize.y1 then result:=moves(d_up,map) else begin
map.occupy(hStrip(slotRange.x0,slotRange.x1,slotRange.y1),FREE_INDEX);
dec(slotRange.y1);
result:=true;
end;
d_down: if (slotRange.y1-slotRange.y0)<=requiredSlotSize.y1 then result:=moves(d_down,map) else begin
map.occupy(hStrip(slotRange.x0,slotRange.x1,slotRange.y0),FREE_INDEX);
inc(slotRange.y0);
result:=true;
end;
end;
writeln(form.toString,' shrinks ',dir,' ',result);
with slotRange do writeln(' ',x0,'..',x1,'x',y0,'..',y1);
end;
FUNCTION T_formMeta.moves(CONST dir: T_direction; VAR map: T_slotMap): boolean;
begin
result:=false;
case dir of
d_left: if map.isFree(vStrip(slotRange.x0-1,slotRange.y0,slotRange.y1)) then begin
dec(slotRange.x0);
map.occupy(slotRange,myIndex);
map.occupy(vStrip(slotRange.x1,slotRange.y0,slotRange.y1),FREE_INDEX);
dec(slotRange.x1);
result:=true;
end;
d_right: if map.isFree(vStrip(slotRange.x1+1,slotRange.y0,slotRange.y1)) then begin
inc(slotRange.x1);
map.occupy(slotRange,myIndex);
map.occupy(vStrip(slotRange.x0,slotRange.y0,slotRange.y1),FREE_INDEX);
inc(slotRange.x0);
result:=true;
end;
d_up: if map.isFree(hStrip(slotRange.x0,slotRange.x1,slotRange.y0-1)) then begin
dec(slotRange.y0);
map.occupy(slotRange,myIndex);
map.occupy(hStrip(slotRange.x0,slotRange.x1,slotRange.y1),FREE_INDEX);
dec(slotRange.y1);
result:=true;
end;
d_down: if map.isFree(hStrip(slotRange.x0,slotRange.x1,slotRange.y1+1)) then begin
inc(slotRange.y1);
map.occupy(slotRange,myIndex);
map.occupy(hStrip(slotRange.x0,slotRange.x1,slotRange.y0),FREE_INDEX);
inc(slotRange.y0);
result:=true;
end;
end;
writeln(form.toString,' moves ',dir,' ',result);
with slotRange do writeln(' ',x0,'..',x1,'x',y0,'..',y1);
end;
FUNCTION T_formMeta.grows(VAR map: T_slotMap): boolean;
begin
if not(visible) then exit(false);
if not(sizable) then exit(moves(d_left ,map) or
moves(d_up ,map) or
moves(d_right,map) or
moves(d_down ,map));
result:=false;
if map.isFree(vStrip(slotRange.x0-1,slotRange.y0,slotRange.y1)) then begin
dec(slotRange.x0);
map.occupy(slotRange,myIndex);
result:=true;
end;
if map.isFree(hStrip(slotRange.x0,slotRange.x1,slotRange.y0-1)) then begin
dec(slotRange.y0);
map.occupy(slotRange,myIndex);
result:=true;
end;
if not(sizable) and result then exit(result);
if map.isFree(vStrip(slotRange.x1+1,slotRange.y0,slotRange.y1)) then begin
inc(slotRange.x1);
map.occupy(slotRange,myIndex);
result:=true;
end;
if map.isFree(hStrip(slotRange.x0,slotRange.x1,slotRange.y1+1)) then begin
inc(slotRange.y1);
map.occupy(slotRange,myIndex);
result:=true;
end;
end;
FUNCTION T_formMeta.visible: boolean;
begin
result:=(form<>nil) and (form.visible) and (form.showing);
end;
FUNCTION T_formMeta.requiredSlotSize: T_slotRange;
begin
result.x0:=0;
result.y0:=0;
if sizable then result.x1:=MIN_FORM_WIDTH-1
else result.x1:=slotRange.x1-slotRange.x0;
if sizable then result.y1:=MIN_FORM_HEIGHT-1
else result.y1:=slotRange.y1-slotRange.y0;
end;
PROCEDURE T_formMeta.FormResize(Sender: TObject);
begin
writeln('FormResize for ',form.toString,' ',form.visible,' ',form.showing);
if Assigned(callbacks.resize) then callbacks.resize(Sender);
formStatusChange(form);
end;
PROCEDURE T_formMeta.FormChangeBounds(Sender: TObject);
begin
writeln('FormChangeBounds for ',form.toString,' ',form.visible,' ',form.showing);
if Assigned(callbacks.changeBounds) then callbacks.changeBounds(Sender);
// formStatusChange(form);
end;
PROCEDURE T_formMeta.FormShow(Sender: TObject);
begin
writeln('FormShow for ',form.toString,' ',form.visible,' ',form.showing);
if Assigned(callbacks.Show) then callbacks.Show(Sender);
formStatusChange(form);
end;
PROCEDURE T_formMeta.FormHide(Sender: TObject);
begin
writeln('FormShow for ',form.toString,' ',form.visible,' ',form.showing);
if Assigned(callbacks.Hide) then callbacks.Hide(Sender);
formStatusChange(form);
end;
FINALIZATION
finalizeUnit;
end.
|
unit ProductsExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
CustomExcelTable, System.Generics.Collections, FieldInfoUnit, Data.DB,
FireDAC.Comp.DataSet, CheckDuplicateInterface, CurrencyInterface;
type
TProductsExcelTable = class(TCustomExcelTable)
private
FCheckDuplicate: ICheckDuplicate;
FCurrencyInt: ICurrency;
FFieldsInfoArr: TArray<TFieldInfoEx>;
function GetComponentGroup: TField;
function GetDollar: TField;
function GetEuro: TField;
function GetLoadDate: TField;
function GetPriceR: TField;
function GetPriceD: TField;
function GetPriceE: TField;
function GetProducer: TField;
function GetAmount: TField;
function GetPrice: TField;
function GetValue: TField;
protected
procedure SetFieldsInfo; override;
public
constructor Create(AOwner: TComponent;
AFieldsInfoArr: TArray<TFieldInfoEx>); reintroduce;
destructor Destroy; override;
function CheckRecord: Boolean; override;
property CheckDuplicate: ICheckDuplicate read FCheckDuplicate
write FCheckDuplicate;
property ComponentGroup: TField read GetComponentGroup;
property Dollar: TField read GetDollar;
property Euro: TField read GetEuro;
property LoadDate: TField read GetLoadDate;
property PriceR: TField read GetPriceR;
property PriceD: TField read GetPriceD;
property PriceE: TField read GetPriceE;
property Producer: TField read GetProducer;
property Amount: TField read GetAmount;
property CurrencyInt: ICurrency read FCurrencyInt write FCurrencyInt;
property Price: TField read GetPrice;
property Value: TField read GetValue;
end;
TProductsExcelDM = class(TExcelDM)
private
FFieldsInfoArr: TArray<TFieldInfoEx>;
function GetExcelTable: TProductsExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
public
destructor Destroy; override;
procedure Init(AFieldsInfoArr: TArray<TFieldInfoEx>);
property ExcelTable: TProductsExcelTable read GetExcelTable;
{ Public declarations }
end;
implementation
uses
ErrorType, RecordCheck;
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
destructor TProductsExcelDM.Destroy;
begin;
inherited;
end;
function TProductsExcelDM.CreateExcelTable: TCustomExcelTable;
begin
if (FFieldsInfoArr <> nil) and (Length(FFieldsInfoArr) > 0) then
Result := TProductsExcelTable.Create(Self, FFieldsInfoArr)
else
Result := nil;
end;
function TProductsExcelDM.GetExcelTable: TProductsExcelTable;
begin
Result := CustomExcelTable as TProductsExcelTable;
end;
procedure TProductsExcelDM.Init(AFieldsInfoArr: TArray<TFieldInfoEx>);
begin
FFieldsInfoArr := AFieldsInfoArr;
TryCreateExcelTable;
end;
constructor TProductsExcelTable.Create(AOwner: TComponent;
AFieldsInfoArr: TArray<TFieldInfoEx>);
begin
inherited Create(AOwner);
FFieldsInfoArr := AFieldsInfoArr;
end;
destructor TProductsExcelTable.Destroy;
begin;
inherited;
end;
function TProductsExcelTable.CheckRecord: Boolean;
var
ADollar: Double;
AEuro: Double;
ALoadDate: TDateTime;
ARecordCheck: TRecordCheck;
FS: TFormatSettings;
k: Integer;
S: string;
x: Integer;
begin
Result := inherited;
if not Result then
Exit;
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
// Проверяем цену в рублях
if (not PriceR.IsNull) then
begin
S := PriceR.AsString.Replace('.', FormatSettings.DecimalSeparator);
Result := StrToFloatDef(S, -1) <> -1;
if not Result then
begin
// Сигнализируем о неверном значении цены
ARecordCheck.Col := PriceR.Index + 1;
ARecordCheck.ErrorMessage := 'Денежное значение';
ARecordCheck.Description := 'Цена в рублях указана в неверном формате';
ProcessErrors(ARecordCheck);
Exit;
end
else
begin
if S <> PriceR.AsString then
begin
Edit;
PriceR.AsString := S;
Post;
end;
end;
end;
// Проверяем цену в долларах
if (not PriceD.IsNull) then
begin
S := PriceD.AsString.Replace('.', FormatSettings.DecimalSeparator);
Result := StrToFloatDef(S, -1) <> -1;
if not Result then
begin
// Сигнализируем о неверном значении цены
ARecordCheck.Col := PriceD.Index + 1;
ARecordCheck.ErrorMessage := 'Денежное значение';
ARecordCheck.Description := 'Цена в долларах указана в неверном формате';
ProcessErrors(ARecordCheck);
Exit;
end
else
begin
if S <> PriceD.AsString then
begin
Edit;
PriceD.AsString := S;
Post;
end;
end;
end;
// Проверяем цену в евро
if (not PriceE.IsNull) then
begin
S := PriceE.AsString.Replace('.', FormatSettings.DecimalSeparator);
Result := StrToFloatDef(S, -1) <> -1;
if not Result then
begin
// Сигнализируем о неверном значении цены
ARecordCheck.Col := PriceE.Index + 1;
ARecordCheck.ErrorMessage := 'Денежное значение';
ARecordCheck.Description := 'Цена в евро указана в неверном формате';
ProcessErrors(ARecordCheck);
Exit;
end
else
begin
if S <> PriceE.AsString then
begin
Edit;
PriceE.AsString := S;
Post;
end;
end;
end;
k := 0;
if not PriceR.IsNull then
Inc(k);
if not PriceD.IsNull then
Inc(k);
if not PriceE.IsNull then
Inc(k);
// Только одна закупочная цена должна быть указана
Result := k = 1;
// если закупочная цена вообще не указана
if k = 0 then
begin
// Сигнализируем что цена не задана
ARecordCheck.Col := PriceR.Index + 1;
ARecordCheck.ErrorMessage := 'Денежное значение';
ARecordCheck.Description := 'Закупочная цена не указана';
ProcessErrors(ARecordCheck);
Exit;
end;
// если указана больше чем одна цена
if k > 1 then
begin
ARecordCheck.Col := PriceR.Index + 1;
ARecordCheck.ErrorMessage := 'Денежное значение';
ARecordCheck.Description := 'Указана больше чем одна закупочная цена';
ProcessErrors(ARecordCheck);
Exit;
end;
// Если задана дата загрузки
if not LoadDate.AsString.Trim.IsEmpty then
begin
// Если в Excel считали дату как целое число
if TryStrToInt(LoadDate.AsString.Trim, x) then
begin
try
ALoadDate := TDate(x);
TryEdit;
// Переводим дату в строку
LoadDate.AsString := FormatDateTime('dd.mm.yyyy', ALoadDate);
TryPost;
except
Result := False;
end;
end
else
begin
// Пытаемся преобразовать строку в дату
FS.ShortDateFormat := 'dd.mm.yyyy';
FS.DateSeparator := '.';
Result := TryStrToDate(LoadDate.AsString, ALoadDate, FS);
end;
// Если дата не в том формате
if not Result then
begin
ARecordCheck.Col := LoadDate.Index + 1;
ARecordCheck.ErrorMessage := 'Дата';
ARecordCheck.Description := 'Поле дата имеет неверный формат';
ProcessErrors(ARecordCheck);
Exit;
end;
end
else
begin
// Если дата не заполнена
ALoadDate := Date;
TryEdit;
LoadDate.AsString := FormatDateTime('dd.mm.yyyy', Date);
TryPost;
end;
Assert(CurrencyInt <> nil);
// Должен быть указан курс доллара или известен курс на нужную нам дату
if Dollar.IsNull then
begin
ADollar := 0;
try
// Пытаемся получить курс доллара
ADollar := CurrencyInt.GetCourses(2, ALoadDate);
except
Result := False;
end;
// Если курс доллара получить не удалось
if (not Result) or (ADollar = 0) then
begin
ARecordCheck.Col := Dollar.Index + 1;
ARecordCheck.ErrorMessage := 'Курс доллара неизвестен';
ARecordCheck.Description := 'Не удалось получить курс доллара';
ProcessErrors(ARecordCheck);
Exit;
end;
TryEdit;
Dollar.AsFloat := ADollar;
TryPost;
end;
// Должен быть указан курс евро или известен курс на нужную нам дату
if Euro.IsNull then
begin
AEuro := 0;
try
// Пытаемся получить курс евро
AEuro := CurrencyInt.GetCourses(3, ALoadDate);
except
Result := False;
end;
// Если курс Евро получить не удалось
if (not Result) or (AEuro = 0) then
begin
ARecordCheck.Col := Euro.Index + 1;
ARecordCheck.ErrorMessage := 'Курс евро неизвестен';
ARecordCheck.Description := 'Не удалось получить курс евро';
ProcessErrors(ARecordCheck);
Exit;
end;
TryEdit;
Euro.AsFloat := AEuro;
TryPost;
end;
// Проверяем, что количество - целое число
Result := StrToFloatDef(Amount.AsString, -1) <> -1;
if not Result then
begin
// Сигнализируем о неверном значении количества
ARecordCheck.Col := Amount.Index + 1;
ARecordCheck.ErrorMessage := 'Неверный формат';
ARecordCheck.Description := 'Количество должно быть числом';
ProcessErrors(ARecordCheck);
Exit;
end;
// Проверяем запись на дубликат
Assert(Assigned(CheckDuplicate));
Result := not CheckDuplicate.HaveDuplicate(Self);
if not Result then
begin
ARecordCheck.Col := Value.Index + 1;
ARecordCheck.ErrorMessage := 'Дубликат';
ARecordCheck.Description :=
'Этот компонент уже был загружен на склад ранее';
ProcessErrors(ARecordCheck);
Exit;
end;
end;
function TProductsExcelTable.GetComponentGroup: TField;
begin
Result := FieldByName('ComponentGroup');
end;
function TProductsExcelTable.GetDollar: TField;
begin
Result := FieldByName('Dollar');
end;
function TProductsExcelTable.GetEuro: TField;
begin
Result := FieldByName('Euro');
end;
function TProductsExcelTable.GetLoadDate: TField;
begin
Result := FieldByName('LoadDate');
end;
function TProductsExcelTable.GetPriceR: TField;
begin
Result := FieldByName('PriceR');
end;
function TProductsExcelTable.GetPriceD: TField;
begin
Result := FieldByName('PriceD');
end;
function TProductsExcelTable.GetPriceE: TField;
begin
Result := FieldByName('PriceE');
end;
function TProductsExcelTable.GetProducer: TField;
begin
Result := FieldByName('Producer');
end;
function TProductsExcelTable.GetAmount: TField;
begin
Result := FieldByName('Amount');
end;
function TProductsExcelTable.GetPrice: TField;
begin
Result := nil;
if not PriceR.IsNull then
begin
Assert(PriceD.IsNull and PriceE.IsNull);
Result := PriceR;
Exit;
end;
if not PriceD.IsNull then
begin
Assert(PriceR.IsNull and PriceE.IsNull);
Result := PriceD;
Exit;
end;
if not PriceE.IsNull then
begin
Assert(PriceR.IsNull and PriceD.IsNull);
Result := PriceE;
Exit;
end;
end;
function TProductsExcelTable.GetValue: TField;
begin
Result := FieldByName('Value');
end;
procedure TProductsExcelTable.SetFieldsInfo;
var
AFI: TFieldInfoEx;
begin
if FieldsInfo.Count > 0 then
Exit;
for AFI in FFieldsInfoArr do
begin
if AFI.Exist then
FieldsInfo.Add(TFieldInfo.Create(AFI.FieldName, AFI.Required,
AFI.ErrorMessage, AFI.IsCellUnion, AFI.Size));
end;
(*
FieldsInfo.Add(TFieldInfo.Create('ComponentGroup', True,
'Группа компонентов не задана', True));
FieldsInfo.Add(TFieldInfo.Create('Value', True, 'Наименование не задано'));
FieldsInfo.Add(TFieldInfo.Create('Producer', True, 'Производитель не задан'));
FieldsInfo.Add(TFieldInfo.Create('PackagePins'));
FieldsInfo.Add(TFieldInfo.Create('ReleaseDate'));
FieldsInfo.Add(TFieldInfo.Create('Amount', True, 'Количество не задано'));
FieldsInfo.Add(TFieldInfo.Create('Packaging'));
FieldsInfo.Add(TFieldInfo.Create('PriceR'));
FieldsInfo.Add(TFieldInfo.Create('PriceD'));
FieldsInfo.Add(TFieldInfo.Create('PriceE'));
FieldsInfo.Add(TFieldInfo.Create('OriginCountryCode'));
FieldsInfo.Add(TFieldInfo.Create('OriginCountry'));
FieldsInfo.Add(TFieldInfo.Create('BatchNumber'));
FieldsInfo.Add(TFieldInfo.Create('CustomsDeclarationNumber'));
FieldsInfo.Add(TFieldInfo.Create('Storage'));
FieldsInfo.Add(TFieldInfo.Create('StoragePlace'));
FieldsInfo.Add(TFieldInfo.Create('Seller'));
FieldsInfo.Add(TFieldInfo.Create('DocumentNumber'));
FieldsInfo.Add(TFieldInfo.Create('Barcode'));
FieldsInfo.Add(TFieldInfo.Create('LoadDate'));
FieldsInfo.Add(TFieldInfo.Create('Dollar'));
FieldsInfo.Add(TFieldInfo.Create('Euro'));
*)
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLVerletClasses<p>
Classes and functions that make integration between verlets and glscene
objects easy.
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Added "VectorTypes.pas" unit to uses
<li>13/04/04 - MF - Verlet call now uses TVerletProgressTimes
<li>06/03/04 - MF - Creation
</ul>
}
unit GLVerletClasses;
interface
uses
GLVerletTypes, GLVectorGeometry, GLScene, GLObjects, GLVectorTypes;
type
// TGLVerletNode
//
{: Specialized verlet node that can be anchored to a GLScene object. If it's
anchored and has the property "NailedDown" set, it will remain in the same
relative position to the GLScene object.}
TGLVerletNode = class(TVerletNode)
private
FRelativePosition: TAffineVector;
FGLBaseSceneObject: TGLBaseSceneObject;
procedure SetGLBaseSceneObject(const Value: TGLBaseSceneObject);
protected
procedure SetLocation(const Value: TAffineVector);override;
public
procedure Verlet(const vpt : TVerletProgressTimes); override;
property GLBaseSceneObject : TGLBaseSceneObject read FGLBaseSceneObject write SetGLBaseSceneObject;
property RelativePosition : TAffineVector read FRelativePosition write FRelativePosition;
end;
function CreateVCPlaneFromGLPlane(Plane : TGLPlane; VerletWorld : TVerletWorld; Offset : single) : TVCFloor;
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
implementation
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
function CreateVCPlaneFromGLPlane(Plane : TGLPlane; VerletWorld : TVerletWorld; Offset : single) : TVCFloor;
begin
result := TVCFloor.Create(VerletWorld);
with result do
begin
Normal := VectorNormalize(Plane.Direction.AsAffineVector);
Location := VectorAdd(Plane.Position.AsAffineVector, VectorScale(Normal, Offset));
end;
end;
{ TGLVerletNode }
procedure TGLVerletNode.SetGLBaseSceneObject(
const Value: TGLBaseSceneObject);
begin
FGLBaseSceneObject := Value;
if Assigned(GLBaseSceneObject) and NailedDown then
FRelativePosition := AffineVectorMake(GLBaseSceneObject.AbsoluteToLocal(VectorMake(FLocation, 1)));
end;
procedure TGLVerletNode.SetLocation(const Value: TAffineVector);
begin
inherited;
if Assigned(GLBaseSceneObject) and NailedDown then
FRelativePosition := GLBaseSceneObject.AbsoluteToLocal(Value);
end;
procedure TGLVerletNode.Verlet(const vpt : TVerletProgressTimes);
begin
if Assigned(GLBaseSceneObject) and NailedDown then
begin
FLocation := GLBaseSceneObject.LocalToAbsolute(FRelativePosition);
end else
inherited;
end;
end.
|
unit MinTransfersplanner;
//# BEGIN TODO Completed by: author name, id.nr., date
{ Replace this line by your text }
//# END TODO
interface
uses
Contnrs,
MetroBase, Planner;
type
TMinTransfersPlanner =
class(TPlanner)
protected
FNetwork: TNetwork;
public
// construction/destruction
constructor Create(ANetwork: TNetwork);
// queries --------------------------------------------
function FindRoutes(A, B: TStationR; AOption: TSearchOption): TRouteSet;
override;
// pre: true
// ret: set of optimal (according to AOption) routes from A to B
function FindRoute(A, B: TStationR; AOption: TSearchOption): TRouteR;
override;
// pre: true
// ret: a route from A to B with minimal number of transfers
end;
implementation //===============================================================
// Auxiliary types
type
TLineState = (lsWhite, lsGrey, lsBlack);
TLineData =
class(TObject)
FState: TLineState;
FParent: TLineR;
FEntry: TStationR;
end;
{ TBFSPlanner }
constructor TMinTransfersPlanner.Create(ANetwork: TNetwork);
begin
inherited Create;
FNetwork := ANetwork;
end;
function TMinTransfersPlanner.FindRoute(A, B: TStationR;
AOption: TSearchOption): TRouteR;
//# BEGIN TODO
// Replace this by your own declarations
//# END TODO
begin
//# BEGIN TODO
// Replace the following code by an algorithm which finds a route with a
// minimal number of TRANSFERS from station A to station B.
// The parameter AOption may be ignored.
// An abstract code scheme for this algorithm can be found in the document
// Metro_Planner_Algorithms.htm .
// niet aan toegekomen
Result := TRouteRW.Create;
//# END TODO
end;
function TMinTransfersPlanner.FindRoutes(A, B: TStationR;
AOption: TSearchOption): TRouteSet;
begin
Result := TRouteSet.Create;
Result.Add(FindRoute(A, B, AOption));
end;
end.
|
{===============================================================================
通讯线程基类
===============================================================================}
unit xThreadBase;
interface
uses System.SysUtils, System.Classes, xProtocolBase,xFunction, xVCL_FMX,
xCommBase, xSerialBase, xTCPClientBase, xTCPServerBase, xUDPServerBase;
type
TOrderObject = class
private
FOrderType: Integer;
FOrderObject: TObject;
FOrderIP: string;
FOrderPort: Integer;
public
/// <summary>
/// 命令类型
/// </summary>
property OrderType : Integer read FOrderType write FOrderType;
/// <summary>
/// 命令对象
/// </summary>
property OrderObject : TObject read FOrderObject write FOrderObject;
/// <summary>
/// 命令IP
/// </summary>
property OrderIP : string read FOrderIP write FOrderIP;
/// <summary>
/// 命令端口
/// </summary>
property OrderPort : Integer read FOrderPort write FOrderPort;
end;
type
/// <summary>
/// 线路类型
/// </summary>
TCommType = (ctNot,
ctSerial, // 串口
ctTCPClient, // TCP客户端
ctTCPServer, // TCP服务器
ctUDPServer // UDP服务器
);
type
/// <summary>
/// 通讯线程基类
/// </summary>
TThreadBase = class(TThread)
private
FTOWaitForSeconds: Cardinal;
FOrderReplayed: Boolean;
FProType: TCommType;
FTimerOrderEnable: Boolean;
FTimeOrderList: TStringList;
FTempIndex : Integer;
FMSeconds : Cardinal; // 设置定时命令有效后计时用
FOrderList : TStringList; // 命令列表
procedure SetProType(const Value: TCommType);
procedure SetTimerOrderEnable(const Value: Boolean);
procedure SetCommBase(const Value: TCommBase);
protected
FIsStop : Boolean; // 是否停止运行
FProtocol : TProtocolBase;
FCommBase : TCommBase; // 通讯线路
procedure Execute; override;
/// <summary>
/// 执行实时命令
/// </summary>
procedure ExecuteOrder(ACmdType: Integer; ADevice: TObject; sIP : string; nPort : Integer); virtual;
/// <summary>
/// 执行定时命令 (如果定时命令要执行列表需要判断 FIsStop 是佛停止运行,如果挺尸运行需要跳出循环)
/// </summary>
procedure ExecuteTimerOrder; virtual;
/// <summary>
/// 退出
/// </summary>
procedure SetExit;
public
constructor Create(CreateSuspended: Boolean); virtual;
destructor Destroy; override;
/// <summary>
/// 线程名称
/// </summary>
function TheardName : string; virtual;
/// <summary>
/// 通讯线路类型
/// </summary>
property ProType : TCommType read FProType write SetProType;
/// <summary>
/// 通讯线路
/// </summary>
property CommBase : TCommBase read FCommBase write SetCommBase;
/// <summary>
/// 执行命令
/// </summary>
/// <param name="ACmdType">命令类型</param>
/// <param name="ADevice">命令对象</param>
/// <param name="bWairtExecute">是否等待执行完命令才推出函数</param>
procedure AddOrder( ACmdType: Integer; ADevice: TObject;
bWairtExecute : Boolean = True; sIP : string = ''; nPort : Integer = 0); virtual;
/// <summary>
/// 命令是否执行完
/// </summary>
function OrdersFinished : Boolean;
/// <summary>
/// 等待命名执行完
/// </summary>
function IsWaitReplied( nCmdTimeOut : Cardinal = 1000 ): Boolean;
/// <summary>
/// 定时命令是否有效
/// </summary>
property TimerOrderEnable: Boolean read FTimerOrderEnable write SetTimerOrderEnable;
/// <summary>
/// 定时命令有效之后等待时间 毫秒
/// </summary>
property TOWaitForSeconds : Cardinal read FTOWaitForSeconds write FTOWaitForSeconds;
/// <summary>
/// 定时命令列表
/// </summary>
property TimeOrderList : TStringList read FTimeOrderList write FTimeOrderList;
/// <summary>
/// 命令是否通讯正常
/// </summary>
property OrderReplayed : Boolean read FOrderReplayed write FOrderReplayed;
/// <summary>
/// 是否打开串口 连接到服务器,侦听端口
/// </summary>
function IsConned : Boolean;
end;
implementation
{ TThreadBase }
procedure TThreadBase.AddOrder(ACmdType: Integer; ADevice: TObject;
bWairtExecute: Boolean;sIP : string; nPort : Integer);
var
nTimeOut : Integer;
AOderObject : TOrderObject;
begin
if IsConned then
begin
AOderObject := TOrderObject.Create;
AOderObject.OrderType := ACmdType;
AOderObject.OrderObject := ADevice;
AOderObject.OrderIP := sIP;
AOderObject.OrderPort := nPort;
FOrderList.AddObject( IntToStr( Integer(ACmdType) ), AOderObject);
if bWairtExecute then
begin
if Assigned(FProtocol) then
begin
nTimeOut := FProtocol.OrderTimeOut;
IsWaitReplied(nTimeOut);
end;
end;
end;
end;
constructor TThreadBase.Create(CreateSuspended: Boolean);
begin
inherited;
FOrderList := TStringList.Create;
FTimeOrderList := TStringList.Create;
FTimerOrderEnable := False;
FTOWaitForSeconds := 3000;
FIsStop := False;
end;
destructor TThreadBase.Destroy;
begin
SetExit;
Terminate;
FOrderList.Free;
ClearStringList(FTimeOrderList);
FTimeOrderList.Free;
if Assigned(FCommBase) then
FCommBase.Free;
inherited;
end;
procedure TThreadBase.Execute;
var
AOrderObject : TOrderObject;
begin
inherited;
while not Terminated do
begin
if FMSeconds > 0 then
begin
if GetTickCount - FMSeconds > FTOWaitForSeconds then
begin
FTimerOrderEnable := True;
FMSeconds := 0;
end;
end;
Sleep(1);
MyProcessMessages;
// 处理所有实时命令
while FOrderList.Count > 0 do
begin
if FIsStop then
Break;
if Assigned( FOrderList.Objects[ 0 ] ) then
begin
AOrderObject := TOrderObject(FOrderList.Objects[ 0 ]);
with AOrderObject do
begin
ExecuteOrder(OrderType, OrderObject, OrderIP, OrderPort);
end;
if FOrderList.Count > 0 then
begin
AOrderObject.Free;
FOrderList.Delete( 0 );
end;
end;
end;
// 处理定时命令
if FTimerOrderEnable and not FIsStop then
ExecuteTimerOrder;
// Sleep(1);
// MyProcessMessages;
end;
end;
procedure TThreadBase.ExecuteOrder(ACmdType: Integer; ADevice: TObject;
sIP : string; nPort : Integer);
begin
if Assigned(FProtocol) then
FOrderReplayed := FProtocol.SendData(ACmdType, ADevice, sIP, IntToStr(nPort))
else
FOrderReplayed := False;
end;
procedure TThreadBase.ExecuteTimerOrder;
begin
if TimeOrderList.Count > FTempIndex then
begin
with TOrderObject(TimeOrderList.Objects[FTempIndex]) do
begin
if Assigned(FProtocol) and not FIsStop then
FProtocol.SendData(OrderType, OrderObject, OrderIP, IntToStr(OrderPort));
end;
end;
Inc(FTempIndex);
if FTempIndex >= TimeOrderList.Count then
begin
FTempIndex := 0;
end;
end;
function TThreadBase.IsConned: Boolean;
begin
if Assigned(FCommBase) then
Result := FCommBase.Active
else
Result := False;
end;
function TThreadBase.IsWaitReplied(nCmdTimeOut: Cardinal): Boolean;
var
nTick : Cardinal;
begin
nTick := GetTickCount;
repeat
MyProcessMessages;
Result := OrdersFinished;
Sleep(1);
until Result or ( GetTickCount - nTick > nCmdTimeOut );
end;
function TThreadBase.OrdersFinished: Boolean;
begin
Result := FOrderList.Count = 0;
end;
procedure TThreadBase.SetCommBase(const Value: TCommBase);
begin
FCommBase := Value;
end;
procedure TThreadBase.SetExit;
begin
FIsStop := True;
if Assigned(FProtocol) then
FProtocol.SetExit;
end;
procedure TThreadBase.SetProType(const Value: TCommType);
begin
FProType := Value;
case FProType of
ctSerial :
begin
if Assigned(FCommBase) then
begin
if FCommBase.ClassName <> TSerialBase.ClassName then
begin
FCommBase.OnRevPacks := nil;
FCommBase.Free;
FCommBase := TSerialBase.Create;
end;
end
else
begin
FCommBase := TSerialBase.Create;
end;
// FProtocol 必须先创建
FProtocol.OnSendData := FCommBase.SendPacksDataBase;
FCommBase.OnRevPacks := FProtocol.ReceivedData;
end;
ctTCPClient:
begin
if Assigned(FCommBase) then
begin
if FCommBase.ClassName <> TTCPClientBase.ClassName then
begin
FCommBase.OnRevPacks := nil;
FCommBase.Free;
FCommBase := TTCPClientBase.Create;
end;
end
else
begin
FCommBase := TTCPClientBase.Create;
end;
FProtocol.OnSendData := FCommBase.SendPacksDataBase;
FCommBase.OnRevPacks := FProtocol.ReceivedData;
end;
ctTCPServer:
begin
if Assigned(FCommBase) then
begin
if FCommBase.ClassName <> TTCPServerBase.ClassName then
begin
FCommBase.OnRevPacks := nil;
FCommBase.Free;
FCommBase := TTCPServerBase.Create;
end;
end
else
begin
FCommBase := TTCPServerBase.Create;
end;
FProtocol.OnSendData := FCommBase.SendPacksDataBase;
FCommBase.OnRevPacks := FProtocol.ReceivedData;
end;
ctUDPServer:
begin
if Assigned(FCommBase) then
begin
if FCommBase.ClassName <> TUDPServerBase.ClassName then
begin
FCommBase.OnRevPacks := nil;
FCommBase.Free;
FCommBase := TUDPServerBase.Create;
end;
end
else
begin
FCommBase := TUDPServerBase.Create;
end;
FProtocol.OnSendData := FCommBase.SendPacksDataBase;
FCommBase.OnRevPacks := FProtocol.ReceivedData;
end;
end;
end;
procedure TThreadBase.SetTimerOrderEnable(const Value: Boolean);
begin
if Value then
begin
FMSeconds := GetTickCount;
end
else
begin
FMSeconds :=0;
FTimerOrderEnable := Value;
end;
end;
function TThreadBase.TheardName: string;
begin
Result := '匿名线程';
end;
end.
|
{
> I whant to draw a new mouse cursor, and the routines that I'm using will
> allow me to do this by passing an array [0..31] of integer; I don't know
> how to draw a cursor thought using this array. Some other routins have
> predifined cursors, but that nubers are out of range.
Here's some explanation:
At the memory location where ES:DX points to, there have to be first 16
words (the screen mask) followed by 16 words (the cursor mask).
The screen mask defines an AND with the background beneath the cursor, and
the cursor mask defines a XOR with the background pixels.
- For each pixel use the following Equations:
1. expand each mask-bit to the width needed to display one colored-pixel
in the used video-mode, e.g. if you are using mode $13 (320x200x256)
each mask-bit is expanded to 8 bits (one byte). If you are using
640x480x16, each mask-bit is expanded to 4 bits.
2. Backgrd._pixel AND screen-mask_pixel XOR cursor-mask_pixel => new
pixel.
Example: (standard arrow-cursor)
screen-mask cursor-mask | cursor-form
|
1001111111111111 0000000000000000 | +00+++++++++++++
1000111111111111 0010000000000000 | +010++++++++++++
1000011111111111 0011000000000000 | +0110+++++++++++
1000001111111111 0011100000000000 | +01110++++++++++
1000000111111111 0011110000000000 | +011110+++++++++
1000000011111111 0011111000000000 | +0111110++++++++
1000000001111111 0011111100000000 | +01111110+++++++
1000000000111111 0011111110000000 | +011111110++++++
1000000000011111 0011111111000000 | +0111111110+++++
1000000000001111 0011111000000000 | +01111100000++++
1000000011111111 0011011000000000 | +0110110++++++++
1000100001111111 0010001100000000 | +01000110+++++++
1001100001111111 0000001100000000 | +00++0110+++++++
1111110000111111 0000000110000000 | ++++++0110++++++
1111110000111111 0000000110000000 | ++++++0110++++++
1111111000111111 0000000000000000 | +++++++000++++++
|
As you can easily see:
screen-mask | cursor-mask | new pixel
-------------+-------------+-----------
0 | 0 | black
0 | 1 | white
1 | 0 | background visible
1 | 1 | background inverted
A quick example for the inverted background:
Lets say we have a 01101101 as a backgroundpixel, ok?
1. 01101101
AND 11111111 (expanded) screen-mask-bit
-----------------------------------------
01101101 leaving the background-pixel untouched.
2. 01101101
XOR 11111111 (expanded) cursor-mask-bit
-----------------------------------------
10010010 inverted background pixel
}
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.ComponentToClipboard;
interface
uses
System.SysUtils, System.Types, System.Classes, FMX.Platform;
procedure StreamToClipboard(aComponents: array of TComponent);
function ComponentToText(AComponent: TComponent): string;
implementation
procedure StreamToClipboard(aComponents: array of TComponent);
var
LSvc: IFMXClipboardService;
LComponentsText, LCompText, LNames: TStringList;
LComp: TComponent;
LLineIdx, LNameIdx: Integer;
LLine, LDefName, LCurName: string;
begin
LNames := nil;
LCompText := nil;
LComponentsText := nil;
try
LComponentsText := TStringList.Create;
LNames := TStringList.Create;
LCompText := TStringList.Create;
for LComp in aComponents do
begin
if LComp <> nil then
begin
LCompText.Text := ComponentToText(LComp);
// Give everything default names
LCurName := Format('%s.%s', [LComp.Owner.Name, LComp.Name]);
LDefName := Copy(LComp.ClassName, 2) + '1'; // Exclude 'T'
LCompText[0] := StringReplace(LCompText[0],
Format('object %s:', [LComp.Name]),
Format('object %s:', [LDefName]), []);
// Save the component text
LComponentsText.AddStrings(LCompText);
// Save the name to clean up referenes later
LNames.Values[LCurName] := LDefName;
end;
end;
// Clean up
for LLineIdx := LComponentsText.Count - 1 downto 0 do
begin
// Remove Left & Top
LLine := Trim(Copy(TrimLeft(LComponentsText[LLineIdx]), 1, 6));
if (LLine = 'Left =') or (LLine = 'Top =') then
LComponentsText.Delete(LLineIdx)
else
begin
// Clean up name references
LLine := LComponentsText[LLineIdx];
for LNameIdx := 0 to LNames.Count - 1 do
begin
if Pos(Format(' = %s', [LNames.Names[LNameIdx]]), LLine) > 0 then
begin
LLine := LLine.Replace(LNames.Names[LNameIdx],
LNames.ValueFromIndex[LNameIdx], []);
LComponentsText[LLineIdx] := LLine;
end;
end;
end;
end;
// Put it all in the clipboard
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService,
LSvc) then
LSvc.SetClipboard(LComponentsText.Text)
finally
LCompText.Free;
LComponentsText.Free;
LNames.Free;
end;
end;
function ComponentToText(AComponent: TComponent): string;
var
LStrStream: TStringStream;
LMemStream: TMemoryStream;
begin
if AComponent = nil then
Exit('');
LStrStream := nil;
LMemStream := nil;
try
LMemStream := TMemoryStream.Create();
LStrStream := TStringStream.Create();
// Stream the component
LMemStream.WriteComponent(AComponent);
LMemStream.Position := 0;
// Convert to text
ObjectBinaryToText(LMemStream, LStrStream);
LStrStream.Position := 0;
// Output the text
Result := LStrStream.ReadString(LStrStream.Size);
finally
LStrStream.Free;
LMemStream.Free;
end;
end;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit provinces;
interface
uses
plasticarrays, genericutils, hashtable, hashfunctions, cardinalhashtable, players;
const
kInitialTroops = 3;
kTroopRecruitmentCount = 3;
type
TProvince = class
public type
TArray = specialize PlasticArray <TProvince, TObjectUtils>;
TTroopHashTable = specialize TPlayerHashTable <Cardinal>;
TReadOnlyArray = TArray.TReadOnlyView;
protected
FName: UTF8String;
FNeighbours: TArray;
FID: Cardinal;
FOwner: TPlayer;
FTroops: TTroopHashTable;
function GetOwnerTroops(): Cardinal;
public
constructor Create(const Name: UTF8String; const ID: Cardinal; const Owner: TPlayer; const Troops: Cardinal);
destructor Destroy(); override;
procedure AddNeighbour(const Neighbour: TProvince);
function HasNeighbour(const Neighbour: TProvince): Boolean;
procedure SetID(const NewID: Cardinal);
procedure AssignInitialPlayer(const Player: TPlayer);
function CanBeSeenBy(const Player: TPlayer): Boolean;
function NeighboursCanBeSeenBy(const Player: TPlayer): Boolean;
function CommitTroops(const Count: Cardinal; const Source: TPlayer): Boolean;
procedure ReceiveTroops(const Count: Cardinal; const Source: TPlayer);
procedure ResolveBattles();
procedure EndTurn();
property Name: UTF8String read FName;
property ID: Cardinal read FID;
property Owner: TPlayer read FOwner;
property ResidentTroopPopulation: Cardinal read GetOwnerTroops;
function GetNeighbours(): TReadOnlyArray;
end;
type
TProvinceHashTable = specialize TCardinalHashTable <TProvince>;
implementation
constructor TProvince.Create(const Name: UTF8String; const ID: Cardinal; const Owner: TPlayer; const Troops: Cardinal);
begin
FName := Name;
FID := ID;
FOwner := Owner;
FTroops := TTroopHashTable.Create();
if (Assigned(FOwner)) then
FTroops[FOwner] := Troops;
end;
destructor TProvince.Destroy();
begin
FTroops.Free();
end;
procedure TProvince.AddNeighbour(const Neighbour: TProvince);
begin
FNeighbours.Push(Neighbour);
end;
function TProvince.HasNeighbour(const Neighbour: TProvince): Boolean;
begin
Result := FNeighbours.Contains(Neighbour);
end;
procedure TProvince.SetID(const NewID: Cardinal);
begin
FID := NewID;
end;
procedure TProvince.AssignInitialPlayer(const Player: TPlayer);
begin
Assert(not Assigned(FOwner));
Assert(Assigned(Player));
FOwner := Player;
FTroops[FOwner] := kInitialTroops;
end;
function TProvince.CanBeSeenBy(const Player: TPlayer): Boolean;
var
Neighbour: TProvince;
begin
Result := True;
if (FOwner = Player) then
exit;
for Neighbour in FNeighbours do // $R-
if (Neighbour.FOwner = Player) then
exit;
Result := False;
end;
function TProvince.NeighboursCanBeSeenBy(const Player: TPlayer): Boolean;
begin
Result := FOwner = Player;
end;
function TProvince.GetNeighbours(): TArray.TReadOnlyView;
begin
Result := FNeighbours.GetReadOnlyView();
end;
function TProvince.GetOwnerTroops(): Cardinal;
begin
Assert(Assigned(FOwner));
Assert(FTroops.Count = 1);
Result := FTroops[FOwner];
end;
function TProvince.CommitTroops(const Count: Cardinal; const Source: TPlayer): Boolean;
begin
Assert(Source = FOwner);
Result := FTroops[Source] >= Count;
if (Result) then
FTroops[Source] := FTroops[Source] - Count; // $R-
end;
procedure TProvince.ReceiveTroops(const Count: Cardinal; const Source: TPlayer);
begin
if (FTroops[Source] < High(Cardinal) - Count) then
FTroops[Source] := FTroops[Source] + Count
else // $R-
FTroops[Source] := High(Cardinal);
end;
type
TBattleEntry = record
Player: TPlayer;
Count: Cardinal;
end;
BattleUtils = record
class function Equals(const A, B: TBattleEntry): Boolean; static; inline;
class function LessThan(const A, B: TBattleEntry): Boolean; static; inline;
class function GreaterThan(const A, B: TBattleEntry): Boolean; static; inline;
end;
class function BattleUtils.Equals(const A, B: TBattleEntry): Boolean;
begin
Assert(False); // only used for PlasticArray.Remove() and PlasticArray.Contains()
Result := False;
end;
class function BattleUtils.LessThan(const A, B: TBattleEntry): Boolean; static; inline;
begin
Result := A.Count < B.Count;
end;
class function BattleUtils.GreaterThan(const A, B: TBattleEntry): Boolean; static; inline;
begin
Result := A.Count > B.Count;
end;
procedure TProvince.ResolveBattles();
var
Armies: specialize PlasticArray <TBattleEntry, BattleUtils>;
Army, BestArmy, SecondBestArmy: TBattleEntry;
Player, Winner: TPlayer;
RemainingTroops, Count: Cardinal;
begin
if (FTroops.Count > 1) then
begin
Armies.Init();
for Player in FTroops do
begin
Army.Player := Player;
Army.Count := FTroops[Player];
Armies.Push(Army);
end;
Assert(Armies.Length > 1);
Armies.Sort();
BestArmy := Armies.Pop();
SecondBestArmy := Armies.Pop();
Winner := BestArmy.Player;
Assert(BestArmy.Count >= SecondBestArmy.Count);
RemainingTroops := BestArmy.Count - SecondBestArmy.Count; // $R-
FTroops.Empty();
if (RemainingTroops > 0) then
begin
FTroops[Winner] := RemainingTroops;
FOwner := Winner;
end
else
FOwner := nil;
end
else
if (Assigned(FOwner)) then
begin
Assert(FTroops.Has(FOwner));
if (FTroops[FOwner] = 0) then
begin
FTroops.Empty();
FOwner := nil;
end;
end
else
begin
Count := 0;
for Player in FTroops do
begin
FOwner := Player;
Inc(Count);
end;
Assert(Count = 1);
end;
Assert(FTroops.Count <= 1);
Assert((FTroops.Count = 0) or (Assigned(FOwner) and (FTroops.Has(FOwner)) and (FTroops[FOwner] > 0)));
end;
procedure TProvince.EndTurn();
begin
if (Assigned(FOwner)) then
begin
if (FTroops[FOwner] < High(Cardinal) - kTroopRecruitmentCount) then
FTroops[FOwner] := FTroops[FOwner] + kTroopRecruitmentCount
else // $R-
FTroops[FOwner] := High(Cardinal);
end;
end;
end. |
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x57;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uXPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
implementation
Uses SysUtils;
(*
Type $57 - UV Sensors
Buffer[0] = packetlength = $09;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = uv
Buffer[7] = temperaturehigh:7/temperaturesign:1
Buffer[8] = temperaturelow
Buffer[9] = battery_level:4/rssi:4
xPL Schema
sensor.basic
{
device=uv1|uv2|uv3 0x<hex sensor id>
type=uv
current=(0-12)
}
sensor.basic
{
device=uv1|uv2|uv30x<hex sensor id>
type=temp
current=<degrees celsius>
units=c
}
sensor.basic
{
device=uv1|uv2|uv30x<hex sensor id>
type=battery
current=0-100
}
*)
const
// Type
UV = $5;
// Subtype
UV1 = $01;
UV2 = $02;
UV3 = $03;
var
SubTypeArray : array[1..3] of TRFXSubTypeRec =
((SubType : UV1; SubTypeString : 'uv1'),
(SubType : UV2; SubTypeString : 'uv2'),
(SubType : UV3; SubTypeString : 'uv3'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
SubType : Byte;
UV : Extended;
Temperature : Extended;
TemperatureSign : String;
BatteryLevel : Integer;
xPLMessage : TxPLMessage;
begin
SubType := Buffer[2];
DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2);
UV := Buffer[6] / 10;
if SubType = UV3 then
begin
if Buffer[7] and $80 > 0 then
TemperatureSign := '-'; // negative value
Buffer[7] := Buffer[7] and $7F; // zero out the temperature sign
Temperature := ((Buffer[7] shl 8) + Buffer[8]) / 10;
end;
if (Buffer[9] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create sensor.basic messages
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+FloatToStr(UV));
xPLMessage.Body.AddKeyValue('type=uv');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
if SubType = UV3 then
begin
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+TemperatureSign+FloatToStr(Temperature));
xPLMessage.Body.AddKeyValue('units=c');
xPLMessage.Body.AddKeyValue('type=temperature');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel));
xPLMessage.Body.AddKeyValue('type=battery');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
end.
|
unit CRSsoStorage;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
Windows, Registry,
{$ENDIF}
SysUtils, Classes,
CRTypes, CRFunctions,
ScBridge;
{$I SecureBridgeVer.inc}
type
TCRSsoStorage = class(TScStorage)
protected
FPKCS12Processor: TScPKCS12Processor;
procedure InternalLoad(Item: TScStorageItem); override;
procedure InternalSave(Item: TScStorageItem); override;
procedure InternalDelete(Item: TScStorageItem); override;
procedure InternalRename(Item: TScStorageItem; const NewName: string; CheckIfExists: boolean); override;
procedure InternalGetNames(const ItemClass: TScStorageItemClass; List: TStrings); override;
procedure InternalDeleteStorage; override;
procedure LoadSSOWallet; virtual; abstract;
public
destructor Destroy; override;
end;
TCRSsoFileStorage = class(TCRSsoStorage)
private
FPath: string;
FFileName: string;
procedure SetPath(const Value: string);
procedure SetFileName(const Value: string);
function GetFullPath: string;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure DefineProperties(Filer: TFiler); override;
procedure ReadPath(Reader: TReader);
procedure WritePath(Writer: TWriter);
procedure ReadFileName(Reader: TReader);
procedure WriteFileName(Writer: TWriter);
procedure LoadSSOWallet; override;
public
constructor Create(AOwner: TComponent); override;
{$IFDEF ODBC_DRIVER}
procedure SetFullWalletPath(const Value: string);
{$ENDIF}
published
property Path: string read FPath write SetPath stored False;
property FileName: string read FFileName write SetFileName stored False;
end;
{$IFDEF MSWINDOWS}
TCRSsoRegStorage = class(TCRSsoStorage)
private
FKeyPath: string;
FValueName: string;
FRegistry: TRegistry;
procedure SetKeyPath(const Value: string);
procedure SetValueName(const Value: string);
procedure SetRootKey(const Value: NativeUint);
function GetRootKey: NativeUint;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure DefineProperties(Filer: TFiler); override;
procedure ReadKeyPath(Reader: TReader);
procedure WriteKeyPath(Writer: TWriter);
procedure ReadValueName(Reader: TReader);
procedure WriteValueName(Writer: TWriter);
procedure LoadSSOWallet; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{$IFDEF ODBC_DRIVER}
procedure SetFullWalletRegPath(const Value: string);
{$ENDIF}
published
{$HPPEMIT '#ifdef KeyPath'}
{$HPPEMIT '#undef KeyPath'}
{$HPPEMIT '#endif'}
property KeyPath: string read FKeyPath write SetKeyPath stored False;
property ValueName: string read FValueName write SetValueName stored False;
property RootKey: NativeUint read GetRootKey write SetRootKey default HKEY_CURRENT_USER;
end;
{$ENDIF}
implementation
const
DefaultWalletPath = '.';
DefaultWalletFileName = 'cwallet.sso';
DefaultWalletKeyPath = '\Software\ORACLE\WALLETS';
DefaultWalletKeyName = 'DEFAULT';
DefaultWalletValueName = 'cwallet.sso';
{ TCRSsoStorage }
destructor TCRSsoStorage.Destroy;
begin
FPKCS12Processor.Free;
inherited;
end;
procedure TCRSsoStorage.InternalLoad(Item: TScStorageItem);
begin
end;
procedure TCRSsoStorage.InternalSave(Item: TScStorageItem);
begin
end;
procedure TCRSsoStorage.InternalDelete(Item: TScStorageItem);
begin
end;
procedure TCRSsoStorage.InternalRename(Item: TScStorageItem; const NewName: string; CheckIfExists: boolean);
begin
end;
procedure TCRSsoStorage.InternalGetNames(const ItemClass: TScStorageItemClass; List: TStrings);
begin
if FPKCS12Processor = nil then
LoadSSOWallet;
end;
procedure TCRSsoStorage.InternalDeleteStorage;
begin
Keys.Clear;
Users.Clear;
Certificates.Clear;
CRLs.Clear;
FreeAndNil(FPKCS12Processor);
end;
{ TCRSsoFileStorage }
constructor TCRSsoFileStorage.Create(AOwner: TComponent);
begin
inherited;
FPath := DefaultWalletPath;
FFileName := DefaultWalletFileName;
end;
procedure TCRSsoFileStorage.SetPath(const Value: string);
begin
if Value <> FPath then begin
FPath := Trim(Value);
Invalidate;
end;
end;
procedure TCRSsoFileStorage.SetFileName(const Value: string);
begin
if Value <> FFileName then begin
FFileName := Trim(Value);
Invalidate;
end;
end;
function TCRSsoFileStorage.GetFullPath: string;
begin
Result := FPath;
if (Result <> '') and (Result[1] = '.') and // Path = '.'; '..'; '.\'; '..\'
(CurrentProjectOutputDir <> '')
then
Result := IncludeTrailingPathDelimiter(CurrentProjectOutputDir) + Result;
end;
procedure TCRSsoFileStorage.AssignTo(Dest: TPersistent);
begin
if IsClass(Dest, TCRSsoFileStorage) then begin
TCRSsoFileStorage(Dest).Path := Path;
TCRSsoFileStorage(Dest).FileName := FileName;
end
else
inherited;
end;
procedure TCRSsoFileStorage.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineProperty('Path', ReadPath, WritePath, FPath <> DefaultWalletPath);
Filer.DefineProperty('FileName', ReadFileName, WriteFileName, FFileName <> DefaultWalletFileName);
end;
procedure TCRSsoFileStorage.ReadPath(Reader: TReader);
begin
FPath := Reader.ReadString;
end;
procedure TCRSsoFileStorage.WritePath(Writer: TWriter);
begin
Writer.WriteString(FPath);
end;
procedure TCRSsoFileStorage.ReadFileName(Reader: TReader);
begin
FFileName := Reader.ReadString;
end;
procedure TCRSsoFileStorage.WriteFileName(Writer: TWriter);
begin
Writer.WriteString(FFileName);
end;
procedure TCRSsoFileStorage.LoadSSOWallet;
var
FullFileName: string;
Stream: TFileStream;
Password: string;
begin
FullFileName := GetFullPath;
if FullFileName <> '' then
FullFileName := IncludeTrailingPathDelimiter(FullFileName);
FullFileName := FullFileName + FFileName;
Stream := TFileStream.Create(FullFileName, fmOpenRead);
try
{$IFDEF SB_DEMO_VER2}
Password := TScPKCS12Processor.ImportPasswordFromSSO(Stream);
{$ELSE}
Password := TScPKCS12Processor.ImportFromSSO(Stream);
{$ENDIF}
FPKCS12Processor := TScPKCS12Processor.Create;
try
FPKCS12Processor.ImportFrom(Stream, Password);
ImportFromPKCS12(FPKCS12Processor);
except
FreeAndNil(FPKCS12Processor);
raise;
end;
finally
Stream.Free;
end;
end;
{$IFDEF ODBC_DRIVER}
procedure TCRSsoFileStorage.SetFullWalletPath(const Value: string);
var
FileName: string;
FileExt: string;
begin
FileName := ExtractFileName(Value);
if FileName = '' then begin
FPath := Value;
FFileName := DefaultWalletFileName;
end
else begin
FileExt := ExtractFileExt(Value);
if (FileExt = '') or (FileExt = '.') then begin
FPath := Value;
FFileName := DefaultWalletFileName;
end
else begin
FPath := ExtractFilePath(Value);
FFileName := FileName;
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
{ TCRSsoRegStorage }
constructor TCRSsoRegStorage.Create(AOwner: TComponent);
begin
inherited;
FRegistry := TRegistry.Create(KEY_READ);
FKeyPath := DefaultWalletKeyPath + '\' + DefaultWalletKeyName;
FValueName := DefaultWalletValueName;
end;
destructor TCRSsoRegStorage.Destroy;
begin
FRegistry.Free;
inherited;
end;
procedure TCRSsoRegStorage.SetKeyPath(const Value: string);
begin
if Value <> FKeyPath then begin
FKeyPath := Trim(Value);
Invalidate;
end;
end;
procedure TCRSsoRegStorage.SetValueName(const Value: string);
begin
if Value <> FValueName then begin
FValueName := Trim(Value);
Invalidate;
end;
end;
procedure TCRSsoRegStorage.SetRootKey(const Value: NativeUint);
begin
if Value <> FRegistry.RootKey then begin
FRegistry.RootKey := Value;
Invalidate;
end;
end;
function TCRSsoRegStorage.GetRootKey: NativeUint;
begin
Result := FRegistry.RootKey;
end;
procedure TCRSsoRegStorage.AssignTo(Dest: TPersistent);
begin
if IsClass(Dest, TCRSsoRegStorage) then begin
TCRSsoRegStorage(Dest).RootKey := RootKey;
TCRSsoRegStorage(Dest).ValueName := ValueName;
TCRSsoRegStorage(Dest).KeyPath := KeyPath;
end
else
inherited;
end;
procedure TCRSsoRegStorage.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineProperty('KeyPath', ReadKeyPath, WriteKeyPath, KeyPath <> DefaultWalletKeyPath + '\' + DefaultWalletKeyName);
Filer.DefineProperty('ValueName', ReadValueName, WriteValueName, KeyPath <> DefaultWalletValueName);
end;
procedure TCRSsoRegStorage.ReadKeyPath(Reader: TReader);
begin
FKeyPath := Reader.ReadString;
end;
procedure TCRSsoRegStorage.WriteKeyPath(Writer: TWriter);
begin
Writer.WriteString(FKeyPath);
end;
procedure TCRSsoRegStorage.ReadValueName(Reader: TReader);
begin
FValueName := Reader.ReadString;
end;
procedure TCRSsoRegStorage.WriteValueName(Writer: TWriter);
begin
Writer.WriteString(FValueName);
end;
procedure TCRSsoRegStorage.LoadSSOWallet;
var
DataSize: Integer;
CertificateData: TBytes;
Stream: TMemoryStream;
Password: string;
begin
if FRegistry.OpenKeyReadOnly(FKeyPath) then begin
DataSize := FRegistry.GetDataSize(ValueName);
if DataSize > 0 then begin
SetLength(CertificateData, DataSize);
FRegistry.ReadBinaryData(ValueName, CertificateData[0], DataSize);
end
else
SetLength(CertificateData, 0);
Stream := TMemoryStream.Create;
try
Stream.Write(CertificateData, Length(CertificateData));
Stream.Seek(0, soBeginning);
{$IFDEF SB_DEMO_VER2}
Password := TScPKCS12Processor.ImportPasswordFromSSO(Stream);
{$ELSE}
Password := TScPKCS12Processor.ImportFromSSO(Stream);
{$ENDIF}
FPKCS12Processor := TScPKCS12Processor.Create;
try
FPKCS12Processor.ImportFrom(Stream, Password);
ImportFromPKCS12(FPKCS12Processor);
except
FreeAndNil(FPKCS12Processor);
raise;
end;
finally
Stream.Free;
end;
end;
end;
{$IFDEF ODBC_DRIVER}
procedure TCRSsoRegStorage.SetFullWalletRegPath(const Value: string);
function DecodeRegPath(out KeyPath, ValueName: string): string;
var
i: Integer;
begin
i := Length(Value);
while (i >= 1) and (Value[i] <> '\') do
Dec(i);
KeyPath := Copy(Value, 1, i - 1);
ValueName := Copy(Value, i + 1, Length(Value) - i);
end;
var
KeyPath: string;
ValueName: string;
begin
DecodeRegPath(KeyPath, ValueName);
if KeyPath = '' then begin
FKeyPath := DefaultWalletKeyPath + '\' + ValueName;
FValueName := DefaultWalletValueName;
end
else if Pos('\', KeyPath) = 0 then begin
FKeyPath := DefaultWalletKeyPath + '\' + KeyPath;
if ValueName <> '' then
FValueName := ValueName
else
FValueName := DefaultWalletValueName;
end
else if FRegistry.KeyExists(KeyPath + '\' + ValueName) then begin
FKeyPath := KeyPath + '\' + ValueName;
FValueName := DefaultWalletValueName;
end
else begin
FKeyPath := KeyPath;
if ValueName <> '' then
FValueName := ValueName
else
FValueName := DefaultWalletValueName;
end;
end;
{$ENDIF}
{$ENDIF}
end. |
unit main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls,
Vcl.Samples.Spin;
type
//=====================================CLASS FORM
TfMain = class(TForm)
btnShow: TSpeedButton;
edtName: TEdit;
isGreen: TCheckBox;
mmoOutput: TMemo;
edtDiameter: TSpinEdit;
isDiameterless: TCheckBox;
procedure btnShowClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//=====================================CLASS FRUIT
Fruit = class
private
_name : string;
_diameter : integer;
_isGreen : boolean;
public
Constructor New(name: string ; diameter : integer ; isGreen : boolean);Overload;
Constructor New(edtName : TEdit ; isDiameterless : tCheckbox; edtDiameter : TSpinEdit ; isGreen : TCheckbox);Overload;
function GetName():string;
function GetDiameter():integer;
function GetIsGreen():boolean;
end;
var
fMain: TfMain;
fr_dull,fr_processed,fr_direct : Fruit;
implementation
{$R *.dfm}
Constructor Fruit.New(name: string ; diameter : integer ; isGreen : boolean);
begin
self._name := name;
self._diameter := diameter;
self._isGreen := isGreen;
end;
Constructor Fruit.New(edtName: TEdit; isDiameterless : tCheckbox; edtDiameter: TSpinEdit; isGreen: TCheckBox);
begin
self._name := edtName.Text;
if(isDiameterless.Checked)
then
self._diameter := -1
else
self._diameter := edtDiameter.Value;
self._isGreen := isGreen.Checked;
end;
function Fruit.GetName():string;
begin
result:=self._name;
end;
function Fruit.GetDiameter():integer;
begin
result:=self._diameter;
end;
function Fruit.GetIsGreen():boolean;
begin
result:=self._isGreen;
end;
// end;
procedure TfMain.btnShowClick(Sender: TObject);
begin
fMain.mmoOutput.Lines.Clear;
fr_dull := Fruit.New('banana',-1,True);
if(fMain.isDiameterless.Checked)
then
fr_processed := Fruit.New(fMain.edtName.Text,-1,fMain.isGreen.Checked)
else
fr_processed := Fruit.New(fMain.edtName.Text,fMain.edtDiameter.Value,fMain.isGreen.Checked);
fr_direct := Fruit.New(fMain.edtName,fMain.isDiameterless,fMain.edtDiameter, fMain.isGreen);
fMain.mmoOutput.Lines.Add('/Fruit 1/ name == '+fr_dull.GetName+'; diameter == '+inttostr(fr_dull.GetDiameter)+'; isGreeen == '+fr_dull.GetIsGreen.ToString());
fMain.mmoOutput.Lines.Add('/Fruit 2/ name == '+fr_processed.GetName+'; diameter == '+inttostr(fr_processed.GetDiameter)+'; isGreeen == '+fr_processed.GetIsGreen.ToString());
fMain.mmoOutput.Lines.Add('/Fruit 3/ name == '+fr_direct.GetName+'; diameter == '+inttostr(fr_direct.GetDiameter)+'; isGreeen == '+fr_direct.GetIsGreen.ToString());
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ToHClasses, Vcl.BaseImageCollection,
Vcl.ImageCollection, Vcl.StdCtrls, Vcl.ExtCtrls, pngimage, HiScore,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client,
System.UITypes, FireDAC.Stan.Param, NewHiscore;
type
TMainForm = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Image1: TImage;
Image2: TImage;
Image3: TImage;
InfoBox: TMemo;
HiScoreButton: TButton;
Conn: TFDConnection;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure HiScoreButtonClick(Sender: TObject);
private
_game: TTohGame;
procedure AddNewHiscore(position: Integer);
procedure AskForNewGame();
procedure CheckForHiScore();
function GetImageName(tower: TTower): String;
procedure LoadImage(owner: TImage; resourceName: String);
procedure UpdateControls;
procedure UpdateImages;
procedure UpdateStatus;
public
constructor Create(owner: TComponent); override;
procedure UpdateAll;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.AddNewHiscore(position: Integer);
var
newHiscoreForm: TNewHiscoreForm;
begin
newHiscoreForm := TNewHiscoreForm.Create(Screen.ActiveForm, position, _game.NumMoves);
newHiscoreForm.ShowModal();
end;
procedure TMainForm.AskForNewGame();
var
buttonSelected: Integer;
begin
buttonSelected := MessageDlg(
'Congratulations!' + sLineBreak +
'You completed the game.' + sLineBreak +
'Try again?',
mtConfirmation,
[mbYes, mbNo],
0
);
if buttonSelected = mrYes then
begin
_game.Free();
InfoBox.Lines.Clear(); // Clear the infobox
_game := TTohGame.Create();
UpdateAll();
end
else
begin
ShowMessage('Thanks and goodbye!');
Application.MainForm.Close();
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
_game.MoveBlock(1, 2);
UpdateAll();
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
_game.MoveBlock(1, 3);
UpdateAll();
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
_game.MoveBlock(2, 1);
UpdateAll();
end;
procedure TMainForm.Button4Click(Sender: TObject);
begin
_game.MoveBlock(2, 3);
UpdateAll();
end;
procedure TMainForm.Button5Click(Sender: TObject);
begin
_game.MoveBlock(3, 2);
UpdateAll();
end;
procedure TMainForm.Button6Click(Sender: TObject);
begin
_game.MoveBlock(3, 1);
UpdateAll();
end;
procedure TMainForm.CheckForHiScore();
var
query: TFDQuery;
beatenBy: Integer;
begin
Conn.Open();
// To qualify for the hiscore list, the game needs to be in the top ten.
query := TFDQuery.Create(nil);
query.Connection := Conn;
query.SQL.Text :=
'SELECT COUNT(initials) AS beatenBy FROM hiscores WHERE num_moves <= :numMoves';
query.ParamByName('numMoves').AsInteger := _game.NumMoves;
query.OpenOrExecute();
query.First();
beatenBy := query.FieldByName('beatenBy').Value;
query.Free();
Conn.Close();
if beatenBy < 10 then AddNewHiscore(beatenBy + 1);
AskForNewGame();
end;
constructor TMainForm.Create(owner: TComponent);
begin
inherited Create(owner);
_game := TTohGame.Create();
UpdateAll();
end;
function TMainForm.GetImageName(tower: TTower): String;
var
b: TBlock;
i: Integer;
r: String;
begin
for i := Low(tower.Blocks) to tower.Height do
begin
b := tower.Blocks[i];
if b = Red then r := Format('%sR', [r])
else if b = Green then r := Format('%sG', [r])
else if b = Blue then r := Format('%sB', [r])
else raise Exception.Create('Invalid block');
end;
if r = '' then Result := 'Tower_E'
else Result := Format('Tower_%s', [r]);
end;
procedure TMainForm.HiScoreButtonClick(Sender: TObject);
var
hiscoreForm: THiScoreForm;
begin
hiScoreForm := THiScoreForm.Create(Screen.ActiveForm);
hiScoreForm.ShowModal();
end;
procedure TMainForm.LoadImage(owner: TImage; resourceName: String);
var
image: TPngImage;
stream: TResourceStream;
begin
image := TPngImage.Create;
try
stream := TResourceStream.Create(hInstance, resourceName, RT_RCDATA);
try
image.LoadFromStream(stream);
owner.Picture.Graphic := image;
finally
stream.Free;
end;
finally
image.Free;
end;
end;
procedure TMainForm.UpdateAll();
begin
UpdateControls();
UpdateImages();
UpdateStatus();
end;
procedure TMainForm.UpdateControls;
begin
// Controls for first tower
Button1.Enabled := _game.CanMoveBlock(1, 2);
Button2.Enabled := _game.CanMoveBlock(1, 3);
// Controls for second tower
Button3.Enabled := _game.CanMoveBlock(2, 1);
Button4.Enabled := _game.CanMoveBlock(2, 3);
// Controls for third tower
Button5.Enabled := _game.CanMoveBlock(3, 2);
Button6.Enabled := _game.CanMoveBlock(3, 1);
end;
procedure TMainForm.UpdateImages();
begin
LoadImage(Image1, GetImageName(_game.Towers[1]));
LoadImage(Image2, GetImageName(_game.Towers[2]));
LoadImage(Image3, GetImageName(_game.Towers[3]));
end;
procedure TMainForm.UpdateStatus();
var
i: Integer;
msg: String;
t: TTower;
begin
InfoBox.Lines.Add(Format('Moves performed: %d', [_game.NumMoves]));
for i := Low(_game.Towers) to High(_game.Towers) do
begin
t := _game.Towers[i];
msg := Format('Tower %d is %s', [i, t.ToString()]);
InfoBox.Lines.Add(msg)
end;
if _game.IsComplete() then
InfoBox.Lines.Add('You beat the game!')
else
InfoBox.Lines.Add('There is still some work to do...');
InfoBox.Lines.Add('----------------------------------------');
// If the game is complete, check if the user belongs to the hiscore list
if _game.IsComplete() then CheckForHiScore();
end;
end.
|
unit UCarteiraVacinacao;
interface
uses
UEntidade
, UCoren
, ULoteVacina
, UPaciente
;
type
TCARTEIRA_VACINACAO = class(TENTIDADE)
public
ID_SUS : TPACIENTE;
//COD_VACINACAO : String;
NOME : String;
VACINA : String;
DOSE : String;
DATA : TDate;
RESPONSAVEL : String;
COD_COREN : String;
COD_LOTE : String;
LOTE_VENCIMENTO : TDate;
UNIDADE_SAUDE : String;
constructor Create; override;
destructor Destroy; override;
end;
const
TBL_CARTEIRA_VACINACAO = 'CARTEIRA_VACINACAO';
FLD_CAR_ID_SUS = 'ID_SUS';
//FLD_CAR_COD_VACINACAO = 'COD_VACINACAO';
FLD_CAR_NOME = 'NOME';
FLD_CAR_VACINA = 'VACINA';
FLD_CAR_DOSE = 'DOSE';
FLD_CAR_DATA = 'DATA';
FLD_CAR_RESPONSAVEL = 'RESPONSAVEL';
FLD_CAR_COD_COREN = 'COD_COREN';
FLD_CAR_COD_LOTE = 'COD_LOTE';
FLD_CAR_LOTE_VENCIMENTO = 'LOTE_VENCIMENTO';
FLD_UNIDADE_SAUDE = 'UNIDADE_SAUDE';
resourcestring
STR_CARTEIRA_VACINACAO = 'Carteira de Vacinação Online';
implementation
uses
SysUtils
, Dialogs
;
{ TCARTEIRA_VACINACAO }
constructor TCARTEIRA_VACINACAO.Create;
begin
inherited;
ID_SUS := TPACIENTE.Create;
// LOTE_VENCIMENTO := TLOTEVACINA.Create;
//COD_LOTE := TLOTEVACINA.Create;
end;
destructor TCARTEIRA_VACINACAO.Destroy;
begin
FreeAndNil(ID_SUS);
//FreeAndNil(COD_LOTE);
//FreeAndNil(LOTE_VENCIMENTO);
inherited;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is LinkedList.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclLinkedLists;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
Classes,
JclBase, JclAbstractContainers, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclLinkedLists.imp}
{$I containers\JclLinkedLists.int}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclIntfLinkedListItem,TJclIntfLinkedList,TJclIntfAbstractContainer,IJclIntfCollection,IJclIntfList,IJclIntfIterator, IJclIntfEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AInterface,IInterface,GetObject,SetObject)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclAnsiStrLinkedListItem,TJclAnsiStrLinkedList,TJclAnsiStrAbstractCollection,IJclAnsiStrCollection,IJclAnsiStrList,IJclAnsiStrIterator, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrFlatContainer\, IJclAnsiStrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,AnsiString,GetString,SetString)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclWideStrLinkedListItem,TJclWideStrLinkedList,TJclWideStrAbstractCollection,IJclWideStrCollection,IJclWideStrList,IJclWideStrIterator, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrFlatContainer\, IJclWideStrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,WideString,GetString,SetString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrLinkedList = TJclAnsiStrLinkedList;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrLinkedList = TJclWideStrLinkedList;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclSingleLinkedListItem,TJclSingleLinkedList,TJclSingleAbstractContainer,IJclSingleCollection,IJclSingleList,IJclSingleIterator, IJclSingleContainer\, IJclSingleEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Single,GetValue,SetValue)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclDoubleLinkedListItem,TJclDoubleLinkedList,TJclDoubleAbstractContainer,IJclDoubleCollection,IJclDoubleList,IJclDoubleIterator, IJclDoubleContainer\, IJclDoubleEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Double,GetValue,SetValue)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclExtendedLinkedListItem,TJclExtendedLinkedList,TJclExtendedAbstractContainer,IJclExtendedCollection,IJclExtendedList,IJclExtendedIterator, IJclExtendedContainer\, IJclExtendedEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Extended,GetValue,SetValue)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatLinkedList = TJclExtendedLinkedList;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatLinkedList = TJclDoubleLinkedList;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatLinkedList = TJclSingleLinkedList;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclIntegerLinkedListItem,TJclIntegerLinkedList,TJclIntegerAbstractContainer,IJclIntegerCollection,IJclIntegerList,IJclIntegerIterator, IJclIntegerEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Integer,GetValue,SetValue)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclCardinalLinkedListItem,TJclCardinalLinkedList,TJclCardinalAbstractContainer,IJclCardinalCollection,IJclCardinalList,IJclCardinalIterator, IJclCardinalEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Cardinal,GetValue,SetValue)*)
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclInt64LinkedListItem,TJclInt64LinkedList,TJclInt64AbstractContainer,IJclInt64Collection,IJclInt64List,IJclInt64Iterator, IJclInt64EqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Int64,GetValue,SetValue)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclPtrLinkedListItem,TJclPtrLinkedList,TJclPtrAbstractContainer,IJclPtrCollection,IJclPtrList,IJclPtrIterator, IJclPtrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,APtr,Pointer,GetPointer,SetPointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclLinkedListItem,TJclLinkedList,TJclAbstractContainer,IJclCollection,IJclList,IJclIterator, IJclObjectOwner\, IJclEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,; AOwnsObjects: Boolean,,AObject,TObject,GetObject,SetObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLLINKEDLISTINT(TJclLinkedListItem<T>,TJclLinkedList<T>,TJclAbstractContainer<T>,IJclCollection<T>,IJclList<T>,IJclIterator<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\,,,,,,; AOwnsItems: Boolean,const ,AItem,T,GetItem,SetItem)*)
// E = External helper to compare items
// GetHashCode is never called
TJclLinkedListE<T> = class(TJclLinkedList<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclEqualityComparer<T>,
IJclItemOwner<T>)
private
FEqualityComparer: IEqualityComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function ItemsEqual(const A, B: T): Boolean; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityComparer: IEqualityComparer<T>; const ACollection: IJclCollection<T>;
AOwnsItems: Boolean);
property EqualityComparer: IEqualityComparer<T> read FEqualityComparer write FEqualityComparer;
end;
// F = Function to compare items for equality
TJclLinkedListF<T> = class(TJclLinkedList<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclEqualityComparer<T>,
IJclItemOwner<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityCompare: TEqualityCompare<T>; const ACollection: IJclCollection<T>;
AOwnsItems: Boolean);
end;
// I = Items can compare themselves to an other
TJclLinkedListI<T: IEquatable<T>> = class(TJclLinkedList<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclEqualityComparer<T>,
IJclItemOwner<T>)
protected
function ItemsEqual(const A, B: T): Boolean; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclLinkedLists.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils;
type
TItrStart = (isFirst, isLast);
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TIntfItr,IJclIntfIterator,IJclIntfList,IJclIntfEqualityComparer,TJclIntfLinkedListItem,const ,AInterface,IInterface,nil,GetObject,SetObject)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := nil}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TIntfItr,IJclIntfIterator,IJclIntfList,IJclIntfEqualityComparer,TJclIntfLinkedListItem,const ,AInterface,IInterface,nil,GetObject,SetObject)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrList,IJclAnsiStrEqualityComparer,TJclAnsiStrLinkedListItem,const ,AString,AnsiString,'',GetString,SetString)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := ''}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrList,IJclAnsiStrEqualityComparer,TJclAnsiStrLinkedListItem,const ,AString,AnsiString,'',GetString,SetString)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TWideStrItr,IJclWideStrIterator,IJclWideStrList,IJclWideStrEqualityComparer,TJclWideStrLinkedListItem,const ,AString,WideString,'',GetString,SetString)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := ''}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TWideStrItr,IJclWideStrIterator,IJclWideStrList,IJclWideStrEqualityComparer,TJclWideStrLinkedListItem,const ,AString,WideString,'',GetString,SetString)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TSingleItr,IJclSingleIterator,IJclSingleList,IJclSingleEqualityComparer,TJclSingleLinkedListItem,const ,AValue,Single,0.0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0.0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TSingleItr,IJclSingleIterator,IJclSingleList,IJclSingleEqualityComparer,TJclSingleLinkedListItem,const ,AValue,Single,0.0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TDoubleItr,IJclDoubleIterator,IJclDoubleList,IJclDoubleEqualityComparer,TJclDoubleLinkedListItem,const ,AValue,Double,0.0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0.0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TDoubleItr,IJclDoubleIterator,IJclDoubleList,IJclDoubleEqualityComparer,TJclDoubleLinkedListItem,const ,AValue,Double,0.0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TExtendedItr,IJclExtendedIterator,IJclExtendedList,IJclExtendedEqualityComparer,TJclExtendedLinkedListItem,const ,AValue,Extended,0.0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0.0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TExtendedItr,IJclExtendedIterator,IJclExtendedList,IJclExtendedEqualityComparer,TJclExtendedLinkedListItem,const ,AValue,Extended,0.0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TIntegerItr,IJclIntegerIterator,IJclIntegerList,IJclIntegerEqualityComparer,TJclIntegerLinkedListItem,,AValue,Integer,0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TIntegerItr,IJclIntegerIterator,IJclIntegerList,IJclIntegerEqualityComparer,TJclIntegerLinkedListItem,,AValue,Integer,0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TCardinalItr,IJclCardinalIterator,IJclCardinalList,IJclCardinalEqualityComparer,TJclCardinalLinkedListItem,,AValue,Cardinal,0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TCardinalItr,IJclCardinalIterator,IJclCardinalList,IJclCardinalEqualityComparer,TJclCardinalLinkedListItem,,AValue,Cardinal,0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TInt64Itr,IJclInt64Iterator,IJclInt64List,IJclInt64EqualityComparer,TJclInt64LinkedListItem,const ,AValue,Int64,0,GetValue,SetValue)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := 0}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TInt64Itr,IJclInt64Iterator,IJclInt64List,IJclInt64EqualityComparer,TJclInt64LinkedListItem,const ,AValue,Int64,0,GetValue,SetValue)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
{$IFNDEF CLR}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TPtrItr,IJclPtrIterator,IJclPtrList,IJclPtrEqualityComparer,TJclPtrLinkedListItem,,AValue,Pointer,nil,GetPointer,SetPointer)*)
{$JPPDEFINEMACRO ITEMFREE(Item)Item := nil}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TPtrItr,IJclPtrIterator,IJclPtrList,IJclPtrEqualityComparer,TJclPtrLinkedListItem,,AValue,Pointer,nil,GetPointer,SetPointer)*)
{$JPPUNDEFMACRO ITEMFREE(Item)}
{$ENDIF ~CLR}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TItr,IJclIterator,IJclList,IJclEqualityComparer,TJclLinkedListItem,,AObject,TObject,nil,GetObject,SetObject)*)
{$JPPDEFINEMACRO ITEMFREE(AObject)(FownList as IJclObjectOwner).FreeObject(AObject)}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TItr,IJclIterator,IJclList,IJclEqualityComparer,TJclLinkedListItem,,AObject,TObject,nil,GetObject,SetObject)*)
{$JPPUNDEFMACRO ITEMFREE(AObject)}
{$IFDEF SUPPORTS_GENERICS}
type
(*$JPPEXPANDMACRO JCLLINKEDLISTITRINT(TItr<T>,IJclIterator<T>,IJclList<T>,IJclEqualityComparer<T>,TJclLinkedListItem<T>,const ,AItem,T,Default(T),GetItem,SetItem)*)
{$JPPDEFINEMACRO ITEMFREE(AItem)(FownList as IJclItemOwner<T>).FreeItem(AItem)}
(*$JPPEXPANDMACRO JCLLINKEDLISTITRIMP(TItr<T>,IJclIterator<T>,IJclList<T>,IJclEqualityComparer<T>,TJclLinkedListItem<T>,const ,AItem,T,Default(T),GetItem,SetItem)*)
{$JPPUNDEFMACRO ITEMFREE(AObject)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclIntfLinkedList,TJclIntfLinkedListItem,IJclIntfCollection,IJclIntfList,IJclIntfIterator,TIntfItr,,,const ,AInterface,IInterface,nil,GetObject,SetObject,FreeObject)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclAnsiStrLinkedList,TJclAnsiStrLinkedListItem,IJclAnsiStrCollection,IJclAnsiStrList,IJclAnsiStrIterator,TAnsiStrItr,,,const ,AString,AnsiString,'',GetString,SetString,FreeString)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclWideStrLinkedList,TJclWideStrLinkedListItem,IJclWideStrCollection,IJclWideStrList,IJclWideStrIterator,TWideStrItr,,,const ,AString,WideString,'',GetString,SetString,FreeString)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclSingleLinkedList,TJclSingleLinkedListItem,IJclSingleCollection,IJclSingleList,IJclSingleIterator,TSingleItr,,,const ,AValue,Single,0.0,GetValue,SetValue,FreeSingle)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclDoubleLinkedList,TJclDoubleLinkedListItem,IJclDoubleCollection,IJclDoubleList,IJclDoubleIterator,TDoubleItr,,,const ,AValue,Double,0.0,GetValue,SetValue,FreeDouble)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclExtendedLinkedList,TJclExtendedLinkedListItem,IJclExtendedCollection,IJclExtendedList,IJclExtendedIterator,TExtendedItr,,,const ,AValue,Extended,0.0,GetValue,SetValue,FreeExtended)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclIntegerLinkedList,TJclIntegerLinkedListItem,IJclIntegerCollection,IJclIntegerList,IJclIntegerIterator,TIntegerItr,,,,AValue,Integer,0,GetValue,SetValue,FreeInteger)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclCardinalLinkedList,TJclCardinalLinkedListItem,IJclCardinalCollection,IJclCardinalList,IJclCardinalIterator,TCardinalItr,,,,AValue,Cardinal,0,GetValue,SetValue,FreeCardinal)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64LinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64LinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclInt64LinkedList,TJclInt64LinkedListItem,IJclInt64Collection,IJclInt64List,IJclInt64Iterator,TInt64Itr,,,const ,AValue,Int64,0,GetValue,SetValue,FreeInt64)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrLinkedList.Create(nil);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclPtrLinkedList,TJclPtrLinkedListItem,IJclPtrCollection,IJclPtrList,IJclPtrIterator,TPtrItr,,,,APtr,Pointer,nil,GetPointer,SetPointer,FreePointer)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclLinkedList.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclLinkedList.Create(nil, False);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclLinkedList,TJclLinkedListItem,IJclCollection,IJclList,IJclIterator,TItr,; AOwnsObjects: Boolean,AOwnsObjects,,AObject,TObject,nil,GetObject,SetObject,FreeObject)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPEXPANDMACRO JCLLINKEDLISTIMP(TJclLinkedList<T>,TJclLinkedListItem<T>,IJclCollection<T>,IJclList<T>,IJclIterator<T>,TItr<T>,; AOwnsItems: Boolean,AOwnsItems,const ,AItem,T,Default(T),GetItem,SetItem,FreeItem)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
//=== { TJclLinkedListE<T> } =================================================
constructor TJclLinkedListE<T>.Create(const AEqualityComparer: IEqualityComparer<T>;
const ACollection: IJclCollection<T>; AOwnsItems: Boolean);
begin
inherited Create(ACollection, AOwnsItems);
FEqualityComparer := AEqualityComparer;
end;
procedure TJclLinkedListE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclLinkedListE<T> then
TJclLinkedListE<T>(Dest).FEqualityComparer := FEqualityComparer;
end;
function TJclLinkedListE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclLinkedListE<T>.Create(EqualityComparer, nil, False);
AssignPropertiesTo(Result);
end;
function TJclLinkedListE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if EqualityComparer <> nil then
Result := EqualityComparer.Equals(A, B)
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclLinkedListF<T> } =================================================
constructor TJclLinkedListF<T>.Create(const AEqualityCompare: TEqualityCompare<T>;
const ACollection: IJclCollection<T>; AOwnsItems: Boolean);
begin
inherited Create(ACollection, AOwnsItems);
SetEqualityCompare(AEqualityCompare);
end;
function TJclLinkedListF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclLinkedListF<T>.Create(EqualityCompare, nil, False);
AssignPropertiesTo(Result);
end;
//=== { TJclLinkedListI<T> } =================================================
function TJclLinkedListI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclLinkedListI<T>.Create(nil, False);
AssignPropertiesTo(Result);
end;
function TJclLinkedListI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
if Assigned(FCompare) then
Result := FCompare(A, B) = 0
else
Result := A.Equals(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QConsts;
interface
const
// Delphi mime types
SDelphiBitmap = 'image/delphi.bitmap';
SDelphiComponent = 'application/delphi.component';
SDelphiPicture = 'image/delphi.picture';
SDelphiDrawing = 'image/delphi.drawing';
resourcestring
SInvalidCreateWidget = 'Class %s could not create QT widget';
STooManyMessageBoxButtons = 'Too many buttons specified for message box';
SmkcBkSp = 'Backspace';
SmkcTab = 'Tab';
SmkcBackTab = 'BackTab';
SmkcEsc = 'Esc';
SmkcReturn = 'Return';
SmkcEnter = 'Enter';
SmkcSpace = 'Space';
SmkcPgUp = 'PgUp';
SmkcPgDn = 'PgDn';
SmkcEnd = 'End';
SmkcHome = 'Home';
SmkcLeft = 'Left';
SmkcUp = 'Up';
SmkcRight = 'Right';
SmkcDown = 'Down';
SmkcIns = 'Ins';
SmkcDel = 'Del';
SmkcShift = 'Shift+';
SmkcCtrl = 'Ctrl+';
SmkcAlt = 'Alt+';
SOpenFileTitle = 'Open';
SAssignError = 'Cannot assign a %s to a %s';
SFCreateError = 'Cannot create file %s';
SFOpenError = 'Cannot open file %s';
SReadError = 'Stream read error';
SWriteError = 'Stream write error';
SMemoryStreamError = 'Out of memory while expanding memory stream';
SCantWriteResourceStreamError = 'Can''t write to a read-only resource stream';
SDuplicateReference = 'WriteObject called twice for the same instance';
SClassNotFound = 'Class %s not found';
SInvalidImage = 'Invalid stream format';
SResNotFound = 'Resource %s not found';
SClassMismatch = 'Resource %s is of incorrect class';
SListIndexError = 'List index out of bounds (%d)';
SListCapacityError = 'List capacity out of bounds (%d)';
SListCountError = 'List count out of bounds (%d)';
SSortedListError = 'Operation not allowed on sorted string list';
SDuplicateString = 'String list does not allow duplicates';
SInvalidTabIndex = 'Tab index out of bounds';
SInvalidTabPosition = 'Tab position incompatible with current tab style';
SInvalidTabStyle = 'Tab style incompatible with current tab position';
SDuplicateName = 'A component named %s already exists';
SInvalidName = '''''%s'''' is not a valid component name';
SDuplicateClass = 'A class named %s already exists';
SInvalidInteger = '''''%s'''' is not a valid integer value';
SLineTooLong = 'Line too long';
SInvalidPropertyValue = 'Invalid property value';
SInvalidPropertyPath = 'Invalid property path';
SInvalidPropertyType = 'Invalid property type: %s';
SInvalidPropertyElement = 'Invalid property element: %s';
SUnknownProperty = 'Property does not exist';
SReadOnlyProperty = 'Property is read-only';
SPropertyException = 'Error reading %s%s%s: %s';
SAncestorNotFound = 'Ancestor for ''%s'' not found';
SInvalidBitmap = 'Bitmap image is not valid';
SInvalidIcon = 'Icon image is not valid';
SInvalidPixelFormat = 'Invalid pixel format';
SBitmapEmpty = 'Bitmap is empty';
SScanLine = 'Scan line index out of range';
SChangeIconSize = 'Cannot change the size of an icon';
SUnknownExtension = 'Unknown picture file extension (.%s)';
SUnknownClipboardFormat = 'Unsupported clipboard format';
SOutOfResources = 'Out of system resources';
SNoCanvasHandle = 'Canvas does not allow drawing';
SInvalidCanvasState = 'Invalid canvas state request';
SInvalidImageSize = 'Invalid image size';
SInvalidWidgetHandle = 'Invalid widget handle';
SInvalidColorDepth = 'Color depth must be 1, 8 or 32 bpp';
STooManyImages = 'Too many images';
SWidgetCreate = 'Error creating widget';
SCannotFocus = 'Cannot focus a disabled or invisible window (%s)';
SParentRequired = 'Control ''%s'' has no parent widget';
SParentGivenNotAParent = 'Parent given is not a parent of ''%s''';
SVisibleChanged = 'Cannot change Visible in OnShow or OnHide';
SCannotShowModal = 'Cannot make a visible window modal';
SScrollBarRange = 'Scrollbar property out of range';
SPropertyOutOfRange = '%s property out of range';
SMenuIndexError = 'Menu index out of range';
SMenuReinserted = 'Menu inserted twice';
SNoMenuRecursion = 'Menu insertion recursion not allowed';
SMenuNotFound = 'Sub-menu is not in menu';
SMenuSetFormError = 'TMenu.SetForm: argument must be TCustomForm';
SNoTimers = 'Not enough timers available';
SNotPrinting = 'Printer is not currently printing';
SPrinting = 'Printing in progress';
SNoAdapter = 'No printer adapter available for printing';
SPrinterIndexError = 'Printer index out of range';
SInvalidPrinter = 'Printer selected is not valid';
SDeviceOnPort = '%s on %s';
SGroupIndexTooLow = 'GroupIndex cannot be less than a previous menu item''s GroupIndex';
SNoMDIForm = 'Cannot create form. No MDI forms are currently active';
SNotAnMDIForm = 'Invalid MDIParent for class %s';
SMDIChildNotVisible = 'Cannot hide an MDI Child Form';
SRegisterError = 'Invalid component registration';
SImageCanvasNeedsBitmap = 'Can only modify an image if it contains a bitmap';
SControlParentSetToSelf = 'A control cannot have itself as its parent';
SOKButton = 'OK';
SCancelButton = 'Cancel';
SYesButton = '&Yes';
SNoButton = '&No';
SHelpButton = '&Help';
SCloseButton = '&Close';
SIgnoreButton = '&Ignore';
SRetryButton = '&Retry';
SAbortButton = 'Abort';
SAllButton = '&All';
SCannotDragForm = 'Cannot drag a form';
SPutObjectError = 'PutObject to undefined item';
SFB = 'FB';
SFG = 'FG';
SBG = 'BG';
SVIcons = 'Icons';
SVBitmaps = 'Bitmaps';
SVPixmaps = 'Pixmaps';
SVPNGs = 'PNGs';
SDrawings = 'Drawings';
SGridTooLarge = 'Grid too large for operation';
STooManyDeleted = 'Too many rows or columns deleted';
SIndexOutOfRange = 'Grid index out of range';
SFixedColTooBig = 'Fixed column count must be less than column count';
SFixedRowTooBig = 'Fixed row count must be less than row count';
SInvalidStringGridOp = 'Cannot insert or delete rows from grid';
SParseError = '%s on line %d';
SIdentifierExpected = 'Identifier expected';
SStringExpected = 'String expected';
SNumberExpected = 'Number expected';
SCharExpected = '''''%s'''' expected';
SSymbolExpected = '%s expected';
SInvalidNumber = 'Invalid numeric value';
SInvalidString = 'Invalid string constant';
SInvalidProperty = 'Invalid property value';
SInvalidBinary = 'Invalid binary value';
SInvalidCurrentItem = 'Invalid value for current item';
SMaskErr = 'Invalid input value';
SMaskEditErr = 'Invalid input value. Use escape key to abandon changes';
SMsgDlgWarning = 'Warning';
SMsgDlgError = 'Error';
SMsgDlgInformation = 'Information';
SMsgDlgConfirm = 'Confirm';
SMsgDlgYes = '&Yes';
SMsgDlgNo = '&No';
SMsgDlgOK = 'OK';
SMsgDlgCancel = 'Cancel';
SMsgDlgHelp = '&Help';
SMsgDlgHelpNone = 'No help available';
SMsgDlgHelpHelp = 'Help';
SMsgDlgAbort = '&Abort';
SMsgDlgRetry = '&Retry';
SMsgDlgIgnore = '&Ignore';
SMsgDlgAll = '&All';
SMsgDlgNoToAll = 'N&o to All';
SMsgDlgYesToAll = 'Yes to &All';
srUnknown = '(Unknown)';
srNone = '(None)';
SOutOfRange = 'Value must be between %d and %d';
SUnnamed = 'Unnamed';
SDateEncodeError = 'Invalid argument to date encode';
STimeEncodeError = 'Invalid argument to time encode';
SInvalidDate = '''''%s'''' is not a valid date';
SInvalidTime = '''''%s'''' is not a valid time';
SInvalidDateTime = '''''%s'''' is not a valid date and time';
SInvalidFileName = 'Invalid file name - %s';
SDefaultFilter = 'All files (*.*)|*.*';
SInsertLineError = 'Unable to insert a line';
SConfirmCreateDir = 'The specified directory does not exist. Create it?';
SSelectDirCap = 'Select Directory';
SCannotCreateDir = 'Unable to create directory';
SDirNameCap = 'Directory &Name:';
SDrivesCap = 'D&rives:';
SDirsCap = '&Directories:';
SFilesCap = '&Files: (*.*)';
SNetworkCap = 'Ne&twork...';
SInvalidClipFmt = 'Invalid clipboard format';
SIconToClipboard = 'Clipboard does not support Icons';
SCannotOpenClipboard = 'Cannot open clipboard';
SInvalidActionRegistration = 'Invalid action registration';
SInvalidActionUnregistration = 'Invalid action unregistration';
SInvalidActionEnumeration = 'Invalid action enumeration';
SInvalidActionCreation = 'Invalid action creation';
SDefault = 'Default';
SInvalidMemoSize = 'Text exceeds memo capacity';
SCustomColors = 'Custom Colors';
SInvalidPrinterOp = 'Operation not supported on selected printer';
SNoDefaultPrinter = 'There is no default printer currently selected';
SIniFileWriteError = 'Unable to write to %s';
SBitsIndexError = 'Bits index out of range';
SUntitled = '(Untitled)';
SDuplicateMenus = 'Menu ''%s'' is already being used by another form';
SPictureLabel = 'Picture:';
SPictureDesc = ' (%dx%d)';
SPreviewLabel = 'Preview';
SBoldItalicFont = 'Bold Italic';
SBoldFont = 'Bold';
SItalicFont = 'Italic';
SRegularFont = 'Regular';
SPropertiesVerb = 'Properties';
sAsyncSocketError = 'Asynchronous socket error %d';
sNoAddress = 'No address specified';
sCannotListenOnOpen = 'Can''t listen on an open socket';
sCannotCreateSocket = 'Can''t create new socket';
sSocketAlreadyOpen = 'Socket already open';
sCantChangeWhileActive = 'Can''t change value while socket is active';
sSocketMustBeBlocking = 'Socket must be in blocking mode';
sSocketIOError = '%s error %d, %s';
sSocketRead = 'Read';
sSocketWrite = 'Write';
SAllCommands = 'All Commands';
SDuplicateItem = 'List does not allow duplicates ($0%x)';
SDuplicatePropertyCategory = 'A property category called %s already exists';
SUnknownPropertyCategory = 'Property category does not exist (%s)';
SInvalidMask = '''%s'' is an invalid mask at (%d)';
SInvalidFilter = 'Property filters may only be name, class or type based (%d:%d)';
SInvalidCategory = 'Categories must define their own name and description';
sOperationNotAllowed = 'Operation not allowed while dispatching application events';
STextNotFound = 'Text not found: "%s"';
SImageIndexError = 'Invalid ImageList Index';
SReplaceImage = 'Unable to Replace Image';
SInvalidImageType = 'Invalid image type';
SInvalidImageDimensions = 'Image width and heigth must match';
SInvalidImageDimension = 'Invalid image dimension';
SErrorResizingImageList = 'Error resizing ImageList';
SInvalidRangeError = 'Range of %d to %d is invalid';
SInvalidMimeSourceStream = 'MimeSource format must have an associated data stream';
SMimeNotSupportedForIcon = 'Mime format not supported for TIcon';
SOpen = 'Open';
SSave = 'Save As';
SFindWhat = 'Fi&nd what:';
SWholeWord = 'Match &whole word only';
SMatchCase = 'Match &case';
SFindNext = '&Find Next';
SCancel = 'Cancel';
SHelp = 'Help';
SFindTitle = 'Find';
SDirection = 'Direction';
SUp = '&Up';
SDown = '&Down';
SReplaceWith = 'Rep&lace with:';
SReplace = '&Replace';
SReplaceTitle = 'Replace';
SReplaceAll = 'Replace &All';
SOverwriteCaption = 'Save %s as';
SOverwriteText = '%s already exists.'#13'Do you want to replace it?';
SFileMustExist = '%s'#13'File not found.'#13'Please verify the correct '+
'filename was given.';
SPathMustExist = '%s'#13'Path not found.'#13'Please verify the correct '+
'path was given.';
SUnknownImageFormat = 'Image format not recognized';
SInvalidHandle = 'Invalid handle value for %s';
SUnableToWrite = 'Unable to write bitmap';
sAllFilter = 'All';
sInvalidSetClipped = 'Cannot set Clipped property while painting';
sInvalidLCDValue = 'Invalid LCDNumber value';
sTabFailDelete = 'Failed to delete tab at index %d';
sPageIndexError = '%d is an invalid PageIndex value. PageIndex must be ' +
'between 0 and %d';
sInvalidLevel = 'Invalid item level assignment';
sInvalidLevelEx = 'Invalid level (%d) for item "%s"';
sTabMustBeMultiLine = 'MultiLine must be True when TabPosition is tpLeft or tpRight';
sStatusBarContainsControl = '%s is already in the StatusBar';
sListRadioItemBadParent = 'Radio items must have a Controller as a parent';
sOwnerNotCustomHeaderSections = 'Owner is not a TCustomHeaderSection';
sHeaderSectionOwnerNotHeaderControl = 'Header Section owner must be a TCustomHeaderControl';
implementation
end.
|
unit AppData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, ConnUtil;
type
TdmApplication = class(TDataModule)
acMain: TADOConnection;
spGenId: TADOStoredProc;
dstUser: TADODataSet;
acCore: TADOConnection;
dstConfig: TADODataSet;
dstClients: TADODataSet;
dscClients: TDataSource;
dstLoans: TADODataSet;
dscLoans: TDataSource;
dstLocation: TADODataSet;
dstPayments: TADODataSet;
dscPayments: TDataSource;
dstPaymentspayment_id: TStringField;
dstPaymentsreceipt_no: TStringField;
dstPaymentspayment_date: TDateTimeField;
dstPaymentsentity_id: TStringField;
dstPaymentsloc_code: TStringField;
dstPaymentscreated_date: TDateTimeField;
dstPaymentscreated_by: TStringField;
dstPaymentsref_no: TStringField;
dstPaymentspost_date: TDateTimeField;
dstPaymentsname: TStringField;
dstPaymentstotal_amount: TFMTBCDField;
dstDuplicate: TADODataSet;
dscDuplicate: TDataSource;
dstPaymentspmt_method: TWordField;
dstPaymentswd_id: TStringField;
dstPaymentsis_advance: TBooleanField;
dstPaymentswd_amt: TBCDField;
dstPaymentschange: TCurrencyField;
procedure DataModuleCreate(Sender: TObject);
procedure acMainBeforeConnect(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure acCoreBeforeConnect(Sender: TObject);
procedure dstPaymentsCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Pub(ADate, ALoanId)lic declarations }
end;
var
dmApplication: TdmApplication;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
procedure TdmApplication.acCoreBeforeConnect(Sender: TObject);
begin
acCore.ConnectionString := GetConnection('','','',true);
end;
procedure TdmApplication.acMainBeforeConnect(Sender: TObject);
begin
acMain.ConnectionString := GetConnection('','','');
end;
procedure TdmApplication.DataModuleCreate(Sender: TObject);
begin
acCore.Open;
end;
procedure TdmApplication.DataModuleDestroy(Sender: TObject);
begin
acMain.Close;
end;
procedure TdmApplication.dstPaymentsCalcFields(DataSet: TDataSet);
begin
with DataSet do
begin
if FieldByName('wd_amt').AsCurrency > 0 then
FieldByName('change').AsCurrency :=
FieldByName('wd_amt').AsCurrency - FieldByName('total_amount').AsCurrency
else FieldByName('change').AsCurrency := 0;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.HttpClient;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections,
System.Net.UrlClient, System.Net.HttpClient;
type
/// <summary>
/// Exception with HTTP error information.
/// </summary>
EHTTPProtocolException = class(Exception)
private
FErrorMessage: string;
FErrorCode: Integer;
public
/// <summary>Create an exception object</summary>
constructor Create(AErrorCode: Integer; const AErrorMessage: string; const AMessage: string);
/// <summary>The HTTP error code</summary>
property ErrorCode: Integer read FErrorCode;
/// <summary>The HTTP error message</summary>
property ErrorMessage: string read FErrorMessage;
end;
/// <summary>
/// Provides HTTP client functionality
/// </summary>
TRESTHTTP = class(TObject)
public type
/// <summary>Proxy server connection parameters</summary>
IProxyConnectionInfo = interface
/// <summary>Set the port of the proxy server</summary>
procedure SetProxyPort(Val: Integer);
/// <summary>Get the port of the proxy server</summary>
function GetProxyPort: Integer;
/// <summary>Get or set the port of the proxy server</summary>
property ProxyPort: Integer read GetProxyPort write SetProxyPort;
/// <summary>Get the proxy server host name</summary>
function GetProxyServer: string;
/// <summary>Set the proxy server host name</summary>
procedure SetProxyServer(Val: string);
/// <summary>Get or set the proxy server host name</summary>
property ProxyServer: string read GetProxyServer write SetProxyServer;
/// <summary>Get a the username used to access the proxy server</summary>
function GetProxyUserName: string;
/// <summary>Set a the username used to access the proxy server</summary>
procedure SetProxyUserName(user: string);
/// <summary>Get or set the username used to access the proxy server</summary>
property ProxyUserName: string read GetProxyUserName write SetProxyUserName;
/// <summary>Get the password used to access the proxy server</summary>
function GetProxyPassword: string;
/// <summary>Set the password used to access the proxy server</summary>
procedure SetProxyPassword(pass: string);
/// <summary>Get or set the passwor used to access the proxy server</summary>
property ProxyPassword: string read GetProxyPassword write SetProxyPassword;
end;
/// <summary>List of HTTP headers</summary>
IHeaderList = interface
/// <summary>Get the count of header.</summary>
function GetCount: Integer;
/// <summary>Get the count of header.</summary>
property Count: Integer read GetCount;
/// <summary>Get the name of a header.</summary>
function GetName(Index: Integer): string;
/// <summary>Get the name of a header.</summary>
property Names[Index: Integer]: string read GetName;
/// <summary>Get the value of a header.</summary>
function GetValue(const Name: string): string;
/// <summary>Get the value of a header.</summary>
property Values[const Name: string]: string read GetValue;
end;
/// <summary>List of HTTP headers that can be modified</summary>
IRequestHeaderList = interface(IHeaderList)
/// <summary>Clear all headers</summary>
procedure Clear;
/// <summary>Add or modify a header</summary>
procedure SetValue(const AName, AValue: string);
/// <summary>Get or set the value of a header</summary>
property Values[const Name: string]: string read GetValue write SetValue;
end;
/// <summary>Properties of an HTTP request</summary>
IRequest = interface
/// <summary>Get the HTTP request accept string</summary>
function GetAccept: string;
/// <summary>Set the HTTP request accept string</summary>
procedure SetAccept(const Val: string);
/// <summary>Get or set the HTTP request accept string</summary>
property Accept: string read GetAccept write SetAccept;
/// <summary>Get the HTTP request charset string</summary>
function GetAcceptCharSet: string;
/// <summary>Set the HTTP request charset string</summary>
procedure SetAcceptCharSet(const Val: string);
/// <summary>Get or set the HTTP request charset string</summary>
property AcceptCharSet: string read GetAcceptCharSet write SetAcceptCharSet;
/// <summary>Get the HTTP request custom headers.</summary>
function GetCustomHeaders: IRequestHeaderList;
/// <summary>Get the HTTP request custom headers.</summary>
property CustomHeaders: IRequestHeaderList read GetCustomHeaders;
/// <summary>Get the HTTP request acceptencoding string</summary>
function GetAcceptEncoding: string;
/// <summary>Set the HTTP request acceptencoding string</summary>
procedure SetAcceptEncoding(const Val: string);
/// <summary>Get or set the HTTP request acceptencoding string</summary>
property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding;
/// <summary>Get the HTTP request contenttype string</summary>
function GetContentType: string;
/// <summary>Set the HTTP request contenttype string</summary>
procedure SetContentType(LContentType: string);
/// <summary>Get or set the HTTP request contenttype string</summary>
property ContentType: string read GetContentType write SetContentType;
/// <summary>Get the HTTP request useragent string</summary>
function GetUserAgent: string;
/// <summary>Set the HTTP request useragent string</summary>
procedure SetUserAgent(const Val: string);
/// <summary>Get or set the HTTP request useragent string</summary>
property UserAgent: string read GetUserAgent write SetUserAgent;
end;
/// <summary>Common interface for an URL response and all of it's related data</summary>
IURLResponse = interface
/// <summary>Function that transforms the ContentStream into a string</summary>
function ContentAsString(const AnEncoding: TEncoding = nil): string;
end;
/// <summary>Properties of an HTTP response</summary>
IResponse = interface(IURLResponse)
/// <summary>Get the HTTP response character set string</summary>
function GetCharSet: string;
/// <summary>Get the HTTP response character set string</summary>
property CharSet: string read GetCharSet;
/// <summary>Get the HTTP response content type string</summary>
function GetContentType: string;
/// <summary>Get the HTTP response content type string</summary>
property ContentType: string read GetContentType;
/// <summary>Get the HTTP response content encoding string</summary>
function GetContentEncoding: string;
/// <summary>Get the HTTP response content encoding string</summary>
property ContentEncoding: string read GetContentEncoding;
/// <summary>Get the HTTP response headers</summary>
function GetHeaders: IHeaderList;
/// <summary>Get the HTTP response headers</summary>
property Headers: IHeaderList read GetHeaders;
end;
private
FHTTPClient: System.Net.HTTPClient.THTTPClient;
FHTTPResponse: IHTTPResponse;
FIPHTTPRequestIntf: IRequest;
FProxyConnectionInfo: TRESTHTTP.IProxyConnectionInfo;
FOnValidateCertificate: TValidateCertificateEvent;
function GetRequest: IRequest;
function GetResponse: IResponse;
function GetProxyParams: IProxyConnectionInfo;
function GetResponseCode: Integer;
function GetResponseText: string;
function GetHandleRedirects: Boolean;
procedure SetHandleRedirects(AValue: Boolean);
function GetAllowCookies: Boolean;
procedure SetAllowCookies(AValue: Boolean);
function GetConnectTimeout: integer;
procedure SetConnectTimeout(const Value: integer);
function GetReadTimeout: integer;
procedure SetReadTimeout(const Value: integer);
procedure CheckResponse;
procedure PrepareRequest(const ARequest: IHTTPRequest);
procedure Execute(const AMethod: string; AURL: string; ASource,
AResponseContent: TStream); overload;
procedure Execute(const AMethod: string; AURL: string;
AResponseContent: TStream); overload;
procedure RaiseProtocolException(const AResponse: IHTTPResponse);
procedure DoValidateServerCertificate(const Sender: TObject;
const ARequest: TURLRequest; const Certificate: TCertificate;
var Accepted: Boolean);
function GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
function GetNeedClientCertificateEvent: TNeedClientCertificateEvent;
function GetRedirectsWithGET: THTTPRedirectsWithGET;
function GetSecureProtocols: THTTPSecureProtocols;
procedure SetAuthEvent(const AValue: TCredentialsStorage.TCredentialAuthevent);
procedure SetNeedClientCertificateEvent(const AValue: TNeedClientCertificateEvent);
procedure SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
procedure SetSecureProtocols(const AValue: THTTPSecureProtocols);
public
/// <summary>Create an HTTP client</summary>
constructor Create;
destructor Destroy; override;
/// <summary>Execute HTTP DELETE</summary>
procedure Delete(const AURL: string; AResponseStream: TStream); overload;
procedure Delete(const AURL: string; ASource, AResponseStream: TStream); overload;
/// <summary>Execute HTTP PATCH</summary>
procedure Patch(const AURL: string; ASource, AResponseContent: TStream);
/// <summary>Execute HTTP PUT</summary>
procedure Put(const AURL: string; ASource, AResponseContent: TStream);
/// <summary>Execute HTTP POST</summary>
procedure Post(const AURL: string; ASource, AResponseContent: TStream);
/// <summary>Execute HTTP GET</summary>
procedure Get(const AURL: string; AResponseContent: TStream); overload;
procedure Get(const AURL: string; ASource, AResponseContent: TStream); overload;
/// <summary>Add a cookie that will be passed to the server with each request</summary>
procedure AddServerCookie(const ACookie: string; const AURL: string);
/// <summary>Get the HTTP request properties</summary>
property Request: IRequest read GetRequest;
/// <summary>Get the HTTP response properties</summary>
property Response: IResponse read GetResponse;
/// <summary>Get the proxy server connection properties</summary>
property ProxyParams: IProxyConnectionInfo read GetProxyParams;
/// <summary>Get the HTTP status code of the last request</summary>
property ResponseCode: Integer read GetResponseCode;
/// <summary>Get the HTTP status test of the last request</summary>
property ResponseText: string read GetResponseText;
/// <summary>Indicate whether redirect responses are handled automatically by making an additional request.</summary>
property HandleRedirects: Boolean read GetHandleRedirects write SetHandleRedirects;
property RedirectsWithGET: THTTPRedirectsWithGET read GetRedirectsWithGET write SetRedirectsWithGET;
property SecureProtocols: THTTPSecureProtocols read GetSecureProtocols write SetSecureProtocols;
/// <summary>Allow the client to set server side cookies</summary>
property AllowCookies: Boolean read GetAllowCookies write SetAllowCookies;
/// <summary>Get or set the timeout when making an HTTP connection</summary>
property ConnectTimeout: integer read GetConnectTimeout write SetConnectTimeout;
/// <summary>Get or set the timeout when reading a HTTP response</summary>
property ReadTimeout: integer read GetReadTimeout write SetReadTimeout;
/// <summary>Validate the certificate provided by a secure (HTTPS) server</summary>
property OnValidateCertificate: TValidateCertificateEvent read FOnValidateCertificate write FOnValidateCertificate;
property OnNeedClientCertificate: TNeedClientCertificateEvent read GetNeedClientCertificateEvent write SetNeedClientCertificateEvent;
property OnAuthEvent: TCredentialsStorage.TCredentialAuthevent read GetAuthEvent write SetAuthEvent;
end;
implementation
uses
System.Hash, System.NetEncoding, System.StrUtils, System.NetConsts;
type
TIPHTTPRequest = class (TInterfacedObject, TRESTHTTP.IRequest)
private
FAccept: string;
FAcceptCharSet: string;
FUserAgent: string;
FContentType: string;
FAcceptEncoding: string;
FCustomHeaders: TStrings;
function GetAccept: string;
procedure SetAccept(const Val: string);
function GetAcceptCharSet: string;
procedure SetAcceptCharSet(const Val: string);
function GetCustomHeaders: TRESTHTTP.IRequestHeaderList;
function GetAcceptEncoding: string;
procedure SetAcceptEncoding(const Val: string);
function GetContentType: string;
procedure SetContentType(LContentType: string);
function GetUserAgent: string;
procedure SetUserAgent(const Val: string);
public
constructor Create;
destructor Destroy; override;
end;
TIPHTTPResponse = class (TInterfacedObject, TRESTHTTP.IResponse)
private
FResponse: IHTTPResponse;
function GetCharSet: string;
function GetContentType: string;
function GetContentEncoding: string;
function GetHeaders: TRESTHTTP.IHeaderList;
public
constructor Create(const AResponse: IHTTPResponse);
/// <summary>Implementation of IURLResponse ContentAsString</summary>
function ContentAsString(const AnEncoding: TEncoding = nil): string;
end;
TIPProxyConnectionInfo = class(TInterfacedObject, TRESTHTTP.IProxyConnectionInfo)
private
FProxySettings: TProxySettings;
procedure SetProxyPort(Val: Integer);
function GetProxyPort: Integer;
function GetProxyServer: string;
procedure SetProxyServer(Val: string);
function GetProxyUserName: string;
procedure SetProxyUserName(user: string);
function GetProxyPassword: string;
procedure SetProxyPassword(pass: string);
end;
TIPResponseHeaderList = class(TInterfacedObject, TRESTHTTP.IHeaderList)
private
FStrings: TStrings;
function GetCount: Integer;
function GetName(Index: Integer): string;
function GetValue(const Name: string): string;
public
constructor Create(const AResponse: IHTTPResponse);
destructor Destroy; override;
end;
TIPRequestHeaderList = class(TInterfacedObject, TRESTHTTP.IHeaderList, TRESTHTTP.IRequestHeaderList)
private
FStrings: TStrings;
function GetCount: Integer;
function GetName(Index: Integer): string;
function GetValue(const Name: string): string;
procedure Clear;
procedure SetValue(const AName, AValue: string);
public
constructor Create(const AStrings: TStrings);
end;
procedure TRESTHTTP.AddServerCookie(const ACookie, AURL: string);
begin
if FHTTPClient.AllowCookies then
FHTTPClient.CookieManager.AddServerCookie(ACookie, AURL);
end;
constructor TRESTHTTP.Create;
begin
FHTTPClient := THTTPClient.Create;
FHTTPClient.OnValidateServerCertificate := DoValidateServerCertificate;
FIPHTTPRequestIntf := TIPHTTPRequest.Create; // Reference count
AllowCookies := true;
end;
procedure TRESTHTTP.DoValidateServerCertificate(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean);
begin
if Assigned(FOnValidateCertificate) then
FOnValidateCertificate(Sender, ARequest, Certificate, Accepted)
else
// Accept by default
Accepted := True;
end;
procedure TRESTHTTP.Delete(const AURL: string; AResponseStream: TStream);
begin
Execute('DELETE', AURL, AResponseStream);
end;
procedure TRESTHTTP.Delete(const AURL: string; ASource, AResponseStream: TStream);
begin
Execute('DELETE', AURL, ASource, AResponseStream);
end;
destructor TRESTHTTP.Destroy;
begin
FHTTPClient.Free;
inherited;
end;
procedure TRESTHTTP.Get(const AURL: string; AResponseContent: TStream);
begin
Execute('GET', AURL, AResponseContent);
end;
procedure TRESTHTTP.Get(const AURL: string; ASource, AResponseContent: TStream);
begin
Execute('GET', AURL, ASource, AResponseContent);
end;
function TRESTHTTP.GetAllowCookies: Boolean;
begin
Result := FHTTPClient.AllowCookies;
end;
function TRESTHTTP.GetConnectTimeout: integer;
begin
Result := FHTTPClient.ConnectionTimeout;
end;
function TRESTHTTP.GetHandleRedirects: Boolean;
begin
Result := FHTTPClient.HandleRedirects;
end;
function TRESTHTTP.GetRedirectsWithGET: THTTPRedirectsWithGET;
begin
Result := FHTTPClient.RedirectsWithGET;
end;
function TRESTHTTP.GetSecureProtocols: THTTPSecureProtocols;
begin
Result := FHTTPClient.SecureProtocols;
end;
function TRESTHTTP.GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
begin
Result := FHTTPClient.AuthEvent;
end;
function TRESTHTTP.GetNeedClientCertificateEvent: TNeedClientCertificateEvent;
begin
Result := FHTTPClient.OnNeedClientCertificate;
end;
function TRESTHTTP.GetProxyParams: IProxyConnectionInfo;
begin
if FProxyConnectionInfo = nil then
FProxyConnectionInfo := TIPProxyConnectionInfo.Create;
Result := FProxyConnectionInfo;
end;
function TRESTHTTP.GetReadTimeout: integer;
begin
Result := FHTTPClient.ResponseTimeout;
end;
function TRESTHTTP.GetRequest: IRequest;
begin
Result := FIPHTTPRequestIntf;
end;
function TRESTHTTP.GetResponse: IResponse;
begin
CheckResponse;
Result := TIPHTTPResponse.Create(FHTTPResponse);
end;
procedure TRESTHTTP.CheckResponse;
begin
if FHTTPResponse = nil then
raise Exception.Create('No response');
end;
function TRESTHTTP.GetResponseCode: Integer;
begin
CheckResponse;
Result := FHTTPResponse.StatusCode;
end;
function TRESTHTTP.GetResponseText: string;
begin
CheckResponse;
Result := FHTTPResponse.StatusText;
end;
procedure TRESTHTTP.Patch(const AURL: string; ASource, AResponseContent: TStream);
begin
Execute('PATCH', AURL, ASource, AResponseContent);
end;
procedure TRESTHTTP.SetAllowCookies(AValue: Boolean);
begin
FHTTPClient.AllowCookies := AValue;
end;
procedure TRESTHTTP.SetConnectTimeout(const Value: integer);
begin
FHTTPClient.ConnectionTimeout := Value;
end;
procedure TRESTHTTP.SetHandleRedirects(AValue: Boolean);
begin
FHTTPClient.HandleRedirects := AValue;
end;
procedure TRESTHTTP.SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
begin
FHTTPClient.RedirectsWithGET := AValue;
end;
procedure TRESTHTTP.SetSecureProtocols(const AValue: THTTPSecureProtocols);
begin
FHTTPClient.SecureProtocols := AValue;
end;
procedure TRESTHTTP.SetAuthEvent(const AValue: TCredentialsStorage.TCredentialAuthevent);
begin
FHTTPClient.AuthEvent := AValue;
end;
procedure TRESTHTTP.SetNeedClientCertificateEvent(const AValue: TNeedClientCertificateEvent);
begin
FHTTPClient.OnNeedClientCertificate := AValue;
end;
procedure TRESTHTTP.SetReadTimeout(const Value: integer);
begin
FHTTPClient.ResponseTimeout := Value;
end;
procedure TRESTHTTP.PrepareRequest(const ARequest: IHTTPRequest);
var
LIPRequest: TIPHTTPRequest;
I: Integer;
begin
if FProxyConnectionInfo <> nil then
FHTTPClient.ProxySettings := TIPProxyConnectionInfo(FProxyConnectionInfo).FProxySettings;
LIPRequest := TIPHTTPRequest(FIPHTTPRequestIntf);
for I := 0 to LIPRequest.FCustomHeaders.Count - 1 do
ARequest.AddHeader(LIPRequest.FCustomHeaders.Names[I], LIPRequest.FCustomHeaders.ValueFromIndex[I]);
if (LIPRequest.FAccept <> '') and (LIPRequest.FCustomHeaders.IndexOfName(sAccept) = -1) then
ARequest.Accept := LIPRequest.FAccept;
if (LIPRequest.FAcceptCharSet <> '') and (LIPRequest.FCustomHeaders.IndexOfName(sAcceptCharset) = -1) then
ARequest.AcceptCharSet := LIPRequest.FAcceptCharSet;
if (LIPRequest.FUserAgent <> '') and (LIPRequest.FCustomHeaders.IndexOfName(sUserAgent) = -1) then
ARequest.UserAgent := LIPRequest.FUserAgent;
if (LIPRequest.FAcceptEncoding <> '') and (LIPRequest.FCustomHeaders.IndexOfName(sAcceptEncoding) = -1) then
ARequest.AcceptEncoding := LIPRequest.FAcceptEncoding;
if (LIPRequest.FContentType <> '') and (LIPRequest.FCustomHeaders.IndexOfName(sContentType) = -1) then
ARequest.AddHeader(sContentType, LIPRequest.FContentType);
end;
procedure TRESTHTTP.RaiseProtocolException(const AResponse: IHTTPResponse);
const
sHTTP10 = 'HTTP/1.0';
sHTTP11 = 'HTTP/1.1';
sHTTP20 = 'HTTP/2.0';
var
LMessage: string;
begin
case AResponse.Version of
THTTPProtocolVersion.UNKNOWN_HTTP: LMessage := '';
THTTPProtocolVersion.HTTP_1_0: LMessage := sHTTP10 + ' ';
THTTPProtocolVersion.HTTP_1_1: LMessage := sHTTP11 + ' ';
THTTPProtocolVersion.HTTP_2_0: LMessage := sHTTP20 + ' ';
end;
LMessage := LMessage + Format('%d %s', [AResponse.StatusCode, AResponse.StatusText]);
raise EHTTPProtocolException.Create(AResponse.StatusCode, AResponse.ContentAsString,
LMessage);
end;
procedure TRESTHTTP.Execute(const AMethod: string; AURL: string; ASource, AResponseContent: TStream);
var
LRequest: IHTTPRequest;
LResponse: IHTTPResponse;
begin
LRequest := FHTTPClient.GetRequest(AMethod, AURL);
PrepareRequest(LRequest);
if ASource <> nil then
begin
ASource.Seek(0, soBeginning);
LRequest.SourceStream := ASource;
end;
LResponse := FHTTPClient.Execute(LRequest, AResponseContent);
FHTTPResponse := LResponse;
if LResponse.StatusCode >= 300 then
RaiseProtocolException(LResponse);
end;
procedure TRESTHTTP.Execute(const AMethod: string; AURL: string; AResponseContent: TStream);
begin
Execute(AMethod, AURL, nil, AResponseContent);
end;
procedure TRESTHTTP.Post(const AURL: string; ASource, AResponseContent: TStream);
begin
Execute('POST', AURL, ASource, AResponseContent);
end;
procedure TRESTHTTP.Put(const AURL: string; ASource, AResponseContent: TStream);
begin
Execute('PUT', AURL, ASource, AResponseContent);
end;
{ TIPHTTPRequest }
constructor TIPHTTPRequest.Create;
begin
FCustomHeaders := TStringList.Create;
end;
destructor TIPHTTPRequest.Destroy;
begin
FCustomHeaders.Free;
inherited;
end;
function TIPHTTPRequest.GetAccept: string;
begin
Result := FAccept;
end;
function TIPHTTPRequest.GetAcceptCharSet: string;
begin
Result := FAcceptCharSet;
end;
function TIPHTTPRequest.GetAcceptEncoding: string;
begin
Result := FAcceptEncoding;
end;
function TIPHTTPRequest.GetContentType: string;
begin
Result := FContentType;
end;
function TIPHTTPRequest.GetCustomHeaders: TRESTHTTP.IRequestHeaderList;
begin
Result := TIPRequestHeaderList.Create(FCustomHeaders);
end;
function TIPHTTPRequest.GetUserAgent: string;
begin
Result := FUserAgent;
end;
procedure TIPHTTPRequest.SetAccept(const Val: string);
begin
FAccept := Val;
end;
procedure TIPHTTPRequest.SetAcceptCharSet(const Val: string);
begin
FAcceptCharSet := Val;
end;
procedure TIPHTTPRequest.SetAcceptEncoding(const Val: string);
begin
FAcceptEncoding := Val;
end;
procedure TIPHTTPRequest.SetContentType(LContentType: string);
begin
FContentType := LContentType;
end;
procedure TIPHTTPRequest.SetUserAgent(const Val: string);
begin
FUserAgent := Val;
end;
{ TIPHTTPResponse }
function TIPHTTPResponse.ContentAsString(const AnEncoding: TEncoding = nil): string;
begin
Result := FResponse.ContentAsString(AnEncoding);
end;
constructor TIPHTTPResponse.Create(const AResponse: IHTTPResponse);
begin
FResponse := AResponse;
end;
function TIPHTTPResponse.GetCharSet: string;
begin
Result := FResponse.ContentCharSet;
end;
function TIPHTTPResponse.GetContentEncoding: string;
begin
Result := FResponse.ContentEncoding;
end;
function TIPHTTPResponse.GetContentType: string;
var
LSplitted: TArray<string>;
LResultValues: TArray<string>;
S: string;
begin
Result := FResponse.MimeType;
LSplitted := Result.Split([';']);
// Remove charset
for S in LSplitted do
if not S.TrimLeft.StartsWith('charset', True) then // do not translate
LResultValues := LResultValues + [S];
if Length(LResultValues) <> Length(LSplitted) then
begin
Result := '';
// Rebuild
for S in LResultValues do
begin
if Result <> '' then
Result := Result + ';';
Result := Result + S;
end;
end;
end;
function TIPHTTPResponse.GetHeaders: TRESTHTTP.IHeaderList;
begin
Result := TIPResponseHeaderList.Create(FResponse);
end;
{ TIPProxyConnectionInfo }
function TIPProxyConnectionInfo.GetProxyPassword: string;
begin
Result := FProxySettings.Password;
end;
function TIPProxyConnectionInfo.GetProxyPort: Integer;
begin
Result := FProxySettings.Port;
end;
function TIPProxyConnectionInfo.GetProxyServer: string;
begin
Result := FProxySettings.Host;
end;
function TIPProxyConnectionInfo.GetProxyUserName: string;
begin
Result := FProxySettings.UserName;
end;
procedure TIPProxyConnectionInfo.SetProxyPassword(pass: string);
begin
FProxySettings.Password := pass;
end;
procedure TIPProxyConnectionInfo.SetProxyPort(Val: Integer);
begin
FProxySettings.Port := Val;
end;
procedure TIPProxyConnectionInfo.SetProxyServer(Val: string);
begin
FProxySettings.Host := Val;
end;
procedure TIPProxyConnectionInfo.SetProxyUserName(user: string);
begin
FProxySettings.UserName := user;
end;
{ TIPResponseHeaderList }
destructor TIPResponseHeaderList.Destroy;
begin
FStrings.Free;
inherited Destroy;
end;
function TIPResponseHeaderList.GetCount: Integer;
begin
Result := FStrings.Count;
end;
function TIPResponseHeaderList.GetName(Index: Integer): string;
begin
Result := FStrings.Names[Index];
end;
function TIPResponseHeaderList.GetValue(const Name: string): string;
begin
Result := FStrings.Values[Name];
end;
constructor TIPResponseHeaderList.Create(const AResponse: IHTTPResponse);
var
LHeader: TNetHeader;
begin
inherited Create;
FStrings := TStringList.Create;
for LHeader in AResponse.Headers do
FStrings.AddPair(LHeader.Name, LHeader.Value);
end;
{ TIPRequestHeaderList }
function TIPRequestHeaderList.GetCount: Integer;
begin
Result := FStrings.Count;
end;
function TIPRequestHeaderList.GetName(Index: Integer): string;
begin
Result := FStrings.Names[Index];
end;
function TIPRequestHeaderList.GetValue(const Name: string): string;
begin
Result := FStrings.Values[Name];
end;
constructor TIPRequestHeaderList.Create(const AStrings: TStrings);
begin
inherited Create;
FStrings := AStrings;
end;
procedure TIPRequestHeaderList.Clear;
begin
FStrings.Clear;
end;
procedure TIPRequestHeaderList.SetValue(const AName, AValue: string);
begin
FStrings.Values[AName] := AValue;
end;
{ EHTTPProtocolException }
constructor EHTTPProtocolException.Create(AErrorCode: Integer; const AErrorMessage: string; const AMessage: string);
begin
FErrorCode := AErrorCode;
FErrorMessage := AErrorMessage;
inherited Create(AMessage);
end;
end.
|
unit ufrmSysLang;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.AppEvnts,
Vcl.Menus, Vcl.Samples.Spin,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.Memo,
Ths.Erp.Helper.ComboBox,
ufrmBase, ufrmBaseInputDB;
type
TfrmSysLang = class(TfrmBaseInputDB)
edtLanguage: TEdit;
lblLanguage: TLabel;
procedure FormCreate(Sender: TObject);override;
procedure Repaint(); override;
procedure RefreshData();override;
private
public
protected
published
procedure FormShow(Sender: TObject); override;
procedure btnAcceptClick(Sender: TObject); override;
end;
implementation
uses
Ths.Erp.Database.Table.SysLang;
{$R *.dfm}
procedure TfrmSysLang.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
TSysLang(Table).Language.Value := edtLanguage.Text;
inherited;
end;
end
else
inherited;
end;
procedure TfrmSysLang.FormCreate(Sender: TObject);
begin
TSysLang(Table).Language.SetControlProperty(Table.TableName, edtLanguage);
inherited;
edtLanguage.CharCase := ecNormal;
end;
procedure TfrmSysLang.FormShow(Sender: TObject);
begin
inherited;
//
end;
procedure TfrmSysLang.Repaint();
begin
inherited;
//
end;
procedure TfrmSysLang.RefreshData();
begin
edtLanguage.Text := TSysLang(Table).Language.Value;
end;
end.
|
unit ParametricExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
CustomExcelTable, Data.DB, System.Generics.Collections,
FieldInfoUnit, SearchComponentOrFamilyQuery, SearchFamily,
ComponentTypeSetUnit, SearchFamilyCategoriesQry, ProductCategoriesMemTable;
{$WARN SYMBOL_PLATFORM OFF}
type
TParametricExcelTable = class(TCustomExcelTable)
private
FComponentTypeSet: TComponentTypeSet;
FCopyCommonValueToFamily: Boolean;
FProductCategoriesMemTbl: TProductCategoriesMemTbl;
FqSearchComponentOrFamily: TQuerySearchComponentOrFamily;
FqSearchFamilyCategories: TQrySearchFamilyCategories;
FReplace: Boolean;
function GetComponentName: TField;
// TODO: GetIDBodyType
// function GetIDBodyType: TField;
function GetIDComponent: TField;
function GetIDParentComponent: TField;
function GetqSearchComponentOrFamily: TQuerySearchComponentOrFamily;
function GetqSearchFamilyCategories: TQrySearchFamilyCategories;
protected
function CheckComponent: Boolean;
procedure CreateFieldDefs; override;
property qSearchComponentOrFamily: TQuerySearchComponentOrFamily
read GetqSearchComponentOrFamily;
property qSearchFamilyCategories: TQrySearchFamilyCategories
read GetqSearchFamilyCategories;
public
constructor Create(AOwner: TComponent; AFieldsInfo: TList<TFieldInfo>;
AComponentTypeSet: TComponentTypeSet;
AReplace, ACopyCommonValueToFamily: Boolean); reintroduce;
function CheckRecord: Boolean; override;
class function GetFieldNameByParamSubParamID(AParamSubParamID: Integer)
: String; static;
function GetParamSubParamIDByFieldName(AFieldName: string;
out AParamSubParamID: Integer): Boolean;
property ComponentName: TField read GetComponentName;
property ComponentTypeSet: TComponentTypeSet read FComponentTypeSet;
property CopyCommonValueToFamily: Boolean read FCopyCommonValueToFamily;
property IDComponent: TField read GetIDComponent;
property IDParentComponent: TField read GetIDParentComponent;
property ProductCategoriesMemTbl: TProductCategoriesMemTbl
read FProductCategoriesMemTbl;
property Replace: Boolean read FReplace;
end;
TParametricExcelDM = class(TExcelDM)
private
FComponentTypeSet: TComponentTypeSet;
FCopyCommonValueToFamily: Boolean;
FFieldsInfo: TList<TFieldInfo>;
FReplace: Boolean;
function GetExcelTable: TParametricExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
public
constructor Create(AOwner: TComponent; AFieldsInfo: TList<TFieldInfo>;
AComponentTypeSet: TComponentTypeSet;
AReplace, ACopyCommonValueToFamily: Boolean); reintroduce; overload;
property ExcelTable: TParametricExcelTable read GetExcelTable;
{ Public declarations }
end;
implementation
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
uses ProgressInfo, System.Variants, ErrorType, RecordCheck, FireDAC.Comp.Client;
const
FParamPrefix = 'Param';
constructor TParametricExcelTable.Create(AOwner: TComponent;
AFieldsInfo: TList<TFieldInfo>; AComponentTypeSet: TComponentTypeSet;
AReplace, ACopyCommonValueToFamily: Boolean);
var
AFieldInfo: TFieldInfo;
begin
inherited Create(AOwner);
for AFieldInfo in AFieldsInfo do
FieldsInfo.Add(AFieldInfo);
FComponentTypeSet := AComponentTypeSet;
FReplace := AReplace;
FCopyCommonValueToFamily := ACopyCommonValueToFamily;
FProductCategoriesMemTbl := TProductCategoriesMemTbl.Create(Self);
end;
function TParametricExcelTable.CheckComponent: Boolean;
var
AErrorMessage: string;
ARecordCheck: TRecordCheck;
begin
Result := False;
AErrorMessage := '';
Assert(FComponentTypeSet <> []);
// Если надо искать только среди семейств
if FComponentTypeSet = [ctFamily] then
begin
// Ищем семейство и категории в которые оно входит
Result := qSearchFamilyCategories.SearchFamily(ComponentName.AsString) > 0;
if Result then
begin
// запоминаем идентификаторы категорий в которые входит наш компонент
qSearchFamilyCategories.FDQuery.First;
while not qSearchFamilyCategories.FDQuery.Eof do
begin
FProductCategoriesMemTbl.Add
(qSearchFamilyCategories.W.ProductCategoryID.F.AsInteger,
qSearchFamilyCategories.W.ExternalID.F.AsString,
qSearchFamilyCategories.W.Category.F.AsString);
qSearchFamilyCategories.FDQuery.Next;
end;
Edit;
IDComponent.AsInteger := qSearchFamilyCategories.W.PK.AsInteger;
IDParentComponent.AsInteger := qSearchFamilyCategories.W.ParentProductID.
F.AsInteger;
Post;
end
else
AErrorMessage := 'Семейство компонентов с таким именем не найдено';
end;
// Ищем компонент
if FComponentTypeSet = [ctComponent] then
begin
Result := qSearchComponentOrFamily.SearchComponent
(ComponentName.AsString) > 0;
if Result then
begin
Edit;
IDComponent.AsInteger := qSearchComponentOrFamily.W.PK.AsInteger;
IDParentComponent.AsInteger := qSearchComponentOrFamily.W.ParentProductID.
F.AsInteger;
Post;
end
else
AErrorMessage := 'Компонент с таким именем не найден';
end;
{
if FComponentTypeSet = [ctComponent, ctFamily] then
begin
Result := qSearchComponentOrFamily.SearchByValue
(ComponentName.AsString) > 0;
if not Result then
AErrorMessage := 'Семейство или компонент с таким именем не найден';
end;
}
if not Result then
begin
// Запоминаем, что в этой строке ошибка
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := ComponentName.Index + 1;
ARecordCheck.ErrorMessage := ComponentName.AsString;
ARecordCheck.Description := AErrorMessage;
ProcessErrors(ARecordCheck);
end;
end;
function TParametricExcelTable.CheckRecord: Boolean;
begin
Result := inherited;
if Result then
begin
// Проверяем что такой компонент существует
Result := CheckComponent;
end;
end;
procedure TParametricExcelTable.CreateFieldDefs;
begin
inherited;
// При проверке, будем заполнять идентификатор компонента
FieldDefs.Add('IDComponent', ftInteger);
FieldDefs.Add('IDParentComponent', ftInteger);
end;
function TParametricExcelTable.GetComponentName: TField;
begin
Result := FieldByName(FieldsInfo[0].FieldName);
end;
class function TParametricExcelTable.GetFieldNameByParamSubParamID
(AParamSubParamID: Integer): String;
begin
Assert(AParamSubParamID > 0);
Assert(not FParamPrefix.IsEmpty);
Result := Format('%s_%d', [FParamPrefix, AParamSubParamID]);
end;
function TParametricExcelTable.GetIDComponent: TField;
begin
Result := FieldByName('IDComponent');
end;
function TParametricExcelTable.GetParamSubParamIDByFieldName(AFieldName: string;
out AParamSubParamID: Integer): Boolean;
var
m: TArray<String>;
begin
Assert(not FParamPrefix.IsEmpty);
Assert(not AFieldName.IsEmpty);
// Делим имя поля на части
m := AFieldName.Split(['_']);
Result := Length(m) = 2;
if Result then
begin
AParamSubParamID := m[1].ToInteger;
Assert(AParamSubParamID > 0);
end
else
begin
Assert(Length(m) = 1);
AParamSubParamID := 0;
end;
end;
function TParametricExcelTable.GetIDParentComponent: TField;
begin
Result := FieldByName('IDParentComponent');
end;
function TParametricExcelTable.GetqSearchComponentOrFamily
: TQuerySearchComponentOrFamily;
begin
if FqSearchComponentOrFamily = nil then
FqSearchComponentOrFamily := TQuerySearchComponentOrFamily.Create(Self);
Result := FqSearchComponentOrFamily;
end;
function TParametricExcelTable.GetqSearchFamilyCategories
: TQrySearchFamilyCategories;
begin
if FqSearchFamilyCategories = nil then
begin
FqSearchFamilyCategories := TQrySearchFamilyCategories.Create(Self);
end;
Result := FqSearchFamilyCategories;
end;
constructor TParametricExcelDM.Create(AOwner: TComponent;
AFieldsInfo: TList<TFieldInfo>; AComponentTypeSet: TComponentTypeSet;
AReplace, ACopyCommonValueToFamily: Boolean);
begin
Assert(AFieldsInfo <> nil);
FFieldsInfo := AFieldsInfo;
FComponentTypeSet := AComponentTypeSet;
FReplace := AReplace;
FCopyCommonValueToFamily := ACopyCommonValueToFamily;
Create(AOwner);
end;
function TParametricExcelDM.CreateExcelTable: TCustomExcelTable;
begin
Assert(FFieldsInfo <> nil);
Result := TParametricExcelTable.Create(Self, FFieldsInfo, FComponentTypeSet,
FReplace, FCopyCommonValueToFamily);
end;
function TParametricExcelDM.GetExcelTable: TParametricExcelTable;
begin
Result := CustomExcelTable as TParametricExcelTable;
end;
end.
|
unit fMyDBFLoader;
interface
uses
SysUtils, Classes;
type
TDBFDetails = record
recCount: LongWord;
headerLen: Word;
rowLen: Word;
end;
TDBFColumn = class(TCollectionItem)
private
fName: ShortString;
fType: Char;
fLength: Byte;
fDecimal: Byte;
function GetName: string;
procedure SetName(Value: string);
procedure SetType(Value: Char);
published
property Decimal: byte read fDecimal write fDecimal;
property FieldType: Char read fType write SetType;
property Length: byte read fLength write fLength;
property Name: String read GetName write SetName;
end;
TDBFColumns = class(TCollection)
private
function GetColumn(Index: Integer): TDBFColumn;
procedure SetColumn(Index: Integer; Value: TDBFColumn);
public
property Items[Index: Integer]: TDBFColumn read GetColumn write SetColumn; default;
function Add: TDBFColumn;
published
constructor Create;
end;
TMyDBFLoader = class(TObject)
private
myfs: TFileStream;
fColumns: TDBFColumns;
fDBFName: string;
fDBFDetails: TDBFDetails;
fEof: boolean;
fheaderLen: Word;
frecNo: LongWord;
frecCount: LongWord;
frowLen: Word;
frowData: string;
function DoSetDBFName(AFileName: string): byte;
function GetDBFDetails: TDBFDetails;
function GetEof: boolean;
function ConvertToSQL(Value: string): string;
function ConvertToFile(Value: string): string;
function TranslateType(Index: Byte): string;
function TranslateDefaultValue(Index: Byte): string;
function GetDBFName: string;
function SQLString(Value: string; const DoQuotes: boolean = true): string;
public
property Columns: TDBFColumns read fColumns;
property DBFDetails : TDBFDetails read GetDBFDetails;
property dbName: string read GetDBFName;
property Eof: boolean read GetEof;
property RecordCount: LongWord read frecCount;
property RecNo: LongWord read frecNo;
constructor Create;
destructor Destroy; override;
function AssignDBF(AFileName: string): byte;
function GetRows(Ammount: byte; const FromBegining: boolean = False): string;
function GetSQLHeader: string;
function GetSQLValues(Ammount: Word; const FromBegining: boolean = False): string;
function GetRawData: string;
procedure First;
procedure Next;
procedure Prev;
procedure Last;
end;
implementation
function TDBFColumn.GetName: String;
begin
Result := String(fName);
end;
procedure TDBFColumn.SetName(Value: String);
begin
if Value <> '' then fName := Copy(Trim(Value), 1, 10);
end;
procedure TDBFColumn.SetType(Value: Char);
begin
if Value = '' then Exit;
if UpCase(Value) in ['C','D','F','L','M','N'] then
fType := UpCase(Value);
end;
constructor TDBFColumns.Create;
begin
inherited Create(TDBFColumn);
end;
function TDBFColumns.Add: TDBFColumn;
begin
Result := TDBFColumn(inherited Add);
Exit;
GetColumn(0); //Otherwise you get function was eliminated by linker while debugging:)
end;
function TDBFColumns.GetColumn(Index: Integer): TDBFColumn;
begin
Result := TDBFColumn(inherited Items[Index]);
end;
procedure TDBFColumns.SetColumn(Index: Integer; Value: TDBFColumn);
begin
Items[Index].Assign(Value);
end;
constructor TMyDBFLoader.Create;
begin
inherited;
fDBFName := '';
frowData := '';
fColumns := TDBFColumns.Create;
end;
destructor TMyDBFLoader.Destroy;
begin
if myfs <> nil then
FreeAndNil(myfs);
inherited Destroy;
end;
function TMyDBFLoader.ConvertToSQL(Value: string): string;
var
i: Word;
s: string;
begin
i := 0;
if Value = '' then begin Result := ''; Exit; end;
Result := '(';
while Value[1] = '*' do begin
Delete(Value,1,frowLen); //Trim deleted rows
if Value = '' then Exit;
end;
Delete(Value, 1, 1);
while Value <> '' do begin
if fColumns[i].FieldType = 'C' then Result := Result + SQLString(Trim(Copy(Value, 1, fColumns[i].Length))) + ',';
if fColumns[i].FieldType = 'D' then Result := Result + '"' + Trim(Copy(Value, 1, fColumns[i].Length)) + '",';
if fColumns[i].FieldType = 'F' then begin
s := Trim(Copy(Value, 1, fColumns[i].Length - fColumns[i].Decimal));
if s = '' then s := '0' + DecimalSeparator + '00';
Result := Result + s + ',';
end;
if fColumns[i].FieldType = 'L' then Result := Result + '"' + Trim(Copy(Value, 1, 1)) + '",';
if fColumns[i].FieldType = 'N' then begin
s := Trim(Copy(Value, 1, fColumns[i].Length));
if s = '' then s := '0';
Result := Result + s + ',';
end;
Delete(Value, 1, fColumns[i].Length);
Inc(i);
if (i = fColumns.Count) and (Value <> '') then begin
i := 0; //reset the count;
while Value[1] = '*' do begin
Delete(Value,1,frowLen); //Trim deleted rows
if Value = '' then Break;
end;
if Value <> '' then begin
Delete(Value, 1, 1);
Result := Copy(Result, 1, Length(Result) - 1) + '), (';
end;
end;
end;
Result := Copy(Result, 1, Length(Result) - 1) + ')';
end;
function TMyDBFLoader.ConvertToFile(Value: string): string;
var
i: Word;
s: string;
begin
i := 0;
if Value = '' then begin Result := ''; Exit; end;
Result := '';
while Value[1] = '*' do begin //Trim deleted rows
Delete(Value,1,frowLen);
if Value = '' then Exit;
end;
Delete(Value, 1, 1);
while Value <> '' do begin
if fColumns[i].FieldType in ['C','D','L'] then
Result := Result + SQLString(Trim(Copy(Value, 1, fColumns[i].Length)), False) + '|';
if fColumns[i].FieldType = 'F' then begin
s := Trim(Copy(Value, 1, fColumns[i].Length - fColumns[i].Decimal));
if s = '' then s := '0' + DecimalSeparator + '00';
Result := Result + s + '|';
end;
if fColumns[i].FieldType = 'N' then begin
s := Trim(Copy(Value, 1, fColumns[i].Length));
if s = '' then s := '0';
Result := Result + s + '|';
end;
Delete(Value, 1, fColumns[i].Length);
Inc(i);
if (i = fColumns.Count) and (Value <> '') then begin
i := 0; //reset the count;
while Value[1] = '*' do begin
Delete(Value,1,frowLen); //Trim deleted rows
if Value = '' then Break;
end;
if Value <> '' then begin
Delete(Value, 1, 1);
Result := Copy(Result, 1, Length(Result) - 1) + '|#|';
end;
end;
end;
Result := Copy(Result, 1, Length(Result) - 1);
end;
function TMyDBFLoader.TranslateType(Index: Byte): string;
var
fieldType: char;
begin
fieldType := fColumns[Index].FieldType;
if fieldType = 'C' then Result := 'char';
if fieldType = 'D' then Result := 'date';
if fieldType = 'F' then Result := 'double';
if fieldType = 'L' then Result := 'char';
if fieldType = 'N' then begin
if fColumns[Index].fDecimal = 0 then Result := 'int'
else Result := 'double';
end;
end;
function TMyDBFLoader.TranslateDefaultValue(Index: Byte): string;
var
fieldType: char;
begin
fieldType := fColumns[Index].FieldType;
if fieldType = 'C' then Result := '""';
if fieldType = 'D' then Result := '"01-01-1970"';
if fieldType = 'F' then Result := '0.00';
if fieldType = 'L' then Result := '""';
if fieldType = 'N' then begin
if fColumns[Index].fDecimal = 0 then Result := '0'
else Result := '0.00';
end;
end;
function TMyDBFLoader.GetDBFName: string;
begin
Result := Copy(fDBFName, 1, Length(fDBFName) - 4);
end;
function TMyDBFLoader.GetEof: boolean;
begin
if (frecNo > frecCount) or (frecCount = 0) then Result := True
else Result := False;
end;
function TMyDBFLoader.DoSetDBFName(AFileName: string): byte;
begin
Result := 1;
if FileExists(AFileName) then begin
Result := 0;
fDBFName := AFileName;
end;
end;
{public methods}
function TMyDBFLoader.AssignDBF(AFileName: string): byte;
var
bt: Byte;
recCount: LongWord;
headerLen: Word;
rowLen: Word;
Buffer: array[1..32] of Char;
myColumn: TDBFColumn;
begin
Result := 1;
if AFileName = '' then Exit;
if Pos('.DBF', UpperCase(AFileName)) = 0 then AFileName := AFileName + '.DBF';
Result := DoSetDBFName(ExtractFileName(AFileName));
if Result <> 0 then Exit; //DBF does not exist - Exit;
myfs := TFileStream.Create(AFileName, fmOpenRead+fmShareDenyNone);
myfs.Read(bt, 1);
Result := 2;
if bt > 3 then Exit; //dBase 7 selected - Exit;
myfs.Seek(4, soFromBeginning);
myfs.Read(recCount, 4);
myfs.Read(headerLen, 2);
myfs.Read(rowLen, 2);
// if (recCount * headerLen * rowLen) = 0 then Exit;
frecCount := recCount;
fheaderLen := headerLen;
frowLen := rowLen;
//Load header
myfs.Seek(32, soFromBeginning);
for bt := 1 to ((headerLen - 1) div 32) - 1 do begin
myfs.Read(Buffer, 32);
myColumn := fColumns.Add;
with myColumn do begin
Name := Trim(Buffer[1] + Buffer[2] + Buffer[3] +
Buffer[4] + Buffer[5] + Buffer[6] +
Buffer[7] + Buffer[8] + Buffer[9] +
Buffer[10]); //Name for the field is less than 10 chars
FieldType := Buffer[12]; //'C','D','F','L','M','N'
Length := Ord(Buffer[17]); //Total bytes of the field
Decimal := Ord(Buffer[18]); //Ammount of decimal bytes
end;
end;
myfs.Seek(fheaderLen, soFromBeginning);
Result := 0; //All ok
end;
function TMyDBFLoader.SQLString(Value: string; const DoQuotes: boolean = true): string;
var
b: boolean;
begin
b := False;
Result := '';
while Value <> '' do begin
if Value[1] = '\' then Result := Result + '\';
if Value[1] = '"' then begin Result := Result + '\'; b := true; end;
Result := Result + Value[1];
Delete(Value,1,1);
end;
if DoQuotes then
if b then Result := '''' + Result + ''''
else Result := '"' + Result + '"';
end;
function TMyDBFLoader.GetDBFDetails: TDBFDetails;
var
myDetails: TDBFDetails;
begin
with myDetails do begin
recCount := frecCount;
headerLen := fheaderLen;
rowLen := frowLen;
end;
Result := myDetails;
end;
function TMyDBFLoader.GetRows(Ammount: byte; const FromBegining: boolean = False): string;
begin
if FromBegining then myfs.Seek(0, soFromBeginning);
if Ammount > frecCount then Exit;
end;
function TMyDBFLoader.GetSQLHeader: string;
var
i: Word;
begin
Result := 'CREATE TABLE ' + Copy(fDBFName, 1, Length(fDBFName) - 4) + ' (';
for i := 0 to fColumns.Count - 1 do begin
Result := Result + '`' + fColumns[i].fName + '` ' + TranslateType(i);
if fColumns[i].FieldType <> 'D' then begin
Result := Result + '(' + IntToStr(fColumns[i].fLength);
if fColumns[i].fDecimal <> 0 then
Result := Result + ',' + IntToStr(fColumns[i].fDecimal);
Result := Result + ')';
end;
Result := Result + ' NOT NULL DEFAULT ' +
TranslateDefaultValue(i) + ',';
end;
Result := Copy(Result, 1, Length(Result) - 1) + ') ENGINE=InnoDB DEFAULT CHARSET=latin1';
end;
function TMyDBFLoader.GetSQLValues(Ammount: Word; const FromBegining: boolean = False): string;
var
rows: LongWord;
begin
if FromBegining then myfs.Seek(fheaderLen, soFromBeginning);
//if (Ammount > frecCount) then Exit;
if FromBegining then rows := Ammount
else begin
if Ammount > (frecCount - frecNo) then
rows := frecCount - frecNo
else rows := Ammount;
end;
SetLength(Result, rows * frowLen);
myfs.Read(Result[1], rows * frowLen);
{$IFDEF LOAD_FROM_FILE}
Result := ConvertToFile(Result);
{$ELSE}
Result := ConvertToSQL(Result);
{$ENDIF}
frecNo := frecNo + rows;
if rows <> Ammount then Inc(frecNo);
end;
function TMyDBFLoader.GetRawData: string;
begin
Result := frowData;
end;
procedure TMyDBFLoader.First;
begin
myfs.Seek(fheaderLen, soFromBeginning);
frecNo := 1;
SetLength(frowData, frowLen);
myfs.Read(frowData[1], frowLen);
end;
procedure TMyDBFLoader.Next;
begin
if Eof then Exit;
SetLength(frowData, frowLen);
myfs.Read(frowData[1], frowLen);
Inc(frecNo);
end;
procedure TMyDBFLoader.Prev;
begin
myfs.Seek(fheaderLen + (frecNo - 2) * frowLen, soFromBeginning);
SetLength(frowData, frowLen);
myfs.Read(frowData[1], frowLen);
Dec(frecNo);
end;
procedure TMyDBFLoader.Last;
begin
myfs.Seek(fheaderLen + (frecCount - 1) * frowLen, soFromBeginning);
frecNo := frecCount;
SetLength(frowData, frowLen);
myfs.Read(frowData[1], frowLen);//
end;
end.
|
unit Utas; // SpyroTAS is licensed under WTFPL
// shared functions and variables
interface
uses
Windows, Forms, Messages, Classes, Graphics, SysUtils, StrUtils, DateUtils,
IniFiles, Math;
const
// customization for other developers / builds:
SpyroTASGlobalName = 'SpyroTAS'; // change here in soruce, but read only by SpyroTASName
SpyroTASVersionMajor: Integer = 2; // don't forget to change these
SpyroTASVersionMinor: Integer = 6; // version constants in .RC also!
SpyroTASVestionString: string = ' v2.6!'; // for strings, according to above
SpyroTASDirectory: string = '.\SpyroTAS\'; // rename here to resolve path collisions
// other constans:
{$IFDEF FPC} // name only for strings and messages:
SpyroTASName: string = SpyroTASGlobalName + ' (Laz)'; // to visually distinguish
SpyroTASHelper: string = 'padSpyroTAShelper_Laz.';
SpyroTASHelperRes: string = 'PADSPYROTASHELPERLAZ';
{$ELSE}
SpyroTASName: string = SpyroTASGlobalName; // Delphi is primary
SpyroTASHelper: string = 'padSpyroTAShelper.';
SpyroTASHelperRes: string = 'PADSPYROTASHELPER';
{$ENDIF}
SpyroTASGlobalIni: string = 'SpyroTAS.ini'; // main/hotkey settings
ExtSaveState = '.SpyroTasSaveState'; // only for export
ExtKeyHistory = '.SpyroTasHistory'; // used when import
ExtSprintHist = '.SpyroTasSprint'; // for sprint mode
ExtForArchive = '.SpyroTAS';
SpyroTASFilters: string = '*' + ExtSaveState + ';*' + ExtKeyHistory + ';*' +
ExtSprintHist + ';*' + ExtForArchive;
SpyroTASForScreenshots: string = 'shots\';
SpyroTASForHistory: string = 'hist\';
SectionSpyrotas: string = 'spyrotas'; // for ini files
SectionLastpath: string = 'lastpath';
SectionSettings: string = 'settings';
HistoryOffsetInRAM: Integer = 348;
SizeOfRAM = 2 * 1024 * 1024; // 2 Mb RAM
PadAlphaDefault = 196;
DefaultActionSleep: Integer = 100; // for several user actions
DefaultFrameWait: Integer = 5000; // 5 sec wait for screenshot and overlay redraw
PaddingForLastest: Integer = 4;
MY80807CW = $27F; // Masked, Double, Nearest
SprintValue: Integer = -3;
var
HistoryPosition: Integer = -1; // current frame in history; -1 in free modes
LastTimepoint: Integer = 0; // position from which to record new history or overwrite
ThresholdTimepoint: Integer = 0; // left position for semi-keys
EmulatorWindow: HWND = 0; // handle of the game window
PointerToRamStart: PChar = nil; // points to game memory, in current process space
SavestateDirectory: string = '.\sstates\'; // will be changed according to .ini
SavestateID: string = ''; // name of default used savestate file, like GAME_XYZ.000
EmulatorRoot: string; // full path to emualtor directory, populated as soon as possible
PathToSpyroTAS: string; // = EmulatorRoot + SpyroTASDirectory
LoadInFree: Boolean; // when should load a keystate without activating the history
StopOnBlur: Boolean; // when history is active to prevant the game to lose focus
GameIsRunning: Boolean; // notification, for when game thread is not in a wait state (TODO)
SwitchRequested: Boolean; // when gui needs to resume the game
AviConfigured: Boolean = False;
AviFrameRate: Integer;
PngCompression: Integer;
ShotNeed: Boolean;
ShotFreeMode: Boolean;
ShotSkipSame: Boolean;
ShotCount: Integer;
AutofireRandom: array[0..15] of Integer;
AutofireButton: array[0..15] of ByteBool;
KeystateList: array of Integer;
KeystateUsedToStart: Integer;
KeystateToLoad: Integer;
SaveWaitForNone: Integer;
SaveWaitForDone: Integer;
SaveWaitAfter: Integer;
SaveInEffect: Boolean;
SaveLoadFailed: Integer;
LoadWaitForNone: Integer;
LoadWaitForDone: Integer;
LoadWaitAfter: Integer;
LoadInEffect: Boolean;
SaveSettingsScheduled: Boolean;
ArchivesList: TStringList;
GlobalPadMask: Integer;
KeyAutofireMask: Integer;
SemiKeysUsed: Boolean;
IsRunDLL: Boolean;
MainIsAlreadyInited: Boolean;
TimeOfStart: TDateTime;
HistoryWasAltered: Boolean;
DontShowHints: Boolean;
DebugRandomKeys: Boolean;
HaveNewScreen: Boolean;
StartFromRecord: Boolean = False;
LiveSaveRequest: Boolean = False;
SpecSaveRequest: Boolean = False;
AllowNextFrame: Boolean = False;
PadToggleFrame: Boolean;
PadShadowFrame: Boolean;
OldToggleFrame: Boolean;
LastFrameKeys: Integer = 0;
FrameAdvanceHold: Integer = 0;
AdvanceRequested: Boolean = False;
AdvanceWaitRelease: Boolean = False;
SelfDllTime: Integer; // assigned with DLL first init, for self-check
IsOneCleanup: Integer = 1;
IsOneMain: Integer = 1;
GpuWatching: Boolean = False;
StoredKeys: Integer = 0;
AllowWarp: Boolean = False;
DoWarpNow: Boolean = False;
WarpRequested: Boolean = False;
WatchFlipRequested: Boolean = False;
WatchNextRequested: Boolean = False;
SpyroOffsetText: string = '';
SpyroOffset: Integer = 0;
MoveLimitMb: Integer = 16;
PathToIni: string;
SprintMode: Boolean = False; // TODO
SprintFile: string = '';
SprintState: string = '';
SprintSave: Integer = 0;
SprintHashBegin: Integer = 0;
SprintHashEnd: Integer = 0;
SprintMiss: Boolean = False;
SprintCalcM: Integer = 0;
SprintCalcD: Integer = 0;
ThisIsRestart: Boolean = False;
FireDeadlock: Integer = 0;
AlwaysAutoinvoke: Boolean = False;
HashWait: Integer = 0;
var // for coordinate measurment
SpyroX1, SpyroY1, SpyroZ1, SpyroX2, SpyroY2, SpyroZ2, SpyroTime2: Integer;
SpyroDist, SpyroDist1Prev, SpyroDist2Prev, SpyroDistMax: Real;
SpyroAway, SpyroApproach, SpyroUse1, SpyroUse2: Boolean;
SpyroOffsetX, SpyroOffsetY, SpyroOffsetZ: Integer;
function UpdateHistoryPosition(): Boolean;
procedure SetHistoryPosition(NewPosition: Integer);
procedure SetLastestPosition(NewPos: Integer);
procedure SetThresholdPosition(NewThres: Integer);
procedure SavestateCopyFrom(CopyFromWhere: string);
procedure SavestateMoveTo(WhereToMove: string);
procedure SavestateDelete();
function SavestateExist(): Boolean;
function ImportExportHistory(Filename: string; DoImport: Boolean): Boolean;
procedure SwitchToEmulator(Intent: Boolean);
function ImportSpyroTAS(Filename: string): Boolean;
procedure MakeGameScreenshot(OnlyForAviOptions: Boolean);
procedure ResetLoadSave();
procedure LoadSettings();
procedure SaveSettings();
function EnsureAbsolutePath(const AnyPath: string): string;
procedure EnterSptintMode(Start: Boolean);
function HashRAM(Frame: Integer): Integer;
procedure SprintFileSave();
function SprintFileLoad(): Boolean;
procedure SprintCompute();
implementation
uses
MMSystem, UFgui, UFext, Uforms, UFover, Uavi, UFview, UFshot, Uglob, Controls,
Types, Uini, Ukey, Umain, Umisc, Uroute, UFedit;
var
OldCaption: string = '';
function PrintWindow(hwnd: HWND; hdcBlt: HDC; nFlags: UINT): BOOL; stdcall;
external 'user32.dll';
// increment history number in game RAM
function UpdateHistoryPosition(): Boolean;
var
MemPointer: PInteger;
NewPosition: Integer;
begin
Result := False;
if ThisIsRestart then
Exit;
if PointerToRamStart = nil then
begin
if RamStartRequest = nil then
begin
if (HistoryPosition <> -1) and (HistoryPosition <> SprintValue) then
Inc(HistoryPosition);
Exit;
end;
HistoryWasAltered := False;
PointerToRamStart := RamStartRequest;
SetHistoryPosition(HistoryPosition);
end;
if IsRunDLL or HistoryWasAltered then
begin
HistoryPosition := -1;
Exit;
end;
MemPointer := PInteger(PointerToRamStart + HistoryOffsetInRAM);
NewPosition := MemPointer^;
if (HistoryPosition <> -1) and (HistoryPosition <> SprintValue) and (NewPosition
<> HistoryPosition) then
Result := True;
HistoryPosition := NewPosition;
if (HistoryPosition = -1) or (HistoryPosition = SprintValue) then // (-1) is a special "don't update"
Exit;
Inc(HistoryPosition); // +1 and put back
MemPointer^ := HistoryPosition;
end;
// force new history positon to game
procedure SetHistoryPosition(NewPosition: Integer);
begin
HistoryPosition := NewPosition; // update global too
if IsRunDLL or HistoryWasAltered or (PointerToRamStart = nil) then
Exit;
PInteger(PointerToRamStart + HistoryOffsetInRAM)^ := HistoryPosition;
end;
// change last saved history point
procedure SetLastestPosition(NewPos: Integer);
begin
LastTimepoint := NewPos;
SendAction(caPositions); // signal GUI
end;
// TODO
procedure SetThresholdPosition(NewThres: Integer);
begin
ThresholdTimepoint := NewThres;
SendAction(caPositions); // signal GUI too
end;
// copy savestate from any file to proper location:
procedure SavestateCopyFrom(CopyFromWhere: string);
begin
if SavestateID = '' then
Exit;
CopyFileA(PChar(CopyFromWhere), PChar(SavestateDirectory + SavestateID), False);
end;
// move (rename) savestate to any filename:
procedure SavestateMoveTo(WhereToMove: string);
begin
DeleteFile(WhereToMove); // replacing
if SavestateID = '' then
Exit;
MoveFileA(PChar(SavestateDirectory + SavestateID), PChar(WhereToMove));
end;
// delete savestate file by index
procedure SavestateDelete();
begin
if SavestateID = '' then
Exit;
DeleteFile(SavestateDirectory + SavestateID);
DeleteFile(SavestateDirectory + SavestateID + '.pic'); // picture also
end;
// test for savestate file by index
function SavestateExist(): Boolean;
var
TestStream: TFileStream;
begin
Result := True;
try
if SavestateID = '' then
Abort;
if not FileExists(SavestateDirectory + SavestateID) then
Abort;
TestStream := TFileStream.Create(SavestateDirectory + SavestateID,
fmOpenRead or fmShareDenyNone);
if TestStream.Size = 0 then
Result := False; // treat empty as non-existed
TestStream.Free;
except
Result := False; // couldn't open
end;
end;
function ImportExportHistory(Filename: string; DoImport: Boolean): Boolean;
var
Size: Integer;
Stream: TFileStream;
Header: array[0..3] of Integer;
begin
Result := False;
Stream := nil;
try
if DoImport then
begin
Header[0] := 0;
Header[1] := 0;
Header[2] := 0;
Header[3] := 0;
Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyNone);
Stream.ReadBuffer(Header, SizeOf(Header));
Size := Header[2];
if (Header[0] <> 1) or (Header[3] <> 0) or (Size <= 0) then // wrong file
begin
Report(SpyroTASName + ' history import error:', Filename, Fgui);
Exit;
end;
History.SetSize(Size + 10);
SetLength(KeystateList, 2);
KeystateList[0] := Header[1];
KeystateList[1] := Size;
SendAction(caListDirty);
History.FromStream(HistoryKeys, Size, Stream);
History.FromStream(HistoryHash, Size, Stream, True);
History.FromStream(HistoryRrec, Size, Stream, True);
SetLastestPosition(Size);
end
else
begin
Size := KeystateList[Length(KeystateList) - 1];
History.SetSize(Size + 10);
Header[0] := 1; // format version
Header[1] := KeystateList[0]; // beginning
Header[2] := Size; // ending
Header[3] := 0; // reserved
Stream := TFileStream.Create(Filename, fmCreate);
Stream.WriteBuffer(Header, SizeOf(Header));
History.ToStream(HistoryKeys, Stream, Size);
History.ToStream(HistoryHash, Stream, Size);
History.ToStream(HistoryRrec, Stream, Size);
end;
Result := True;
except
on e: Exception do
Report(SpyroTASName + ' ImportExportHistory() exception:', e.Message);
end;
Stream.Free();
end;
function ImportSpyroTAS(Filename: string): Boolean;
var
Name, State: string;
begin
Result := False;
if not FileExists(Filename) then
Exit;
if SprintMode then
EnterSptintMode(False);
Name := LowerCase(ExtractFileExt(Filename));
if Name = LowerCase(ExtSprintHist) then
begin
Name := ChangeFileExt(ChangeFileExt(Filename, ''), ExtSaveState);
if not FileExists(Name) then
Exit;
SprintFile := Filename;
SprintState := Name;
Fgui.b_free.Click();
EnterSptintMode(True);
Exit;
end;
SwitchToEmulator(True);
State := Filename;
Name := ChangeFileExt(Filename, ExtKeyHistory);
if FileExists(Name) then
begin
Result := ImportExportHistory(Name, True);
if LowerCase(Name) = LowerCase(Filename) then
State := ChangeFileExt(Filename, ExtSaveState);
end;
if FileExists(State) then
CopyFile(PChar(State), PChar(NameOfKeystate(0)), False);
if Fgui.lst_history.Items.Count > 0 then
Fgui.lst_history.ItemIndex := 0;
KeystateToLoad := 0;
LoadInFree := not Result;
LoadRequsted := True;
WaitBeforeLoading := 20;
SendAction(caListDirty);
SwitchToEmulator(False);
end;
// called from gui thread
procedure SwitchToEmulator(Intent: Boolean);
begin
SwitchingEffect := True;
SkipLocks();
if Intent and (EmulatorWindow <> 0) then
begin
ResetEvent(EventEmulatorTrap);
TrapRequested := True;
while WaitForSingleObject(EventEmulatorTrap, 50) = WAIT_TIMEOUT do
SkipLocks();
end
else
begin
SwitchRequested := False;
if ThisIsRestart then
SetColorStatus(StatusSaving)
else
begin
if HistoryPosition <> -1 then
begin
if HistoryPosition >= LastTimepoint then
SetColorStatus(StatusRecord)
else
SetColorStatus(StatusPlay);
end
else
SetColorStatus(StatusFree);
end;
StopOnBlur := False;
ClearCatchedKeys();
LastFrameTimestamp := timeGetTime();
AllFormsAction(afaGhost);
ResetEvent(EventEmulatorTrap);
SetEvent(EventContinueGame);
SetEvent(EventEmulatorWait);
SkipLocks();
if EmulatorWindow <> 0 then
begin
FireDeadlock := 1;
BringWindowToTop(EmulatorWindow);
SetForegroundWindow(EmulatorWindow);
FireDeadlock := 0;
end;
SwitchingEffect := False;
end;
PadToggleFrame := False;
SendAction(caPopup);
end;
//
procedure MakeGameScreenshot(OnlyForAviOptions: Boolean);
const
CAPTUREBLT = $40000000; // winapi constant
PW_CLIENTONLY = $00000001;
var
TargetRect: TRect;
TargetWidth, TargetHeight, ImageSize: Integer;
ShotBitmap: TBitmap;
Rop: Cardinal;
TargetDC, PreviewDC: HDC;
ImageName: string;
ImageData: PChar;
begin
if IsRunDLL or (EmulatorWindow = 0) then
Exit;
if ShotSkipSame and (not OnlyForAviOptions) and (not HaveNewScreen) then
Exit;
if AreOverlaysVisible() then
Rop := SRCCOPY or CAPTUREBLT
else
Rop := SRCCOPY;
// TargetRect := Rect(0, 0, 0, 0);
// GetClientRect(EmulatorWindow, TargetRect);
TargetRect := TFSpyroTAS(nil).GetSizeClient(EmulatorWindow);
TargetWidth := TargetRect.Right - TargetRect.Left;
TargetHeight := TargetRect.Bottom - TargetRect.Top;
if (TargetWidth < 4) or (TargetHeight < 4) then
Exit;
ShotBitmap := TBitmap.Create();
if (TargetWidth mod 4) = 0 then
ShotBitmap.PixelFormat := pf24bit
else
ShotBitmap.PixelFormat := pf32bit;
ShotBitmap.Width := TargetWidth;
ShotBitmap.Height := TargetHeight;
{$IFDEF FPC}
ShotBitmap.Canvas.Changed();
{$ENDIF}
// TargetDC := GetDC(EmulatorWindow);
// BitBlt(ShotBitmap.Canvas.Handle, 0, 0, TargetWidth, TargetHeight, TargetDC, 0, 0, Rop);
// PrintWindow(EmulatorWindow, ShotBitmap.Canvas.Handle,0);
TargetDC := GetDC(0);
BitBlt(ShotBitmap.Canvas.Handle, 0, 0, TargetWidth, TargetHeight, TargetDC,
TargetRect.Left, TargetRect.Top, Rop);
{$IFDEF FPC}
ShotBitmap.Canvas.Changed();
{$ENDIF}
BitmapDataAndSize(ShotBitmap, ImageData, ImageSize);
if OnlyForAviOptions then
begin
ReleaseDC(EmulatorWindow, TargetDC);
if not AviConfigured then
begin
if avi_settings(Fshot, ShotBitmap, AviFrameRate) then
AviConfigured := True;
end
else
avi_settings(Fshot, ShotBitmap, AviFrameRate);
ShotBitmap.Free();
Exit;
end;
ReleaseDC(EmulatorWindow, TargetDC);
if Fview.Visible then
begin
PreviewDC := GetDC(Fview.Handle);
StretchBlt(PreviewDC, 0, 0, Fview.ClientWidth, Fview.ClientHeight,
ShotBitmap.Canvas.Handle, 0, 0, TargetWidth, TargetHeight, SRCCOPY);
ReleaseDC(Fview.Handle, PreviewDC);
end;
if ShotFreeMode then
ImageName := FormatNumberWithZero(ShotCount, 6)
else
ImageName := FormatNumberWithZero(HistoryPosition, 6);
ImageName := ShotPath + 'TAS_' + ImageName;
if ShotType = stAvi then
begin
if not avi_write(ShotBitmap) then
begin
if Fgui.c_shot.Checked then
begin
Fgui.c_shot.Checked := False;
Report(SpyroTASName + ' screenshots:', 'AVI error!', Fgui);
end;
end;
end
else if ShotType = stPng then
begin
ImageName := ImageName + '.png';
SaveBitmapToPng(ShotBitmap, ImageName, PngCompression);
end
else if ShotType = stBmp then
begin
ImageName := ImageName + '.bmp';
DeleteFile(ImageName);
ShotBitmap.SaveToFile(ImageName);
end;
Inc(ShotCount);
ShotBitmap.Free();
end;
procedure ResetLoadSave();
begin
HashWait := 0;
SaveWaitForNone := 0;
SaveWaitForDone := 0;
SaveWaitAfter := 0;
SaveInEffect := False;
LoadWaitForNone := 0;
LoadWaitForDone := 0;
LoadWaitAfter := 0;
LoadInEffect := False;
WaitBeforeLoading := 0;
LiveSaveRequest := False;
SpecSaveRequest := False;
end;
//
procedure LoadSettings();
var
Scr: Integer;
Ini: TTasIni;
begin
if SprintMode then
Exit;
SaveSettingsScheduled := False;
Ini := TTasIni.Create();
Ini.Put('gui_type', 0);
Ini.Put('gui_fire', False);
Ini.Put('gui_2nd', False);
Ini.Put('gui_hash', True);
Ini.Put('gui_png', 6);
Ini.Put('gui_avi', 30);
Ini.Put('gui_semi', 0);
Ini.Put('gui_auto', 0);
Ini.Put('gui_diff', True);
Ini.Put('gui_ever', False);
Ini.Put('gui_fps', 60);
Ini.Put('gui_alpha', PadAlphaDefault);
Ini.Put('gui_warp', False);
Ini.Put('gui_spyro', '0x00000000');
Ini.ReadFrom(SectionSettings);
Ini.Get(Scr);
Ini.Get(UseAutofire);
Ini.Get(UseSecond);
Ini.Get(UseHashing);
Ini.Get(PngCompression);
Ini.Get(AviFrameRate);
Ini.Get(GlobalPadMask);
Ini.Get(KeyAutofireMask);
Ini.Get(ShotSkipSame);
Ini.Get(ShotFreeMode);
Ini.Get(TargetEmulationFps);
Ini.Get(PadWindowsAlpha);
Ini.Get(AllowWarp);
Ini.Get(SpyroOffsetText);
Ini.Free();
AviConfigured := True; // suppress AVI setting display
ShotType := stBmp;
if Scr = 2 then
begin
Fshot.r_avi.Checked := True;
Fgui.c_shot.Enabled := False;
ShotType := stAvi;
end
else if Scr = 1 then
begin
Fshot.r_png.Checked := True;
ShotType := stPng;
end
else
Fshot.r_bmp.Checked := True;
AviConfigured := False;
Fgui.c_auto.Checked := UseAutofire;
Fgui.c_2nd.Checked := UseSecond;
Fgui.c_hash.Checked := UseHashing;
Fshot.se_png.Value := PngCompression;
Fshot.se_avi.Value := AviFrameRate;
Fshot.c_diff.Checked := ShotSkipSame;
Fshot.c_ever.Checked := ShotFreeMode;
Fgui.se_fps.Value := TargetEmulationFps;
Fshot.tr_alpha.Position := PadWindowsAlpha;
Fgui.c_warp.Checked := AllowWarp;
Fext.e_spyro.Text := SpyroOffsetText;
Fext.e_spyroChange(nil);
AdjustAllAlpha(PadWindowsAlpha);
SaveSettingsScheduled := False;
end;
procedure SaveSettings();
var
Scr: Integer;
Ini: TTasIni;
begin
if SprintMode then
Exit;
if not SaveSettingsScheduled then
Exit;
SaveSettingsScheduled := False;
if ShotType = stAvi then
Scr := 2
else if ShotType = stPng then
Scr := 1
else
Scr := 0;
Ini := TTasIni.Create();
Ini.Put('gui_type', Scr);
Ini.Put('gui_fire', UseAutofire);
Ini.Put('gui_2nd', UseSecond);
Ini.Put('gui_hash', UseHashing);
Ini.Put('gui_png', PngCompression);
Ini.Put('gui_avi', AviFrameRate);
Ini.Put('gui_semi', GlobalPadMask);
Ini.Put('gui_auto', KeyAutofireMask);
Ini.Put('gui_diff', ShotSkipSame);
Ini.Put('gui_ever', ShotFreeMode);
Ini.Put('gui_fps', TargetEmulationFps);
Ini.Put('gui_alpha', PadWindowsAlpha);
Ini.Put('gui_warp', AllowWarp);
Ini.Put('gui_spyro', SpyroOffsetText);
Ini.WriteTo(SectionSettings);
Ini.Free();
end;
function EnsureAbsolutePath(const AnyPath: string): string;
begin
Result := PathFixBackslash(AnyPath);
if not IsAbsolutePath(AnyPath) then
Result := EmulatorRoot + Result;
end;
procedure EnterSptintMode(Start: Boolean);
begin
ChooseSemiAuto();
SprintSave := 0;
SprintHashBegin := 0;
SprintHashEnd := 0;
SprintMiss := False;
SprintCalcM := 0;
SprintCalcD := 0;
if Start then
begin
if SprintMode then
EnterSptintMode(False);
SaveSettings();
SprintMode := True;
Fgui.lst_history.Enabled := False;
Fgui.b_delete.Enabled := False;
Fgui.c_hash.Checked := False;
Fgui.c_hash.Enabled := False;
Fgui.c_semi.Checked := False;
Fgui.c_semi.Enabled := False;
Fgui.c_warp.Checked := False;
Fgui.c_warp.Enabled := False;
Fgui.c_skip.Checked := False;
Fgui.c_skip.Enabled := False;
Fext.c_spyro2.Checked := False;
Fext.c_spyro.Checked := False;
Fext.b_clear.Click();
Fext.c_spyro.Enabled := False;
Fext.e_spyro.Enabled := False;
Fext.b_clear.Enabled := False;
Fext.b_unpack.Enabled := False;
Fext.b_store.Enabled := False;
Fext.b_remove.Enabled := False;
Fext.lst_arch.Enabled := False;
Fedit.Close();
Fgui.se_threshold.Enabled := False;
Fgui.e_position.Enabled := False;
Fgui.se_timepoint.Enabled := False;
Fgui.b_load.Enabled := True;
Fgui.b_save.Enabled := True;
Fgui.b_restart.Enabled := True;
Fgui.b_free.Enabled := True;
Fgui.b_current.Enabled := True;
OldCaption := Fgui.Caption;
Fgui.Caption := 'SPRINT! - ' + OldCaption;
SetLastestPosition(0);
SetThresholdPosition(0);
SprintFileLoad();
Fgui.b_load.Click();
end
else
begin
SprintMode := False;
Fgui.lst_history.Enabled := True;
Fgui.b_delete.Enabled := True;
Fgui.c_hash.Enabled := True;
Fgui.c_semi.Enabled := True;
Fgui.c_warp.Enabled := True;
Fgui.c_skip.Enabled := True;
Fext.e_spyro.Enabled := True;
Fext.e_spyroChange(nil);
Fext.b_clear.Enabled := True;
Fext.lst_arch.Enabled := True;
Fgui.se_threshold.Enabled := True;
Fgui.e_position.Enabled := True;
Fgui.se_timepoint.Enabled := True;
LoadSettings();
Fgui.Caption := OldCaption;
Fgui.timer_mainTimer(nil);
end;
FoverF.FormShow(nil);
FoverR.FormShow(nil);
end;
procedure SprintFileSave();
var
Stream: TFileStream;
Hash, Size: Integer;
Data, From: PInteger;
const
Head = 4;
begin
if not FileExists(SprintState) then
Exit;
if LastTimepoint < 1 then
Exit;
Size := (LastTimepoint * 2 + Head) * 4;
Hash := HashFile(SprintState);
GetMem(Data, Size);
From := Data;
Inc(From);
From^ := SprintHashBegin;
Inc(From);
From^ := SprintHashEnd;
Inc(From);
From^ := 1;
Inc(From);
Move(History.Addr(HistoryKeys)^, From^, LastTimepoint * 4);
Inc(From, LastTimepoint);
Move(History.Addr(HistoryRrec)^, From^, LastTimepoint * 4);
From := Data;
Inc(From);
Data^ := HashCRC(From, Size - 4);
CryptData(Data, LastTimepoint * 2 + Head, Hash, True);
From := Data;
Inc(From);
Hash := From^;
Inc(From);
Hash := Hash xor From^;
CryptData(Data, LastTimepoint * 2 + Head, Hash, False);
Stream := nil;
SprintFile := ChangeFileExt(SprintState, '.' + TimeToString(Now())) + ExtSprintHist;
try
Stream := TFileStream.Create(SprintFile, fmCreate);
Stream.WriteBuffer(Data^, Size);
except
end;
Stream.Free();
FreeMem(Data);
end;
function SprintFileLoad(): Boolean;
var
Stream: TFileStream;
Hash, Size, Last: Integer;
Data, From: PInteger;
const
Head = 4;
begin
Result := False;
Stream := nil;
Data := nil;
try
if (not FileExists(SprintState)) or (not FileExists(SprintFile)) then
Abort;
Stream := TFileStream.Create(SprintFile, fmOpenRead or fmShareDenyNone);
Size := Stream.Size;
if Size < (4 + 60) * 4 then
Abort;
if Size > 100 * 1024 * 1024 then
Abort;
if (Size mod 8) <> 0 then
Abort;
Last := (Size - Head * 4) div 8;
GetMem(Data, Size);
Stream.ReadBuffer(Data^, Size);
From := Data;
Inc(From);
Hash := From^;
Inc(From);
Hash := Hash xor From^;
CryptData(Data, Last * 2 + Head, Hash, False);
Hash := HashFile(SprintState);
if Hash = 0 then
Abort;
CryptData(Data, Last * 2 + Head, Hash, True);
From := Data;
Inc(From);
if Data^ <> HashCRC(From, Size - 4) then
Abort;
History.SetSize(Last);
From := Data;
Inc(From);
SprintHashBegin := From^;
Inc(From);
SprintHashEnd := From^;
Inc(From);
Inc(From);
Move(From^, History.Addr(HistoryKeys)^, Last * 4);
Inc(From, Last);
Move(From^, History.Addr(HistoryRrec)^, Last * 4);
LastTimepoint := Last;
SprintCompute();
Result := True;
except
end;
Stream.Free();
if Data <> nil then
FreeMem(Data);
end;
function HashRAM(Frame: Integer): Integer;
var
Cur: Integer;
Off: PInteger;
const
Bits = 5;
begin
Result := 0;
if IsRunDLL or (PointerToRamStart = nil) then
Exit;
Off := PInteger(PointerToRamStart + HistoryOffsetInRAM);
Cur := Off^;
Off^ := 0;
if Frame = -1 then
Result := HashCRC(PointerToRamStart, SizeOfRAM)
else
begin
Result := HashCRC(PointerToRamStart + (Frame and ((1 shl Bits) - 1)) * (SizeOfRAM
shr Bits), SizeOfRAM shr Bits);
end;
Off^ := Cur;
end;
procedure SprintCompute();
var
M, D: Double;
begin
if not SprintMode then
Exit;
if LastTimepoint < 60 then
Exit;
M := ArrayCalc(History.Addr(HistoryRrec, 30), LastTimepoint - 60, D);
SprintCalcM := Round(M);
SprintCalcD := Round(D);
end;
end.
|
unit SequenceQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TSequenceW = class(TDSWrap)
private
FName: TFieldWrap;
FSeq: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
function GetNextValue(const AName: string): Integer;
property Name: TFieldWrap read FName;
property Seq: TFieldWrap read FSeq;
end;
TQuerySequence = class(TQueryBase)
FDUpdateSQL: TFDUpdateSQL;
private
FW: TSequenceW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
class function NextValue(AName: string): Integer; static;
property W: TSequenceW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQuerySequence.Create(AOwner: TComponent);
begin
inherited;
FW := TSequenceW.Create(FDQuery);
end;
class function TQuerySequence.NextValue(AName: string): Integer;
var
Q: TQuerySequence;
begin
Q := TQuerySequence.Create(nil);
try
Result := Q.W.GetNextValue(AName);
finally
FreeAndNil(Q);
end;
end;
constructor TSequenceW.Create(AOwner: TComponent);
begin
inherited;
FName := TFieldWrap.Create(Self, 'Name');
FSeq := TFieldWrap.Create(Self, 'Seq');
end;
function TSequenceW.GetNextValue(const AName: string): Integer;
begin
Assert(not AName.IsEmpty);
// Выбираем последнее значение нашей последовательности
Load([Name.FieldName], [AName]);
case DataSet.RecordCount of
0: // Если такой последовательности не существует
begin
TryAppend;
Name.F.AsString := AName;
Seq.F.AsInteger := 1;
TryPost;
end;
1: // Если такая последовательность существует
begin
// Сохраняем в БД новое значение последовательности
TryEdit;
Seq.F.AsInteger := Seq.F.AsInteger + 1;
TryPost;
end
else
raise Exception.CreateFmt
('Найдено более одной последовательности с именем %s', [AName]);
end;
Result := Seq.F.AsInteger;
end;
end.
|
unit ncaFrmConfigDanfe_NFe;
{$I NEX.INC}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ncaFrmBaseOpcao, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Menus, cxControls, cxContainer, cxEdit, StdCtrls, cxRadioGroup, jpeg, cxImage,
cxDropDownEdit, cxMaskEdit, cxSpinEdit, cxTextEdit, cxLabel, cxMemo, PngImage,
ExtCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, printers,
LMDCustomBevelPanel, LMDSimplePanel, ImgList, LMDPNGImage, ncaFrmConfigRec_Serial,
cxGroupBox, cxCheckBox, cxButtonEdit, ncaDocEdit, dxGDIPlusClasses;
type
TFrmConfigDanfe_NFe = class(TFrmBaseOpcao)
Image1: TImage;
LMDSimplePanel6: TLMDSimplePanel;
panImpressora: TLMDSimplePanel;
lbImpressora: TcxLabel;
cbImpressoras: TcxComboBox;
panTipoImpressora: TLMDSimplePanel;
lbModelo: TcxLabel;
edModelo: TncDocEdit;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbImpressorasPropertiesChange(Sender: TObject);
procedure cbImprimirPropertiesEditValueChanged(Sender: TObject);
private
fSerial : TFrmConfigRec_Serial;
fOnAlterou : TNotifyEvent;
{ Private declarations }
function NomeImpressora: String;
public
{ Public declarations }
procedure Atualizar;
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
function NumItens: Integer; override;
function GenericPrinter: Boolean;
property OnAlterou: TNotifyEvent
read FOnAlterou write FOnAlterou;
end;
var
FrmConfigDanfe_NFe: TFrmConfigDanfe_NFe;
implementation
uses
ncClassesBase,
ncaDM,
uNexTransResourceStrings_PT,
ncaDMComp,
ncaFrmTipoRec,
ncaFrmRecursoPRO, ncaConfigRecibo;
resourcestring
rsSelecionarModelo = 'É necessário selecionar um modelo/layout de impressão';
{$R *.dfm}
procedure SetDefaultPrinter(PrinterName: String) ;
var
j: Integer;
Device : PChar;
Driver : Pchar;
Port : Pchar;
HdeviceMode: Thandle;
aPrinter : TPrinter;
begin
Printer.PrinterIndex := -1;
getmem(Device, 255) ;
getmem(Driver, 255) ;
getmem(Port, 255) ;
aPrinter := TPrinter.create;
for j := 0 to Printer.printers.Count-1 do begin
if Printer.printers[j] = PrinterName then begin
aprinter.printerindex := j;
aPrinter.getprinter(device, driver, port, HdeviceMode) ;
StrCat(Device, ',') ;
StrCat(Device, Driver ) ;
StrCat(Device, Port ) ;
WriteProfileString('windows', 'device', Device) ;
StrCopy( Device, 'windows' ) ;
SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, Longint(@Device)) ;
end;
end;
Freemem(Device, 255) ;
Freemem(Driver, 255) ;
Freemem(Port, 255) ;
aPrinter.Free;
end;
procedure TFrmConfigDanfe_NFe.FormCreate(Sender: TObject);
begin
inherited;
FOnAlterou := nil;
end;
procedure TFrmConfigDanfe_NFe.cbImpressorasPropertiesChange(Sender: TObject);
begin
inherited;
if not cbImpressoras.Focused then Exit;
Atualizar;
end;
procedure TFrmConfigDanfe_NFe.cbImprimirPropertiesEditValueChanged(Sender: TObject);
begin
inherited;
Atualizar;
end;
{ TFrmBaseOpcao1 }
function TFrmConfigDanfe_NFe.Alterou: Boolean;
begin
Result := True;
with Dados do begin
if NomeImpressora <> gRecibo.Impressora[tipodoc_nfe] then Exit;
if edModelo.IDDoc <> gRecibo.Modelo[tipodoc_nfe] then Exit;
end;
Result := False;
end;
procedure TFrmConfigDanfe_NFe.Atualizar;
begin
try
btnOk.Enabled := Alterou and Dados.CM.UA.Admin;
finally
if Assigned(FOnAlterou) then FOnAlterou(Self);
end;
end;
procedure TFrmConfigDanfe_NFe.FormShow(Sender: TObject);
begin
inherited;
Renumera;
end;
function TFrmConfigDanfe_NFe.GenericPrinter: Boolean;
begin
result := (Pos('Generic', cbImpressoras.Text)>0);
end;
procedure TFrmConfigDanfe_NFe.Ler;
var
idx :integer;
begin
inherited;
edModelo.IDDoc := gRecibo.Modelo[tipodoc_nfe];
cbImpressoras.Properties.OnChange := nil;
try
cbImpressoras.Properties.Items.Assign(Printer.Printers);
finally
cbImpressoras.Properties.OnChange := cbImpressorasPropertiesChange;
end;
idx := cbImpressoras.Properties.Items.IndexOf(gRecibo.Impressora[tipodoc_nfe]);
if idx>-1 then begin
cbImpressoras.ItemIndex := idx;
cbImpressoras.Text := gRecibo.Impressora[tipodoc_nfe];
end else
cbImpressoras.ItemIndex := 0;
Atualizar;
end;
function TFrmConfigDanfe_NFe.NomeImpressora: String;
begin
Result := cbImpressoras.Text;
end;
function TFrmConfigDanfe_NFe.NumItens: Integer;
begin
Result := 3;
end;
procedure TFrmConfigDanfe_NFe.Renumera;
begin
inherited;
lbImpressora.Caption := IntToStr(InicioNumItem+0)+'. '+lbImpressora.Caption;
lbModelo.Caption := IntToStr(InicioNumItem+1)+'. '+lbModelo.Caption;
end;
procedure TFrmConfigDanfe_NFe.Salvar;
begin
inherited;
if edModelo.IDDoc='' then begin
edModelo.SetFocus;
Raise Exception.Create(rsSelecionarModelo);
end;
gRecibo.Modelo[tipodoc_nfe] := edModelo.IDDoc;
gRecibo.Impressora[tipodoc_nfe] := NomeImpressora;
gRecibo.Save;
end;
end.
|
unit mRadioListView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.ComCtrls, ORFn;
type
TRadioLVFrame = class(TFrame)
lvRadioList: TListView;
imgRadioButtons: TImageList;
procedure lvRadioListClick(Sender: TObject);
procedure lvRadioListChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure lvRadioListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
private
{ Private declarations }
FCode: String;
FSelectedGroup: TListGroup;
procedure ClearGroupButtons;
procedure ClearItemButtons;
// procedure GroupSelect(GroupID: Integer);
public
{ Public declarations }
procedure SetRadioListViewModel(ResultSet: TStrings);
property Code: String read FCode;
end;
implementation
{$R *.dfm}
const
lsNotSelected = 0;
lsSelected = 1;
lsNonSelectable = -1;
procedure TRadioLVFrame.ClearGroupButtons;
var
lgs: TListGroups;
lgi: Integer;
begin
lgs := lvRadioList.Groups;
for lgi := 0 to (TCollection(lgs).Count - 1) do
if lgs[lgi].TitleImage <> lsNonSelectable then
lgs[lgi].TitleImage := lsNotSelected;
end;
procedure TRadioLVFrame.ClearItemButtons;
var
lii : TListItem;
begin
for lii in lvRadioList.Items do
if lii.StateIndex <> lsNonSelectable then
lii.StateIndex := lsNotSelected;
end;
{procedure TRadioLVFrame.GroupSelect(GroupID: Integer);
var
i: Integer;
begin
for i := 0 to lvRadioList.Items.Count - 1 do
begin
if (GroupID = lvRadioList.Items[i].GroupID) and not lvRadioList.Items[i].Selected then
begin
lvRadioList.Items[i].Selected := true;
end;
end;
end;}
procedure TRadioLVFrame.lvRadioListChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
// OnChange
end;
procedure TRadioLVFrame.lvRadioListClick(Sender: TObject);
var
hts: THitTests;
lvCursorPos: TPoint;
li: TListItem;
begin
inherited;
//position of the mouse cursor related to ListView
lvCursorPos := lvRadioList.ScreenToClient(Mouse.CursorPos) ;
//click where?
hts := lvRadioList.GetHitTestInfoAt(lvCursorPos.X, lvCursorPos.Y);
//locate the state-clicked item
if (htOnStateIcon in hts) or (htOnItem in hts) then
begin
li := lvRadioList.GetItemAt(lvCursorPos.X, lvCursorPos.Y);
if Assigned(li) then
begin
if li.StateIndex = lsNonSelectable then
Exit;
ClearItemButtons;
li.StateIndex := lsSelected;
end;
end;
end;
procedure TRadioLVFrame.lvRadioListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
var
lgid: Integer;
lg: TListGroup;
begin
if lvRadioList.GroupView then
begin
lgid := Item.GroupID;
lg := lvRadioList.Groups[lgid];
if lg.TitleImage = lsNonSelectable then
Exit;
ClearGroupButtons;
if (lg <> FSelectedGroup) then
begin
FCode := '';
FSelectedGroup := lg;
end;
lg.TitleImage := lsSelected;
end;
if (Item.SubItems[0] <> '') then
begin
if FCode = '' then
FCode := Item.SubItems[0]
else
FCode := Item.SubItems[0] + '/' + FCode;
end;
end;
procedure TRadioLVFrame.SetRadioListViewModel(ResultSet: TStrings);
var
i, gid: Integer;
Item: TListItem;
Group: TListGroup;
RecStr: String;
function FindGroup(gid: Integer): TListGroup;
var
i: integer;
begin
for i := 0 to lvRadioList.Groups.Count - 1 do
if lvRadioList.Groups[i].GroupID = gid then
begin
result := lvRadioList.Groups[i];
Exit;
end;
result := nil;
end;
begin
lvRadioList.Items.Clear;
lvRadioList.Groups.Clear;
FCode := '';
// loop through ResultSet and create groups
for i := 0 to ResultSet.Count - 1 do
begin
RecStr := ResultSet[i];
Item := lvRadioList.Items.Add;
Item.ImageIndex := 0;
Item.StateIndex := -1;
Item.Caption := piece(RecStr, '^', 2);
Item.SubItems.Add(piece(RecStr, '^', 3));
gid := -1;
if (Piece(RecStr, '^', 1) <> '') then
gid := StrToInt(Piece(RecStr, '^', 1)) - 1;
if gid > -1 then
begin
Group := FindGroup(gid);
if Group = nil then
begin
Group := lvRadioList.Groups.Add;
Group.GroupID := gid;
Group.Header := 'Alternative ' + IntToStr(gid + 1);
Group.TitleImage := 0;
end;
Item.GroupID := Group.GroupID;
end;
end;
if lvRadioList.Items.Count = 1 then
lvRadioList.SelectAll;
end;
end.
|
unit record_overload_op_1;
interface
implementation
type
TRec = record
V: Int32;
operator Add(const Left: TRec; const Right: Int32): TRec;
end;
operator TRec.Add(const Left: TRec; const Right: Int32): TRec;
begin
Result.V := Left.V + Right;
end;
var
R: TRec;
procedure Test;
begin
R.V := 1;
R := R + 5;
end;
initialization
Test();
finalization
Assert(R.V = 6);
end. |
unit uTestuDrawingCommand;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, uExceptions, Graphics, uBaseCommand, uDrawingCommand, uBase,
uGraphicPrimitive, Variants;
type
// Test methods for class TBaseDrawingCommand
TestTBaseDrawingCommand = class(TTestCase)
strict private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestDrawingCommandFactory;
end;
// Test methods for class TChangeBackgroundColorCommand
TestTChangeBackgroundColorCommand = class(TTestCase)
strict private
FChangeBackgroundColorCommand: TChangeBackgroundColorCommand;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
end;
implementation
procedure TestTBaseDrawingCommand.SetUp;
begin
//
end;
procedure TestTBaseDrawingCommand.TearDown;
begin
//
end;
procedure TestTBaseDrawingCommand.TestDrawingCommandFactory;
var
Prim : TBaseDrawingCommand;
i : TDrawingCommandType;
begin
for I := Low( TDrawingCommandType ) to High( TDrawingCommandType ) do begin
Prim := DrawingCommandFactory( I );
Check( Prim <> nil );
end;
end;
procedure TestTChangeBackgroundColorCommand.SetUp;
begin
FChangeBackgroundColorCommand := TChangeBackgroundColorCommand.Create;
end;
procedure TestTChangeBackgroundColorCommand.TearDown;
begin
FChangeBackgroundColorCommand.Free;
FChangeBackgroundColorCommand := nil;
end;
procedure TestTChangeBackgroundColorCommand.TestExecute;
var
aData: variant;
aPrimitive: TGraphicPrimitive;
begin
aData := clBlue;
aPrimitive := TGraphicPrimitive.Create(nil);
aPrimitive.BackgroundColor := clRed;
try
FChangeBackgroundColorCommand.Execute(aPrimitive, aData);
Check( aPrimitive.BackgroundColor = clBlue );
finally
aPrimitive.Free;
end;
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTBaseDrawingCommand.Suite);
RegisterTest(TestTChangeBackgroundColorCommand.Suite);
end.
|
unit PropRewrite;
interface
uses
TMatcher,
Prop;
var
VPropmatcher: TMatcher;
implementation //===============================================================
initialization //===============================================================
VPropMatcher := TMatcher.Create;
with VPropMatcher, VPropFactory do
begin
AddRule(TRule.Create(
'Comm and',
MakeAnd(
MakeMeta('P'),
Makemeta('Q')),
MakeAnd(
MakeMeta('Q'),
MakeMeta('P'))
));
AddRule(TRule.Create(
'Comm or',
MakeOr(
MakeMeta('P'),
Makemeta('Q')),
MakeOr(
MakeMeta('Q'),
MakeMeta('P'))
));
AddRule(TRule.Create(
'Comm equiv',
MakeEquiv(
MakeMeta('P'),
Makemeta('Q')),
MakeEquiv(
MakeMeta('Q'),
MakeMeta('P'))
));
AddRule(TRule.Create(
'Null left or',
MakeOr(
MakeConst(vkTrue),
MakeMeta('P')),
MakeConst(vkTrue),
));
AddRule(TRule.Create(
'Null right or',
MakeOr(
MakeMeta('P'),
MakeConst(vkTrue)),
MakeConst(vkTrue)
));
AddRule(TRule.Create(
'Null left and',
MakeAnd(
MakeConst(vkFalse),
MakeMeta('P')),
MakeConst(vkFalse)
));
AddRule(TRule.Create(
'Null right and',
MakeAnd(
MakeMeta('P'),
MakeConst(vkFalse)),
MakeConst(vkFalse)
));
AddRule(TRule.Create(
'Unit left or',
MakeOr(
MakeConst(vkFalse),
MakeMeta('P')),
MakeMeta('P'),
));
AddRule(TRule.Create(
'Unit right or',
MakeOr(
MakeMeta('P'),
MakeConst(vkFalse)),
MakeMeta('P')
));
AddRule(TRule.Create(
'Unit left and',
MakeAnd(
MakeConst(vkTrue),
MakeMeta('P')),
MakeMeta('P')
));
AddRule(TRule.Create(
'Unit right and',
MakeAnd(
MakeMeta('P'),
MakeConst(vkTrue)),
MakeMeta('P')
));
AddRule(TRule.Create(
'Double negation',
MakeNot(
MakeNot(
Makemeta('P'))),
MakeMeta('P')
));
AddRule(TRule.Create(
'Exclude or',
MakeOr(
Makemeta('P'),
MakeNot(
Makemeta('P'))),
MakeConst(vkTrue)
));
AddRule(TRule.Create(
'Exclude and',
MakeAnd(
Makemeta('P'),
MakeNot(
Makemeta('P'))),
MakeConst(vkFalse)
));
AddRule(Trule.Create(
'De Morgan 1',
MakeNot(
MakeOr(
MakeMeta('P'),
MakeMeta('Q'))),
MakeAnd(
MakeNot(
MakeMeta('P')),
MakeNot(
Makemeta('Q')))
));
AddRule(Trule.Create(
'De Morgan 2',
MakeNot(
MakeAnd(
MakeMeta('P'),
MakeMeta('Q'))),
MakeOr(
MakeNot(
MakeMeta('P')),
MakeNot(
Makemeta('Q')))
));
AddRule(TRule.Create(
'Left distr and or',
MakeAnd(
MakeMeta('P'),
MakeOr(
MakeMeta('Q'),
Makemeta('R'))),
MakeOr(
MakeAnd(
MakeMeta('P'),
MakeMeta('Q')),
MakeAnd(
MakeMeta('P'),
MakeMeta('R')))
));
AddRule(TRule.Create(
'Left distr or and',
MakeOr(
MakeMeta('P'),
MakeAnd(
MakeMeta('Q'),
Makemeta('R'))),
MakeAnd(
MakeOr(
MakeMeta('P'),
MakeMeta('Q')),
MakeOr(
MakeMeta('P'),
MakeMeta('R')))
));
AddRule(TRule.Create(
'Left distr or equiv',
MakeOr(
MakeMeta('P'),
MakeEquiv(
MakeMeta('Q'),
Makemeta('R'))),
MakeEquiv(
MakeOr(
MakeMeta('P'),
MakeMeta('Q')),
MakeOr(
MakeMeta('P'),
MakeMeta('R')))
));
AddRule(Trule.Create(
'Implication',
MakeImp(
MakeMeta('P'),
MakeMeta('Q')),
MakeOr(
MakeNot(
MakeMeta('P')),
MakeMeta('Q'))
));
AddRule(TRule.Create(
'Equivalence',
MakeEquiv(
MakeMeta('P'),
MakeMeta('Q')),
MakeAnd(
MakeImp(
MakeMeta('P'),
MakeMeta('Q')),
MakeImp(
MakeMeta('Q'),
MakeMeta('P')))
));
end;{with}
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIListView.pas
// Creator : Shen Min
// Date : 2002-10-03 V1-V3
// 2003-07-04 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIListView;
interface
{$I SUIPack.inc}
uses Windows, SysUtils, Classes, Controls, ComCtrls, Graphics, Messages, Forms,
CommCtrl, SUIThemes, SUIMgr, SUIScrollBar;
type
TsuiListView = class(TCustomListView)
private
m_BorderColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
// scroll bar
m_VScrollBar : TsuiScrollBar;
m_HScrollBar : TsuiScrollBar;
m_MouseDown : Boolean;
m_SelfChanging : Boolean;
procedure SetVScrollBar(const Value: TsuiScrollBar);
procedure SetHScrollBar(const Value: TsuiScrollBar);
procedure OnVScrollBarChange(Sender : TObject);
procedure OnHScrollBarChange(Sender : TObject);
procedure UpdateScrollBars();
procedure UpdateScrollBarsPos();
procedure CMEnabledChanged(var Msg : TMessage); message CM_ENABLEDCHANGED;
procedure CMVisibleChanged(var Msg : TMEssage); message CM_VISIBLECHANGED;
procedure WMSIZE(var Msg : TMessage); message WM_SIZE;
procedure WMMOVE(var Msg : TMessage); message WM_MOVE;
procedure WMMOUSEWHEEL(var Message: TMessage); message WM_MOUSEWHEEL;
procedure WMLBUTTONDOWN(var Message: TMessage); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message: TMessage); message WM_LBUTTONUP;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure WMDELETEITEM(var Msg : TMessage); message WM_DELETEITEM;
procedure WMMOUSEMOVE(var Message: TMessage); message WM_MOUSEMOVE;
procedure WMVSCROLL(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMHSCROLL(var Message: TWMHScroll); message WM_HSCROLL;
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
procedure WMSETREDRAW(var Msg : TMessage); message WM_SETREDRAW;
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetFileTheme(const Value: TsuiFileTheme);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
// scroll bar
property VScrollBar : TsuiScrollBar read m_VScrollBar write SetVScrollBar;
property HScrollBar : TsuiScrollBar read m_HScrollBar write SetHScrollBar;
property Action;
property Align;
property AllocBy;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind default bkNone;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property Checkboxes;
property Color;
property Columns;
property ColumnClick;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property FlatScrollBars;
property FullDrag;
property GridLines;
property HideSelection;
property HotTrack;
property HotTrackStyles;
property HoverTime;
property IconOptions;
property Items;
property LargeImages;
property MultiSelect;
property OwnerData;
property OwnerDraw;
property ReadOnly default False;
property RowSelect;
property ParentBiDiMode;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowColumnHeaders;
property ShowWorkAreas;
property ShowHint;
property SmallImages;
property SortType;
property StateImages;
property TabOrder;
property TabStop default True;
property ViewStyle;
property Visible;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnAdvancedCustomDrawSubItem;
property OnChange;
property OnChanging;
property OnClick;
property OnColumnClick;
property OnColumnDragged;
property OnColumnRightClick;
property OnCompare;
property OnContextPopup;
property OnCustomDraw;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnData;
property OnDataFind;
property OnDataHint;
property OnDataStateChange;
property OnDblClick;
property OnDeletion;
property OnDrawItem;
property OnEdited;
property OnEditing;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnGetSubItemImage;
property OnDragDrop;
property OnDragOver;
property OnInfoTip;
property OnInsert;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSelectItem;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses SUIPublic, SUIProgressBar;
{ TsuiListView }
procedure TsuiListView.CMEnabledChanged(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiListView.CMVisibleChanged(var Msg: TMEssage);
begin
inherited;
if not Visible then
begin
if m_VScrollBar <> nil then
m_VScrollBar.Visible := Visible;
if m_HScrollBar <> nil then
m_HScrollBar.Visible := Visible;
end
else
UpdateScrollBarsPos();
end;
constructor TsuiListView.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderStyle := bsNone;
BorderWidth := 2;
m_SelfChanging := false;
m_MouseDown := false;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiListView.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_VScrollBar)
)then
m_VScrollBar := nil;
if (
(Operation = opRemove) and
(AComponent = m_HScrollBar)
)then
m_HScrollBar := nil;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiListView.OnHScrollBarChange(Sender: TObject);
begin
if m_SelfChanging then
Exit;
Scroll(m_HScrollBar.LastChange, 0);
end;
procedure TsuiListView.OnVScrollBarChange(Sender: TObject);
var
i : Integer;
LastChange : Integer;
begin
if m_SelfChanging then
Exit;
if ViewStyle = vsReport then
begin
LastChange := m_VScrollBar.LastChange;
if LastChange > 0 then
begin
for i := 0 to LastChange - 1 do
SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_LINEDOWN, 0), 0);
end
else
begin
for i := LastChange + 1 to 0 do
SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_LINEUP, 0), 0);
end;
Invalidate;
end
else
Scroll(0, m_VScrollBar.LastChange)
end;
procedure TsuiListView.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiListView.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiListView.SetHScrollBar(const Value: TsuiScrollBar);
begin
if m_HScrollBar = Value then
Exit;
if m_HScrollBar <> nil then
begin
m_HScrollBar.OnChange := nil;
m_HScrollBar.LineButton := 0;
m_HScrollBar.Max := 100;
m_HScrollBar.Enabled := true;
end;
m_HScrollBar := Value;
if m_HScrollBar = nil then
Exit;
m_HScrollBar.SmallChange := 5;
m_HScrollBar.Orientation := suiHorizontal;
m_HScrollBar.OnChange := OnHScrollBArChange;
m_HScrollBar.BringToFront();
UpdateScrollBarsPos();
end;
procedure TsuiListView.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR)
else
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
if m_VScrollBar <> nil then
m_VScrollBar.UIStyle := OutUIStyle;
if m_HScrollBar <> nil then
m_HScrollBar.UIStyle := OutUIStyle;
Repaint();
end;
procedure TsuiListView.SetVScrollBar(const Value: TsuiScrollBar);
begin
if m_VScrollBar = Value then
Exit;
if m_VScrollBar <> nil then
begin
m_VScrollBar.OnChange := nil;
m_VScrollBar.LineButton := 0;
m_VScrollBar.Max := 100;
m_VScrollBar.Enabled := true;
end;
m_VScrollBar := Value;
if m_VScrollBar = nil then
Exit;
m_VScrollBar.SmallChange := 5;
m_VScrollBar.Orientation := suiVertical;
m_VScrollBar.OnChange := OnVScrollBArChange;
m_VScrollBar.BringToFront();
UpdateScrollBarsPos();
end;
procedure TsuiListView.UpdateScrollBars;
var
info : tagScrollInfo;
barinfo : tagScrollBarInfo;
R : Boolean;
begin
if csLoading in ComponentState then
Exit;
m_SelfChanging := true;
if m_VScrollBar <> nil then
begin
barinfo.cbSize := SizeOf(barinfo);
R := SUIGetScrollBarInfo(Handle, Integer(OBJID_VSCROLL), barinfo);
if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or
(barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or
(not R) then
begin
m_VScrollBar.LineButton := 0;
m_VScrollBar.Enabled := false;
m_VScrollBar.Visible := false;
end
else if not Enabled then
m_VScrollBar.Enabled := false
else
begin
m_VScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop);
m_VScrollBar.Enabled := true;
m_VScrollBar.Visible := true;
end;
info.cbSize := SizeOf(info);
info.fMask := SIF_ALL;
GetScrollInfo(Handle, SB_VERT, info);
m_VScrollBar.Max := info.nMax - Integer(info.nPage) + 1;
m_VScrollBar.Min := info.nMin;
m_VScrollBar.Position := info.nPos;
end;
if m_HScrollBar <> nil then
begin
barinfo.cbSize := SizeOf(barinfo);
R := SUIGetScrollBarInfo(Handle, Integer(OBJID_HSCROLL), barinfo);
if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or
(barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or
(not R) then
begin
m_HScrollBar.LineButton := 0;
m_HScrollBar.Enabled := false;
m_HScrollBar.Visible := false;
end
else if not Enabled then
m_HScrollBar.Enabled := false
else
begin
m_HScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop);
m_HScrollBar.Enabled := true;
m_HScrollBar.Visible := true;
end;
info.cbSize := SizeOf(info);
info.fMask := SIF_ALL;
GetScrollInfo(Handle, SB_HORZ, info);
m_HScrollBar.Max := info.nMax - Integer(info.nPage) + 1;
m_HScrollBar.Min := info.nMin;
m_HScrollBar.Position := info.nPos;
end;
m_SelfChanging := false;
end;
procedure TsuiListView.UpdateScrollBarsPos;
var
L2R : Boolean;
begin
inherited;
if csLoading in ComponentState then
Exit;
L2R := ((BidiMode = bdLeftToRight) or (BidiMode = bdRightToLeftReadingOnly)) or (not SysLocale.MiddleEast);
if m_HScrollBar <> nil then
begin
if m_HScrollBar.Height > Height then
m_HScrollBar.Top := Top
else
begin
if L2R then
begin
m_HScrollBar.Left := Left + 1;
m_HScrollBar.Top := Top + Height - m_HScrollBar.Height - 2;
if m_VScrollBar <> nil then
begin
if m_VScrollBar.Visible then
m_HScrollBar.Width := Width - 2 - m_VScrollBar.Width
else
m_HScrollBar.Width := Width - 2
end
else
m_HScrollBar.Width := Width - 2
end
else
begin
m_HScrollBar.Top := Top + Height - m_HScrollBar.Height - 2;
if m_VScrollBar <> nil then
begin
m_HScrollBar.Left := Left + m_VScrollBar.Width + 1;
if m_VScrollBar.Visible then
m_HScrollBar.Width := Width - 2 - m_VScrollBar.Width
else
m_HScrollBar.Width := Width - 2
end
else
begin
m_HScrollBar.Left := Left + 1;
m_HScrollBar.Width := Width - 2;
end;
end;
end;
end;
if m_VScrollBar <> nil then
begin
if m_VScrollBar.Width > Width then
m_VScrollBar.Left := Left
else
begin
if L2R then
begin
m_VScrollBar.Left := Left + Width - m_VScrollBar.Width - 2;
m_VScrollBar.Top := Top + 1;
if m_HScrollBar <> nil then
begin
if m_HScrollBar.Visible then
m_VScrollBar.Height := Height - 2 - m_HScrollBar.Height
else
m_VScrollBar.Height := Height - 2;
end
else
m_VScrollBar.Height := Height - 2;
end
else
begin
m_VScrollBar.Left := Left + 2;
m_VScrollBar.Top := Top + 1;
if m_HScrollBar <> nil then
begin
if m_HScrollBar.Visible then
m_VScrollBar.Height := Height - 2 - m_HScrollBar.Height
else
m_VScrollBar.Height := Height - 2;
end
else
m_VScrollBar.Height := Height - 2;
end;
end;
end;
UpdateScrollBars();
end;
procedure TsuiListView.WMDELETEITEM(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiListView.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
procedure TsuiListView.WMHSCROLL(var Message: TWMHScroll);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiListView.WMKeyDown(var Message: TWMKeyDown);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiListView.WMLBUTTONDOWN(var Message: TMessage);
begin
inherited;
m_MouseDown := true;
UpdateScrollBars();
end;
procedure TsuiListView.WMLButtonUp(var Message: TMessage);
begin
inherited;
m_MouseDown := false;
end;
procedure TsuiListView.WMMOUSEMOVE(var Message: TMessage);
begin
inherited;
if m_MouseDown then UpdateScrollBars();
end;
procedure TsuiListView.WMMOUSEWHEEL(var Message: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiListView.WMMOVE(var Msg: TMessage);
begin
inherited;
UpdateScrollBarsPos();
end;
procedure TsuiListView.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
procedure TsuiListView.WMSETREDRAW(var Msg: TMessage);
begin
inherited;
if Boolean(Msg.WParam) and (Items.Count = 0) then
AlphaSort();
end;
procedure TsuiListView.WMSIZE(var Msg: TMessage);
begin
UpdateScrollBarsPos();
inherited;
UpdateScrollBarsPos();
end;
procedure TsuiListView.WMVSCROLL(var Message: TWMVScroll);
begin
inherited;
UpdateScrollBars();
end;
end.
|
unit HKStringGrid;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Grids,
HKCompPacksTypes;
type
THKGridColumn=class;
TOnBtnAction=procedure(Sender:TObject; const vCol:THKGridColumn;
const aRows:TStrings)of object;
TColumnType=(CTTxt, CTNumber, CTButton, CTDateTimeISO, CTBtnEdit, CTBtnDelete);
THKStringGrid=class;
{ THKGridColumn }
THKGridColumn=class(TCollectionItem)
private
FAlignment: TAlignment;
FColumnType: TColumnType;
FFieldName: String;
FImageIndex: Integer;
FImageList: TImageList;
FTitle: String;
FWidth: Integer;
procedure SetAlignment(AValue: TAlignment);
procedure SetColumnType(AValue: TColumnType);
procedure SetFieldName(AValue: String);
procedure SetImageIndex(AValue: Integer);
procedure SetImageList(AValue: TImageList);
procedure SetTitle(AValue: String);
procedure SetWidth(AValue: Integer);
public
constructor Create(ACollection: TCollection); override;
published
property FieldName:String read FFieldName write SetFieldName;
property Title:String read FTitle write SetTitle;
property ColumnType:TColumnType read FColumnType write SetColumnType;
property Alignment:TAlignment read FAlignment write SetAlignment;
property Width:Integer read FWidth write SetWidth default 80;
property ImageList:TImageList read FImageList write SetImageList;
property ImageIndex:Integer read FImageIndex write SetImageIndex;
end;
{ THKGridColumns }
THKGridColumns=class(TCollection)
private
fOwnerGrid:THKStringGrid;
public
function Add: THKGridColumn;
procedure clear;
procedure UpdateColumn;
constructor Create(OwnerGrid:THKStringGrid; AItemClass: TCollectionItemClass);
end;
{ THKStringGrid }
THKStringGrid = class(TCustomStringGrid)
private
FEvenColor: TColor;
FHKGridColumns: THKGridColumns;
FNegativeColor: TColor;
FNegativeColorActive: Boolean;
FOddColor: TColor;
FOnBtnCustomClicked: TOnBtnAction;
FOnBtnEditClicked: TOnBtnAction;
FOnBtnRemoveClicked: TOnBtnAction;
procedure SetEvenColor(AValue: TColor);
procedure SetHKGridColumns(AValue: THKGridColumns);
procedure SetNegativeColor(AValue: TColor);
procedure SetNegativeColorActive(AValue: Boolean);
procedure SetOddColor(AValue: TColor);
procedure SetOnBtnCustomClicked(AValue: TOnBtnAction);
procedure SetOnBtnEditClicked(AValue: TOnBtnAction);
procedure SetOnBtnRemoveClicked(AValue: TOnBtnAction);
protected
procedure DoEditClicked(aCol: THKGridColumn);
procedure DoRemoveClicked(aCol: THKGridColumn);
procedure DoCustomeClicked(aCol: THKGridColumn);
procedure DoEditBtnClicked(Sender: TObject; aCol, aRow:Integer);
procedure DoPrepareCanvas(aCol, aRow: Integer; aState: TGridDrawState);
override;
function GetNegativeData(aCol, aRow:Integer):Boolean;virtual;
//procedure SelectEditor; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property HKGridColumns:THKGridColumns read FHKGridColumns write SetHKGridColumns;
property OnBtnEditClicked:TOnBtnAction read FOnBtnEditClicked write SetOnBtnEditClicked;
property OnBtnRemoveClicked:TOnBtnAction read FOnBtnRemoveClicked write SetOnBtnRemoveClicked;
property OnBtnCustomClicked:TOnBtnAction read FOnBtnCustomClicked write SetOnBtnCustomClicked;
property OddColor:TColor read FOddColor write SetOddColor;
property EvenColor:TColor read FEvenColor write SetEvenColor;
property NegativeColor:TColor read FNegativeColor write SetNegativeColor;
property NegativeColorActive:Boolean read FNegativeColorActive write SetNegativeColorActive;
property Align;
property AlternateColor;
property Anchors;
property AutoAdvance;
property AutoEdit;
property AutoFillColumns;
property BiDiMode;
property BorderSpacing;
property BorderStyle;
property CellHintPriority;
property Color;
property ColCount;
property ColumnClickSorts;
property Columns;
property Constraints;
property DefaultColWidth;
property DefaultDrawing;
property DefaultRowHeight;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ExtendedSelect;
property FixedColor;
property FixedCols;
property FixedRows;
property Flat;
property Font;
property GridLineWidth;
property HeaderHotZones;
property HeaderPushZones;
property ImageIndexSortAsc;
property ImageIndexSortDesc;
property MouseWheelOption;
property Options;
property Options2;
property ParentBiDiMode;
property ParentColor default false;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RangeSelectMode;
property RowCount;
property ScrollBars;
property ShowHint;
property TabAdvance;
property TabOrder;
property TabStop;
property TitleFont;
property TitleImageList;
property TitleStyle;
property UseXORFeatures;
property Visible;
property VisibleColCount;
property VisibleRowCount;
end;
procedure Register;
implementation
procedure Register;
begin
{$I hkstringgrid_icon.lrs}
RegisterComponents('HKCompPacks',[THKStringGrid]);
end;
{ THKStringGrid }
procedure THKStringGrid.SetHKGridColumns(AValue: THKGridColumns);
begin
if FHKGridColumns=AValue then Exit;
FHKGridColumns:=AValue;
end;
procedure THKStringGrid.SetNegativeColor(AValue: TColor);
begin
if FNegativeColor=AValue then Exit;
FNegativeColor:=AValue;
end;
procedure THKStringGrid.SetNegativeColorActive(AValue: Boolean);
begin
if FNegativeColorActive=AValue then Exit;
FNegativeColorActive:=AValue;
end;
procedure THKStringGrid.SetEvenColor(AValue: TColor);
begin
if FEvenColor=AValue then Exit;
FEvenColor:=AValue;
end;
procedure THKStringGrid.SetOddColor(AValue: TColor);
begin
if FOddColor=AValue then Exit;
FOddColor:=AValue;
end;
procedure THKStringGrid.SetOnBtnCustomClicked(AValue: TOnBtnAction);
begin
if FOnBtnCustomClicked=AValue then Exit;
FOnBtnCustomClicked:=AValue;
end;
procedure THKStringGrid.SetOnBtnEditClicked(AValue: TOnBtnAction);
begin
if FOnBtnEditClicked=AValue then Exit;
FOnBtnEditClicked:=AValue;
end;
procedure THKStringGrid.SetOnBtnRemoveClicked(AValue: TOnBtnAction);
begin
if FOnBtnRemoveClicked=AValue then Exit;
FOnBtnRemoveClicked:=AValue;
end;
procedure THKStringGrid.DoEditClicked(aCol:THKGridColumn);
begin
if Assigned(OnBtnEditClicked) then OnBtnEditClicked(Self, aCol, Rows[Row]);
end;
procedure THKStringGrid.DoRemoveClicked(aCol:THKGridColumn);
begin
if Assigned(OnBtnRemoveClicked) then OnBtnRemoveClicked(Self, aCol, Rows[Row]);
end;
procedure THKStringGrid.DoCustomeClicked(aCol:THKGridColumn);
begin
if Assigned(OnBtnCustomClicked) then OnBtnCustomClicked(Self, aCol, Rows[Row]);
end;
procedure THKStringGrid.DoEditBtnClicked(Sender: TObject; aCol, aRow: Integer);
var
vCol: THKGridColumn;
begin
vCol:=HKGridColumns.Items[aCol-1] as THKGridColumn;
case vCol.ColumnType of
CTBtnDelete:DoRemoveClicked(vCol);
CTBtnEdit:DoEditClicked(vCol);
CTButton:DoCustomeClicked(vCol);
else Exit;
end;
end;
procedure THKStringGrid.DoPrepareCanvas(aCol, aRow: Integer;
aState: TGridDrawState);
var isNegative:Boolean;
aaa: Integer;
begin
inherited DoPrepareCanvas(aCol, aRow, aState);
if aRow=0 then exit;
isNegative:=False;
if NegativeColorActive then
begin
for aaa:=0 to ColCount-1 do
begin
isNegative:=GetNegativeData(aaa, aRow);
if isNegative then break;
end;
end;
if isNegative then
begin
Canvas.Font.Color:=NegativeColor;
Canvas.Font.Style:=[fsBold];
end
else
Canvas.Font.Color:=clBlack;
if (aRow mod 2)=1 then
begin
Canvas.Brush.Color:=OddColor;
end
else
begin
Canvas.Brush.Color:=EvenColor;
end;
end;
function THKStringGrid.GetNegativeData(aCol, aRow: Integer): Boolean;
var
vCol: THKGridColumn;
str: String;
xxx: Longint;
begin
Result:=False;
if aCol=0 then exit;
vCol:=HKGridColumns.Items[aCol-1] as THKGridColumn;
if vCol=nil then exit;
if vCol.ColumnType<>CTNumber then exit;
str:=Cells[aCol, aRow].Replace('.','',[rfReplaceAll]).Replace(',','',[rfReplaceAll]);
TryStrToInt(str,xxx);
Result:=xxx < 0;
end;
constructor THKStringGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHKGridColumns:=THKGridColumns.Create(Self, THKGridColumn);
OnButtonClick:=@DoEditBtnClicked;
//OddColor:=clWhite;
OddColor:=$00FEFEFE;
EvenColor:=$00EFEFEF;
NegativeColor:=$0000D7;
NegativeColorActive:=True;
Options:=[goHorzLine, goVertLine, goFixedHorzLine, goFixedVertLine];
MouseWheelOption:=mwGrid;
end;
destructor THKStringGrid.Destroy;
begin
Clear;
FreeAndNil(FHKGridColumns);
inherited Destroy;
end;
{ THKGridColumns }
function THKGridColumns.Add: THKGridColumn;
begin
result := THKGridColumn( inherited add );
end;
procedure THKGridColumns.clear;
begin
BeginUpdate;
inherited Clear;
EndUpdate;
end;
procedure THKGridColumns.UpdateColumn;
var
aaa: Integer;
vCol: TGridColumn;
temp: THKGridColumn;
begin
if Count=0 then exit;
//oldFixedRow:=fOwnerGrid.FixedRows;
fOwnerGrid.RowCount:=1;
fOwnerGrid.FixedCols:=0;
fOwnerGrid.FixedRows:=1;
fOwnerGrid.Columns.Clear;
vCol:=fOwnerGrid.Columns.Add;
vCol.Title.Caption:='#';
vCol.Title.Alignment:=taRightJustify;
vCol.Alignment:=taRightJustify;
vCol.Width:=50;
for aaa:=0 to Count-1 do
begin
vCol:=fOwnerGrid.Columns.Add;
temp:=THKGridColumn(Items[aaa]);
vCol.Title.Caption:= temp.Title;
vCol.Alignment:=temp.Alignment;
vCol.Title.Alignment:=temp.Alignment;
vCol.Width:=temp.Width;
if temp.ColumnType in [CTBtnDelete, CTBtnEdit, CTButton] then
begin
vCol.ButtonStyle:=cbsButtonColumn;
end;
end;
end;
constructor THKGridColumns.Create(OwnerGrid: THKStringGrid;
AItemClass: TCollectionItemClass);
begin
fOwnerGrid:=OwnerGrid;
Inherited Create(AItemClass);
end;
{ THKGridColumn }
procedure THKGridColumn.SetAlignment(AValue: TAlignment);
begin
if FAlignment=AValue then Exit;
FAlignment:=AValue;
end;
procedure THKGridColumn.SetColumnType(AValue: TColumnType);
begin
if FColumnType=AValue then Exit;
FColumnType:=AValue;
end;
procedure THKGridColumn.SetFieldName(AValue: String);
begin
if FFieldName=AValue then Exit;
FFieldName:=AValue;
end;
procedure THKGridColumn.SetImageIndex(AValue: Integer);
begin
if FImageIndex=AValue then Exit;
FImageIndex:=AValue;
end;
procedure THKGridColumn.SetImageList(AValue: TImageList);
begin
if FImageList=AValue then Exit;
FImageList:=AValue;
end;
procedure THKGridColumn.SetTitle(AValue: String);
begin
if FTitle=AValue then Exit;
FTitle:=AValue;
end;
procedure THKGridColumn.SetWidth(AValue: Integer);
begin
if FWidth=AValue then Exit;
FWidth:=AValue;
end;
constructor THKGridColumn.Create(ACollection: TCollection);
begin
FAlignment:=taLeftJustify;
FColumnType:=CTTxt;
FWidth:=80;
inherited Create(ACollection);
end;
end.
|
unit ANovoContasaPagar;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
ExtCtrls, PainelGradiente, Componentes1, Db, DBTables, Tabela, StdCtrls,
DBCtrls, BotaoCadastro, Buttons, Localizacao, UnDados,
Grids, DBGrids, constantes, Mask, DBKeyViolation, LabelCorMove,
Spin, EditorImagem, numericos, unContasaPagar, UnDespesas, UnDadosCR, UnClientes,
FMTBcd, SqlExpr, ComCtrls, CGrades, UnDadosLocaliza;
type
TFNovoContasAPagar = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
Localiza: TConsultaPadrao;
Imagem: TEditorImagem;
ValidaGravacao: TValidaGravacao;
Aux: TSQLQuery;
PanelColor2: TPanelColor;
BFechar: TBitBtn;
BotaoGravar1: TBitBtn;
BNovo: TBitBtn;
BotaoCancelar1: TBitBtn;
PanelColor1: TPanelColor;
Paginas: TPageControl;
PGeral: TTabSheet;
PanelColor3: TPanelColor;
PCabecalho: TPanelColor;
Label1: TLabel;
Label3: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
LNomFornecedor: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton3: TSpeedButton;
Label2: TLabel;
Label6: TLabel;
LPlano: TLabel;
BPlano: TSpeedButton;
Label11: TLabel;
SpeedButton2: TSpeedButton;
Label17: TLabel;
Label12: TLabel;
Label10: TLabel;
LParcelas: TLabel;
EFilial: TEditColor;
ELanPagar: TEditColor;
EFornecedor: TEditLocaliza;
EMoeda: TEditLocaliza;
ENota: Tnumerico;
Tempo: TPainelTempo;
EPlano: TEditColor;
ECentroCusto: TEditLocaliza;
ECodBarras: TEditColor;
EValorparcelas: Tnumerico;
EValorTotal: Tnumerico;
PRodape: TPanelColor;
Label5: TLabel;
LFoto: TLabel;
Label20: TLabel;
SpeedButton4: TSpeedButton;
Label7: TLabel;
Label4: TLabel;
SpeedButton5: TSpeedButton;
Label9: TLabel;
EDataEmissao: TMaskEditColor;
EdcFormaPgto: TEditLocaliza;
BFoto: TBitBtn;
EContaCaixa: TEditLocaliza;
CBaixarConta: TCheckBox;
PProjeto: TPanelColor;
Label16: TLabel;
SpeedButton6: TSpeedButton;
LNomProjeto: TLabel;
EProjeto: TRBEditLocaliza;
PaginaProjeto: TTabSheet;
GProjetos: TRBStringGridColor;
BAutorizacaoPagamento: TBitBtn;
EConsultaProjeto: TRBEditLocaliza;
ECondicaoPagamento: TRBEditLocaliza;
Label18: TLabel;
SpeedButton7: TSpeedButton;
Label8: TLabel;
CDespesaPrevista: TCheckBox;
BitBtn1: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DBEditButton4Exit(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure BNovoClick(Sender: TObject);
procedure EFornecedorCadastrar(Sender: TObject);
procedure DBEditColor20Exit(Sender: TObject);
procedure EValorparcelasExit(Sender: TObject);
procedure EFilialChange(Sender: TObject);
procedure EdcFormaPgtoCadastrar(Sender: TObject);
procedure EPlanoExit(Sender: TObject);
procedure EPlanoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BotaoGravar1Click(Sender: TObject);
procedure BotaoCancelar1Click(Sender: TObject);
procedure EFornecedorAlterar(Sender: TObject);
procedure ECentroCustoCadastrar(Sender: TObject);
procedure BFotoClick(Sender: TObject);
procedure EdcFormaPgtoRetorno(Retorno1, Retorno2: String);
procedure CBaixarContaClick(Sender: TObject);
procedure ECodBarrasKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EFornecedorRetorno(Retorno1, Retorno2: String);
procedure EDataEmissaoExit(Sender: TObject);
procedure EProjetoCadastrar(Sender: TObject);
procedure BAutorizacaoPagamentoClick(Sender: TObject);
procedure GProjetosCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GProjetosDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GProjetosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure GProjetosKeyPress(Sender: TObject; var Key: Char);
procedure GProjetosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer);
procedure GProjetosNovaLinha(Sender: TObject);
procedure GProjetosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure EConsultaProjetoRetorno(VpaColunas: TRBColunasLocaliza);
procedure EProjetoFimConsulta(Sender: TObject);
procedure PaginasChange(Sender: TObject);
procedure ECondicaoPagamentoCadastrar(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
VprDContasAPagar : TRBDContasaPagar;
VprDatEmissao :TDAteTime;
VprAcao : Boolean;
VprPressionadoR,
VprEsconderParcela : Boolean;
VprContaCaixa : String;
VprDCliente : TRBDCliente;
VprDDespesaProjeto : TRBDContasaPagarProjeto;
VprTransacao : TTransactionDesc;
procedure CarDClasse;
function DadosValidos : string;
procedure InicializaTela;
procedure AlteraEstadoBotoes(VpaEstado : Boolean);
procedure InterpretaCodigoBarras;
procedure ConfiguraTela;
procedure AdicionaDespesaProjeto;
procedure CarTitulosGrade;
procedure CarDProjetoClasse;
procedure CarValoresGrade;
procedure CalculaValorDespesaPeloPercentual;
procedure CalculaPercentualDespesaPeloValor;
public
function NovoContasaPagar(VpaCodFornecedor : Integer) : Boolean;
end;
var
FNovoContasAPagar: TFNovoContasAPagar;
implementation
uses ConstMsg, FunData, APrincipal, funString,
ANovoCliente, funObjeto, funsql, AFormasPagamento, FunNumeros,
ADespesas, APlanoConta, UnClassesImprimir, ACentroCusto, AProjetos, dmRave, UnSistema,
ACondicaoPagamento, ANovaCondicaoPagamento, AContasAReceber;
{$R *.DFM}
{**************************Na criação do Formulário****************************}
procedure TFNovoContasAPagar.FormCreate(Sender: TObject);
begin
VprPressionadoR := false;
VprEsconderParcela := false;
VprDCliente := TRBDCliente.cria;
VprDContasAPagar := TRBDContasaPagar.cria;
VprAcao := false;
VprDatEmissao := date;
EDataEmissao.EditMask := FPrincipal.CorFoco.AMascaraData;
ConfiguraTela;
CarTitulosGrade;
end;
{**********************Quando o formulario e fechado***************************}
procedure TFNovoContasAPagar.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FPrincipal.BaseDados.InTransaction then
FPrincipal.BaseDados.Rollback(VprTransacao);
VprDContasAPagar.free;
VprDCliente.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações de Inicialização
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFNovoContasAPagar.CarDClasse;
begin
VprDContasAPagar.CodFilial := Varia.CodigoEmpFil;
VprDContasAPagar.NumNota := ENota.AsInteger;
VprDContasAPagar.SeqNota := 0;
VprDContasAPagar.CodFornecedor := EFornecedor.AInteiro;
VprDContasAPagar.CodBarras := ECodBarras.Text;
VprDContasAPagar.NomFornecedor := LNomFornecedor.Caption;
VprDContasAPagar.CodCentroCusto := ECentroCusto.AInteiro;
VprDContasAPagar.CodFormaPagamento := EdcFormaPgto.AInteiro;
VprDContasAPagar.CodMoeda := EMoeda.AInteiro;
VprDContasAPagar.CodUsuario := varia.CodigoUsuario;
VprDContasAPagar.DatEmissao := StrToDate(EDataEmissao.Text);
VprDContasAPagar.CodPlanoConta := EPlano.text;
VprDContasAPagar.NumContaCaixa := EContaCaixa.Text;
VprDContasAPagar.DesPathFoto := LFoto.Caption;
VprDContasAPagar.CodCondicaoPagamento := ECondicaoPagamento.AInteiro;
if EValorparcelas.AValor = 0 then
begin
VprDContasAPagar.ValParcela :=ArredondaDecimais(EValorTotal.AValor / sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro),2);
VprDContasAPagar.ValTotal := EValorTotal.AValor;
end
else
begin
VprDContasAPagar.ValParcela := EValorparcelas.AValor;
VprDContasAPagar.ValTotal := EValorparcelas.AValor * sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro);
end;
VprDContasAPagar.PerDescontoAcrescimo := 0;
VprDContasAPagar.IndMostrarParcelas := true;
VprDContasAPagar.IndEsconderConta := VprEsconderParcela;
VprDContasAPagar.IndBaixarConta := CBaixarConta.Checked;
VprDContasAPagar.IndDespesaPrevista := CDespesaPrevista.Checked;
VprContaCaixa := EContaCaixa.Text;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.CarDProjetoClasse;
begin
if VprDDespesaProjeto.PerDespesa <> StrToFloat(DeletaChars(DeletaChars(GProjetos.Cells[3,GProjetos.ALinha],'.'),'%')) then
begin
CalculaValorDespesaPeloPercentual;
end
else
if VprDDespesaProjeto.ValDespesa <> StrToFloat(DeletaChars(GProjetos.Cells[4,GProjetos.ALinha],'.')) then
begin
CalculaPercentualDespesaPeloValor;
end;
CarValoresGrade;
end;
{******************************************************************************}
function TFNovoContasAPagar.DadosValidos : string;
begin
result := '';
if EValorTotal.avalor = 0 then
EValorTotal.AValor := EValorParcelas.AValor * Sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro);
if EValorTotal.AValor = 0 then
begin
result := 'VALOR DO TÍTULO NÃO PREENCHIDO!!!'#13'É necessário informar um valor para o título.';
EValorTotal.SetFocus;
end;
if result = '' then
begin
if CBaixarConta.Checked and (EContaCaixa.Text = '') then
begin
Result := 'CONTA CAIXA NÃO PREENCHIDO!!!'#13'É necessário preencher a conta caixa na baixa automatica.';
end;
end;
if config.ControlarProjeto then
begin
if VprDContasAPagar.DespesaProjeto.Count > 0 then
result := FunContasAPagar.ValorProjetosMaiorQueContasaPagar(VprDContasAPagar,EValorTotal.avalor);
end;
end;
{*******************permite atualizar os campos relacionados*******************}
procedure TFNovoContasAPagar.InicializaTela;
begin
VprDContasAPagar.free;
VprDContasAPagar := TRBDContasaPagar.cria;
GProjetos.ADados := VprDContasAPagar.DespesaProjeto;
GProjetos.CarregaGrade;
VprDCliente.Free;
VprDCliente := TRBDCliente.cria;
PanelColor3.Enabled := true;
LimpaComponentes(PanelColor3,0);
LPlano.Caption := '';
EMoeda.Text := IntTostr(Varia.MoedaBase);
EMoeda.Atualiza;
ECentroCusto.AInteiro := varia.CentroCustoPadrao;
ECentroCusto.Atualiza;
EContaCaixa.Text := VprContaCaixa;
EContaCaixa.Atualiza;
EFilial.Text := IntTostr(Varia.CodigoEmpFil); // adiciona o codigo da filial
EDataEmissao.Text := dateTostr(VprDatEmissao); // valida campo data
AlteraEstadoBotoes(true);
ValidaGravacao.execute;
Paginas.ActivePage := PGeral;
ActiveControl := ECodBarras;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Chamadas para telas de Cadastros
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************Cadastro na Consulta do campo Fornecedores******************}
procedure TFNovoContasAPagar.EFornecedorCadastrar(Sender: TObject);
begin
FNovoCliente := TFNovoCliente.CriarSDI(application,'',true);
FNovoCliente.CadClientes.Insert;
FNovoCliente.CadClientesC_IND_FOR.AsString := 'S';
FNovoCliente.CadClientesC_IND_CLI.AsString := 'N';
FNovoCliente.ShowModal;
Localiza.AtualizaConsulta;
end;
{*****************Cadastra uma nova forma de Pagamento*************************}
procedure TFNovoContasAPagar.EdcFormaPgtoCadastrar(Sender: TObject);
begin
FFormasPagamento := TFFormasPagamento.CriarSDI(Application,'',FPrincipal.VerificaPermisao('FFormasPagamento'));
FFormasPagamento.BotaoCadastrar1.Click;
FFormasPagamento.ShowModal;
Localiza.AtualizaConsulta;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Validação dos campos relacionados
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*************************valida o numero da nota fiscal***********************}
procedure TFNovoContasAPagar.DBEditButton4Exit(Sender: TObject);
begin
aux.close;
if (ENota.Text <> '') and (Efornecedor.Text <> '' ) then // verifica se exixte o nro da not, forn, e filial ja cadastrado no CP.
begin
AdicionaSQLAbreTabela(aux, 'select I_NRO_NOT from CADCONTASAPAGAR '+
' where I_EMP_FIL = ' + IntToStr(varia.CodigoEmpFil) +
' and I_NRO_NOT = ' + ENota.Text +
' and I_COD_CLI = ' + EFornecedor.Text);
if not (aux.EOF) then
if confirmacao(' Já existe uma Nota Fiscal Cadastrada no Contas a Pagar com o Nº ' + ENota.Text + ' do Fornecedor "' +
LNomFornecedor.Caption + '". Deseja cancelar o cadastro ? ' ) then
BotaoCancelar1.Click
end;
aux.close;
end;
{((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Validação dos campos Gerais
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*****************caso o valor total > 0 zera o valor das parcelas*************}
procedure TFNovoContasAPagar.DBEditColor20Exit(Sender: TObject);
begin
if (EValorTotal.avalor > 0) then
EValorParcelas.AValor := 0;
end;
{******************caso o valor da parcela > 0 zera o valor total**************}
procedure TFNovoContasAPagar.EValorparcelasExit(Sender: TObject);
begin
if (EValorParcelas.AValor > 0) then
EValorTotal.AValor := 0;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Botoes de Atividade, novo, alterar, parcelas, etc
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{****Qunado fechar o formulario verifica o capa de lote e o CadContasaPagar****}
procedure TFNovoContasAPagar.BFecharClick(Sender: TObject);
begin
close;
end;
{***************************adiciona uma nova conta****************************}
procedure TFNovoContasAPagar.BNovoClick(Sender: TObject);
begin
InicializaTela;
if Self.Visible then
ECodBarras.SetFocus;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
function TFNovoContasAPagar.NovoContasaPagar(VpaCodFornecedor : Integer) : Boolean;
begin
InicializaTela;
EFornecedor.AInteiro := VpaCodFornecedor;
EFornecedor.Atualiza;
if VpaCodFornecedor <> 0 then
ActiveControl := ENota;
showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.PaginasChange(Sender: TObject);
begin
if Paginas.ActivePage = PaginaProjeto then
GProjetos.CarregaGrade;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.AlteraEstadoBotoes(VpaEstado : Boolean);
begin
BNovo.Enabled := not VpaEstado;
BFechar.Enabled := not VpaEstado;
BotaoCancelar1.Enabled := VpaEstado;
BotaoGravar1.Enabled := VpaEstado;
BAutorizacaoPagamento.Enabled := not VpaEstado;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.InterpretaCodigoBarras;
begin
if length(ECodBarras.Text)>=20 then
begin
FunContasAPagar.InterpretaCodigoBarras(VprDContasAPagar,ECodBarras.Text);
EValorTotal.AValor := VprDContasAPagar.ValBoleto;
EdcFormaPgto.AInteiro := VprDContasAPagar.CodFormaPagamento;
EdcFormaPgto.Atualiza;
EFornecedor.AInteiro := VprDContasAPagar.CodFornecedor;
EFornecedor.Atualiza;
end;
if EFornecedor.AInteiro = 0 then
ActiveControl := EFornecedor
else
ActiveControl := ENota;
end;
{ ***************** valida a gravacao dos registros *********************** }
procedure TFNovoContasAPagar.ConfiguraTela;
begin
PaginaProjeto.TabVisible := Config.ControlarProjeto;
PProjeto.Visible := Config.ControlarProjeto;
if not config.ControlarProjeto then
self.Height := self.Height -24 ;
end;
{ ***************** valida a gravacao dos registros *********************** }
procedure TFNovoContasAPagar.AdicionaDespesaProjeto;
var
VpfDDespesaProjeto : TRBDContasaPagarProjeto;
begin
if config.ControlarProjeto then
begin
if EProjeto.AInteiro = 0 then
begin
if VprDContasAPagar.DespesaProjeto.Count = 1 then
begin
if TRBDContasaPagarProjeto(VprDContasAPagar.DespesaProjeto.Items[0]).CodProjeto = VprDContasAPagar.CodProjeto then
FreeTObjectsList(VprDContasAPagar.DespesaProjeto);
end;
end
else
begin
FreeTObjectsList(VprDContasAPagar.DespesaProjeto);
VpfDDespesaProjeto := VprDContasAPagar.addDespesaProjeto;
VpfDDespesaProjeto.CodProjeto := EProjeto.AInteiro;
VpfDDespesaProjeto.NomProjeto := LNomProjeto.Caption;
VpfDDespesaProjeto.PerDespesa := 100;
if EValorparcelas.AValor <> 0 then
VpfDDespesaProjeto.ValDespesa := EValorparcelas.AValor * Sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro)
else
VpfDDespesaProjeto.ValDespesa := EValorTotal.AValor;
end;
VprDContasAPagar.CodProjeto := EProjeto.AInteiro;
end;
end;
{***************************************************************************}
procedure TFNovoContasAPagar.CarTitulosGrade;
begin
GProjetos.Cells[1,0] := 'Código';
GProjetos.Cells[2,0] := 'Projeto';
GProjetos.Cells[3,0] := 'Percentual';
GProjetos.Cells[4,0] := 'Valor';
end;
{******************************************************************************}
procedure TFNovoContasAPagar.CarValoresGrade;
begin
GProjetos.Cells[3,GProjetos.ALinha]:= FormatFloat('0.00 %',VprDDespesaProjeto.PerDespesa);
GProjetos.Cells[4,GProjetos.ALinha]:= FormatFloat('#,###,###,##0.00',VprDDespesaProjeto.ValDespesa);
end;
{******************************************************************************}
procedure TFNovoContasAPagar.CalculaPercentualDespesaPeloValor;
var
VpfValContasAPagar : Double;
begin
if EValorTotal.AValor <> 0 then
VpfValContasAPagar := EValorTotal.AValor
else
VpfValContasAPagar := EValorparcelas.AValor * Sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro);
if VpfValContasAPagar > 0 then
begin
VprDDespesaProjeto.ValDespesa := StrToFloat(DeletaChars(GProjetos.Cells[4,GProjetos.ALinha],'.'));
VprDDespesaProjeto.PerDespesa := (VprDDespesaProjeto.ValDespesa *100)/VpfValContasAPagar;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.CalculaValorDespesaPeloPercentual;
var
VpfValContasAPagar : Double;
begin
if EValorTotal.AValor <> 0 then
VpfValContasAPagar := EValorTotal.AValor
else
VpfValContasAPagar := EValorparcelas.AValor * Sistema.RQtdParcelasCondicaoPagamento(ECondicaoPagamento.AInteiro);
if VpfValContasAPagar > 0 then
begin
VprDDespesaProjeto.PerDespesa := StrToFloat(DeletaChars(DeletaChars(GProjetos.Cells[3,GProjetos.ALinha],'.'),'%'));
VprDDespesaProjeto.ValDespesa := VpfValContasAPagar * (VprDDespesaProjeto.PerDespesa / 100);
end;
end;
{ ***************** valida a gravacao dos registros *********************** }
procedure TFNovoContasAPagar.EFilialChange(Sender: TObject);
begin
if BotaoGravar1 <> nil then
begin
ValidaGravacao.execute;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EPlanoExit(Sender: TObject);
var
VpfCodigo : string;
begin
FPlanoConta := TFPlanoConta.criarSDI(Self, '', True);
VpfCodigo := EPlano.Text;
if not FPlanoConta.verificaCodigo(VpfCodigo, 'D', LPlano, False, (Sender is TSpeedButton)) then
EPlano.SetFocus;
EPlano.text := VpfCodigo;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EPlanoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 114 then
BPlano.Click;
end;
{************************************************************************************}
procedure TFNovoContasAPagar.EProjetoCadastrar(Sender: TObject);
begin
FProjetos := tFProjetos.CriarSDI(self,'',true);
FProjetos.BotaoCadastrar1.Click;
FProjetos.ShowModal;
FProjetos.free;
end;
{************************************************************************************}
procedure TFNovoContasAPagar.EProjetoFimConsulta(Sender: TObject);
begin
if EProjeto.AInteiro <> VprDContasAPagar.CodProjeto then
begin
AdicionaDespesaProjeto;
end;
end;
{************************************************************************************}
procedure TFNovoContasAPagar.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl,ssAlt]) then
begin
if (key = 82) then
VprPressionadoR := true
else
if VprPressionadoR then
if (key = 87) then
begin
if BotaoGravar1.Enabled then
begin
VprEsconderParcela := true;
BotaoGravar1.Click;
VprEsconderParcela := false;
VprPressionadoR := false;
end;
end
else
VprPressionadoR := false;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.GProjetosCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
begin
VprDDespesaProjeto := TRBDContasaPagarProjeto(VprDContasAPagar.DespesaProjeto.Items[VpaLinha-1]);
if VprDDespesaProjeto.CodProjeto <> 0 then
GProjetos.Cells[1,VpaLinha]:= InttoStr(VprDDespesaProjeto.CodProjeto)
else
GProjetos.Cells[1,VpaLinha]:= '';
GProjetos.Cells[2,VpaLinha]:= VprDDespesaProjeto.NomProjeto;
CarValoresGrade;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.GProjetosDadosValidos(Sender: TObject; var VpaValidos: Boolean);
begin
VpaValidos := true;
if not EConsultaProjeto.AExisteCodigo(GProjetos.Cells[1,GProjetos.ALinha]) then
begin
VpaValidos := false;
aviso('PROJETO NÃO CADASTRADO!!!'#13'O projeto digitado não existe cadastrado.');
GProjetos.Col := 1;
end
else
if (DeletaChars(DeletaChars(DeletaChars(GProjetos.Cells[3,GProjetos.ALinha],'%'),'0'),' ') = '') then
begin
VpaValidos := false;
aviso('PERCENTUAL NÃO PREENCHIDO!!!'#13'É necessário digitar o percentual da despesa no projeto.');
GProjetos.Col := 3;
end
else
if (DeletaChars(DeletaChars(GProjetos.Cells[4,GProjetos.ALinha],'0'),' ') = '') then
begin
VpaValidos := false;
aviso('VALOR NÃO PREENCHIDO!!!'#13'É necessário digitar o valor da despesa no projeto.');
GProjetos.Col := 4;
end;
if VpaValidos then
begin
CarDProjetoClasse;
if VprDDespesaProjeto.PerDespesa = 0 then
begin
VpaValidos := false;
aviso('PERCENTUAL NÃO PREENCHIDO!!!'#13'É necessário digitar o percentual da despesa no projeto.');
GProjetos.Col := 3;
end
else
if VprDDespesaProjeto.ValDespesa = 0 then
begin
VpaValidos := false;
aviso('VALOR NÃO PREENCHIDO!!!'#13'É necessário digitar o valor da despesa no projeto.');
GProjetos.Col := 4;
end;
end;
if Vpavalidos then
begin
if FunContasAPagar.ProjetoDuplicado(VprDContasAPagar) then
begin
vpaValidos := false;
aviso('PROJETO DUPLICADO!!!'#13'Esse projeto já foi digitado.');
GProjetos.Col := 1;
end;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.GProjetosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case key of
114 :
begin
case GProjetos.AColuna of
1: EConsultaProjeto.AAbreLocalizacao;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.GProjetosKeyPress(Sender: TObject; var Key: Char);
begin
if (key = '.') and not(GProjetos.col in [3,4]) then
key := DecimalSeparator;
end;
procedure TFNovoContasAPagar.GProjetosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer);
begin
if VprDContasAPagar.DespesaProjeto.Count >0 then
VprDDespesaProjeto := TRBDContasaPagarProjeto(VprDContasAPagar.DespesaProjeto.Items[VpaLinhaAtual-1]);
end;
procedure TFNovoContasAPagar.GProjetosNovaLinha(Sender: TObject);
begin
VprDDespesaProjeto := VprDContasAPagar.addDespesaProjeto;
VprDDespesaProjeto.PerDespesa := FunContasAPagar.RPercentualProjetoFaltante(VprDContasAPagar);
CarValoresGrade;
CalculaValorDespesaPeloPercentual;
CarValoresGrade;
end;
procedure TFNovoContasAPagar.GProjetosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
if GProjetos.AEstadoGrade in [egInsercao,EgEdicao] then
begin
if GProjetos.AColuna <> ACol then
begin
case GProjetos.AColuna of
1 :if not EConsultaProjeto.AExisteCodigo(GProjetos.Cells[1,GProjetos.ALinha]) then
begin
if not EConsultaProjeto.AAbreLocalizacao then
begin
GProjetos.Cells[1,GProjetos.ALinha] := '';
abort;
end;
end;
3 : if VprDDespesaProjeto.PerDespesa <> StrToFloat(DeletaChars(DeletaChars(GProjetos.Cells[3,GProjetos.ALinha],'.'),'%')) then
begin
CalculaValorDespesaPeloPercentual;
CarValoresGrade;
end;
4 : if VprDDespesaProjeto.ValDespesa <> StrToFloat(DeletaChars(GProjetos.Cells[4,GProjetos.ALinha],'.')) then
begin
CalculaPercentualDespesaPeloValor;
CarValoresGrade;
end;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.BotaoGravar1Click(Sender: TObject);
var
vpfResultado : String;
begin
vpfResultado := DadosValidos;
Tempo.execute('Criando as Parcelas...');
if vpfResultado = '' then
begin
CarDClasse;
if not FPrincipal.BaseDados.InTransaction then
begin
// VprTransacao.IsolationLevel := xilREADCOMMITTED;
// FPrincipal.Basedados.StartTransaction(VprTransacao);
end;
vpfResultado := FunContasAPagar.CriaContaPagar(VprDContasAPagar,VprDCliente);
if vpfResultado = '' then
begin
ELanPagar.AInteiro := VprDContasAPagar.LanPagar;
EValorTotal.AValor := VprDContasAPagar.ValTotal;
end;
end;
Tempo.Fecha;
if vpfResultado = '' then
begin
if FPrincipal.BaseDados.InTransaction then
FPrincipal.BaseDados.Commit(VprTransacao);
AlteraEstadoBotoes(false);
VprAcao := true;
end
else
begin
if FPrincipal.BaseDados.InTransaction then
FPrincipal.BaseDados.Rollback(VprTransacao);
aviso(vpfResultado);
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.BotaoCancelar1Click(Sender: TObject);
begin
if confirmacao('Tem certeza que deseja cancelar a digitação do Contas a Pagar?') then
begin
AlteraEstadoBotoes(false);
PanelColor3.Enabled := false;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EFornecedorAlterar(Sender: TObject);
begin
if EFornecedor.ALocaliza.Loca.Tabela.FieldByName(EFornecedor.AInfo.CampoCodigo).AsInteger <> 0 then
begin
FNovoCliente := TFNovoCliente.CriarSDI(application,'', FPrincipal.VerificaPermisao('FNovoCliente'));
AdicionaSQlAbreTabela(FNovoCliente.CadClientes,'Select * from CadClientes '+
' Where I_COD_CLI = '+EFornecedor.ALocaliza.Loca.Tabela.FieldByName(EFornecedor.AInfo.CampoCodigo).asString);
FNovoCliente.CadClientes.Edit;
FNovoCliente.ShowModal;
FNovoCliente.Free;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.ECentroCustoCadastrar(Sender: TObject);
begin
FCentroCusto := TFCentroCusto.CriarSDI(self,'',FPrincipal.VerificaPermisao('FCentroCusto'));
FCentroCusto.BotaoCadastrar1.Click;
FCentroCusto.Showmodal;
FCentroCusto.free;
Localiza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.BFotoClick(Sender: TObject);
begin
if Imagem.execute(varia.DriveFoto) then
LFoto.Caption := Imagem.PathImagem;
end;
procedure TFNovoContasAPagar.BitBtn1Click(Sender: TObject);
begin
FContasaReceber := TFContasaReceber.criarSDI(Application,'',FPrincipal.VerificaPermisao('FContasaReceber'));
FContasaReceber.showmodal;
FContasaReceber.free;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.BAutorizacaoPagamentoClick(Sender: TObject);
begin
dtRave := TdtRave.Create(self);
dtRave.ImprimeAutorizacaoPagamento(VprDContasAPagar.CodFilial,VprDContasAPagar.LanPagar,0,Date,date);
dtRave.free;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EdcFormaPgtoRetorno(Retorno1,
Retorno2: String);
begin
CBaixarConta.Enabled := Retorno2 = 'S';
if not CBaixarConta.Enabled then
CBaixarConta.Checked := false;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.CBaixarContaClick(Sender: TObject);
begin
EContaCaixa.ACampoObrigatorio := CBaixarConta.Checked;
ValidaGravacao.execute;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.ECodBarrasKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = 13 then
InterpretaCodigoBarras;
end;
{***************************************************************************** }
procedure TFNovoContasAPagar.ECondicaoPagamentoCadastrar(Sender: TObject);
begin
FNovaCondicaoPagamento := TFNovaCondicaoPagamento.CriarSDI(self,'',true);
FNovaCondicaoPagamento.NovaCondicaoPagamento;
FNovaCondicaoPagamento.free;
end;
{***************************************************************************** }
procedure TFNovoContasAPagar.EConsultaProjetoRetorno(VpaColunas: TRBColunasLocaliza);
begin
if VpaColunas.items[0].AValorRetorno <> '' then
begin
VprDDespesaProjeto.CodProjeto := StrToINt(VpaColunas.items[0].AValorRetorno);
VprDDespesaProjeto.NomProjeto := VpaColunas.items[1].AValorRetorno;
GProjetos.Cells[1,GProjetos.ALinha] := VpaColunas.items[0].AValorRetorno;
GProjetos.Cells[2,GProjetos.ALinha] := VpaColunas.items[1].AValorRetorno;
end
else
begin
VprDDespesaProjeto.CodProjeto := 0;
VprDDespesaProjeto.NomProjeto := '';
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EFornecedorRetorno(Retorno1,
Retorno2: String);
begin
if EFornecedor.AInteiro <> 0 then
begin
if EFornecedor.AInteiro <> VprDCliente.CodCliente then
begin
VprDCliente.CodCliente := EFornecedor.AInteiro;
FunClientes.CarDCliente(VprDCliente,true);
IF VprDCliente.CodPlanoContas <> '' then
begin
EPlano.Text := VprDCliente.CodPlanoContas;
EPlanoExit(EPlano);
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoContasAPagar.EDataEmissaoExit(Sender: TObject);
begin
VprDatEmissao := StrToDate(EDataEmissao.Text);
end;
Initialization
RegisterClasses([TFNovoContasAPagar]);
end.
|
unit WizardPrenoController;
interface
uses
BaseController,
System.SysUtils, System.Classes,
Generics.Collections,
Data.DB,
RemoteDB.Client.Dataset,
gmClientDataset;
type
TDMWizardPrenoController = class(TdmBaseController)
qBranche: TgmClientDataset;
qBrancheDESCRIZIONE: TStringField;
qBrancheDATA_FINE: TDateTimeField;
qBrancheNOTA: TStringField;
qBranchePKBRANCHE: TStringField;
qBrancheDATA_INIZIO: TDateTimeField;
qCodiciRad: TgmClientDataset;
qCodiciRadPKCODICIRAD: TIntegerField;
qCodiciRadCODICE: TStringField;
qCodiciRadLAST_MOD: TDateTimeField;
qCodiciRadIDENT_FK: TStringField;
qCodiciRadDATA_INIZIO: TDateTimeField;
qCodiciRadDATA_FINE: TDateTimeField;
qCodiciRadUSER_ID: TIntegerField;
qCodiciRadDOSE: TFloatField;
qCodiciRadCOMPOSTO: TIntegerField;
qCodiciRadBRANCA: TStringField;
qCodiciRadDESCRIZIONE: TStringField;
qCodiciRadGRSPEC_FK: TIntegerField;
qCodiciRadPESO_TECNICO: TFloatField;
qCodiciRadPESO_MEDICO: TFloatField;
qCodiciRadDESCBRANCA: TStringField;
qFarmacie: TgmClientDataset;
qFarmaciePKREPARTI: TIntegerField;
qFarmacieDESCRIZIONE: TStringField;
gmClientDataset1: TgmClientDataset;
gmClientDataset1PKAMBULATORI: TIntegerField;
gmClientDataset1REPARTI_FK: TIntegerField;
gmClientDataset1DESCRIZIONE: TStringField;
gmClientDataset1DATA_FINE: TDateTimeField;
gmClientDataset1DATA_INIZIO: TDateTimeField;
procedure gmClientDataset1NewRecord(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure GetCodiciRadByBranca(pBranca: Variant);
procedure GetCodiciRadByDesc(const cerca: string); overload;
procedure GetCodiciRadByDesc(const cerca: string; pBranca: Variant); overload;
procedure GetAllBranche;
{
function GetAllCodiciRad: TList<TCODICIRAD>;
}
procedure GetAllFarmacie;
end;
implementation
uses
DMCommon;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
constructor TDMWizardPrenoController.Create;
begin
inherited;
end;
destructor TDMWizardPrenoController.Destroy;
begin
inherited;
end;
(*
function TDMWizardPrenoController.GetAllCodiciRad: TList<TCODICIRAD>;
begin
qCodiciRad.Close;
// Result := FManager.FindAll<TCODICIRAD>;
Result := FManager.Find<TCODICIRAD>
.Add( TLinq.Eq('PKCODICIRAD',-1) )
.List;
qCodiciRad.SetSourceList(Result);
qCodiciRad.Open;
end;
*)
procedure TDMWizardPrenoController.GetCodiciRadByDesc(const cerca: string);
begin
if qCodiciRad.Active then
qCodiciRad.Close;
{
qCodiciRad.SetSourceList(
FManager.Find<TCODICIRAD>
.Add( TLinq.Like('DESCRIZIONE', cerca) )
.List);
}
qCodiciRad.Open;
end;
procedure TDMWizardPrenoController.GetCodiciRadByDesc(const cerca: string; pBranca: Variant);
begin
if qCodiciRad.Active then
qCodiciRad.Close;
{
qCodiciRad.SetSourceList(
FManager.Find<TCODICIRAD>
.Add( TLinq.Like('DESCRIZIONE', cerca) and TLinq.Eq('BRANCA', pBranca))
.List);
}
qCodiciRad.Open;
end;
procedure TDMWizardPrenoController.gmClientDataset1NewRecord(DataSet: TDataSet);
begin
inherited;
gmClientDataset1REPARTI_FK.AsInteger := 141;
end;
procedure TDMWizardPrenoController.GetCodiciRadByBranca(pBranca: Variant);
begin
if qCodiciRad.Active then
qCodiciRad.Close;
{
qCodiciRad.SetSourceList(
FManager.Find<TCODICIRAD>
.Add( TLinq.Eq('BRANCA', pBranca))
.List);
}
qCodiciRad.Open;
end;
procedure TDMWizardPrenoController.GetAllBranche;
begin
qBranche.Close;
qBranche.Open;
end;
procedure TDMWizardPrenoController.GetAllFarmacie;
begin
qFarmacie.Close;
qFarmacie.ParamByName('data').AsDateTime := Date();
qFarmacie.Open;
gmClientDataset1.Open;
end;
end.
|
unit copy_str_7;
interface
implementation
var S1, S2: string;
procedure Test;
var
i, c: Int32;
begin
i := 7;
c := 2;
S2 := copy(S1, i, c - i);
end;
initialization
S1 := 'ABCD';
Test();
finalization
Assert(S2 = '');
end. |
unit HeaderFooterFormwithNavigation;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Graphics, FMX.Forms, FMX.Dialogs, FMX.TabControl, System.Actions, FMX.ActnList,
FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.SearchBox,
FMX.ListBox, FMX.Layouts ,
OleDB, ComObj, ActiveX;
type
THeaderFooterwithNavigation = class(TForm)
ActionList1: TActionList;
PreviousTabAction1: TPreviousTabAction;
TitleAction: TControlAction;
NextTabAction1: TNextTabAction;
TopToolBar: TToolBar;
btnBack: TSpeedButton;
ToolBarLabel: TLabel;
btnNext: TSpeedButton;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
BottomToolBar: TToolBar;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxHeader2: TListBoxHeader;
SearchBox1: TSearchBox;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxItem11: TListBoxItem;
ListBoxItem12: TListBoxItem;
ListBoxItem13: TListBoxItem;
ListBoxItem14: TListBoxItem;
ListBoxItem15: TListBoxItem;
ListBoxItem16: TListBoxItem;
ListBoxItem17: TListBoxItem;
ListBoxItem18: TListBoxItem;
ListBoxItem19: TListBoxItem;
ListBoxItem20: TListBoxItem;
ListBoxItem21: TListBoxItem;
ListBoxItem22: TListBoxItem;
ListBoxItem23: TListBoxItem;
ListBoxItem24: TListBoxItem;
ListBoxItem25: TListBoxItem;
ListBoxItem26: TListBoxItem;
ListBoxItem27: TListBoxItem;
ListBoxItem28: TListBoxItem;
ListBoxItem29: TListBoxItem;
ListBoxItem30: TListBoxItem;
ListBoxItem31: TListBoxItem;
ListBoxItem32: TListBoxItem;
ListBoxItem33: TListBoxItem;
ListBoxItem34: TListBoxItem;
ListBoxItem35: TListBoxItem;
ListBoxItem36: TListBoxItem;
ListBoxItem37: TListBoxItem;
ListBoxItem38: TListBoxItem;
ListBoxItem39: TListBoxItem;
ListBoxItem40: TListBoxItem;
procedure FormCreate(Sender: TObject);
procedure TitleActionUpdate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HeaderFooterwithNavigation: THeaderFooterwithNavigation;
implementation
{$R *.fmx}
{$R *.iPhone4in.fmx IOS}
procedure THeaderFooterwithNavigation.TitleActionUpdate(Sender: TObject);
begin
if Sender is TCustomAction then
begin
if TabControl1.ActiveTab <> nil then
TCustomAction(Sender).Text := TabControl1.ActiveTab.Text
else
TCustomAction(Sender).Text := '';
end;
end;
procedure THeaderFooterwithNavigation.FormCreate(Sender: TObject);
{I see always people manually building the connection string.
Wy not use the dialog that windows provide for us ? Of course
it is possible to use the PromptDataSource in ADODB, but this
give not the opportunity to see if the user has pressed OK or
Cancel, so we dont know when to save the changes. So I use this
code instead. I hope it benefit many people. Rgds, Wilfried}
function ADOConnectionString(ParentHandle: THandle; InitialString: WideString;
out NewString: string): Boolean;
var
DataInit: IDataInitialize;
DBPrompt: IDBPromptInitialize;
DataSource: IUnknown;
InitStr: PWideChar;
begin
Result := False;
DataInit := CreateComObject(CLSID_DataLinks) as IDataInitialize;
if InitialString <> '' then
DataInit.GetDataSource(nil, CLSCTX_INPROC_SERVER, PWideChar(InitialString),
IUnknown, DataSource);
DBPrompt := CreateComObject(CLSID_DataLinks) as IDBPromptInitialize;
if Succeeded(DBPrompt.PromptDataSource(nil, ParentHandle,
DBPROMPTOPTIONS_PROPERTYSHEET, 0, nil, nil, IUnknown, DataSource)) then
begin
InitStr := nil;
DataInit.GetInitializationString(DataSource, True, InitStr);
NewString := InitStr;
Result := True;
end;
end;
var
sString: string;
begin
{ This defines the default active tab at runtime }
TabControl1.First(TTabTransition.None);
ADOConnectionString(0, '', sString);
ShowMessage(sString);
end;
procedure THeaderFooterwithNavigation.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if (Key = vkHardwareBack) and (TabControl1.TabIndex <> 0) then
begin
TabControl1.First;
Key := 0;
end;
end;
end.
|
(*************************************************************************
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from C to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
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 (www.fsf.org); 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.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit normaldistr;
interface
uses Math, Sysutils, Ap;
function Erf(X : AlglibFloat):AlglibFloat;
function ErfC(X : AlglibFloat):AlglibFloat;
function NormalDistribution(X : AlglibFloat):AlglibFloat;
function InvErf(E : AlglibFloat):AlglibFloat;
function InvNormalDistribution(y0 : AlglibFloat):AlglibFloat;
implementation
(*************************************************************************
Error function
The integral is
x
-
2 | | 2
erf(x) = -------- | exp( - t ) dt.
sqrt(pi) | |
-
0
For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise
erf(x) = 1 - erfc(x).
ACCURACY:
Relative error:
arithmetic domain # trials peak rms
IEEE 0,1 30000 3.7e-16 1.0e-16
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
*************************************************************************)
function Erf(X : AlglibFloat):AlglibFloat;
var
XSq : AlglibFloat;
S : AlglibFloat;
P : AlglibFloat;
Q : AlglibFloat;
begin
S := Sign(X);
X := AbsReal(X);
if AP_FP_Less(X,0.5) then
begin
XSq := X*X;
P := 0.007547728033418631287834;
P := 0.288805137207594084924010+XSq*P;
P := 14.3383842191748205576712+XSq*P;
P := 38.0140318123903008244444+XSq*P;
P := 3017.82788536507577809226+XSq*P;
P := 7404.07142710151470082064+XSq*P;
P := 80437.3630960840172832162+XSq*P;
Q := 0.0;
Q := 1.00000000000000000000000+XSq*Q;
Q := 38.0190713951939403753468+XSq*Q;
Q := 658.070155459240506326937+XSq*Q;
Q := 6379.60017324428279487120+XSq*Q;
Q := 34216.5257924628539769006+XSq*Q;
Q := 80437.3630960840172826266+XSq*Q;
Result := S*1.1283791670955125738961589031*X*P/Q;
Exit;
end;
if AP_FP_Greater_Eq(X,10) then
begin
Result := S;
Exit;
end;
Result := S*(1-ErfC(X));
end;
(*************************************************************************
Complementary error function
1 - erf(x) =
inf.
-
2 | | 2
erfc(x) = -------- | exp( - t ) dt
sqrt(pi) | |
-
x
For small x, erfc(x) = 1 - erf(x); otherwise rational
approximations are computed.
ACCURACY:
Relative error:
arithmetic domain # trials peak rms
IEEE 0,26.6417 30000 5.7e-14 1.5e-14
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
*************************************************************************)
function ErfC(X : AlglibFloat):AlglibFloat;
var
P : AlglibFloat;
Q : AlglibFloat;
begin
if AP_FP_Less(X,0) then
begin
Result := 2-ErfC(-X);
Exit;
end;
if AP_FP_Less(X,0.5) then
begin
Result := 1.0-Erf(X);
Exit;
end;
if AP_FP_Greater_Eq(X,10) then
begin
Result := 0;
Exit;
end;
P := 0.0;
P := 0.5641877825507397413087057563+X*P;
P := 9.675807882987265400604202961+X*P;
P := 77.08161730368428609781633646+X*P;
P := 368.5196154710010637133875746+X*P;
P := 1143.262070703886173606073338+X*P;
P := 2320.439590251635247384768711+X*P;
P := 2898.0293292167655611275846+X*P;
P := 1826.3348842295112592168999+X*P;
Q := 1.0;
Q := 17.14980943627607849376131193+X*Q;
Q := 137.1255960500622202878443578+X*Q;
Q := 661.7361207107653469211984771+X*Q;
Q := 2094.384367789539593790281779+X*Q;
Q := 4429.612803883682726711528526+X*Q;
Q := 6089.5424232724435504633068+X*Q;
Q := 4958.82756472114071495438422+X*Q;
Q := 1826.3348842295112595576438+X*Q;
Result := Exp(-AP_Sqr(X))*P/Q;
end;
(*************************************************************************
Normal distribution function
Returns the area under the Gaussian probability density
function, integrated from minus infinity to x:
x
-
1 | | 2
ndtr(x) = --------- | exp( - t /2 ) dt
sqrt(2pi) | |
-
-inf.
= ( 1 + erf(z) ) / 2
= erfc(z) / 2
where z = x/sqrt(2). Computation is via the functions
erf and erfc.
ACCURACY:
Relative error:
arithmetic domain # trials peak rms
IEEE -13,0 30000 3.4e-14 6.7e-15
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
*************************************************************************)
function NormalDistribution(X : AlglibFloat):AlglibFloat;
begin
Result := 0.5*(Erf(x/1.41421356237309504880)+1);
end;
(*************************************************************************
Inverse of the error function
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
*************************************************************************)
function InvErf(E : AlglibFloat):AlglibFloat;
begin
Result := InvNormalDistribution(0.5*(E+1))/Sqrt(2);
end;
(*************************************************************************
Inverse of Normal distribution function
Returns the argument, x, for which the area under the
Gaussian probability density function (integrated from
minus infinity to x) is equal to y.
For small arguments 0 < y < exp(-2), the program computes
z = sqrt( -2.0 * log(y) ); then the approximation is
x = z - log(z)/z - (1/z) P(1/z) / Q(1/z).
There are two rational functions P/Q, one for 0 < y < exp(-32)
and the other for y up to exp(-2). For larger arguments,
w = y - 0.5, and x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2)).
ACCURACY:
Relative error:
arithmetic domain # trials peak rms
IEEE 0.125, 1 20000 7.2e-16 1.3e-16
IEEE 3e-308, 0.135 50000 4.6e-16 9.8e-17
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1988, 1992, 2000 by Stephen L. Moshier
*************************************************************************)
function InvNormalDistribution(y0 : AlglibFloat):AlglibFloat;
var
Expm2 : AlglibFloat;
S2Pi : AlglibFloat;
x : AlglibFloat;
y : AlglibFloat;
z : AlglibFloat;
y2 : AlglibFloat;
x0 : AlglibFloat;
x1 : AlglibFloat;
code : AlglibInteger;
P0 : AlglibFloat;
Q0 : AlglibFloat;
P1 : AlglibFloat;
Q1 : AlglibFloat;
P2 : AlglibFloat;
Q2 : AlglibFloat;
begin
Expm2 := 0.13533528323661269189;
s2pi := 2.50662827463100050242;
if AP_FP_Less_Eq(y0,0) then
begin
Result := -MaxRealNumber;
Exit;
end;
if AP_FP_Greater_Eq(y0,1) then
begin
Result := MaxRealNumber;
Exit;
end;
code := 1;
y := y0;
if AP_FP_Greater(y,1.0-Expm2) then
begin
y := 1.0-y;
code := 0;
end;
if AP_FP_Greater(y,Expm2) then
begin
y := y-0.5;
y2 := y*y;
P0 := -59.9633501014107895267;
P0 := 98.0010754185999661536+y2*P0;
P0 := -56.6762857469070293439+y2*P0;
P0 := 13.9312609387279679503+y2*P0;
P0 := -1.23916583867381258016+y2*P0;
Q0 := 1;
Q0 := 1.95448858338141759834+y2*Q0;
Q0 := 4.67627912898881538453+y2*Q0;
Q0 := 86.3602421390890590575+y2*Q0;
Q0 := -225.462687854119370527+y2*Q0;
Q0 := 200.260212380060660359+y2*Q0;
Q0 := -82.0372256168333339912+y2*Q0;
Q0 := 15.9056225126211695515+y2*Q0;
Q0 := -1.18331621121330003142+y2*Q0;
x := y+y*y2*P0/Q0;
x := x*s2pi;
Result := X;
Exit;
end;
x := Sqrt(-2.0*Ln(y));
x0 := x-Ln(x)/x;
z := 1.0/x;
if AP_FP_Less(x,8.0) then
begin
P1 := 4.05544892305962419923;
P1 := 31.5251094599893866154+z*P1;
P1 := 57.1628192246421288162+z*P1;
P1 := 44.0805073893200834700+z*P1;
P1 := 14.6849561928858024014+z*P1;
P1 := 2.18663306850790267539+z*P1;
P1 := -1.40256079171354495875*0.1+z*P1;
P1 := -3.50424626827848203418*0.01+z*P1;
P1 := -8.57456785154685413611*0.0001+z*P1;
Q1 := 1;
Q1 := 15.7799883256466749731+z*Q1;
Q1 := 45.3907635128879210584+z*Q1;
Q1 := 41.3172038254672030440+z*Q1;
Q1 := 15.0425385692907503408+z*Q1;
Q1 := 2.50464946208309415979+z*Q1;
Q1 := -1.42182922854787788574*0.1+z*Q1;
Q1 := -3.80806407691578277194*0.01+z*Q1;
Q1 := -9.33259480895457427372*0.0001+z*Q1;
x1 := z*P1/Q1;
end
else
begin
P2 := 3.23774891776946035970;
P2 := 6.91522889068984211695+z*P2;
P2 := 3.93881025292474443415+z*P2;
P2 := 1.33303460815807542389+z*P2;
P2 := 2.01485389549179081538*0.1+z*P2;
P2 := 1.23716634817820021358*0.01+z*P2;
P2 := 3.01581553508235416007*0.0001+z*P2;
P2 := 2.65806974686737550832*0.000001+z*P2;
P2 := 6.23974539184983293730*0.000000001+z*P2;
Q2 := 1;
Q2 := 6.02427039364742014255+z*Q2;
Q2 := 3.67983563856160859403+z*Q2;
Q2 := 1.37702099489081330271+z*Q2;
Q2 := 2.16236993594496635890*0.1+z*Q2;
Q2 := 1.34204006088543189037*0.01+z*Q2;
Q2 := 3.28014464682127739104*0.0001+z*Q2;
Q2 := 2.89247864745380683936*0.000001+z*Q2;
Q2 := 6.79019408009981274425*0.000000001+z*Q2;
x1 := z*P2/Q2;
end;
x := x0-x1;
if code<>0 then
begin
x := -x;
end;
Result := x;
end;
end. |
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is BinaryTree.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclBinaryTrees;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Classes,
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclAlgorithms, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclBinaryTrees.imp}
{$I containers\JclBinaryTrees.int}
type
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclIntfBinaryNode,TJclIntfBinaryTree,TJclIntfAbstractContainer,IJclIntfCollection,IJclIntfTree,IJclIntfIterator,IJclIntfTreeIterator, IJclIntfEqualityComparer\, IJclIntfComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TIntfCompare,,const ,AInterface,IInterface)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclAnsiStrBinaryNode,TJclAnsiStrBinaryTree,TJclAnsiStrAbstractCollection,IJclAnsiStrCollection,IJclAnsiStrTree,IJclAnsiStrIterator,IJclAnsiStrTreeIterator, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrFlatContainer\, IJclAnsiStrEqualityComparer\, IJclAnsiStrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TAnsiStrCompare, override;,const ,AString,AnsiString)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclWideStrBinaryNode,TJclWideStrBinaryTree,TJclWideStrAbstractCollection,IJclWideStrCollection,IJclWideStrTree,IJclWideStrIterator,IJclWideStrTreeIterator, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrFlatContainer\, IJclWideStrEqualityComparer\, IJclWideStrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TWideStrCompare, override;,const ,AString,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrBinaryTree = TJclAnsiStrBinaryTree;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrBinaryTree = TJclWideStrBinaryTree;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclSingleBinaryNode,TJclSingleBinaryTree,TJclSingleAbstractContainer,IJclSingleCollection,IJclSingleTree,IJclSingleIterator,IJclSingleTreeIterator, IJclSingleContainer\, IJclSingleEqualityComparer\, IJclSingleComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TSingleCompare,,const ,AValue,Single)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclDoubleBinaryNode,TJclDoubleBinaryTree,TJclDoubleAbstractContainer,IJclDoubleCollection,IJclDoubleTree,IJclDoubleIterator,IJclDoubleTreeIterator, IJclDoubleContainer\, IJclDoubleEqualityComparer\, IJclDoubleComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TDoubleCompare,,const ,AValue,Double)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclExtendedBinaryNode,TJclExtendedBinaryTree,TJclExtendedAbstractContainer,IJclExtendedCollection,IJclExtendedTree,IJclExtendedIterator,IJclExtendedTreeIterator, IJclExtendedContainer\, IJclExtendedEqualityComparer\, IJclExtendedComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TExtendedCompare,,const ,AValue,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatBinaryTree = TJclExtendedBinaryTree;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatBinaryTree = TJclDoubleBinaryTree;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatBinaryTree = TJclSingleBinaryTree;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclIntegerBinaryNode,TJclIntegerBinaryTree,TJclIntegerAbstractContainer,IJclIntegerCollection,IJclIntegerTree,IJclIntegerIterator,IJclIntegerTreeIterator, IJclIntegerEqualityComparer\, IJclIntegerComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TIntegerCompare,,,AValue,Integer)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclCardinalBinaryNode,TJclCardinalBinaryTree,TJclCardinalAbstractContainer,IJclCardinalCollection,IJclCardinalTree,IJclCardinalIterator,IJclCardinalTreeIterator, IJclCardinalEqualityComparer\, IJclCardinalComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TCardinalCompare,,,AValue,Cardinal)*)
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclInt64BinaryNode,TJclInt64BinaryTree,TJclInt64AbstractContainer,IJclInt64Collection,IJclInt64Tree,IJclInt64Iterator,IJclInt64TreeIterator, IJclInt64EqualityComparer\, IJclInt64Comparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TInt64Compare,,const ,AValue,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclPtrBinaryNode,TJclPtrBinaryTree,TJclPtrAbstractContainer,IJclPtrCollection,IJclPtrTree,IJclPtrIterator,IJclPtrTreeIterator, IJclPtrEqualityComparer\, IJclPtrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TPtrCompare,,,APtr,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclBinaryNode,TJclBinaryTree,TJclAbstractContainer,IJclCollection,IJclTree,IJclIterator,IJclTreeIterator, IJclObjectOwner\, IJclEqualityComparer\, IJclComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,ACompare: TCompare; AOwnsObjects: Boolean,,,AObject,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLBINARYTREEINT(TJclBinaryNode<T>,TJclBinaryTree<T>,TJclAbstractContainer<T>,IJclCollection<T>,IJclTree<T>,IJclIterator<T>,IJclTreeIterator<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\, IJclComparer<T>\,,,,,AOwnsItems: Boolean,,const ,AItem,T)*)
// E = External helper to compare items
TJclBinaryTreeE<T> = class(TJclBinaryTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclTree<T>)
private
FComparer: IComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclComparer<T> }
function ItemsCompare(const A, B: T): Integer; override;
{ IJclEqualityComparer<T> }
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AComparer: IComparer<T>; AOwnsItems: Boolean);
property Comparer: IComparer<T> read FComparer write FComparer;
end;
// F = Function to compare items
TJclBinaryTreeF<T> = class(TJclBinaryTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclTree<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(ACompare: TCompare<T>; AOwnsItems: Boolean);
end;
// I = Items can compare themselves to an other
TJclBinaryTreeI<T: IComparable<T>> = class(TJclBinaryTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclTree<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclComparer<T> }
function ItemsCompare(const A, B: T): Integer; override;
{ IJclEqualityComparer<T> }
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclBinaryTrees.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils;
type
TItrStart = (isFirst, isLast, isRoot);
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TIntfItr,TPreOrderIntfItr,TInOrderIntfItr,TPostOrderIntfItr,IJclIntfIterator,IJclIntfTreeIterator,IJclIntfBinaryTreeIterator,IJclIntfCollection,IJclIntfEqualityComparer,TJclIntfBinaryNode,const ,AInterface,IInterface,GetObject,SetObject)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TIntfItr,TPreOrderIntfItr,TInOrderIntfItr,TPostOrderIntfItr,IJclIntfIterator,IJclIntfCollection,IJclIntfEqualityComparer,TJclIntfBinaryNode,const ,AInterface,IInterface,nil,GetObject,SetObject,FreeObject)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TAnsiStrItr,TPreOrderAnsiStrItr,TInOrderAnsiStrItr,TPostOrderAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrTreeIterator,IJclAnsiStrBinaryTreeIterator,IJclAnsiStrCollection,IJclAnsiStrEqualityComparer,TJclAnsiStrBinaryNode,const ,AString,AnsiString,GetString,SetString)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TAnsiStrItr,TPreOrderAnsiStrItr,TInOrderAnsiStrItr,TPostOrderAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrCollection,IJclAnsiStrEqualityComparer,TJclAnsiStrBinaryNode,const ,AString,AnsiString,'',GetString,SetString,FreeString)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TWideStrItr,TPreOrderWideStrItr,TInOrderWideStrItr,TPostOrderWideStrItr,IJclWideStrIterator,IJclWideStrTreeIterator,IJclWideStrBinaryTreeIterator,IJclWideStrCollection,IJclWideStrEqualityComparer,TJclWideStrBinaryNode,const ,AString,WideString,GetString,SetString)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TWideStrItr,TPreOrderWideStrItr,TInOrderWideStrItr,TPostOrderWideStrItr,IJclWideStrIterator,IJclWideStrCollection,IJclWideStrEqualityComparer,TJclWideStrBinaryNode,const ,AString,WideString,'',GetString,SetString,FreeString)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TSingleItr,TPreOrderSingleItr,TInOrderSingleItr,TPostOrderSingleItr,IJclSingleIterator,IJclSingleTreeIterator,IJclSingleBinaryTreeIterator,IJclSingleCollection,IJclSingleEqualityComparer,TJclSingleBinaryNode,const ,AValue,Single,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TSingleItr,TPreOrderSingleItr,TInOrderSingleItr,TPostOrderSingleItr,IJclSingleIterator,IJclSingleCollection,IJclSingleEqualityComparer,TJclSingleBinaryNode,const ,AValue,Single,0.0,GetValue,SetValue,FreeValue)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TDoubleItr,TPreOrderDoubleItr,TInOrderDoubleItr,TPostOrderDoubleItr,IJclDoubleIterator,IJclDoubleTreeIterator,IJclDoubleBinaryTreeIterator,IJclDoubleCollection,IJclDoubleEqualityComparer,TJclDoubleBinaryNode,const ,AValue,Double,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TDoubleItr,TPreOrderDoubleItr,TInOrderDoubleItr,TPostOrderDoubleItr,IJclDoubleIterator,IJclDoubleCollection,IJclDoubleEqualityComparer,TJclDoubleBinaryNode,const ,AValue,Double,0.0,GetValue,SetValue,FreeValue)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TExtendedItr,TPreOrderExtendedItr,TInOrderExtendedItr,TPostOrderExtendedItr,IJclExtendedIterator,IJclExtendedTreeIterator,IJclExtendedBinaryTreeIterator,IJclExtendedCollection,IJclExtendedEqualityComparer,TJclExtendedBinaryNode,const ,AValue,Extended,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TExtendedItr,TPreOrderExtendedItr,TInOrderExtendedItr,TPostOrderExtendedItr,IJclExtendedIterator,IJclExtendedCollection,IJclExtendedEqualityComparer,TJclExtendedBinaryNode,const ,AValue,Extended,0.0,GetValue,SetValue,FreeValue)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TIntegerItr,TPreOrderIntegerItr,TInOrderIntegerItr,TPostOrderIntegerItr,IJclIntegerIterator,IJclIntegerTreeIterator,IJclIntegerBinaryTreeIterator,IJclIntegerCollection,IJclIntegerEqualityComparer,TJclIntegerBinaryNode,,AValue,Integer,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TIntegerItr,TPreOrderIntegerItr,TInOrderIntegerItr,TPostOrderIntegerItr,IJclIntegerIterator,IJclIntegerCollection,IJclIntegerEqualityComparer,TJclIntegerBinaryNode,,AValue,Integer,0,GetValue,SetValue,FreeValue)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TCardinalItr,TPreOrderCardinalItr,TInOrderCardinalItr,TPostOrderCardinalItr,IJclCardinalIterator,IJclCardinalTreeIterator,IJclCardinalBinaryTreeIterator,IJclCardinalCollection,IJclCardinalEqualityComparer,TJclCardinalBinaryNode,,AValue,Cardinal,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TCardinalItr,TPreOrderCardinalItr,TInOrderCardinalItr,TPostOrderCardinalItr,IJclCardinalIterator,IJclCardinalCollection,IJclCardinalEqualityComparer,TJclCardinalBinaryNode,,AValue,Cardinal,0,GetValue,SetValue,FreeValue)}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TInt64Itr,TPreOrderInt64Itr,TInOrderInt64Itr,TPostOrderInt64Itr,IJclInt64Iterator,IJclInt64TreeIterator,IJclInt64BinaryTreeIterator,IJclInt64Collection,IJclInt64EqualityComparer,TJclInt64BinaryNode,const ,AValue,Int64,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TInt64Itr,TPreOrderInt64Itr,TInOrderInt64Itr,TPostOrderInt64Itr,IJclInt64Iterator,IJclInt64Collection,IJclInt64EqualityComparer,TJclInt64BinaryNode,const ,AValue,Int64,0,GetValue,SetValue,FreeValue)}
{$IFNDEF CLR}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TPtrItr,TPreOrderPtrItr,TInOrderPtrItr,TPostOrderPtrItr,IJclPtrIterator,IJclPtrTreeIterator,IJclPtrBinaryTreeIterator,IJclPtrCollection,IJclPtrEqualityComparer,TJclPtrBinaryNode,,APtr,Pointer,GetPointer,SetPointer)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TPtrItr,TPreOrderPtrItr,TInOrderPtrItr,TPostOrderPtrItr,IJclPtrIterator,IJclPtrCollection,IJclPtrEqualityComparer,TJclPtrBinaryNode,,APtr,Pointer,nil,GetPointer,SetPointer,FreePointer)}
{$ENDIF ~CLR}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TItr,TPreOrderItr,TInOrderItr,TPostOrderItr,IJclIterator,IJclTreeIterator,IJclBinaryTreeIterator,IJclCollection,IJclEqualityComparer,TJclBinaryNode,,AObject,TObject,GetObject,SetObject)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TItr,TPreOrderItr,TInOrderItr,TPostOrderItr,IJclIterator,IJclCollection,IJclEqualityComparer,TJclBinaryNode,,AObject,TObject,nil,GetObject,SetObject,FreeObject)}
{$IFDEF SUPPORTS_GENERICS}
type
{$JPPEXPANDMACRO JCLBINARYTREEITRINT(TItr<T>,TPreOrderItr<T>,TInOrderItr<T>,TPostOrderItr<T>,IJclIterator<T>,IJclTreeIterator<T>,IJclBinaryTreeIterator<T>,IJclCollection<T>,IJclEqualityComparer<T>,TJclBinaryNode<T>,const ,AItem,T,GetItem,SetItem)}
{$JPPEXPANDMACRO JCLBINARYTREEITRIMP(TItr<T>,TPreOrderItr<T>,TInOrderItr<T>,TPostOrderItr<T>,IJclIterator<T>,IJclCollection<T>,IJclEqualityComparer<T>,TJclBinaryNode<T>,const ,AItem,T,Default(T),GetItem,SetItem,FreeItem)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclIntfBinaryTree,TJclIntfBinaryNode,TPreOrderIntfItr,TInOrderIntfItr,TPostOrderIntfItr,IJclIntfCollection,IJclIntfIterator,IJclIntfTreeIterator,ACompare: TIntfCompare,
SetCompare(ACompare);,,const ,AInterface,IInterface,nil,FreeObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclAnsiStrBinaryTree,TJclAnsiStrBinaryNode,TPreOrderAnsiStrItr,TInOrderAnsiStrItr,TPostOrderAnsiStrItr,IJclAnsiStrCollection,IJclAnsiStrIterator,IJclAnsiStrTreeIterator,ACompare: TAnsiStrCompare,
SetCompare(ACompare);,,const ,AString,AnsiString,'',FreeString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclWideStrBinaryTree,TJclWideStrBinaryNode,TPreOrderWideStrItr,TInOrderWideStrItr,TPostOrderWideStrItr,IJclWideStrCollection,IJclWideStrIterator,IJclWideStrTreeIterator,ACompare: TWideStrCompare,
SetCompare(ACompare);,,const ,AString,WideString,'',FreeString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclSingleBinaryTree,TJclSingleBinaryNode,TPreOrderSingleItr,TInOrderSingleItr,TPostOrderSingleItr,IJclSingleCollection,IJclSingleIterator,IJclSingleTreeIterator,ACompare: TSingleCompare,
SetCompare(ACompare);,,const ,AValue,Single,0.0,FreeSingle)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclDoubleBinaryTree,TJclDoubleBinaryNode,TPreOrderDoubleItr,TInOrderDoubleItr,TPostOrderDoubleItr,IJclDoubleCollection,IJclDoubleIterator,IJclDoubleTreeIterator,ACompare: TDoubleCompare,
SetCompare(ACompare);,,const ,AValue,Double,0.0,FreeDouble)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclExtendedBinaryTree,TJclExtendedBinaryNode,TPreOrderExtendedItr,TInOrderExtendedItr,TPostOrderExtendedItr,IJclExtendedCollection,IJclExtendedIterator,IJclExtendedTreeIterator,ACompare: TExtendedCompare,
SetCompare(ACompare);,,const ,AValue,Extended,0.0,FreeExtended)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclIntegerBinaryTree,TJclIntegerBinaryNode,TPreOrderIntegerItr,TInOrderIntegerItr,TPostOrderIntegerItr,IJclIntegerCollection,IJclIntegerIterator,IJclIntegerTreeIterator,ACompare: TIntegerCompare,
SetCompare(ACompare);,,,AValue,Integer,0,FreeInteger)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclCardinalBinaryTree,TJclCardinalBinaryNode,TPreOrderCardinalItr,TInOrderCardinalItr,TPostOrderCardinalItr,IJclCardinalCollection,IJclCardinalIterator,IJclCardinalTreeIterator,ACompare: TCardinalCompare,
SetCompare(ACompare);,,,AValue,Cardinal,0,FreeCardinal)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64BinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64BinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclInt64BinaryTree,TJclInt64BinaryNode,TPreOrderInt64Itr,TInOrderInt64Itr,TPostOrderInt64Itr,IJclInt64Collection,IJclInt64Iterator,IJclInt64TreeIterator,ACompare: TInt64Compare,
SetCompare(ACompare);,,const ,AValue,Int64,0,FreeInt64)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrBinaryTree.Create(Compare);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclPtrBinaryTree,TJclPtrBinaryNode,TPreOrderPtrItr,TInOrderPtrItr,TPostOrderPtrItr,IJclPtrCollection,IJclPtrIterator,IJclPtrTreeIterator,ACompare: TPtrCompare,
SetCompare(ACompare);,,,APtr,Pointer,nil,FreePointer)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclBinaryTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclBinaryTree.Create(Compare, False);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclBinaryTree,TJclBinaryNode,TPreOrderItr,TInOrderItr,TPostOrderItr,IJclCollection,IJclIterator,IJclTreeIterator,ACompare: TCompare; AOwnsObjects: Boolean,
SetCompare(ACompare);,AOwnsObjects,,AObject,TObject,nil,FreeObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
(*$JPPEXPANDMACRO JCLBINARYTREEIMP(TJclBinaryTree<T>,TJclBinaryNode<T>,TPreOrderItr<T>,TInOrderItr<T>,TPostOrderItr<T>,IJclCollection<T>,IJclIterator<T>,IJclTreeIterator<T>,AOwnsItems: Boolean,,AOwnsItems,const ,AItem,T,Default(T),FreeItem)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
//=== { TJclBinaryTreeE<T> } =================================================
constructor TJclBinaryTreeE<T>.Create(const AComparer: IComparer<T>; AOwnsItems: Boolean);
begin
inherited Create(AOwnsItems);
FComparer := AComparer;
end;
procedure TJclBinaryTreeE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclBinaryTreeE<T> then
TJclBinaryTreeE<T>(Dest).FComparer := FComparer;
end;
function TJclBinaryTreeE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclBinaryTreeE<T>.Create(Comparer, False);
AssignPropertiesTo(Result);
end;
function TJclBinaryTreeE<T>.ItemsCompare(const A, B: T): Integer;
begin
if Comparer <> nil then
Result := Comparer.Compare(A, B)
else
Result := inherited ItemsCompare(A, B);
end;
function TJclBinaryTreeE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Comparer <> nil then
Result := Comparer.Compare(A, B) = 0
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclBinaryTreeF<T> } =================================================
constructor TJclBinaryTreeF<T>.Create(ACompare: TCompare<T>; AOwnsItems: Boolean);
begin
inherited Create(AOwnsItems);
SetCompare(ACompare);
end;
function TJclBinaryTreeF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclBinaryTreeF<T>.Create(Compare, False);
AssignPropertiesTo(Result);
end;
//=== { TJclBinaryTreeI<T> } =================================================
function TJclBinaryTreeI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclBinaryTreeI<T>.Create(False);
AssignPropertiesTo(Result);
end;
function TJclBinaryTreeI<T>.ItemsCompare(const A, B: T): Integer;
begin
if Assigned(FCompare) then
Result := FCompare(A, B)
else
Result := A.CompareTo(B);
end;
function TJclBinaryTreeI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
if Assigned(FCompare) then
Result := FCompare(A, B) = 0
else
Result := A.CompareTo(B) = 0;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit WorkerThread;
interface
uses
System.SysUtils, System.Classes, Oracle, OracleMonitor, Data.DB, Vcl.SvcMgr,
IdHTTPWebBrokerBridge;
type
TMyService = class(TService);
TdmWorkerThread = class(TDataModule)
OracleSession: TOracleSession;
OracleQueueInput: TOracleQueue;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FServer: TIdHTTPWebBrokerBridge;
Fusn: string;
Fpwd: string;
FEventLogger: TEventLogger;
FService: TService;
public
procedure StartServer(porta: integer = 8080);
procedure StopServer;
procedure ConnectAtDB;
property usn: string read Fusn write Fusn;
property pwd: string read Fpwd write Fpwd;
property EventLogger: TEventLogger read FEventLogger write FEventLogger;
property Service: TService read FService write FService;
property Server: TIdHTTPWebBrokerBridge read FServer write FServer;
end;
TWorkerThread = class(TThread)
private
FPaused: Boolean;
Fdm: TdmWorkerThread;
protected
procedure Execute; override;
public
destructor Destroy; override;
procedure Pause;
procedure Continue;
function IsPaused: Boolean;
property dm: TdmWorkerThread read Fdm write Fdm;
end;
implementation
uses Soap.XSBuiltIns, System.DateUtils, System.ioutils, Winapi.ActiveX,
Winapi.Windows, SetExamStateImpl, uCMDLineOptions, ServiceU;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmWorkerThread.DataModuleCreate(Sender: TObject);
begin
FServer := TIdHTTPWebBrokerBridge.Create(Self);
end;
procedure TdmWorkerThread.DataModuleDestroy(Sender: TObject);
begin
FServer.Free;
end;
procedure TdmWorkerThread.StartServer(porta: integer = 8080);
begin
if not FServer.Active then
begin
FServer.Bindings.Clear;
FServer.DefaultPort := porta;
FServer.Active := True;
ConnectAtDB;
// -- connessione all'implementazione
TSetExamState.SendQueue := OracleQueueInput;
TSetExamState.usn := Fusn;
TSetExamState.pwd := Fpwd;
end;
end;
procedure TdmWorkerThread.StopServer;
begin
FServer.Active := False;
FServer.Bindings.Clear;
end;
procedure TdmWorkerThread.ConnectAtDB;
begin
try
if not OracleSession.Connected then
begin
OracleSession.LogonDatabase := TCMDLineOptions.NomeDB;
OracleSession.LogonUsername := TCMDLineOptions.User;
OracleSession.LogonPassword := TCMDLineOptions.Pswd;
OracleSession.Connected := True;
if FEventLogger<>nil then
FEventLogger.LogMessage(format('Connected to: %s',[OracleSession.LogonDatabase]), EVENTLOG_INFORMATION_TYPE,0,2);
end;
except
on E: Exception do
begin
if FEventLogger<>nil then
begin
FEventLogger.LogMessage(E.ClassName + ' ' + E.Message, EVENTLOG_ERROR_TYPE,0,4);
TChorafarma_InputQueue(FService).StopService;
end;
raise;
end;
end;
end;
{ -- TWorkerThread -- }
destructor TWorkerThread.Destroy;
begin
if dm<>nil then
dm.Free;
inherited;
end;
procedure TWorkerThread.Continue;
begin
FPaused := False;
end;
procedure TWorkerThread.Execute;
begin
{$IFDEF DEBUG}
dm.EventLogger.LogMessage('Thread executed', EVENTLOG_INFORMATION_TYPE,0,2);
{$ENDIF}
try
dm.StartServer(TCMDLineOptions.Porta);
while not Terminated do
begin
if not FPaused then
begin
// dm.WriteLog('Message from thread: ' + TimeToStr(now));
end;
TThread.Sleep(1000);
end;
except
on E: Exception do
begin
// TFile.WriteAllText(TPath.Combine(ExePath, 'CRASH_LOG.TXT'), E.ClassName + ' ' + E.Message);
// dm.WriteLog('*** Error ***');
// dm.WriteLog(E.ClassName + ' ' + E.Message);
dm.EventLogger.LogMessage(E.ClassName + ' ' + E.Message, EVENTLOG_ERROR_TYPE,0,4);
// raise;
end
end;
end;
function TWorkerThread.IsPaused: Boolean;
begin
Result := FPaused;
end;
procedure TWorkerThread.Pause;
begin
FPaused := True;
end;
end.
|
CONST
Level : GLUInt = 10; // уровень детализации
CoeffZ : GLFloat = 0.01; // множитель по Z
CoeffX : GLFloat = 0.01; // множитель по X
CoeffY : GLFloat = 0.01; // множитель по Y
CONST
SmallB : GLFloat = 200.0; // расстояние от плиты исполнительного органа до плоскости угла
SmallL4 : GLFloat = 10.0; // толщина плиты исполнительного органа
CONST
Rad1 : GLFloat = 25.0; // радиус шпильковерта
H1 : GLFloat = 35.0; // высота шпильковерта
Rad1a : GLFloat = 40.0; // радиус диска
H1a : GLFloat = 5.0; // высота диска
LPlit : GLFloat = 160.0; // сторона плиты
CONST
Smallh : GLFloat = 20.0; // высота до плоскости нижней крышки шпильковерта
Rad3 : GLFloat = 15.0; // радиус центрального отверстия в плите
H2 : GLFloat = 140.0; // длина шпинделя
Rad4 : GLFloat = 10.0; // радиус шпинделя
Rad5 : GLFloat = 15.0; // радиус патрона
H3 : GLFloat = 40.0; // длина патрона
Rad6 : GLFloat = 7.0; // радиус детали
H4 : GLFloat = 70.0; // длина детали
Rad7 : GLFloat = 5.0; // радиус шляпки болта
H5 : GLFloat = 5.0; // высота шляпки болта
Rad8 : GLFloat = 2.0; // радиус основной части болта
H6 : GLFloat = 40.0; // высота основной части болта
Rad9 : GLFloat = 6.0; // радиус дырки под болт
|
{**********************************************}
{ TCumulative Function Component }
{ Copyright (c) 1997-2004 by David Berneda }
{**********************************************}
unit TeeCumu;
{$I TeeDefs.inc}
interface
{ The TCumulative function sums the Series values
starting from the first point.
Example:
Given these values : 1 2 3
The TCumulative function returns : 1 3 6 ( 1=1, 1+2=3 and 1+2+3=6 )
}
uses {$IFDEF CLR}
Classes,
{$ELSE}
Classes,
{$ENDIF}
TeEngine, Chart;
type
TCumulative = class(TTeeFunction)
public
{ Public declarations }
Constructor Create(AOwner: TComponent); override;
Function Calculate(Series:TChartSeries; First,Last:Integer):Double; override;
Function CalculateMany(SeriesList:TList; ValueIndex:Integer):Double; override;
published
{ Published declarations }
property Period;
end;
implementation
Uses TeeProCo, TeeConst;
{ TCumulative }
Constructor TCumulative.Create(AOwner: TComponent);
Begin
inherited;
InternalSetPeriod(1);
end;
Function TCumulative.Calculate(Series:TChartSeries; First,Last:Integer):Double;
begin
if First>0 then result:=ParentSeries.MandatoryValueList.Last
else result:=0;
if First>=0 then
result:=result+ValueList(Series).Value[First];
end;
{ Returns the sum( ) of the current ValueIndex point of all Series PLUS the
accumulated calculation of the previous ValueIndex point.
}
Function TCumulative.CalculateMany(SeriesList:TList; ValueIndex:Integer):Double;
var t : Integer;
tmpList : TChartValueList;
begin
if ValueIndex=0 then result:=0
else result:=ParentSeries.MandatoryValueList.Value[ValueIndex-1];
for t:=0 to SeriesList.Count-1 do
begin
tmpList:=ValueList(TChartSeries(SeriesList[t]));
if tmpList.Count>ValueIndex then result:=result+tmpList.Value[ValueIndex];
end;
end;
initialization
RegisterTeeFunction( TCumulative, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionCumulative,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended, 2 );
finalization
UnRegisterTeeFunctions([TCumulative]);
end.
|
PROGRAM RevString(INPUT, OUTPUT);
PROCEDURE RCopy(VAR FileInp: TEXT);
VAR
Ch: CHAR;
BEGIN{RCopy}
IF NOT EOLN(FileInp)
THEN
BEGIN
READ(FileInp, Ch);
WRITE(Ch);
RCopy(FileInp)
END;
END;{RCopy}
BEGIN{RevString}
RCopy(INPUT);
END.{RevString}
|
{******************************************************************************}
{ }
{ GMV_VitalsViewEnter }
{ }
{ Updated Version information to be pulled from the actual file }
{ ZZZZZZBELLC 1/27/2015 }
{******************************************************************************}
unit uGMV_VersionInfo;
interface
uses Windows,
SysUtils,
Classes,
Graphics,
Forms,
Controls,
StdCtrls,
Buttons,
ExtCtrls,
uGMV_Common
;
const
VersionInfoKeys: array[1..13] of string = (
'CompanyName',
'FileDescription',
'FileVersion',
'InternalName',
'LegalCopyRight',
'OriginalFileName',
'ProductName',
'ProductVersion',
'Comments',
'VAReleaseDate',
'VANamespace',
'VASourceInformation',
'PreviousVersion'// ZZZZZZBELLC 1/27/2015
);
USEnglish = $040904E4;
type
TVersionInfo = class(TComponent)
(*
Retrieves Version Info data about a given binary file.
*)
private
FFileName: string;
FLanguageID: DWord;
FInfo: pointer;
FInfoSize: longint;
FCtlCompanyName: TControl;
FCtlFileDescription: TControl;
FCtlFileVersion: TControl;
FCtlInternalName: TControl;
FCtlLegalCopyRight: TControl;
FCtlOriginalFileName: TControl;
FCtlProductName: TControl;
FCtlProductVersion: TControl;
FCtlComments: TControl;
FCtlVAReleaseDate: TControl;
FCtlVANamespace: TControl;
FCtlVASourceInformation: TControl;
procedure SetFileName(Value: string);
procedure SetVerProp(index: Integer; value: TControl);
function GetVerProp(index: Integer): TControl;
function GetIndexKey(index: Integer): string;
// function GetKey(const KName: string): string;
function GetCompileDateTime: TDateTime;
function GetVAPatchNumber: string;
function GetVAServerVersion: string;
function GetVATestVersion: Boolean;
procedure Refresh;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
InternalVersion:String;
function GetKey(const KName: string): string;
property FileName: string read FFileName write SetFileName;
property LanguageID: DWord read FLanguageID write FLanguageID;
property CompileDateTime: TDateTime read GetCompileDateTime;
property CompanyName: string index 1 read GetIndexKey;
property FileDescription: string index 2 read GetIndexKey;
property FileVersion: string index 3 read GetIndexKey;
property InternalName: string index 4 read GetIndexKey;
property LegalCopyRight: string index 5 read GetIndexKey;
property OriginalFileName: string index 6 read GetIndexKey;
property ProductName: string index 7 read GetIndexKey;
property ProductVersion: string index 8 read GetIndexKey;
property Comments: string index 9 read GetIndexKey;
property VAReleaseDate: string index 10 read GetIndexKey;
property VANamespace: string index 11 read GetIndexKey;
property VASourceInformation: string index 12 read GetIndexKey;//AAN 08/05/2002
property PreviousVersion: string index 13 read GetIndexKey; // ZZZZZZBELLC 1/27/2015
property VAPatchNumber: string read GetVAPatchNumber;
property VAServerVersion: string read GetVAServerVersion;
property VATestVersion: Boolean read GetVATestVersion;
constructor Create(AOwner: TComponent); override;
(*
Allocates memory and initializes variables for the object.
*)
destructor Destroy; override;
(*
Releases all memory allocated for the object.
*)
procedure OpenFile(FName: string);
(*
Uses method GetFileVersionInfo to retrieve version information for file
FName. If FName is blank, version information is obtained for the
current executable (Application.ExeName).
*)
procedure Close;
(*
Releases memory allocated and clears all storage variables.
*)
published
property CtlCompanyName: TControl index 1 read GetVerProp write SetVerProp;
property CtlFileDescription: TControl index 2 read GetVerProp write SetVerProp;
property CtlFileVersion: TControl index 3 read GetVerProp write SetVerProp;
property CtlInternalName: TControl index 4 read GetVerProp write SetVerProp;
property CtlLegalCopyRight: TControl index 5 read GetVerProp write SetVerProp;
property CtlOriginalFileName: TControl index 6 read GetVerProp write SetVerProp;
property CtlProductName: TControl index 7 read GetVerProp write SetVerProp;
property CtlProductVersion: TControl index 8 read GetVerProp write SetVerProp;
property CtlComments: TControl index 9 read GetVerProp write SetVerProp;
property CtlVAReleaseDate: TControl index 10 read GetVerProp write SetVerProp;
property CtlVANamespace: TControl index 11 read GetVerProp write SetVerProp;
property CtlVASourceInfo: TControl index 12 read GetVerProp write SetVerProp;
end;
function CurrentExeNameAndVersion: string;
function RequiredServerVersion: string;
function CurrentDllNameAndVersion: string;
function PrevDllNameAndVersion: string;
implementation
uses
Dialogs
, TypInfo
, uGMV_Const
;
function RequiredServerVersion: string;
begin
with TVersionInfo.Create(Application) do
try
OpenFile(Application.ExeName);
Result := VAServerVersion;
if VAPatchNumber <> '' then
Result := Result + ' with patch ' + VAPatchNumber;
finally
free;
end;
end;
function CurrentExeNameAndVersion: string;
begin
with TVersionInfo.Create(Application) do
try
OpenFile(Application.ExeName);
{$IFDEF IGNOREEXENAME}
Result := UpperCase('Vitals.exe:' + FileVersion);
{$ELSE}
Result := UpperCase(ExtractFileName(Application.ExeName) + ':' + FileVersion);
{$ENDIF}
finally
free;
end;
end;
function PrevDllNameAndVersion: string;
begin
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 09/06/05 11:29'; // Max-Min error corrected
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 09/22/05 11:43';
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 10/18/05 10:50'; // T12
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/03/05 11:47';
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/21/05 15:53'; //T14
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/30/05 18:00'; //T15
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 12/29/05 16:20'; //T16
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/20/06 09:08'; //T17
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 02/15/06 15:55'; //T18
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 10/04/07 16:52'; //T22 - was not released only tested
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/03/08 11:04'; //T22.2
{$IFDEF PATCH_5_0_22} Result := 'GMV_VITALSVIEWENTER.DLL:v. 03/14/06 16:35';{$ENDIF}
//{ $IFDEF PATCH_5_0_23 } Result := 'DUMMY';{$ENDIF} // T23.1
// Patch 23 does not support any previous versions of dll
//{ $IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 10/14/08 15:42';{$ENDIF} // T23.4
//{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/20/09 16:30'; {$ENDIF} //T23.5
//{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 08/11/09 15:00'; {$ENDIF} //T23.8
{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/21/11 12:52'; {$ENDIF} //T26.1
end;
function CurrentDllNameAndVersion: string;
begin
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 09/22/05 11:43'; // Max-Min error corrected
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 10/18/05 10:50';
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/03/05 11:47'; //T13
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/21/05 15:53'; //T14
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/30/05 18:00'; //T15
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 12/29/05 16:20'; //T16
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/20/06 09:08'; //T17
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 02/15/06 15:55'; //T18 - ignores CCOW Cancel patient change
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 03/14/06 16:35'; //T19
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 10/04/07 16:52'; //T22 - was not released only tested
// Result := 'GMV_VITALSVIEWENTER.DLL:v. 01/03/08 11:04'; //T22.2 - was notreleased
//{ $IFDEF PATCH_5_0_22} Result := 'GMV_VITALSVIEWENTER.DLL:v. 05/12/08 08:44'; {$ENDIF} //T22.6
//{ $IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 05/13/08 09:27'; {$ENDIF} //T23.1
//{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 04/07/09 16:30'; {$ENDIF} //T23.7
//{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 08/11/09 15:00'; {$ENDIF} //T23.8
{$IFDEF PATCH_5_0_23} Result := 'GMV_VITALSVIEWENTER.DLL:v. 11/05/13 10:00'; {$ENDIF} //T28.1
end;
(*=== TVersionInfo Methods ==================================================*)
constructor TVersionInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLanguageID := USEnglish;
{$IFDEF DLL}
SetFileName('GMV_VitalsViewEnter.dll');
{$ELSE}
SetFileName(EmptyStr);
{$ENDIF}
end;
destructor TVersionInfo.Destroy;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
inherited Destroy;
end;
procedure TVersionInfo.SetFileName(Value: string);
begin
FFileName := Value;
if Value = EmptyStr then
FFileName := ExtractFileName(Application.ExeName);
if csDesigning in ComponentState then
Refresh
else
OpenFile(Value);
end;
procedure TVersionInfo.OpenFile(FName: string);
var
vlen: DWord;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
if Length(FName) <= 0 then
FName := Application.ExeName;
FInfoSize := GetFileVersionInfoSize(pchar(fname), vlen);
if FInfoSize > 0 then
begin
GetMem(FInfo, FInfoSize);
if not GetFileVersionInfo(pchar(fname), vlen, FInfoSize, FInfo) then
raise Exception.Create('Cannot retrieve Version Information for ' + fname);
Refresh;
end;
end;
procedure TVersionInfo.Close;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
FInfoSize := 0;
FFileName := EmptyStr;
end;
const
vqvFmt = '\StringFileInfo\%8.8x\%s';
function TVersionInfo.GetKey(const KName: string): string;
var
vptr: pchar;
vlen: DWord;
begin
Result := EmptyStr;
if FInfoSize <= 0 then
exit;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [FLanguageID, KName])), pointer(vptr), vlen) then
Result := vptr;
end;
function TVersionInfo.GetIndexKey(index: Integer): string;
begin
Result := GetKey(VersionInfoKeys[index]);
end;
function TVersionInfo.GetVerProp(index: Integer): TControl;
begin
case index of
1: Result := FCtlCompanyName;
2: Result := FCtlFileDescription;
3: Result := FCtlFileVersion;
4: Result := FCtlInternalName;
5: Result := FCtlLegalCopyRight;
6: Result := FCtlOriginalFileName;
7: Result := FCtlProductName;
8: Result := FCtlProductVersion;
9: Result := FCtlComments;
10: Result := FCtlVAReleaseDate;
11: Result := FCtlVANamespace;
12: Result := FCtlVASourceInformation;
else
Result := nil;
end;
end;
procedure TVersionInfo.SetVerProp(index: Integer; value: TControl);
begin
case index of
1: FCtlCompanyName := Value;
2: FCtlFileDescription := Value;
3: FCtlFileVersion := Value;
4: FCtlInternalName := Value;
5: FCtlLegalCopyRight := Value;
6: FCtlOriginalFileName := Value;
7: FCtlProductName := Value;
8: FCtlProductVersion := Value;
9: FCtlComments := Value;
10: FCtlVAReleaseDate := Value;
11: FCtlVANamespace := Value;
12: FCtlVASourceInformation := Value;
end;
Refresh;
end;
procedure TVersionInfo.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Operation = opRemove then
begin
if AComponent = FCtlCompanyName then
FCtlCompanyName := nil
else if AComponent = FCtlFileDescription then
FCtlFileDescription := nil
else if AComponent = FCtlFileVersion then
FCtlFileVersion := nil
else if AComponent = FCtlInternalName then
FCtlInternalName := nil
else if AComponent = FCtlLegalCopyRight then
FCtlLegalCopyRight := nil
else if AComponent = FCtlOriginalFileName then
FCtlOriginalFileName := nil
else if AComponent = FCtlProductName then
FCtlProductName := nil
else if AComponent = FCtlProductVersion then
FCtlProductVersion := nil
else if AComponent = FCtlComments then
FCtlComments := nil
else if AComponent = FCtlVAReleaseDate then
FCtlVAReleaseDate := nil
else if AComponent = FCtlVANamespace then
FCtlVANamespace := nil
else if AComponent = FCtlVASourceInformation then
FCtlVASourceInformation := nil;
end;
end;
procedure TVersionInfo.Refresh;
var
PropInfo: PPropInfo;
procedure AssignText(Actl: TComponent; txt: string);
begin
if Assigned(ACtl) then
begin
PropInfo := GetPropInfo(ACtl.ClassInfo, 'Caption');
if PropInfo <> nil then
SetStrProp(ACtl, PropInfo, txt)
else
begin
PropInfo := GetPropInfo(ACtl.ClassInfo, 'Text');
if PropInfo <> nil then
SetStrProp(ACtl, PropInfo, txt)
end;
end;
end;
begin
if csDesigning in ComponentState then
begin
AssignText(FCtlCompanyName, VersionInfoKeys[1]);
AssignText(FCtlFileDescription, VersionInfoKeys[2]);
AssignText(FCtlFileVersion, VersionInfoKeys[3]);
AssignText(FCtlInternalName, VersionInfoKeys[4]);
AssignText(FCtlLegalCopyRight, VersionInfoKeys[5]);
AssignText(FCtlOriginalFileName, VersionInfoKeys[6]);
AssignText(FCtlProductName, VersionInfoKeys[7]);
AssignText(FCtlProductVersion, VersionInfoKeys[8]);
AssignText(FCtlComments, VersionInfoKeys[9]);
AssignText(FCtlVAReleaseDate, VersionInfoKeys[10]);
AssignText(FCtlVANamespace, VersionInfoKeys[11]);
AssignText(FCtlVASourceInformation, VersionInfoKeys[12]);
end
else
begin
AssignText(FCtlCompanyName, CompanyName);
AssignText(FCtlFileDescription, FileDescription);
AssignText(FCtlFileVersion, FileVersion);
AssignText(FCtlInternalName, InternalName);
AssignText(FCtlLegalCopyRight, LegalCopyRight);
AssignText(FCtlOriginalFileName, OriginalFileName);
AssignText(FCtlProductName, ProductName);
AssignText(FCtlProductVersion, ProductVersion);
AssignText(FCtlComments, Comments);
AssignText(FCtlVAReleaseDate, VAReleaseDate);
AssignText(FCtlVANamespace, VANamespace);
AssignText(FCtlVASourceInformation, VASourceInformation);
end;
end;
function TVersionInfo.GetCompileDateTime: TDateTime;
begin
{$IFDEF DLL}
FileAge(GetModuleName(HInstance), Result);
// FileAge(GetProgramFilesPath+'\Vista\Common Files\GMV_VitalsViewEnter.dll', Result);
// Result := FileDateToDateTime(FileAge(GetProgramFilesPath+'\Vista\Common Files\GMV_VitalsViewEnter.dll'));
{$ELSE}
FileAge(Application.ExeName, Result);
// Result := FileDateToDateTime(FileAge(Application.ExeName));
{$ENDIF}
end;
function TVersionInfo.GetVAPatchNumber: string;
begin
if StrToIntDef(Piece(FileVersion, '.', 3), 0) > 0 then
begin
Result := VANamespace + '*' + VAServerVersion + '*' + Piece(FileVersion, '.', 3);
// if StrToIntDef(Piece(FileVersion, '.', 4), 0) > 0 then // zzzzzzandria 060223
// Result := Result + 'T' + Piece(FileVersion, '.', 4); // zzzzzzandria 060223
// Result := 'GMRV*5.0*3T7'; // 6
// Result := 'GMRV*5.0*3T8'; // 7
// Result := 'GMRV*5.0*3T9'; // 8
// Result := 'GMRV*5.0*3T12';
// Result := 'GMRV*5.0*3T13';
// Result := 'GMRV*5.0*3T14';
// Result := 'GMRV*5.0*3T16';
// Result := 'GMRV*5.0*3T17';
// Result := 'GMRV*5.0*3T18'; // zzzzzzandria 060223
end
else
Result := '';
end;
function TVersionInfo.GetVAServerVersion: string;
begin
Result := Piece(FileVersion, '.', 1) + '.' + Piece(FileVersion, '.', 2);
end;
function TVersionInfo.GetVATestVersion: Boolean;
begin
Result := False;
end;
end.
|
(**
This module contains simple types to be used through the application.
@Author David Hoyle
@Version 1.0
@Date 04 Jan 2018
**)
Unit ITHelper.Types;
Interface
Type
(** An enumerate to describe which font is to be read or written. **)
TITHFonts = (ithfHeader, ithfDefault, ithfSuccess, ithfFailure, ithfWarning);
(** An enumerate to describe the different font names. **)
TITHFontNames = (fnHeader, fnTools);
(** An enumerate for the different parts of the process. **)
TITHEnabledOption = (
eoBefore,
eoAfter,
eoZip,
eoGroupEnabled,
eoCopyVersionInfo,
eoBuildVersionResource,
eoIncrementBuild
);
(** A set of enumerates. **)
TITHEnabledOptions = Set Of TITHEnabledOption;
Implementation
End.
|
unit Test.Devices.ModbusRTU;
interface
uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst, SysUtils,
Test.Devices.Base.ReqParser, Threads.ResponceParser, Devices.ModbusBase;
type
TModusRTUReqCreatorTest = class(TDeviceReqCreatorTestBase)
private
procedure CheckOneFirstReqLink(n: int);
protected
procedure SetUp; override;
function GetDevType(): int; override;
procedure DoCheckRequests; override;
published
end;
TModusRTUParserTest = class(TDeviceReqParserTestBase)
private
protected
function GetDevType(): int; override;
function GetThreadClass(): TSQLWriteThreadForTestClass; override;
published
procedure Fnc_04;
procedure Fnc_02;
procedure CustomDataTypes;
end;
implementation
uses
Devices.Modbus.ReqCreatorBase, System.Math;
{ TModusRTUReqCreatorTest }
procedure TModusRTUReqCreatorTest.CheckOneFirstReqLink(n: int);
begin
CheckEquals(1, ReqList[n].ReqLinkCount);
Check(ReqList[n].ReqLinks[0].id > 0);
end;
procedure TModusRTUReqCreatorTest.DoCheckRequests;
begin
CheckReqHexString(0, '$24, 4, 0, 0, 0, 3, $B7, $3E');
Check(ReqList[0].ReqLinkCount = 3);
Check(ReqList[0].ReqLinks[0].id > 0);
Check(ReqList[0].ReqLinks[1].id = 0);
Check(ReqList[0].ReqLinks[2].id > 0);
CheckReqHexString(1, '$24, 4, 1, 2, 0, 1, $96, $C3');
CheckOneFirstReqLink(1);
CheckReqHexString(2, '24 04 03 E7 00 01 86 8C');
CheckOneFirstReqLink(2);
CheckEquals(0, ReqList[2].ReqLinks[0].ext);
CheckReqHexString(3, '24 04 04 4B 00 01 47 D9');
CheckOneFirstReqLink(3);
CheckEquals(1, ReqList[3].ReqLinks[0].ext);
CheckReqHexString(4, '24 04 04 AF 00 02 47 EF');
CheckOneFirstReqLink(4);
CheckEquals(2, ReqList[4].ReqLinks[0].ext);
CheckReqHexString(5, '24 04 05 13 00 02 87 F7');
CheckOneFirstReqLink(5);
CheckEquals(3, ReqList[5].ReqLinks[0].ext);
CheckReqHexString(6, '24 04 05 77 00 02 C6 28');
CheckOneFirstReqLink(6);
CheckEquals(4, ReqList[6].ReqLinks[0].ext);
CheckReqHexString(7, '24 04 05 DB 00 02 06 09');
CheckOneFirstReqLink(7);
CheckEquals(5, ReqList[7].ReqLinks[0].ext);
CheckReqHexString(8, '24 04 06 3F 00 04 C6 78');
CheckOneFirstReqLink(8);
CheckEquals(6, ReqList[8].ReqLinks[0].ext);
CheckReqHexString(9, '24 04 06 A3 00 04 06 56');
CheckOneFirstReqLink(9);
CheckEquals(7, ReqList[9].ReqLinks[0].ext);
CheckReqHexString(10, '$24, 2, 1, 2, 0, 1, $1E, $C3');
Check(ReqList[10].ReqLinkCount = 1);
Check(ReqList[10].ReqLinks[0].id > 0);
end;
function TModusRTUReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_MODBUS_RTU;
end;
procedure TModusRTUReqCreatorTest.SetUp;
begin
inherited;
end;
{ TModusRTUParserTest }
type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest);
function TModusRTUParserTest.GetDevType: int;
begin
Result := DEVTYPE_MODBUS_RTU;
end;
function TModusRTUParserTest.GetThreadClass: TSQLWriteThreadForTestClass;
begin
Result := TLocalSQLWriteThreadForTest;
end;
procedure TModusRTUParserTest.CustomDataTypes;
var buf: ArrayOfByte;
begin
gbv.ReqDetails.rqtp := rqtUSER_DEFINED;
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('24 04 08');
SetLength(buf, Length(buf) + 10);
WriteFloat(buf, 3, 2.5);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_USR;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 1700;
gbv.ReqDetails.ReqLinkCount := 1;
gbv.ReqDetails.ReqLinks[0].id := 1700;
gbv.ReqDetails.ReqLinks[0].ext := MODBUS_RESULT_DOUBLE_LITTLE_ENDIAN;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = 2.5);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('24 04 04 1A 2A 43 5E');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
gbv.ReqDetails.ReqLinks[0].ext := MODBUS_RESULT_SINGLE_SHUFFLE;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1);
Check(Floor(TLocalSQLWriteThreadForTest(thread).Values[0].Val) = 222);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
end;
procedure TModusRTUParserTest.Fnc_04;
var buf: ArrayOfByte;
begin
gbv.ReqDetails.rqtp := rqtUSER_DEFINED;
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('24 04 02 03 E8');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_USR;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 1;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = 1000);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
buf := TextNumbersStringToArray('24 04 02 FF FD');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = -3);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
// колхозом
buf := TextNumbersStringToArray('24 04 06 FF FD 00 00 03 E8');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
gbv.ReqDetails.ClearReqLink();
gbv.ReqDetails.ReqLinkCount := 3;
gbv.ReqDetails.ReqLinks[0].id := 1;
gbv.ReqDetails.ReqLinks[2].id := 3;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 2);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Chn = TObject(1));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = -3);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
Check(TLocalSQLWriteThreadForTest(thread).Values[1].Chn = TObject(3));
Check(TLocalSQLWriteThreadForTest(thread).Values[1].Val = 1000);
Check(TLocalSQLWriteThreadForTest(thread).Values[1].UTime = gbv.gmTime);
end;
procedure TModusRTUParserTest.Fnc_02;
var buf: ArrayOfByte;
i: int;
begin
gbv.ReqDetails.rqtp := rqtUSER_DEFINED;
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('24 02 01 01');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_USR;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 1;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime);
// колхозом
buf := TextNumbersStringToArray('24 02 02 02 01');
SetLength(buf, Length(buf) + 2);
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
gbv.ReqDetails.ClearReqLink();
gbv.ReqDetails.ReqLinkCount := 11;
gbv.ReqDetails.ReqLinks[0].id := 1;
gbv.ReqDetails.ReqLinks[8].id := 2;
gbv.ReqDetails.ReqLinks[9].id := 3;
gbv.ReqDetails.ReqLinks[10].id := 4;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 4);
for i := 0 to 3 do
begin
Check(TLocalSQLWriteThreadForTest(thread).Values[i].Chn = TObject(i + 1));
Check(TLocalSQLWriteThreadForTest(thread).Values[i].UTime = gbv.gmTime);
end;
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[1].Val = 0);
Check(TLocalSQLWriteThreadForTest(thread).Values[2].Val = 1);
Check(TLocalSQLWriteThreadForTest(thread).Values[3].Val = 0);
end;
initialization
RegisterTest('GMIOPSrv/Devices/ModusRTU', TModusRTUReqCreatorTest.Suite);
RegisterTest('GMIOPSrv/Devices/ModusRTU', TModusRTUParserTest.Suite);
end.
|
unit SHL_LameStream; // SemVersion: 0.3.0
// Contains TLameStream class for
// Changelog:
// 0.1.0 - test version
// 0.2.0 - priority
// 0.3.0 - no header
// TODO:
//
interface // SpyroHackingLib is licensed under WTFPL
uses
SysUtils, Classes, SHL_ProcessStream, SHL_Types;
type
TLameStream = class(TStream)
constructor Create(const PathToLamaExe: WideString);
destructor Destroy(); override;
private
FLame: WideString;
FProcess: TProcessStream;
FIsEncode, FIsDecode: Boolean;
// FDump: TFileStream;
public
procedure Decode(const ReadFromMp3: WideString; NoHeader: Boolean = False);
procedure Encode(const SaveToMp3: WideString; InRate, OutRate: TextString; InStereo, OutStereo: Boolean);
procedure WaitExit(Timeout: Integer = 10000);
function IsTerminated(): Boolean;
procedure SetPriority(Prio: Cardinal);
function Write(const Buffer; Count: Longint): Longint; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
end;
implementation
constructor TLameStream.Create(const PathToLamaExe: WideString);
begin
inherited Create();
FLame := PathToLamaExe;
if not FileExists(FLame) then
Abort;
// FDump := TFileStream.Create(IntToStr(GetTickCount()) + '_.wav', fmCreate);
end;
destructor TLameStream.Destroy();
begin
FProcess.Free();
// FDump.Free();
inherited Destroy();
end;
procedure TLameStream.WaitExit(Timeout: Integer = 10000);
begin
if FIsEncode then
FProcess.Close(True, False);
if FIsDecode then
FProcess.Close(False, True);
FProcess.IsRunning(Timeout);
end;
procedure TLameStream.Encode(const SaveToMp3: WideString; InRate, OutRate: TextString; InStereo, OutStereo: Boolean);
var
Line: WideString;
begin
FIsEncode := True;
if InStereo and OutStereo then
Line := ' -m j'
else if InStereo and not OutStereo then
Line := ' -a'
else if not InStereo and OutStereo then
Line := ' -m d'
else if not InStereo and not OutStereo then
Line := ' -m m';
Line := ExtractFileName(FLame) + Line + ' -r -x -s ' + InRate + ' --resample ' + OutRate + ' --silent --preset extreme - "' + SaveToMp3 + '"';
FProcess := TProcessStream.Create(FLame, Line, '', True, False, False, False);
end;
procedure TLameStream.Decode(const ReadFromMp3: WideString; NoHeader: Boolean = False);
var
Line: WideString;
begin
FIsDecode := True;
Line := ExtractFileName(FLame);
if NoHeader then
Line := Line + ' -t';
Line := Line + ' --quiet --decode "' + ReadFromMp3 + '" -';
FProcess := TProcessStream.Create(FLame, Line, '', False, True, False, False);
end;
function TLameStream.IsTerminated(): Boolean;
begin
Result := not FProcess.IsRunning();
end;
procedure TLameStream.SetPriority(Prio: Cardinal);
begin
FProcess.SetPriority(Prio);
end;
function TLameStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := FProcess.Write(Buffer, Count);
end;
function TLameStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := FProcess.Read(Buffer, Count);
// FDump.Write(Buffer, Result);
end;
function TLameStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
Result := 0;
end;
end.
|
unit NtUtils.Lsa.Sid;
interface
uses
Winapi.WinNt, NtUtils.Exceptions, NtUtils.Security.Sid, NtUtils.Lsa;
type
TTranslatedName = record
DomainName, UserName: String;
SidType: TSidNameUse;
function FullName: String;
end;
// Convert SIDs to account names
function LsaxLookupSid(Sid: PSid; out Name: TTranslatedName; hxPolicy:
ILsaHandle = nil): TNtxStatus;
function LsaxLookupSids(Sids: TArray<PSid>; out Names: TArray<TTranslatedName>;
hxPolicy: ILsaHandle = nil): TNtxStatus;
// Convert SID to full account name or at least to SDDL
function LsaxSidToString(Sid: PSid): String;
// Convert an account name / SDDL string to a SID
function LsaxLookupName(AccountName: String; out Sid: ISid; hxPolicy:
ILsaHandle = nil): TNtxStatus;
function LsaxLookupNameOrSddl(AccountOrSddl: String; out Sid: ISid; hxPolicy:
ILsaHandle = nil): TNtxStatus;
// Get current user name and domain
function LsaxGetUserName(out Domain, UserName: String): TNtxStatus; overload;
function LsaxGetUserName(out FullName: String): TNtxStatus; overload;
implementation
uses
Winapi.ntlsa, Winapi.NtSecApi, Ntapi.ntstatus, System.SysUtils;
{ TTranslatedName }
function TTranslatedName.FullName: String;
begin
if SidType = SidTypeDomain then
Result := DomainName
else if (UserName <> '') and (DomainName <> '') then
Result := DomainName + '\' + UserName
else if (UserName <> '') then
Result := UserName
else
Result := '';
end;
{ Functions }
function LsaxLookupSid(Sid: PSid; out Name: TTranslatedName;
hxPolicy: ILsaHandle): TNtxStatus;
var
Sids: TArray<PSid>;
Names: TArray<TTranslatedName>;
begin
SetLength(Sids, 1);
Sids[0] := Sid;
Result := LsaxLookupSids(Sids, Names, hxPolicy);
if Result.IsSuccess then
Name := Names[0];
end;
function LsaxLookupSids(Sids: TArray<PSid>; out Names: TArray<TTranslatedName>;
hxPolicy: ILsaHandle = nil): TNtxStatus;
var
BufferDomains: PLsaReferencedDomainList;
BufferNames: PLsaTranslatedNameArray;
i: Integer;
begin
Result := LsaxpEnsureConnected(hxPolicy, POLICY_LOOKUP_NAMES);
if not Result.IsSuccess then
Exit;
// Request translation for all SIDs at once
Result.Location := 'LsaLookupSids';
Result.Status := LsaLookupSids(hxPolicy.Handle, Length(Sids), Sids,
BufferDomains, BufferNames);
// Even without mapping we get to know SID types
if Result.Status = STATUS_NONE_MAPPED then
Result.Status := STATUS_SOME_NOT_MAPPED;
if not Result.IsSuccess then
Exit;
SetLength(Names, Length(SIDs));
for i := 0 to High(Sids) do
begin
Names[i].SidType := BufferNames{$R-}[i]{$R+}.Use;
// Note: for some SID types LsaLookupSids might return SID's SDDL
// representation in the Name field. In rare cases it might be empty.
// According to [MS-LSAT] the name is valid unless the SID type is
// SidTypeUnknown
Names[i].UserName := BufferNames{$R-}[i]{$R+}.Name.ToString;
// Negative DomainIndex means the SID does not reference a domain
if (BufferNames{$R-}[i]{$R+}.DomainIndex >= 0) and
(BufferNames{$R-}[i]{$R+}.DomainIndex < BufferDomains.Entries) then
Names[i].DomainName := BufferDomains.Domains[
BufferNames{$R-}[i]{$R+}.DomainIndex].Name.ToString
else
Names[i].DomainName := '';
end;
LsaFreeMemory(BufferDomains);
LsaFreeMemory(BufferNames);
end;
function LsaxSidToString(Sid: PSid): String;
var
AccountName: TTranslatedName;
begin
if LsaxLookupSid(Sid, AccountName).IsSuccess and not (AccountName.SidType in
[SidTypeUndefined, SidTypeInvalid, SidTypeUnknown]) then
Result := AccountName.FullName
else
Result := RtlxConvertSidToString(Sid);
end;
function LsaxLookupName(AccountName: String; out Sid: ISid; hxPolicy:
ILsaHandle): TNtxStatus;
var
Name: TLsaUnicodeString;
BufferDomain: PLsaReferencedDomainList;
BufferTranslatedSid: PLsaTranslatedSid2;
NeedsFreeMemory: Boolean;
begin
Result := LsaxpEnsureConnected(hxPolicy, POLICY_LOOKUP_NAMES);
if not Result.IsSuccess then
Exit;
Name.FromString(AccountName);
// Request translation of one name
Result.Location := 'LsaLookupNames2';
Result.Status := LsaLookupNames2(hxPolicy.Handle, 0, 1, Name, BufferDomain,
BufferTranslatedSid);
// LsaLookupNames2 allocates memory even on some errors
NeedsFreeMemory := Result.IsSuccess or (Result.Status = STATUS_NONE_MAPPED);
if Result.IsSuccess then
Result := RtlxCaptureCopySid(BufferTranslatedSid.Sid, Sid);
if NeedsFreeMemory then
begin
LsaFreeMemory(BufferDomain);
LsaFreeMemory(BufferTranslatedSid);
end;
end;
function LsaxLookupNameOrSddl(AccountOrSddl: String; out Sid: ISid; hxPolicy:
ILsaHandle): TNtxStatus;
var
Status: TNtxStatus;
begin
// Since someone might create an account which name is a valid SDDL string,
// lookup the account name first. Parse it as SDDL only if this lookup failed.
Result := LsaxLookupName(AccountOrSddl, Sid, hxPolicy);
if Result.IsSuccess then
Exit;
// The string can start with "S-1-" and represent an arbitrary SID or can be
// one of ~40 double-letter abbreviations. See [MS-DTYP] for SDDL definition.
if (Length(AccountOrSddl) = 2) or AccountOrSddl.StartsWith('S-1-', True) then
begin
Status := RtlxConvertStringToSid(AccountOrSddl, Sid);
if Status.IsSuccess then
Result := Status;
end;
end;
function LsaxGetUserName(out Domain, UserName: String): TNtxStatus;
var
BufferUser, BufferDomain: PLsaUnicodeString;
begin
Result.Location := 'LsaGetUserName';
Result.Status := LsaGetUserName(BufferUser, BufferDomain);
if Result.IsSuccess then
begin
Domain := BufferDomain.ToString;
UserName := BufferUser.ToString;
LsaFreeMemory(BufferUser);
LsaFreeMemory(BufferDomain);
end;
end;
function LsaxGetUserName(out FullName: String): TNtxStatus;
var
Domain, UserName: String;
begin
Result := LsaxGetUserName(Domain, UserName);
if not Result.IsSuccess then
Exit;
if (Domain <> '') and (UserName <> '') then
FullName := Domain + '\' + UserName
else if Domain <> '' then
FullName := Domain
else if UserName <> '' then
FullName := UserName
else
begin
Result.Location := 'LsaxGetUserName';
Result.Status := STATUS_UNSUCCESSFUL;
end;
end;
end.
|
unit UFrmDeposito;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Grids, DBGrids, Menus, Buttons, StdCtrls, ExtCtrls, Mask
, URegraCRUDLoteVacina
, URepositorioLoteVacina
, ULoteVacina
, UUtilitarios, FMTBcd, DBXFirebird, DB, SqlExpr, DBClient, Provider
;
type
TfrmDeposito = class(TFrmCRUD)
gbDeposito: TGroupBox;
dbDeposito: TDBGrid;
edNomeVacina: TLabeledEdit;
edLaboratorio: TLabeledEdit;
edLoteVacina: TLabeledEdit;
edQuantidade: TLabeledEdit;
edVencimento: TMaskEdit;
lbVencimento: TLabel;
tbDeposito: TSQLTable;
DataSetProvider1: TDataSetProvider;
ClientDataSet1: TClientDataSet;
DataSource1: TDataSource;
SQLConnection1: TSQLConnection;
Timer1: TTimer;
procedure Timer1Timer(Sender: TObject);
protected
FLOTEVACINA: TLOTEVACINA;
FRegraCRUDLOTEVACINA: TRegraCRUDLOTEVACINA;
procedure Inicializa; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
frmDeposito: TfrmDeposito;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UDialogo;
{$R *.dfm}
{ TfrmDeposito }
procedure TfrmDeposito.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbDeposito.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TfrmDeposito.Inicializa;
begin
inherited;
DefineEntidade(@FLOTEVACINA, TLOTEVACINA);
DefineRegraCRUD(@FRegraCRUDLOTEVACINA, TRegraCRUDLOTEVACINA);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_VACINA_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_LOTE_VACINA)
.DefineVisao(TBL_LOTE_VACINA));
end;
procedure TfrmDeposito.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNomeVacina.SetFocus;
end;
procedure TfrmDeposito.PreencheEntidade;
begin
inherited;
begin
FLOTEVACINA.VACINA_NOME := edNomeVacina.Text ;
FLOTEVACINA.LOTE := edLoteVacina.Text ;
FLOTEVACINA.LABORATORIO := edLaboratorio.Text ;
FLOTEVACINA.VENCIMENTO_LOTE := StrToDate(edVencimento.Text) ;
FLOTEVACINA.QUANTIDADE_ESTOQUE := edQuantidade.Text ;
end;
end;
procedure TfrmDeposito.PreencheFormulario;
begin
inherited;
begin
edNomeVacina.Text := FLOTEVACINA.VACINA_NOME ;
edLoteVacina.Text := FLOTEVACINA.LOTE ;
edLaboratorio.Text := FLOTEVACINA.LABORATORIO ;
edVencimento.Text := DateToStr(FLOTEVACINA.VENCIMENTO_LOTE) ;
edQuantidade.Text := FLOTEVACINA.QUANTIDADE_ESTOQUE ;
end;
end;
procedure TfrmDeposito.Timer1Timer(Sender: TObject);
begin
inherited;
tbDeposito.Refresh;
ClientDataSet1.Refresh;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FileOCT<p>
Loader for FSRad OCT files.<p>
<b>History : </b><font size=-1><ul>
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009
<li>02/04/07 - DaStr - Added $I GLScene.inc
<li>30/01/03 - Egg - Creation
</ul></font>
}
unit FileOCT;
interface
{$I GLScene.inc}
uses Classes, GLVectorGeometry, GLVectorLists;
type
TOCTHeader = record
numVerts : Integer;
numFaces : Integer;
numTextures : Integer;
numLightmaps : Integer;
numLights : Integer;
end;
TOCTVertex = record
tv : TTexPoint; // texture coordinates
lv : TTexpoint; // lightmap coordinates
pos : TAffineVector; // vertex position
end;
TOCTFace = record
start : Integer; // first face vert in vertex array
num : Integer; // number of verts in the face
id : Integer; // texture index into the texture array
lid : Integer; // lightmap index into the lightmap array
p : THmgPlane;
end;
POCTFace = ^TOCTFace;
TOCTTexture = record
id : Integer; // texture id
Name : array [0..63] of AnsiChar; // texture name
end;
TOCTLightmap = record
id : Integer; // lightmaps id
map : array [0..49151] of Byte; // 128 x 128 raw RGB data
end;
POCTLightmap = ^TOCTLightmap;
TOCTLight = record
pos : TAffineVector; // Position
color : TAffineVector; // Color (RGB)
intensity : Integer; // Intensity
end;
// TOCTFile
//
TOCTFile = class (TObject)
public
{ Public Declarations }
Header : TOCTHeader;
Vertices : array of TOCTVertex;
Faces : array of TOCTFace;
Textures : array of TOCTTexture;
Lightmaps : array of TOCTLightmap;
Lights : array of TOCTLight;
PlayerPos : TAffineVector;
constructor Create; overload;
constructor Create(octStream : TStream); overload;
{: Saves content to stream in OCT format.<p>
The Header is automatically prepared before streaming. }
procedure SaveToStream(aStream : TStream);
procedure AddTriangles(vertexCoords : TAffineVectorList;
texMapCoords : TAffineVectorList;
const textureName : String);
procedure AddLight(const lightPos : TAffineVector;
const lightColor : TVector;
lightIntensity : Integer);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, GLMeshUtils;
// ------------------
// ------------------ TOCTFile ------------------
// ------------------
// Create
//
constructor TOCTFile.Create;
begin
inherited Create;
end;
// Create
//
constructor TOCTFile.Create(octStream : TStream);
begin
inherited Create;
// Read in the header
octStream.Read(Header, SizeOf(Header));
// then the rest of the stuff
SetLength(Vertices, Header.numVerts);
octStream.Read(Vertices[0], Header.numVerts*SizeOf(TOCTVertex));
SetLength(Faces, Header.numFaces);
octStream.Read(Faces[0], Header.numFaces*SizeOf(TOCTFace));
SetLength(Textures, Header.numTextures);
octStream.Read(Textures[0], Header.numTextures*SizeOf(TOCTTexture));
SetLength(Lightmaps, Header.numLightmaps);
octStream.Read(Lightmaps[0], Header.numLightmaps*SizeOf(TOCTLightmap));
SetLength(Lights, Header.numLights);
octStream.Read(Lights[0], Header.numLights*SizeOf(TOCTLight));
octStream.Read(PlayerPos, SizeOf(PlayerPos))
end;
// SaveToStream
//
procedure TOCTFile.SaveToStream(aStream : TStream);
begin
with Header, aStream do begin
numVerts:=Length(Vertices);
numFaces:=Length(Faces);
numTextures:=Length(Textures);
numLightmaps:=Length(Lightmaps);
numLights:=Length(Lights);
Write(Header, SizeOf(Header));
Write(Vertices[0], numVerts*SizeOf(TOCTVertex));
Write(Faces[0], numFaces*SizeOf(TOCTFace));
Write(Textures[0], numTextures*SizeOf(TOCTTexture));
Write(Lightmaps[0], numLightmaps*SizeOf(TOCTLightmap));
Write(Lights[0], numLights*SizeOf(TOCTLight));
Write(PlayerPos, SizeOf(PlayerPos))
end;
end;
// AddTriangles
//
procedure TOCTFile.AddTriangles(vertexCoords : TAffineVectorList;
texMapCoords : TAffineVectorList;
const textureName : String);
var
i : Integer;
baseIdx, texIdx : Integer;
begin
Assert((texMapCoords=nil) or (texMapCoords.Count=vertexCoords.Count));
texIdx:=Length(Textures);
SetLength(Textures, texIdx+1);
Move(textureName[1], Textures[texIdx].Name[0], Length(textureName));
SetLength(Lightmaps, 1);
FillChar(Lightmaps[0].map[0], 128*3, 255);
baseIdx:=Length(Vertices);
SetLength(Vertices, baseIdx+vertexCoords.Count);
for i:=0 to vertexCoords.Count-1 do with Vertices[baseIdx+i] do begin
pos:=vertexCoords.List[i];
if Assigned(texMapCoords) then
tv:=PTexPoint(@texMapCoords.List[i])^;
end;
SetLength(Faces, vertexCoords.Count div 3);
i:=0; while i<vertexCoords.Count do begin
with Faces[i div 3] do begin
start:=baseIdx+i;
num:=3;
id:=texIdx;
p:=PlaneMake(vertexCoords[i],
CalcPlaneNormal(vertexCoords[i+0], vertexCoords[i+1], vertexCoords[i+0]));
end;
Inc(i, 3);
end;
end;
// AddLight
//
procedure TOCTFile.AddLight(const lightPos : TAffineVector;
const lightColor : TVector;
lightIntensity : Integer);
var
n : Integer;
begin
n:=Length(Lights);
SetLength(Lights, n+1);
with Lights[n] do begin
pos:=lightPos;
color:=PAffineVector(@lightColor)^;
intensity:=lightIntensity;
end;
end;
end.
|
unit fNotificationProcessor;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
System.Actions,
Vcl.ActnList,
System.UITypes;
type
TNotificationAction = (naCancel, naNewNote, naAddendum);
TfrmNotificationProcessor = class(TForm)
btnCancel: TButton;
btnOK: TButton;
bvlBottom: TBevel;
lbxCurrentNotesAvailable: TListBox;
memNotificationSpecifications: TMemo;
rbtnNewNote: TRadioButton;
rbtnAddendOneOfTheFollowing: TRadioButton;
stxtNotificationName: TStaticText;
btnDefer: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NewOrAddendClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnDeferClick(Sender: TObject);
private
fAlert: string;
fAlertDescription: string;
fDFN: string;
fName: string;
fNotificationAction: TNotificationAction;
fNotificationName: string;
fNotificationIEN: integer;
fNoteTitleIEN: integer;
fNoteTitle: string;
fNoteAllowAddendum: boolean;
fNoteDescription: TStringList;
fNoteList: TStringList;
fParams: TStringList;
fNoteIndex: integer;
procedure Setup;
public
class function Execute(aParams: TStringList; aDescription: string): TNotificationAction;
end;
var
NotificationProcessor: TfrmNotificationProcessor;
implementation
uses
mFunStr,
uCore,
ORNet,
fFrame,
fDeferDialog;
{$R *.dfm}
type
TAvailableNote = class(TObject)
private
FIEN: integer;
FTitle: string;
FDate: string;
end;
const
STXT_CAPTION = 'Notification - %s';
NOTE_CAPTION = 'Create New Note [Title: %s]';
RBTN_CAPTION = '%d Notes available to addend';
procedure TfrmNotificationProcessor.btnDeferClick(Sender: TObject);
var
aResult: string;
begin
with TfrmDeferDialog.Create(Self) do
try
Title := 'Defer Patient Notification';
Description := StringReplace(fAlertDescription,fAlert,'', [rfReplaceAll]);
if Execute then
try
aResult := sCallV('ORB3UTL DEFER', [User.DUZ, fAlert, DeferUntilFM]);
if aResult <> '1' then
raise Exception.Create(Copy(aResult, Pos(aResult, '^') + 1, Length(aResult)))
else
begin
fNotificationAction := naCancel;
end;
except
on e: Exception do
MessageDlg(e.Message, mtError, [mbOk], 0);
end
else
MessageDlg('Deferral cancelled', mtInformation, [mbOk], 0);
finally
Free;
end;
end;
procedure TfrmNotificationProcessor.btnOKClick(Sender: TObject);
var
aNoteToAddend: TAvailableNote;
begin
if rbtnNewNote.Checked then
fNotificationAction := naNewNote
else if rbtnAddendOneOfTheFollowing.Checked then
begin
fNoteIndex := lbxCurrentNotesAvailable.ItemIndex;
fNotificationAction := naAddendum;
aNoteToAddend := TAvailableNote(lbxCurrentNotesAvailable.Items.Objects[fNoteIndex]);
fParams.Values['ADDEND NOTE IEN'] := IntToStr(aNoteToAddend.FIEN);
fParams.Values['ADDEND NOTE TITLE'] := aNoteToAddend.FTitle;
end
else
fNotificationAction := naCancel;
end;
class function TfrmNotificationProcessor.Execute(aParams: TStringList; aDescription: string)
: TNotificationAction;
var
notProcFrm: TfrmNotificationProcessor;
begin
notProcFrm := TfrmNotificationProcessor.Create(Application);
notProcFrm.fAlertDescription := aDescription;
with notProcFrm do
begin
try
fParams := aParams;
Setup;
case ShowModal of
mrOk:
Result := fNotificationAction;
mrCancel:
Result := naCancel;
else
Result := naCancel;
end;
if Result = naCancel then
begin
CallVistA('ORBSMART OUSMALRT', [fAlert]);
end;
finally
Free;
end;
end;
end;
procedure TfrmNotificationProcessor.FormCreate(Sender: TObject);
begin
Font := Application.MainForm.Font;
fNoteDescription := TStringList.Create;
fNoteList := TStringList.Create;
fNoteIndex := -1;
end;
procedure TfrmNotificationProcessor.FormDestroy(Sender: TObject);
begin
while lbxCurrentNotesAvailable.Count > 0 do
begin
lbxCurrentNotesAvailable.Items.Objects[0].Free;
lbxCurrentNotesAvailable.Items.Delete(0);
end;
FreeAndNil(fNoteDescription);
FreeAndNil(fNoteList);
end;
procedure TfrmNotificationProcessor.NewOrAddendClick(Sender: TObject);
begin
if not rbtnAddendOneOfTheFollowing.Checked then
begin
lbxCurrentNotesAvailable.ItemIndex := -1;
lbxCurrentNotesAvailable.Enabled := False;
end
else
begin
lbxCurrentNotesAvailable.Enabled := True;
end;
if fNoteAllowAddendum and rbtnAddendOneOfTheFollowing.Checked then
btnOK.Enabled := lbxCurrentNotesAvailable.ItemIndex > -1
else
btnOK.Enabled := rbtnNewNote.Checked;
end;
procedure TfrmNotificationProcessor.Setup;
var
aAvailableNote: TAvailableNote;
y: integer;
begin
fNotificationAction := naCancel; // Just to make sure ;-)
fAlert := fParams.Values['ALERT'];
fNotificationIEN := StrToIntDef(fParams.Values['NOTIFICATION IEN'], -1);
fNotificationName := fParams.Values['NOTIFICATION NAME'];
fNoteTitle := fParams.Values['NOTE TITLE'];
fNoteTitleIEN := StrToIntDef(fParams.Values['NOTE TITLE IEN'], -1);
fNoteAllowAddendum := fParams.Values['ALLOW ADDENDUM'] = '1';
fDFN := fParams.Values['DFN'];
fName := fParams.Values['PATIENT NAME'];
self.Caption := self.Caption + ' (' + fName + ')';
// Sets this alert as in process on M side in user context
CallVistA('ORBSMART INSMALRT', [fAlert]);
CallVistA('ORB3UTL GET DESCRIPTION', [fAlert], fNoteDescription);
if fNoteAllowAddendum then
begin
CallVistA('ORB3UTL GET EXISTING NOTES', [fNoteTitleIEN, fDFN], fNoteList);
lbxCurrentNotesAvailable.Items.Clear;
while fNoteList.Count > 1 do
begin
aAvailableNote := TAvailableNote.Create;
aAvailableNote.FIEN := StrToIntDef(Piece(fNoteList[1], '^', 1), -1);
aAvailableNote.FTitle := Piece(fNoteList[1], '^', 2);
aAvailableNote.FDate := Piece(fNoteList[1], '^', 3);
lbxCurrentNotesAvailable.Items.AddObject(aAvailableNote.FTitle + ' ' + aAvailableNote.FDate, aAvailableNote);
fNoteList.Delete(1);
end;
if lbxCurrentNotesAvailable.Count > 0 then
rbtnAddendOneOfTheFollowing.Caption := Format(RBTN_CAPTION, [lbxCurrentNotesAvailable.Count])
else
begin
y := lbxCurrentNotesAvailable.Top + lbxCurrentNotesAvailable.Height;
rbtnAddendOneOfTheFollowing.Caption := 'No notes available to addend';
rbtnAddendOneOfTheFollowing.Visible := false;
rbtnNewNote.Visible := false;
lbxCurrentNotesAvailable.Visible := false;
memNotificationSpecifications.Height := y - memNotificationSpecifications.Top;
end;
rbtnAddendOneOfTheFollowing.Enabled := (lbxCurrentNotesAvailable.Count > 0);
lbxCurrentNotesAvailable.Enabled := False;
end
else
begin
rbtnAddendOneOfTheFollowing.Caption := 'Addendums not allowed for this notification';
rbtnAddendOneOfTheFollowing.Enabled := False;
lbxCurrentNotesAvailable.Enabled := False;
end;
stxtNotificationName.Caption := Format(STXT_CAPTION, [fNotificationName]);
rbtnNewNote.Caption := Format(NOTE_CAPTION, [fNoteTitle]);
rbtnNewNote.Checked := True; // Default to new note
memNotificationSpecifications.Text := fNoteDescription.Text;
lbxCurrentNotesAvailable.ItemIndex := -1;
end;
end.
|
unit RelocateDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Forms, Dialogs, Controls, StdCtrls,
Buttons, IntelHEX;
type
TRelocateDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
SrcList: TListBox;
DstList: TListBox;
SrcLabel: TLabel;
DstLabel: TLabel;
IncludeBtn: TSpeedButton;
CopyBtn: TSpeedButton;
ExcludeBtn: TSpeedButton;
EditOffset: TEdit;
procedure IncludeBtnClick(Sender: TObject);
procedure ExcludeBtnClick(Sender: TObject);
procedure CopyBtnClick(Sender: TObject);
private
{ déclarations privées }
public
{ déclarations publiques }
procedure SetItem(List: TListBox; Index: Integer);
function GetFirstSelection(List: TCustomListBox): Integer;
procedure SetButtons;
function Execute(Source, Dest : TIntelHexFile) : integer;
end;
var
RelocateDlg: TRelocateDlg;
implementation
{$R *.dfm}
procedure TRelocateDlg.IncludeBtnClick(Sender: TObject);
var
Index: Integer;
begin
Index := GetFirstSelection(SrcList);
DstList.Items.AddObject(Format('[Relocated] %s', [SrcList.Items[Index]]),
SrcList.Items.Objects[Index]);
SrcList.Items.Delete(Index);
SetItem(SrcList, Index);
end;
procedure TRelocateDlg.CopyBtnClick(Sender: TObject);
var
Index: Integer;
begin
Index := GetFirstSelection(SrcList);
DstList.Items.AddObject(SrcList.Items[Index],
SrcList.Items.Objects[Index]);
SrcList.Items.Delete(Index);
SetItem(SrcList, Index);
end;
procedure TRelocateDlg.ExcludeBtnClick(Sender: TObject);
var
Index: Integer;
S : String;
begin
Index := GetFirstSelection(DstList);
S := DstList.Items[Index];
if S[1]='[' then Delete(S, 1, Pos(']', S)+1);
SrcList.Items.AddObject(S, DstList.Items.Objects[Index]);
DstList.Items.Delete(Index);
SetItem(DstList, Index);
end;
procedure TRelocateDlg.SetButtons;
var
SrcEmpty, DstEmpty: Boolean;
begin
SrcEmpty := SrcList.Items.Count = 0;
DstEmpty := DstList.Items.Count = 0;
IncludeBtn.Enabled := not SrcEmpty;
CopyBtn.Enabled := not SrcEmpty;
ExcludeBtn.Enabled := not DstEmpty;
end;
function TRelocateDlg.GetFirstSelection(List: TCustomListBox): Integer;
begin
for Result := 0 to List.Items.Count - 1 do
if List.Selected[Result] then Exit;
Result := LB_ERR;
end;
procedure TRelocateDlg.SetItem(List: TListBox; Index: Integer);
var
MaxIndex: Integer;
begin
with List do
begin
SetFocus;
MaxIndex := List.Items.Count - 1;
if Index = LB_ERR then Index := 0
else if Index > MaxIndex then Index := MaxIndex;
Selected[Index] := True;
end;
SetButtons;
end;
function TRelocateDlg.Execute(Source, Dest : TIntelHexFile) : integer;
var
i,j : integer;
Offset : integer;
begin
SrcLabel.Caption := ExtractFileName(Source.FileName);
SrcList.Clear;
DstList.Clear;
i := 0;
while i < Source.HexSections.Count do begin
if Source.HexSections.Item[i].Count>0 then
SrcList.AddItem(Source.HexSections.Item[i].SectionName, Source.HexSections.Item[i]);
inc(i);
end;
SetButtons;
result := ShowModal;
if result <> mrOK then exit;
TryStrToInt(EditOffset.Text, Offset);
i := 0;
while i < DstList.Items.Count do begin
j := 0;
while j< TIntelHexSection(DstList.Items.Objects[i]).Count do begin
with TIntelHexSection(DstList.Items.Objects[i]).Item[j] do
if DstList.Items[i][1] = '[' then
Dest.AddData(Address+Offset, DataPtr^, ByteCount)
else
Dest.AddData(Address, DataPtr^, ByteCount);
inc(j);
end;
inc(i);
end;
end;
end.
|
unit UFMessage;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, UMessageResultType;
type
TFMessage = class(TForm)
pnlBackground: TPanel;
imgMessageType: TImage;
lblTitle: TLabel;
edtMsg: TRichEdit;
pnlDividerBottom: TPanel;
pnlBtnOk: TPanel;
pnlDividerTitle: TPanel;
pnlBtnNo: TPanel;
pnlBtnCancel: TPanel;
procedure pnlBtnOkClick(Sender: TObject);
procedure pnlBtnNoClick(Sender: TObject);
procedure pnlBtnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ShowMessageInformation(Msg: string);
procedure ShowMessageSuccess(Msg: string);
procedure ShowMessageError(Msg: string);
procedure ShowMessageAlert(Msg: string);
function ShowMessageConfirm(Msg: string; ShowCancelButton: Boolean): TMessageResultType;
end;
var
FMessage: TFMessage;
implementation
{$R *.dfm}
{ TFMessage }
procedure TFMessage.pnlBtnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
Close;
end;
procedure TFMessage.pnlBtnNoClick(Sender: TObject);
begin
ModalResult := mrNo;
Close;
end;
procedure TFMessage.pnlBtnOkClick(Sender: TObject);
begin
ModalResult := mrYes;
Close;
end;
procedure TFMessage.ShowMessageAlert(Msg: string);
begin
lblTitle.Caption := 'Atenção...';
imgMessageType.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Warning96px',RT_RCDATA));
edtMsg.Text := Msg;
pnlBtnCancel.Visible := False;
pnlBtnNo.Visible := False;
pnlBtnOk.Left := 8;
pnlBtnOk.Width := pnlDividerBottom.Width;
Self.ShowModal;
end;
function TFMessage.ShowMessageConfirm(Msg: string;
ShowCancelButton: Boolean): TMessageResultType;
var
ResultDialog: integer;
begin
lblTitle.Caption := 'Certeza?';
imgMessageType.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Question96px',RT_RCDATA));
edtMsg.Text := Msg;
if ShowCancelButton then
begin
pnlBtnCancel.Visible := true;
pnlBtnCancel.Width := 132;
pnlBtnCancel.Left := 8;
pnlBtnNo.Visible := true;
pnlBtnNo.Width := 132;
pnlBtnNo.Left := 146;
pnlBtnOk.Visible := true;
pnlBtnOk.Width := 132;
pnlBtnOk.Left := 284;
end
else
begin
pnlBtnCancel.Visible := false;
pnlBtnNo.Visible := true;
pnlBtnNo.Width := 201;
pnlBtnNo.Left := 8;
pnlBtnOk.Visible := true;
pnlBtnOk.Width := 202;
pnlBtnOk.Left := 2015;
end;
ResultDialog := Self.ShowModal;
if ResultDialog = 6 then
Result := mstYes
else if ResultDialog = 7 then
Result := mstNo
else
Result := mstCancel;
end;
procedure TFMessage.ShowMessageError(Msg: string);
begin
lblTitle.Caption := 'Ops...';
imgMessageType.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Error96px',RT_RCDATA));
edtMsg.Text := Msg;
pnlBtnCancel.Visible := False;
pnlBtnNo.Visible := False;
pnlBtnOk.Left := 8;
pnlBtnOk.Width := pnlDividerBottom.Width;
Self.ShowModal;
end;
procedure TFMessage.ShowMessageInformation(Msg: string);
begin
lblTitle.Caption := 'Informação...';
imgMessageType.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Information96px',RT_RCDATA));
edtMsg.Text := Msg;
pnlBtnCancel.Visible := False;
pnlBtnNo.Visible := False;
pnlBtnOk.Left := 8;
pnlBtnOk.Width := pnlDividerBottom.Width;
Self.ShowModal;
end;
procedure TFMessage.ShowMessageSuccess(Msg: string);
begin
lblTitle.Caption := 'Opa...';
imgMessageType.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Success96px',RT_RCDATA));
edtMsg.Text := Msg;
pnlBtnCancel.Visible := False;
pnlBtnNo.Visible := False;
pnlBtnOk.Left := 8;
pnlBtnOk.Width := pnlDividerBottom.Width;
Self.ShowModal;
end;
end.
|
unit SubjectsTests;
interface
uses Classes, TestFramework, Rx, Generics.Collections, SysUtils,
Rx.Subjects;
type
TSubjectsTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure PublishSubject1;
procedure PublishSubject2;
procedure PublishSubject3;
procedure ReplaySubject;
procedure ReplaySubjectWithSize;
procedure ReplaySubjectWithTime;
procedure BehaviorSubject1;
procedure BehaviorSubject2;
procedure AsyncSubject;
end;
implementation
uses BaseTests;
{ TSubjectsTests }
procedure TSubjectsTests.AsyncSubject;
var
O: TAsyncSubject<Integer>;
OnNext1, OnNext2: TOnNext<Integer>;
OnCompleted1, OnCompleted2: TOnCompleted;
begin
OnNext1 := procedure(const Data: Integer)
begin
FStream.Add(Format('[1]:%d', [Data]))
end;
OnNext2 := procedure(const Data: Integer)
begin
FStream.Add(Format('[2]:%d', [Data]))
end;
OnCompleted1 := procedure
begin
FStream.Add('[1]:completed')
end;
OnCompleted2 := procedure
begin
FStream.Add('[2]:completed')
end;
O := TAsyncSubject<Integer>.Create;
O.Subscribe(OnNext1, OnCompleted1);
try
O.OnNext(1);
O.OnNext(2);
O.Subscribe(OnNext2, OnCompleted2);
O.OnNext(3);
O.OnNext(4);
O.OnCompleted;
O.OnNext(5);
Check(IsEqual(FStream, ['[1]:1', '[1]:2', '[1]:3', '[1]:4', '[2]:1', '[2]:2', '[2]:3', '[2]:4', '[1]:completed', '[2]:completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.BehaviorSubject1;
var
O: TBehaviorSubject<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(Format('%d', [Data]))
end;
OnCompleted := procedure
begin
FStream.Add('completed')
end;
O := TBehaviorSubject<Integer>.Create;
try
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.Subscribe(OnNext, OnCompleted);
O.OnNext(4);
O.OnCompleted;
O.OnNext(5);
Check(IsEqual(FStream, ['3', '4', 'completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.BehaviorSubject2;
var
O: TBehaviorSubject<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(Format('%d', [Data]))
end;
OnCompleted := procedure
begin
FStream.Add('completed')
end;
O := TBehaviorSubject<Integer>.Create(100);
try
O.Subscribe(OnNext, OnCompleted);
O.OnNext(4);
O.OnCompleted;
Check(IsEqual(FStream, ['100', '4', 'completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.PublishSubject1;
var
O: TPublishSubject<Integer>;
OnNext1, OnNext2: TOnNext<Integer>;
OnCompleted1, OnCompleted2: TOnCompleted;
begin
OnNext1 := procedure(const Data: Integer)
begin
FStream.Add(Format('[1]:%d', [Data]))
end;
OnNext2 := procedure(const Data: Integer)
begin
FStream.Add(Format('[2]:%d', [Data]))
end;
OnCompleted1 := procedure
begin
FStream.Add('[1]:completed')
end;
OnCompleted2 := procedure
begin
FStream.Add('[2]:completed')
end;
O := TPublishSubject<Integer>.Create;
O.Subscribe(OnNext1, OnCompleted1);
O.Subscribe(OnNext2, OnCompleted2);
try
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnCompleted;
Check(IsEqual(FStream, ['[1]:1', '[2]:1', '[1]:2', '[2]:2', '[1]:3', '[2]:3', '[1]:completed', '[2]:completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.PublishSubject2;
var
O: TPublishSubject<Integer>;
OnNext1, OnNext2: TOnNext<Integer>;
OnCompleted1, OnCompleted2: TOnCompleted;
OnSubscribe: TOnSubscribe<Integer>;
begin
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnCompleted;
end;
OnNext1 := procedure(const Data: Integer)
begin
FStream.Add(Format('[1]:%d', [Data]))
end;
OnNext2 := procedure(const Data: Integer)
begin
FStream.Add(Format('[2]:%d', [Data]))
end;
OnCompleted1 := procedure
begin
FStream.Add('[1]:completed')
end;
OnCompleted2 := procedure
begin
FStream.Add('[2]:completed')
end;
O := TPublishSubject<Integer>.Create(OnSubscribe);
try
O.Subscribe(OnNext1, OnCompleted1);
O.Subscribe(OnNext2, OnCompleted2);
Check(IsEqual(FStream, ['[1]:1', '[1]:2', '[1]:3', '[1]:completed', '[2]:1', '[2]:2', '[2]:3', '[2]:completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.PublishSubject3;
var
O: TPublishSubject<Integer>;
OnNext1, OnNext2: TOnNext<Integer>;
OnError1, OnError2: TOnError;
begin
OnNext1 := procedure(const Data: Integer)
begin
FStream.Add(Format('[1]:%d', [Data]))
end;
OnNext2 := procedure(const Data: Integer)
begin
FStream.Add(Format('[2]:%d', [Data]))
end;
OnError1 := procedure(Throwable: IThrowable)
begin
FStream.Add('[1]:error');
end;
OnError2 := procedure(Throwable: IThrowable)
begin
FStream.Add('[2]:error');
end;
O := TPublishSubject<Integer>.Create;
O.Subscribe(OnNext1, OnError1);
O.Subscribe(OnNext2, OnError2);
try
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
try
raise ETestError.Create('test');
except
O.OnError(Observable.CatchException)
end;
Check(IsEqual(FStream, ['[1]:1', '[2]:1', '[1]:2', '[2]:2', '[1]:3', '[2]:3', '[1]:error', '[2]:error']));
finally
O.Free
end;
end;
procedure TSubjectsTests.ReplaySubject;
var
O: TReplaySubject<Integer>;
OnNext1, OnNext2, OnNext3: TOnNext<Integer>;
OnCompleted1, OnCompleted2: TOnCompleted;
begin
OnNext1 := procedure(const Data: Integer)
begin
FStream.Add(Format('[1]:%d', [Data]))
end;
OnNext2 := procedure(const Data: Integer)
begin
FStream.Add(Format('[2]:%d', [Data]))
end;
OnNext3 := procedure(const Data: Integer)
begin
FStream.Add(Format('[3]:%d', [Data]))
end;
OnCompleted1 := procedure
begin
FStream.Add('[1]:completed')
end;
OnCompleted2 := procedure
begin
FStream.Add('[2]:completed')
end;
O := TReplaySubject<Integer>.Create;
O.Subscribe(OnNext1, OnCompleted1);
try
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.Subscribe(OnNext2, OnCompleted2);
O.OnCompleted;
O.Subscribe(OnNext3);
Check(IsEqual(FStream, ['[1]:1', '[1]:2', '[1]:3', '[2]:1', '[2]:2', '[2]:3', '[1]:completed', '[2]:completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.ReplaySubjectWithSize;
var
O: TReplaySubject<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(Format('%d', [Data]))
end;
OnCompleted := procedure
begin
FStream.Add('completed')
end;
O := TReplaySubject<Integer>.CreateWithSize(3);
try
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
O.Subscribe(OnNext, OnCompleted);
O.OnNext(6);
O.OnCompleted;
O.OnNext(7);
Check(IsEqual(FStream, ['3', '4', '5', '6', 'completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.ReplaySubjectWithTime;
var
O: TReplaySubject<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(Format('%d', [Data]))
end;
OnCompleted := procedure
begin
FStream.Add('completed')
end;
O := TReplaySubject<Integer>.CreateWithTime(100, Rx.TimeUnit.MILLISECONDS, Now + EncodeTime(0, 0, 0, 100));
try
O.OnNext(1); // must be losed cause of initial from parameter
Sleep(100);
O.OnNext(2);
Sleep(90);
O.OnNext(3);
Sleep(10);
O.OnNext(4);
Sleep(10);
O.OnNext(5);
O.OnNext(6);
O.Subscribe(OnNext, OnCompleted);
O.OnCompleted;
Check(IsEqual(FStream, ['3', '4', '5', '6', 'completed']));
finally
O.Free
end;
end;
procedure TSubjectsTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TSubjectsTests.TearDown;
begin
inherited;
FStream.Free;
end;
initialization
RegisterTests('Subjects', [
TSubjectsTests.Suite
]);
end.
|
program Shape;
type
TEllipse = class
xr: Integer;
yr: Integer;
procedure Draw; virtual;
procedure Hide; virtual;
procedure Rotate(angle: Integer); virtual;
end;
TCircle = class (TEllipse)
procedure Rotate(angle: Integer); override;
function Center: Integer; virtual;
end;
procedure TEllipse.Draw;
begin
Writeln('TEllipse.Draw !');
end;
procedure TEllipse.Hide;
begin
Writeln('TEllipse.Hide !');
end;
procedure TEllipse.Rotate(angle: Integer);
begin
Write('TEllipse.Rotate: ');
Writeln(angle);
end;
procedure TCircle.Rotate(angle: Integer);
begin
Write('TCircle.Rotate: ');
Writeln(angle);
end;
function TCircle.Center: Integer;
begin
Write('TCircle.Center !');
Result := 10;
end;
var
ellipse: TEllipse;
circle: TCircle;
p: TEllipse;
begin
ellipse := TEllipse.Create;
circle := TCircle.Create;
ellipse.Draw;
circle.Draw;
ellipse.Rotate(180);
circle.Rotate(360);
p := circle;
p.Rotate(90);
p := ellipse;
p.Rotate(80);
ellipse.Free;
circle.Free;
end.
|
unit Extern.Rufus;
interface
uses
Windows, SysUtils, Messages, Dialogs, IOUtils, Math, ShellAPI,
OS.EnvironmentVariable, Getter.CodesignVerifier, AsciiCheck;
type
TRufus = class
public
function CheckRufus: Boolean;
procedure RunRufus(const DestDrive, FromISO: String;
const IsISOHybrid: Boolean);
procedure SetRufus(const RufusPath, DriveName, ISOPath: String;
const IsISOHybrid: Boolean);
class function Create: TRufus;
private
function FindMainWindow: THandle;
function FindFTCombo(const MWHandle: THandle): THandle;
function GetFTComboText(const EDTHandle: THandle): String;
function FindDriveCombo(const MWHandle: THandle): THandle;
function EditDriveCombo(const EDTHandle: THandle;
const Text: String): Boolean;
function FindStartButton(const MWHandle: THandle): THandle;
function ClickStartButton(const MWHandle, BTHandle: THandle): Boolean;
function FindConfirmWindow: THandle;
function FindOKButton(const SWHandle: THandle): THandle;
function ClickOKButton(const SWHandle, BTHandle: THandle): Boolean;
function FindCloseButton(const MWHandle: THandle): THandle;
function ClickCloseButton(const MWHandle, BTHandle: THandle): Boolean;
procedure SetRufusToHandle(const MWHandle: THandle;
const DriveName: String; const IsISOHybrid: Boolean);
function IsValidHandle(const Handle: THandle): Boolean;
function FindISOHybridWindow: THandle;
function FindISOHybridOKButton(const SWHandle: THandle): THandle;
procedure WaitForISOHybrid;
end;
var
Rufus: TRufus;
GlobalISOHybridHandleResult: THandle;
implementation
{ TRufus }
const
RufusWinCap = 'Rufus 2.10.973';
RufusWinCap2 = 'Rufus 2.10.973 ';
ISOHybridStr = 'ISOHybrid';
MAX_LENGTH = 1024;
ISOPosition = 5;
StartPosition = 16;
ClosePosition = 17;
var
EnumWindowsWC: Array of WideChar;
function EnumWindowsCallback(Handle: THandle;
LParamAsParameter: DWORD): Boolean; stdcall;
var
ReceivedCaptionStr: String;
SendMessageResult: DWORD;
begin
if SendMessageTimeout(Handle, WM_GETTEXT,
MAX_LENGTH, LParam(@EnumWindowsWC[0]), SMTO_ABORTIFHUNG, 100,
@SendMessageResult) > 0 then
begin
ReceivedCaptionStr := PWideChar(EnumWindowsWC);
if Pos(ISOHybridStr, ReceivedCaptionStr, 1) > 0 then
GlobalISOHybridHandleResult := Handle;
end;
result := true;
end;
function TRufus.CheckRufus: Boolean;
var
CodesignVerifier: TCodesignVerifier;
begin
result := FileExists(EnvironmentVariable.AppPath + 'Rufus\rufus.exe');
if not result then
exit;
CodesignVerifier := TCodesignVerifier.Create;
result := CodesignVerifier.VerifySignByPublisher(
EnvironmentVariable.AppPath + 'Rufus\rufus.exe', 'Akeo Consulting');
FreeAndNil(CodesignVerifier);
end;
procedure TRufus.RunRufus(const DestDrive, FromISO: String;
const IsISOHybrid: Boolean);
var
CutDestDrive: String;
begin
CutDestDrive := Copy(DestDrive, 1, 2);
SetRufus(
EnvironmentVariable.AppPath + '\Rufus\rufus.exe',
CutDestDrive, FromISO, Pos('all.iso', FromISO, 1) > 0);
DeleteFile(FromISO);
end;
function TRufus.IsValidHandle(const Handle: THandle): Boolean;
begin
result := (Handle <> INVALID_HANDLE_VALUE) and (Handle <> 0);
end;
function TRufus.FindMainWindow: THandle;
begin
repeat
Sleep(100);
result := FindWindow(nil, RufusWinCap);
if not IsValidHandle(result) then
result := FindWindow(nil, RufusWinCap2);
until IsValidHandle(result);
end;
function TRufus.FindFTCombo(const MWHandle: THandle): THandle;
var
CurrentCount: Integer;
begin
result := 0;
for CurrentCount := 0 to ISOPosition do
begin
result :=
FindWindowEx(MWHandle, result, 'ComboBox', nil);
end;
end;
function TRufus.GetFTComboText(const EDTHandle: THandle): String;
var
ReceivedCaptionWC: Array of WideChar;
SendMessageResult: DWORD;
begin
SetLength(ReceivedCaptionWC, MAX_LENGTH);
SendMessageTimeout(EDTHandle, WM_GETTEXT,
MAX_LENGTH, LParam(@ReceivedCaptionWC[0]), SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
result := PWideChar(ReceivedCaptionWC);
SetLength(ReceivedCaptionWC, 0);
end;
function TRufus.FindDriveCombo(const MWHandle: THandle): THandle;
var
ReceivedCaptionWC: Array of WideChar;
ReceivedCaptionStr: String;
SendMessageResult: DWORD;
begin
result := 0;
SetLength(ReceivedCaptionWC, MAX_LENGTH);
repeat
result :=
FindWindowEx(MWHandle, result, 'ComboBox', nil);
SendMessageTimeout(result, WM_GETTEXT,
MAX_LENGTH, LParam(@ReceivedCaptionWC[0]), SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
ReceivedCaptionStr := PWideChar(ReceivedCaptionWC);
until Pos(':)', ReceivedCaptionStr) > 0;
end;
function TRufus.EditDriveCombo(const EDTHandle: THandle;
const Text: String): Boolean;
var
ReceivedCaptionWC: Array of WideChar;
ReceivedCaptionStr: String;
CurrItem, AllCount: Integer;
UpperCaseText: String;
SendMessageResult: DWORD;
begin
UpperCaseText := UpperCase(Text);
SendMessageTimeout(EDTHandle, WM_LBUTTONDOWN, 0, 0, SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
Sleep(0);
SendMessageTimeout(EDTHandle, WM_LBUTTONUP, 0, 0, SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
Sleep(0);
SendMessageTimeout(EDTHandle, WM_LBUTTONDOWN, 0, 0, SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
Sleep(0);
SendMessageTimeout(EDTHandle, WM_LBUTTONUP, 0, 0, SMTO_ABORTIFHUNG, 100,
@SendMessageResult);
AllCount := SendMessageTimeout(EDTHandle, CB_GETCOUNT, 0, 0, SMTO_ABORTIFHUNG,
100, @SendMessageResult);
SetLength(ReceivedCaptionWC, MAX_LENGTH);
for CurrItem := 0 to AllCount - 1 do
begin
SendMessageTimeout(EDTHandle, CB_SETCURSEL, CurrItem, 0, SMTO_ABORTIFHUNG,
100, @SendMessageResult);
SendMessageTimeout(EDTHandle, CB_GETITEMDATA, CurrItem, 0, SMTO_ABORTIFHUNG,
100, @SendMessageResult);
SendMessageTimeout(EDTHandle, WM_GETTEXT,
MAX_LENGTH, LParam(@ReceivedCaptionWC[0]), SMTO_ABORTIFHUNG,
100, @SendMessageResult);
ReceivedCaptionStr := PWideChar(ReceivedCaptionWC);
if Pos(UpperCaseText, ReceivedCaptionStr) > 0 then
break;
SendMessageTimeout(EDTHandle, WM_KEYDOWN, VK_DOWN, 0, SMTO_ABORTIFHUNG,
100, @SendMessageResult);
SendMessageTimeout(EDTHandle, WM_KEYUP, VK_DOWN, 0, SMTO_ABORTIFHUNG,
100, @SendMessageResult);
end;
result := GetLastError = 0;
end;
function TRufus.FindStartButton(const MWHandle: THandle): THandle;
var
CurrentCount: Integer;
begin
result := 0;
for CurrentCount := 0 to StartPosition do
begin
result :=
FindWindowEx(MWHandle, result, 'Button', nil);
end;
end;
function TRufus.ClickStartButton(const MWHandle, BTHandle: THandle): Boolean;
begin
exit(
PostMessage(MWHandle, WM_COMMAND,
MakeLong(GetDlgCtrlID(BTHandle), BN_CLICKED), LPARAM(BTHandle)));
end;
class function TRufus.Create: TRufus;
begin
if Rufus = nil then
result := inherited Create as self
else
result := Rufus;
end;
function TRufus.FindConfirmWindow: THandle;
begin
repeat
Sleep(100);
result := FindWindow(Nil, 'Rufus');
until (result <> INVALID_HANDLE_VALUE) and
(result <> 0);
end;
function TRufus.FindISOHybridWindow: THandle;
begin
GlobalISOHybridHandleResult := INVALID_HANDLE_VALUE;
SetLength(EnumWindowsWC, MAX_LENGTH);
ZeroMemory(EnumWindowsWC, MAX_LENGTH);
while GlobalISOHybridHandleResult = INVALID_HANDLE_VALUE do
EnumWindows(@EnumWindowsCallback, 0);
result := GlobalISOHybridHandleResult;
end;
function TRufus.FindISOHybridOKButton(const SWHandle: THandle): THandle;
begin
result :=
FindWindowEx(SWHandle, 0, 'Button', nil);
result :=
FindWindowEx(SWHandle, result, 'Button', nil);
end;
procedure TRufus.WaitForISOHybrid;
var
ISOHybridHandleResult: THandle;
OKButtonHandle: THandle;
begin
ISOHybridHandleResult := FindISOHybridWindow;
while ISOHybridHandleResult <> INVALID_HANDLE_VALUE do
begin
OKButtonHandle := FindISOHybridOKButton(ISOHybridHandleResult);
ClickOKButton(ISOHybridHandleResult, OKButtonHandle);
GlobalISOHybridHandleResult := INVALID_HANDLE_VALUE;
ZeroMemory(EnumWindowsWC, MAX_LENGTH);
EnumWindows(@EnumWindowsCallback, 0);
ISOHybridHandleResult := GlobalISOHybridHandleResult;
end;
end;
function TRufus.FindOKButton(const SWHandle: THandle): THandle;
begin
result :=
FindWindowEx(SWHandle, 0, 'Button', nil);
end;
function TRufus.ClickOKButton(const SWHandle, BTHandle: THandle): Boolean;
begin
exit(
PostMessage(SWHandle, WM_COMMAND,
MakeLong(GetDlgCtrlID(BTHandle), BN_CLICKED), LPARAM(BTHandle)));
end;
function TRufus.FindCloseButton(const MWHandle: THandle): THandle;
var
CurrentCount: Integer;
begin
result := 0;
for CurrentCount := 0 to ClosePosition do
begin
result :=
FindWindowEx(MWHandle, result, 'Button', nil);
end;
end;
function TRufus.ClickCloseButton(const MWHandle, BTHandle: THandle): Boolean;
begin
exit(
PostMessage(MWHandle, WM_COMMAND,
MakeLong(GetDlgCtrlID(BTHandle), BN_CLICKED), LPARAM(BTHandle)));
end;
procedure TRufus.SetRufusToHandle(const MWHandle: THandle;
const DriveName: String; const IsISOHybrid: Boolean);
var
FileTypeComboHandle: THandle;
DriveComboHandle: THandle;
StartButtonHandle: THandle;
SWHandle: THandle;
OKButtonHandle: THandle;
CloseButtonHandle: THandle;
begin
repeat
FileTypeComboHandle := FindFTCombo(MWHandle);
Sleep(10);
until Pos('ISO', GetFTComboText(FileTypeComboHandle), 1) > 0;
DriveComboHandle := FindDriveCombo(MWHandle);
EditDriveCombo(DriveComboHandle, DriveName);
StartButtonHandle := FindStartButton(MWHandle);
ClickStartButton(MWHandle, StartButtonHandle);
if IsISOHybrid then
WaitForISOHybrid;
repeat
SWHandle := FindConfirmWindow;
OKButtonHandle := FindOKButton(SWHandle);
ClickOKButton(SWHandle, OKButtonHandle);
Sleep(100);
until not IsWindowEnabled(DriveComboHandle);
repeat
Sleep(100);
until IsWindowEnabled(DriveComboHandle);
CloseButtonHandle := FindCloseButton(MWHandle);
ClickCloseButton(MWHandle, CloseButtonHandle);
end;
procedure TRufus.SetRufus(const RufusPath, DriveName, ISOPath: String;
const IsISOHybrid: Boolean);
var
MWHandle: THandle;
begin
if not StringHelper.IsAscii(ISOPath) then
raise EInvalidArgument.Create(
'Invalid argument: Don''t use unicode to rufus');
ShellExecute(0, 'open',
PChar(RufusPath),
PChar('--iso="' + ISOPath + '"'),
PChar(ExtractFilePath(RufusPath)), SW_NORMAL);
MWHandle := FindMainWindow;
SetRufusToHandle(MWHandle, DriveName, IsISOHybrid);
end;
initialization
Rufus := TRufus.Create;
finalization
Rufus.Free;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ CGI/WinCGI Web server application components }
{ }
{ Copyright (c) 1997-2001 Borland Software Corporation }
{ }
{*******************************************************}
{$DENYPACKAGEUNIT}
unit IsapiStubApp;
interface
uses Windows, Classes, IsapiHTTP, HTTPApp, WebBroker, IniFiles, Isapi2;
type
TISAPIStubRequest = class(TISAPIRequest)
public
function TranslateURI(const URI: string): string; override;
function WriteString(const AString: string): Boolean; override;
end;
TISAPIStubResponse = class(TISAPIResponse)
protected
function GetContent: string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetLogMessage: string; override;
function GetStatusCode: Integer; override;
function GetStringVariable(Index: Integer): string; override;
procedure SetContent(const Value: string); override;
procedure SetDateVariable(Index: Integer; const Value: TDateTime); override;
procedure SetIntegerVariable(Index: Integer; Value: Integer); override;
procedure SetLogMessage(const Value: string); override;
procedure SetStatusCode(Value: Integer); override;
procedure SetStringVariable(Index: Integer; const Value: string); override;
procedure InitResponse; override;
public
procedure SendResponse; override;
procedure SendRedirect(const URI: string); override;
procedure SendStream(AStream: TStream); override;
end;
implementation
uses SysUtils, BrkrConst, ISAPIApp;
type
TISAPIStubFactory = class(TISAPIFactory)
protected
function NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest; override;
function NewResponse(ISAPIRequest: TISAPIRequest): TISAPIResponse; override;
end;
{ TISAPIStubRequest }
function TISAPIStubRequest.TranslateURI(const URI: string): string;
begin
Assert(False, 'Unexpected call');
end;
function TISAPIStubRequest.WriteString(const AString: string): Boolean;
begin
if AString <> '' then
Result := WriteClient(Pointer(AString)^, Length(AString)) = Length(AString)
else Result := False;
end;
{ TISAPIResponse }
function TISAPIStubResponse.GetContent: string;
begin
Assert(False, 'Unexpected call');
end;
function TISAPIStubResponse.GetDateVariable(Index: Integer): TDateTime;
begin
Assert(False, 'Unexpected call');
Result := Now;
end;
function TISAPIStubResponse.GetIntegerVariable(Index: Integer): Integer;
begin
Assert(False, 'Unexpected call');
Result := 0;
end;
function TISAPIStubResponse.GetLogMessage: string;
begin
// Result := TISAPIRequest(HTTPRequest).ECB.lpszLogData;
end;
function TISAPIStubResponse.GetStatusCode: Integer;
begin
Assert(False, 'Unexpected call');
Result := 0;
end;
function TISAPIStubResponse.GetStringVariable(Index: Integer): string;
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SetContent(const Value: string);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SetDateVariable(Index: Integer; const Value: TDateTime);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SetIntegerVariable(Index: Integer; Value: Integer);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SetLogMessage(const Value: string);
begin
// StrPLCopy(TISAPIRequest(HTTPRequest).ECB.lpszLogData, Value, HSE_LOG_BUFFER_LEN);
end;
procedure TISAPIStubResponse.SetStatusCode(Value: Integer);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SetStringVariable(Index: Integer; const Value: string);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SendResponse;
begin
// Ignore SendResponse, COM object is responsible for
// formatting headers and content into HTTP response
// This method will be called because the FSent instance
// variable is not being set.
end;
procedure TISAPIStubResponse.SendRedirect(const URI: string);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.SendStream(AStream: TStream);
begin
Assert(False, 'Unexpected call');
end;
procedure TISAPIStubResponse.InitResponse;
begin
// Do not initialize properties. The
// COM objects is responsible for setting all
// response fields.
end;
{ TISAPIStubFactory }
function TISAPIStubFactory.NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest;
begin
Result := TISAPIStubRequest.Create(@AECB);
end;
function TISAPIStubFactory.NewResponse(
ISAPIRequest: TISAPIRequest): TISAPIResponse;
begin
Result := TISAPIStubResponse.Create(ISAPIRequest);
end;
initialization
TISAPIStubFactory.Create;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBPlatform;
interface
uses System.SysUtils, Data.FMTBcd, Data.DB
{$IF DEFINED(CLR)}
, System.Runtime.InteropServices
{$IFEND}
;
type
TPlatformBytes = class
class procedure StringToBytes(Value: String; Bytes: array of byte); static;
class procedure WideStringToBytes(Value: WideString; Bytes: array of byte); static;
class procedure Int16ToBytes(Value: SmallInt; Bytes: array of byte); static;
class procedure Int32ToBytes(Value: Integer; Bytes: array of byte); static;
class procedure Int64ToBytes(Value: Int64; Bytes: array of byte); static;
class procedure DoubleToBytes(Value: Double; Bytes: array of byte); static;
class procedure BcdToBytes(Value: TBcd; Bytes: array of byte); static;
class procedure TimeStampToBytes(Value: TBcd; Bytes: array of byte); static;
end;
{$IF DEFINED(CLR)}
TValueBuffer = IntPtr;
TPSResult = TObject;
{$ELSE}
TValueBuffer = Pointer;
TPSResult = Pointer;
{$IFEND}
TPlatformRecordBuffer = class
class function CreateRecordBuffer(Length: Integer): TRecordBuffer; static;
class procedure Free(Buffer: TRecordBuffer); static;
class procedure SetFMTBcd(Buffer: TRecordBuffer; value: TBcd); static;
class procedure GetFMTBcd(Buffer: TRecordBuffer; var value: TBcd); static;
class procedure FillChar(Buffer: TRecordBuffer; Length: Integer; value: Byte); static;
class procedure Copy(Buffer: TRecordBuffer; Dest: TBytes; Offset: Integer; Length: Integer); static;
end;
TPlatformValueBuffer = class
class function CreateValueBuffer(Length: Integer): TValueBuffer; static;
class procedure Free(Buffer: TValueBuffer); static;
class procedure Copy(Buffer: TValueBuffer; Dest: TBytes; Offset: Integer; Count: Integer); overload; static; inline;
class procedure Copy(Source: TBytes; Offset: Integer; Buffer: TValueBuffer; Count: Integer); overload; static; inline;
end;
TPlatformPSResult = class
class procedure SetPSResult(var PSResult: TPSResult; Value: TObject); static;
end;
TPlatformField = class
class function AsWideString(Field: TField): WideString; static;
end;
implementation
{ TPlatformRecordBuffer }
{$IF DEFINED(CLR)}
class function TPlatformRecordBuffer.CreateRecordBuffer(
Length: Integer): TRecordBuffer;
begin
Result := Marshal.AllocHGlobal(Length);
end;
class procedure TPlatformRecordBuffer.Free(Buffer: TRecordBuffer);
begin
Marshal.FreeHGlobal(Buffer);
end;
class procedure TPlatformRecordBuffer.SetFMTBcd(Buffer: TRecordBuffer;
value: TBcd);
begin
Assert(false, 'TPlatformRecordBuffer.SetFMTBcd not implemented yet');
// TBcd.ToBytes(AsFMTBcd)
// TBcd(Buffer^) := AsFMTBcd
end;
class procedure TPlatformRecordBuffer.FillChar(Buffer: TRecordBuffer;
Length: Integer; value: Byte);
var
J: Integer;
begin
for J := 0 to Length - 1 do
Marshal.WriteByte(Buffer, J, value);
end;
class procedure TPlatformRecordBuffer.GetFMTBcd(Buffer: TRecordBuffer;
var value: TBcd);
var
Temp: TBytes;
begin
SetLength(Temp, SizeOfTBcd);
Marshal.Copy(Buffer, Temp, 0, SizeOfTBcd);
value := TBcd.FromBytes(Temp);
end;
class procedure TPlatformRecordBuffer.Copy(Buffer: TRecordBuffer;
Dest: array of Byte; Offset, Length: Integer);
begin
Marshal.Copy(Buffer, Dest, Offset, Length);
end;
{$ELSE}
class function TPlatformRecordBuffer.CreateRecordBuffer(
Length: Integer): TRecordBuffer;
begin
Result := AllocMem(Length);
end;
class procedure TPlatformRecordBuffer.Free(Buffer: TRecordBuffer);
begin
FreeMem(Buffer);
end;
class procedure TPlatformRecordBuffer.FillChar(Buffer: TRecordBuffer;
Length: Integer; value: Byte);
begin
System.FillChar(Buffer^, Length, value);
end;
class procedure TPlatformRecordBuffer.SetFMTBcd(Buffer: TRecordBuffer;
value: TBcd);
begin
TBcd(Pointer(Buffer)^) := value;
end;
class procedure TPlatformRecordBuffer.GetFMTBcd(Buffer: TRecordBuffer;
var value: TBcd);
var
SBcd: string;
begin
SBcd := BcdToStr(PBcd(Buffer)^);
value := StrToBcd(SBcd);
end;
class procedure TPlatformRecordBuffer.Copy(Buffer: TRecordBuffer;
Dest: TBytes; Offset, Length: Integer);
begin
Move(Buffer^, Dest[Offset], Length);
end;
{$IFEND}
{ TPlatformPSResult }
{$IF DEFINED(CLR)}
class procedure TPlatformPSResult.SetPSResult(var PSResult: TPSResult;
Value: TObject);
begin
PSResult := Value;
end;
{$ELSE}
class procedure TPlatformPSResult.SetPSResult(var PSResult: TPSResult;
Value: TObject);
begin
TObject(PSResult^) := Value;
end;
{$IFEND}
{ TPlatformField }
{$IF DEFINED(CLR)}
class function TPlatformField.AsWideString(Field: TField): WideString;
begin
Result := Field.AsString;
end;
{$ELSE}
class function TPlatformField.AsWideString(Field: TField): WideString;
begin
Result := Field.AsWideString;
end;
{$IFEND}
{ TPlatformValueBuffer }
{$IF DEFINED(CLR)}
class function TPlatformValueBuffer.CreateValueBuffer(
Length: Integer): TValueBuffer;
begin
Result := Marshal.AllocHGlobal(Length);
end;
class procedure TPlatformValueBuffer.Free(Buffer: TValueBuffer);
begin
Marshal.FreeHGlobal(Buffer);
end;
class procedure TPlatformValueBuffer.Copy(Buffer: TValueBuffer;
Dest: TBytes; Offset: Integer; Count: Integer);
begin
Marshal.Copy(Buffer, Dest, Offset, Count);
end;
class procedure TPlatformValueBuffer.Copy(Source: TBytes;
Offset: Integer; Buffer: TValueBuffer; Count: Integer);
begin
Marshal.Copy(Source, Offset, Buffer, Count);
end;
{$ELSE}
class function TPlatformValueBuffer.CreateValueBuffer(
Length: Integer): TValueBuffer;
begin
Result := AllocMem(Length);
end;
class procedure TPlatformValueBuffer.Free(Buffer: TValueBuffer);
begin
FreeMem(Buffer);
end;
{$INLINE ON}
class procedure TPlatformValueBuffer.Copy(Buffer: TValueBuffer;
Dest: TBytes; Offset, Count: Integer);
begin
Move(Buffer^, Dest[Offset], Count);
end;
class procedure TPlatformValueBuffer.Copy(Source: TBytes;
Offset: Integer; Buffer: TValueBuffer; Count: Integer);
begin
Move(Source[Offset], Buffer^, Count);
end;
{$INLINE OFF}
{$IFEND}
{ TPlatformBytes }
class procedure TPlatformBytes.BcdToBytes(Value: TBcd; Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.DoubleToBytes(Value: Double;
Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.Int16ToBytes(Value: SmallInt;
Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.Int32ToBytes(Value: Integer;
Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.Int64ToBytes(Value: Int64; Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.StringToBytes(Value: String;
Bytes: array of byte);
begin
Assert(false);
{$IF DEFINED(CLR)}
{$ELSE}
// Move(PCHAR(Value), Bytes, Length(Value));
{$IFEND}
end;
class procedure TPlatformBytes.TimeStampToBytes(Value: TBcd;
Bytes: array of byte);
begin
Assert(false);
end;
class procedure TPlatformBytes.WideStringToBytes(Value: WideString;
Bytes: array of byte);
begin
Assert(false);
end;
end.
|
unit ANU_OMAC;
(*************************************************************************
DESCRIPTION : Anubis (tweaked) OMAC1/2 routines
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : OMAC page: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
T.Iwata and K.Kurosawa. OMAC: One-Key CBC MAC - Addendum
(http://csrc.nist.gov/CryptoToolkit/modes/proposedmodes/omac/omac-ad.pdf)
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 05.08.08 W.Ehrhardt Initial version analog AES_OMAC
0.11 24.11.08 we Uses BTypes
0.12 01.08.10 we EAX_OMAC_Update with ILen: longint, XL Version with $define OLD_XL_Version
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
{.$define OLD_XL_Version}
interface
uses
BTypes, ANU_Base;
function ANU_OMAC_Init({$ifdef CONST} const Key {$else} var Key {$endif};
KeyBits: word; var ctx: TANUContext): integer;
{-OMAC init: Anubis key expansion, error if inv. key size}
{$ifdef DLL} stdcall; {$endif}
function ANU_OMAC_Update(data: pointer; ILen: longint; var ctx: TANUContext): integer;
{-OMAC data input, may be called more than once}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_OMAC_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC=OMAC1 tag}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_OMAC1_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC1 tag}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_OMAC2_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC2 tag}
{$ifdef DLL} stdcall; {$endif}
{$ifdef OLD_XL_Version}
function ANU_OMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TANUContext): integer;
{-OMAC data input, may be called more than once}
{$endif}
{---------------------------------------------------------------------------}
{interfaced for ANU_CMAC, no need for OMAC usage}
procedure ANU_OMACx_Final(OMAC2: boolean; var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC tag}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
function ANU_OMAC_Init({$ifdef CONST} const Key {$else} var Key {$endif};
KeyBits: word; var ctx: TANUContext): integer;
{-OMAC init: Anubis key expansion, error if inv. key size}
begin
{Anubis key expansion, error if inv. key size}
{IV = Y[0] = [0]}
ANU_OMAC_Init := ANU_Init_Encr(Key, KeyBits, ctx);
if ANU_GetFastInit then fillchar(ctx.IV,sizeof(ctx.IV),0);
end;
{---------------------------------------------------------------------------}
function ANU_OMAC_Update(data: pointer; ILen: longint; var ctx: TANUContext): integer;
{-OMAC data input, may be called more than once}
var
n: word;
begin
if (data=nil) and (ILen<>0) then begin
ANU_OMAC_Update := ANU_Err_NIL_Pointer;
exit;
end;
{$ifdef BIT16}
if (ofs(data^)+ILen>$FFFF) then begin
ANU_OMAC_Update := ANU_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
ANU_OMAC_Update := 0;
while ILen>0 do with ctx do begin
if bLen>=ANUBLKSIZE then begin
{process full buffer}
{X[i] := M[i] xor Y[i-1]}
ANU_XorBlock(buf, IV, buf);
ANU_Encrypt(ctx, buf, IV);
bLen := 0;
while ILen>ANUBLKSIZE do with ctx do begin
{continue with full blocks if more }
{than one block remains unprocessed}
{X[i] := M[i] xor Y[i-1]}
ANU_XorBlock(PANUBlock(data)^, IV, buf);
{Y[i] := EK[X[i]}
ANU_Encrypt(ctx, buf, IV);
inc(Ptr2Inc(data), ANUBLKSIZE);
dec(ILen, ANUBLKSIZE); {ILen>0!}
end;
end;
n := ANUBLKSIZE-bLen; if ILen<n then n:=ILen;
{n>0 because ILen>0 and bLen<ANUBLKSIZE}
move(data^, buf[bLen], n);
inc(bLen,n);
inc(Ptr2Inc(data),n);
dec(ILen,n);
end;
end;
{$ifdef OLD_XL_Version}
{---------------------------------------------------------------------------}
function ANU_OMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TANUContext): integer;
{-OMAC data input, may be called more than once}
begin
ANU_OMAC_UpdateXL := ANU_OMAC_Update(data, ILen, ctx);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure ANU_OMACx_Final(OMAC2: boolean; var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC tag}
{Turn off range checking for byte shifts}
{$ifopt R+} {$define SetRPlus} {$else} {$undef SetRPlus} {$endif}
{$R-}
{---------------------------------------}
procedure mul_u(var L: TANUBlock);
{-Calculate L.u}
const
masks: array[0..1] of byte = (0,$87);
var
i: integer;
mask: byte;
begin
mask := masks[L[0] shr 7];
for i:=0 to ANUBLKSIZE-2 do L[i] := (L[i] shl 1) or (L[i+1] shr 7);
L[ANUBLKSIZE-1] := (L[ANUBLKSIZE-1] shl 1) xor mask;
end;
{---------------------------------------}
procedure div_u(var L: TANUBlock);
{-Calculate L.u^-1}
const
mask1: array[0..1] of byte = (0, $43);
mask2: array[0..1] of byte = (0, $80);
var
i,j: integer;
begin
j := L[ANUBLKSIZE-1] and 1;
for i:=ANUBLKSIZE-1 downto 1 do L[i] := (L[i] shr 1) or (L[i-1] shl 7);
L[0] := (L[0] shr 1) xor mask2[j];
L[ANUBLKSIZE-1] := L[ANUBLKSIZE-1] xor mask1[j];
end;
{$ifdef SetRPlus}
{$R+}
{$endif}
begin
with ctx do begin
fillchar(tag, sizeof(tag), 0);
{L := EK(0)}
ANU_Encrypt(ctx, tag, tag);
if blen>=ANUBLKSIZE then begin
{Complete last block, no padding and use L.u}
mul_u(tag);
end
else begin
{Incomplete last block, pad buf and use L.u^2 or L.u^-1}
buf[bLen] := $80;
inc(bLen);
while blen<ANUBLKSIZE do begin
buf[bLen] := 0;
inc(bLen);
end;
if OMAC2 then begin
{calc L.u^-1}
div_u(tag);
end
else begin
{calc L.u^2}
mul_u(tag);
mul_u(tag);
end;
end;
{X[m] := pad(M[n]) xor Y[m-1]}
ANU_XorBlock(buf, IV, buf);
{X[m] := X[m] xor L.u^e, e=-1,1,2}
ANU_XorBlock(buf, tag, buf);
{T := EK(X[m])}
ANU_Encrypt(ctx, buf, tag);
end;
end;
{---------------------------------------------------------------------------}
procedure ANU_OMAC_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC=OMAC1 tag}
begin
ANU_OMACx_Final(false, tag, ctx);
end;
{---------------------------------------------------------------------------}
procedure ANU_OMAC1_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC1 tag}
begin
ANU_OMACx_Final(false, tag, ctx);
end;
{---------------------------------------------------------------------------}
procedure ANU_OMAC2_Final(var tag: TANUBlock; var ctx: TANUContext);
{-end data input, calculate OMAC2 tag}
begin
ANU_OMACx_Final(true, tag, ctx);
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N+} {Numeric coprocessor IS present}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
PROGRAM Cartog;
{ This program plots geographic data from the file
WORLD.DAT and coordinate grids on the Mercator,
Equidistant Cylindrical, Sinusoidal, Hammer, and
Orthographic map projections.
}
Uses
Crt ,
Graph ;
CONST Sqrt2 = 1.4142135623731;
PI = 3.1415926535898;
HalfPI = 1.5707963267949;
TwoPI = 6.2831853071796;
Radian = 1.7453292519943E-2;
RadianDiv100 = 1.7453292519943E-4; { PI/180/100, needed to convert }
{ data in WORLD.DAT to radians }
CONST XCENTER : INTEGER = 320; { ATT Graphics constants. }
YCENTER : INTEGER = 240; { Screen center X and Y }
ASPECT : REAL = 1.33; { 640x400 aspect ratio }
R : REAL = 40; { Default map radius }
NotVisible : INTEGER = -32767; { Flag for point visibility }
TYPE LLREC = RECORD
CODE : ARRAY[0..1] OF CHAR;
LONGI, LATI: INTEGER; END;
VAR LL : LLREC;
LLF : FILE OF LLREC;
VAR LastX, LastY, XP, YP : INTEGER; { Save variables for plotting }
COLOR_GLB : INTEGER;
GraphMode,
GraphDriver : INTEGER;
VAR I, J, K, MapType, M, X1,Y1,
X2, Y2, SX, SY, CENTER : INTEGER;
VAR L, L1, LONGR, LSTEP,
B, LATR, BSTEP, X, Y,
PHI1, Lambda0 : REAL;
VAR XX, YY, SA, SB : REAL;
VAR LastPtVis, GRID : BOOLEAN;
VAR CH : CHAR;
FUNCTION ArcCos(X: REAL): REAL;
BEGIN
IF ABS(X) < 1 THEN ArcCos:= ARCTAN(SQRT(1-SQR(X))/X)
ELSE IF X = 1 THEN ArcCos:= 0
ELSE IF X =-1 THEN ArcCos:= PI;
END; { ArcCos. }
FUNCTION ArcSin(X: REAL): REAL;
BEGIN
IF ABS(X) < 1 THEN ArcSin:= ARCTAN(X/SQRT(1-SQR(X)))
ELSE IF X = 1 THEN ArcSin:= HalfPI
ELSE IF X =-1 THEN ArcSin:=-HalfPI;
END; { ArcSin. }
FUNCTION ArcTanH(X : Real): Real;
VAR A,T : REAL;
BEGIN
T:=ABS(X);
IF T < 1 THEN
BEGIN
A := 0.5 * LN((1 + T)/(1 - T));
IF X < 0 THEN ArcTanH := -A ELSE ArcTanH :=A;
END;
END; { ArcTanH. }
FUNCTION Meridian(Lambda, Lambda0: REAL):REAL;
{ Returns difference between current longitude and map center. }
VAR DelLam : REAL;
BEGIN
DelLam := Lambda - Lambda0;
IF DelLam < -PI THEN DelLam := DelLam + TwoPI
ELSE
IF DelLam > PI THEN DelLam := DelLam - TwoPI;
Meridian:=DelLam;
END; { Meridian. }
PROCEDURE Mercator(Lambda, Lambda0, Phi, R : REAL; VAR X, Y : REAL);
{ For R = 1: -Pi <= X <= Pi, -Pi/2 <= Y <= Pi/2. }
CONST MaxLat : REAL = 1.397; {~80 degrees. }
{ REAL = 1.483; ~85 degrees. }
BEGIN
IF ABS(Phi) < MaxLat THEN
BEGIN
Lambda := Meridian(Lambda, Lambda0);
X := R * Lambda;
Y := R * ArcTanH(SIN(Phi));
END
ELSE X := NotVisible;
END; { Mercator. }
PROCEDURE EquiCyl(Lambda, Lambda0, Phi, Phi1, R : REAL; VAR X, Y : REAL);
{ For R = 1: -Pi <= X <= Pi, -Pi/2 <= Y <= Pi/2. }
BEGIN
Lambda := Meridian(Lambda, Lambda0);
X := R * Lambda * COS(Phi1);
Y := R * Phi;
END; { EquiCyl. }
PROCEDURE Sinusoidal(Lambda, Lambda0, Phi, R : REAL; VAR X, Y : REAL);
{ For R = 1: -Pi <= X <= Pi and -Pi/2 <= Y <= Pi/2. }
BEGIN
Lambda := Meridian(Lambda, Lambda0);
X := R * Cos(Phi) * Lambda ;
Y := R * Phi;
END; { Sinusoidal. }
PROCEDURE Hammer(Lambda, Lambda0, Phi, R : REAL; VAR X, Y : REAL);
{ For R = 1: -2û2 <= X <=2û2 and - û2 <= Y <= û2. }
VAR K, CosPhi, HalfLambda : REAL;
BEGIN
HalfLambda := 0.5*Meridian(Lambda, Lambda0);
CosPhi:=COS(Phi);
K := R * SQRT2 / SQRT(1 +CosPhi * COS(HalfLambda));
X := 2 * K * CosPhi * (SIN(HalfLambda));
Y := K * SIN(Phi);
END; { Hammer. }
PROCEDURE Orthographic(Lambda, Lambda0, Phi, Phi1, R: REAL; VAR X, Y : REAL);
{ For R = 1: -2 <= X,Y <= 2. }
VAR CosC, CosL, SinPhi1, CosPhi1, SinPhi, CosPhi, R2 : Real;
BEGIN
Lambda :=Meridian(Lambda, Lambda0); R2:=R+R;
CosPhi1:=COS(Phi1); SinPhi1:=SIN(Phi1);
CosPhi :=COS(Phi); SinPhi:= SIN(Phi);
CosL :=COS(Lambda)*CosPhi;
CosC :=SinPhi1 * SinPhi + CosPhi1 * COSL;
IF CosC >= 0 THEN
BEGIN
X :=R2 * CosPhi * SIN(Lambda);
Y :=R2 * (CosPhi1 * SinPhi - SinPhi1 * COSL);
END ELSE X:=NotVisible;
END; { Orthographic. }
PROCEDURE Beep;
{ Sounds a tone when map is complete. }
BEGIN
Sound(880); Delay(250); NoSound;
END;
PROCEDURE PlotPt(VAR LastPtVis: BOOLEAN);
{ Draws a line from the last point to the current (XP,YP) if it is visible. }
VAR IX,IY: INTEGER;
LABEL XIT;
BEGIN
IX:=ROUND(XP); IY:=ROUND(YP);
IF LastPtVis THEN Line(LastX,LastY,IX,IY);
LastX:=IX; LastY:=IY;
LastPtVis:=TRUE;
XIT:
END; { PlotPt. }
PROCEDURE CoordinateGrid(OUTLINE: BOOLEAN; MapType: INTEGER);
CONST LatitudeSpacing = 30;
LongitudeSpacing = 30;
VAR Longitude, Latitude, LatLimit,
MaxLat, LongIncr, LatIncr : INTEGER;
VAR LL, PP, A, R2, RA, XN, YN,
SINDT, COSDT : REAL;
BEGIN
CASE MapType OF
1: BEGIN MaxLat:=80; LongIncr:=360; LatIncr:=160; END;
2: BEGIN MaxLat:=90; LongIncr:=360; LatIncr:=180; END;
3: BEGIN MaxLat:=90; LongIncr:=360; LatIncr:=5; END;
4..5: BEGIN Maxlat:=90; LongIncr:=5; LatIncr:=5; END;
END; { CASE...}
LL:=0; PP:=Phi1;
IF OUTLINE THEN
BEGIN
IF MapType = 5 THEN PP:=0;
LatLimit:=MaxLat; { Draw only extreme latitudes }
{ to make map outline }
END
ELSE LatLimit:= MaxLat DIV LatitudeSpacing*LatitudeSpacing;
Latitude:=LatLimit;
WHILE Latitude >= -LatLimit DO { Draw parallels }
BEGIN
LATR:=Latitude*Radian;
LastPtVis:=FALSE;
Longitude:=-180;
WHILE Longitude <= 180 DO
BEGIN
LONGR:=Longitude*Radian;
CASE MapType OF
1: BEGIN MERCATOR(LONGR, LL, LATR, R, X, Y); END;
2: BEGIN EQUICYL(LONGR, LL, LATR, PP, R, X, Y); END;
3: BEGIN SINUSOIDAL(LONGR, LL, LATR, R, X, Y); END;
4: BEGIN HAMMER(LONGR, LL, LATR, R, X, Y); END;
5: BEGIN ORTHOGRAPHIC (LONGR, LL, LATR, PP, R, X, Y); END;
END; { CASE...}
IF X > -300 THEN
BEGIN
XP:=ROUND(X*ASPECT)+XCENTER;
YP:=YCENTER-ROUND(Y);
PlotPt(LastPtVis);
END ELSE LastPtVis:=FALSE;
Longitude:=Longitude+LongIncr;
END;
IF OUTLINE THEN
Latitude:=Latitude-2*MaxLat
ELSE
Latitude:=Latitude-LatitudeSpacing;
END;
IF OUTLINE THEN LL:=0 ELSE LL:=Lambda0;
Longitude:=-180; { Draw meridians }
IF MapType >= 4 THEN MaxLat:=90;
WHILE Longitude <= 180 DO
BEGIN
LONGR:=Longitude*Radian;
LastPtVis:=FALSE;
Latitude:=MaxLat;
WHILE Latitude >= -MaxLat DO
BEGIN
LATR:=Latitude*Radian;
CASE MapType OF
1: BEGIN MERCATOR(LONGR, LL, LATR, R, X, Y); END;
2: BEGIN EQUICYL(LONGR, LL, LATR, PP, R, X, Y); END;
3: BEGIN SINUSOIDAL(LONGR, LL, LATR, R, X, Y); END;
4: BEGIN HAMMER(LONGR, LL, LATR, R, X, Y); END;
5: BEGIN ORTHOGRAPHIC( LONGR, LL, LATR, PP, R, X, Y); END;
END; { CASE...}
IF X > -300 THEN
BEGIN
XP:=ROUND(X*ASPECT)+XCENTER;
YP:=YCENTER-ROUND(Y);
PlotPt(LastPtVis);
END ELSE LastPtVis:=FALSE;
Latitude:=Latitude-LatIncr;
END;
IF OUTLINE THEN
Longitude:=Longitude+360
ELSE
Longitude:=Longitude+LongitudeSpacing;
END;
IF OUTLINE AND (MapType=5) THEN
BEGIN
A:=0; { Draw circular outline }
LastPtVis:=False;
R2:=R + R;
RA:= R2 * Aspect;
SINDT:= 0.05996400648;
COSDT:= 0.99820053993;
X:=1; Y:=0;
XP:= ROUND(XCENTER + RA);
YP:= ROUND(YCENTER);
PlotPt(LastPtVis);
WHILE A <= TwoPI DO
BEGIN { Compute points on the circle }
XN:= X * COSDT - Y * SINDT;
YN:= X * SINDT + Y * COSDT;
X:= XN; Y:= YN;
XP:= XCENTER + ROUND(X*RA);
YP:= YCENTER + ROUND(Y*R2);
PlotPt(LastPtVis);
A:= A+0.06;
END; { While. }
END;
END; { CoordinateGrid. }
PROCEDURE DrawMap(MapType: INTEGER);
VAR Latitude, Longitude : REAL;
VAR LastX : INTEGER;
LABEL XIT;
BEGIN
LastPtVis:=FALSE; LastX:=0;
ASSIGN(LLF, '\TP\PROGS\WORLD.DAT'); RESET(LLF);
WHILE NOT EOF(LLF) DO
BEGIN
READ(LLF, LL);
IF KeyPressed THEN GOTO XIT;
LONGR:=LL.LONGI * RadianDiv100;
LATR :=LL.LATI * RadianDiv100;
IF LL.CODE = 'LS' THEN LastPtVis:=FALSE;
IF (LL.CODE = 'S ') OR (LL.CODE = 'LS') THEN
BEGIN
CASE MapType OF
1: BEGIN MERCATOR(LONGR, Lambda0, LATR, R, X, Y); END;
2: BEGIN EQUICYL(LONGR, Lambda0, LATR, Phi1, R, X, Y); END;
3: BEGIN SINUSOIDAL(LONGR, Lambda0, LATR, R, X, Y); END;
4: BEGIN HAMMER(LONGR, Lambda0, LATR, R, X, Y); END;
5: BEGIN ORTHOGRAPHIC(LONGR, Lambda0, LATR, Phi1, R, X, Y); END;
END; { CASE...}
IF X > -300 THEN
BEGIN
XP:=ROUND(X*ASPECT)+XCENTER;
IF ABS(LastX-XP) > 100 THEN LastPtVis:=FALSE;
YP:= YCENTER-ROUND(Y);
PlotPt(LastPtVis); LastX:=XP;
END ELSE LastPtVis:=FALSE;
END;
END;
XIT:
END; { DrawMap. }
(* --------------------- MAIN PROGRAM ------------------ *)
VAR RESP : CHAR;
LABEL XIT;
BEGIN
MapType:=1;
WHILE MapType > 0 DO (* MENU *)
BEGIN
ClrScr;
GOTOXY(24,1); WRITE('C A R T O G');
LowVideo;
{! 1. Th^e effects of HighVideo,LowVideo,NormVideo are different in Turbo 4.0.}
GOTOXY(1,24);
WRITE('':4,'Copyright 1987 by Robert Miller and Francis Reddy');
GOTOXY(1,3);
WRITELN(' ':4,'To PLOT: Choose a projection. Enter the Central ');
WRITELN(' ':4,'Meridian of the map (180 to -180 degrees, longitudes');
WRITELN(' ':4,'west of Greenwich negative). If applicable, enter');
WRITELN(' ':4,'the Standard Parallel (90 to -90 degrees, southern');
WRITELN(' ':4,'latitudes negative). The file WORLD.DAT must also be');
WRITELN(' ':4,'on the logged drive. A tone means the map is done.');
WRITELN;
WRITELN(' ':4,'Any key ABORTS plot. Hit return to restore MENU.');
NormVideo;
{! 2. Th^e effects of HighVideo,LowVideo,NormVideo are different in Turbo 4.0.}
WRITELN;
WRITELN;
WRITE(' ':6,'1. Mercator');
WRITELN(' ':21,'4. Hammer');
WRITE(' ':6,'2. Equidistant Cylindrical');
WRITELN(' ':6,'5. Orthographic');
WRITELN(' ':6,'3. Sinusoidal');
WRITELN;
WRITE(' ':8,'Projection number (1-5) or 0 to quit: ');
READLN(MapType);
If MapType = 0 THEN GOTO XIT;
WRITELN;
WRITE(' ':8,'Central Longitude of Map (default = 0): ');
Lambda0:=0;
READLN(Lambda0); Lambda0:=Lambda0*Radian;
IF (MapType = 2) OR (MapType = 5) THEN
BEGIN
WRITE(' ':8,'Central Latitude of Map (default = 0): ');
Phi1:=0; READLN(Phi1);
IF Phi1 = 90 THEN Phi1 := HalfPI
ELSE
Phi1:=Phi1*Radian;
END;
IF MapType >= 4 THEN R:=83 ELSE R:=70;
WRITE(' ':8,'Plot grid, continents or both (G/C/B)? ');
READLN(RESP); RESP:=UPCASE(RESP);
GRID:=(RESP ='G') OR (RESP = 'B');
GraphDriver := VGA { ATT400 };
GraphMode := VGAHi { ATT400HI };
InitGraph(GraphDriver,GraphMode,'');
(*
HiRes; HiResColor(15); { Set CGA Graphics Mode }
*)
IF GRID THEN CoordinateGrid(FALSE, MapType);
CoordinateGrid(TRUE, MapType);
IF (RESP = 'B') OR (RESP = 'C') THEN DrawMap(MapType);
Beep;
XIT:
IF MapType > 0 THEN
While NOT KeyPressed DO ; { Wait for key strike }
CloseGraph;
(* TEXTMODE(BW80); { Return to Text Mode }
*)
ClrScr;
END; { WHILE MapType > 0...}
END.
|
unit Vigilante.Infra.ChangeSetItem.JSONDataAdapter;
interface
uses
System.SysUtils, System.JSON, System.Generics.Collections,
Vigilante.Infra.ChangeSetItem.DataAdapter;
type
TChangeSetItemAdapterJSON = class(TInterfacedObject, IChangeSetItemAdapter)
private
FChangeSet: TJSONObject;
FAutor: string;
FArquivos: TList<TFileName>;
FDescricao: string;
procedure CarregarInformacoes;
procedure CarregarListaArquivos;
procedure CarregarAutor;
public
constructor Create(const AChangeSetItem: TJSONObject);
destructor Destroy; override;
function GetAutor: string;
function GetDescricao: string;
function GetArquivos: TArray<TFileName>;
end;
implementation
constructor TChangeSetItemAdapterJSON.Create(const AChangeSetItem: TJSONObject);
begin
FArquivos := TList<TFileName>.Create;
FChangeSet := AChangeSetItem;
CarregarInformacoes;
end;
destructor TChangeSetItemAdapterJSON.Destroy;
begin
FArquivos.Clear;
FreeAndNil(FArquivos);
inherited;
end;
procedure TChangeSetItemAdapterJSON.CarregarInformacoes;
begin
FDescricao := FChangeSet.GetValue('msg').Value;
CarregarAutor;
CarregarListaArquivos;
end;
procedure TChangeSetItemAdapterJSON.CarregarAutor;
var
_author: TJSONObject;
begin
_author := FChangeSet.GetValue('author') as TJSONObject;
FAutor := _author.GetValue('fullName').Value;
end;
procedure TChangeSetItemAdapterJSON.CarregarListaArquivos;
var
_arquivosAlterados: TJSONArray;
_item: TJSONValue;
begin
_arquivosAlterados := FChangeSet.GetValue('affectedPaths') as TJSONArray;
for _item in _arquivosAlterados do
FArquivos.Add(_item.Value);
end;
function TChangeSetItemAdapterJSON.GetAutor: string;
begin
Result := FAutor;
end;
function TChangeSetItemAdapterJSON.GetDescricao: string;
begin
Result := FDescricao;
end;
function TChangeSetItemAdapterJSON.GetArquivos: TArray<TFileName>;
begin
Result := FArquivos.ToArray;
end;
end.
|
{
Version 12
Copyright (c) 1995-2008 by L. David Baldwin,
Copyright (c) 2008-2010 by HtmlViewer Team
Copyright (c) 2011-2012 by Bernd Gabriel
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.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit HtmlCaches;
interface
uses
SysUtils,
HtmlGlobals;
type
//BG, 30.04.2011:
ThtCachable = class(TObject)
private
AccessCount: Integer;
UsageCount: Integer; {how many times in use}
public
destructor Destroy; override;
procedure BeginUse;
procedure EndUse;
end;
//------------------------------------------------------------------------------
// ThtCache is the cache, that holds the above cacheable items.
//------------------------------------------------------------------------------
ThtCache = class(ThtStringList)
private
FMaxCache: Integer;
function GetObject(Index: Integer): ThtCachable; reintroduce;
protected
function GetCachable(I: Integer): ThtCachable; {$ifdef UseInline} inline; {$endif}
property Objects[Index: Integer]: ThtCachable read GetObject;
public
constructor Create;
destructor Destroy; override;
function AddObject(const S: ThtString; AObject: ThtCachable): Integer; reintroduce;
procedure BumpAndCheck;
procedure Clear; override;
procedure DecUsage(const S: ThtString);
procedure IncUsage(const S: ThtString);
procedure PurgeCache;
procedure SetCacheCount(N: Integer);
property MaxCache: Integer read FMaxCache;
end;
implementation
{ ThtCachable }
//-- BG ---------------------------------------------------------- 16.04.2011 --
procedure ThtCachable.BeginUse;
begin
Inc(UsageCount);
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
destructor ThtCachable.Destroy;
begin
Assert(UsageCount = 0, 'Freeing cached ' + ClassName + ' that''s still in use ' + IntToStr(UsageCount) + ' time/s.' );
inherited;
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
procedure ThtCachable.EndUse;
begin
Dec(UsageCount);
Assert(UsageCount >= 0, 'Cached ' + ClassName + ' usage count < 0');
end;
{ ThtCache }
//------------------------------------------------------------------------------
function ThtCache.AddObject(const S: ThtString; AObject: ThtCachable): Integer;
begin
Result := inherited AddObject(S, AObject);
Inc(AObject.UsageCount);
end;
//------------------------------------------------------------------------------
procedure ThtCache.BumpAndCheck;
var
I: Integer;
Tmp: ThtCachable;
begin
for I := Count - 1 downto 0 do
begin
Tmp := Objects[I];
Inc(Tmp.AccessCount);
if (Tmp.AccessCount > FMaxCache) and (Tmp.UsageCount <= 0) then
begin
Delete(I);
Tmp.Free; {the ThtCachable}
end;
end;
end;
//------------------------------------------------------------------------------
procedure ThtCache.Clear;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Objects[I].Free;
inherited Clear;
end;
//------------------------------------------------------------------------------
constructor ThtCache.Create;
begin
inherited Create;
FMaxCache := 100;
Sorted := True;
end;
//------------------------------------------------------------------------------
procedure ThtCache.DecUsage(const S: ThtString);
var
I: Integer;
begin
I := IndexOf(S);
if I >= 0 then
Objects[I].EndUse;
end;
//------------------------------------------------------------------------------
destructor ThtCache.Destroy;
begin
Clear;
inherited Destroy;
end;
//------------------------------------------------------------------------------
function ThtCache.GetCachable(I: Integer): ThtCachable;
begin
Result := Objects[I];
Result.AccessCount := 0;
Inc(Result.UsageCount);
end;
//-- BG ---------------------------------------------------------- 06.03.2011 --
function ThtCache.GetObject(Index: Integer): ThtCachable;
begin
Result := ThtCachable(inherited GetObject(Index));
end;
//------------------------------------------------------------------------------
procedure ThtCache.IncUsage(const S: ThtString);
var
I: Integer;
begin
I := IndexOf(S);
if I >= 0 then
Objects[I].BeginUse;
end;
//------------------------------------------------------------------------------
procedure ThtCache.PurgeCache;
var
I: Integer;
Tmp: ThtCachable;
begin
for I := Count - 1 downto 0 do
begin
Tmp := Objects[I];
if (Tmp.UsageCount <= 0) then
begin
Delete(I);
Tmp.Free; {the ThtCachable}
end;
end;
end;
//------------------------------------------------------------------------------
procedure ThtCache.SetCacheCount(N: Integer);
var
I: Integer;
begin
for I := Count - 1 downto 0 do
with Objects[I] do
begin
if (AccessCount > N) and (UsageCount <= 0) then
begin
Delete(I);
Free;
end;
end;
FMaxCache := N;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC fetch options editing frame }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.UpdateOptions;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.Buttons,
FireDAC.Stan.Option,
FireDAC.VCLUI.Controls;
type
TfrmFDGUIxFormsUpdateOptions = class(TFrame)
uo_GroupBox3: TPanel;
uo_Label4: TLabel;
uo_Label5: TLabel;
uo_edtUpdateTableName: TEdit;
uo_cbxUpdateMode: TComboBox;
uo_cbUpdateChangedFields: TCheckBox;
uo_cbCountUpdatedRecords: TCheckBox;
uo_GroupBox2: TPanel;
uo_Label1: TLabel;
uo_Label2: TLabel;
uo_cbxLockMode: TComboBox;
uo_cbxLockPoint: TComboBox;
uo_cbLockWait: TCheckBox;
uo_GroupBox4: TPanel;
uo_Panel6: TPanel;
uo_PopupMenu1: TPopupMenu;
uo_ReadOnly1: TMenuItem;
uo_ReadWrite1: TMenuItem;
uo_N1: TMenuItem;
uo_Fastupdates1: TMenuItem;
uo_Standardupdates1: TMenuItem;
uo_cbEnableInsert: TCheckBox;
uo_cbEnableUpdate: TCheckBox;
uo_cbEnableDelete: TCheckBox;
uo_SpeedButton1: TSpeedButton;
Label1: TLabel;
uo_cbRefreshMode: TComboBox;
uo_Label6: TLabel;
uo_edtKeyFields: TEdit;
uo_GroupBox5: TPanel;
uo_Label7: TLabel;
uo_cbxFetchGeneratorsPoint: TComboBox;
uo_Label8: TLabel;
uo_edtGeneratorName: TEdit;
uo_Label9: TLabel;
uo_edtAutoIncFields: TEdit;
uo_cbCheckRequired: TCheckBox;
uo_cbCheckReadOnly: TCheckBox;
uo_cbUpdateNonBaseFields: TCheckBox;
procedure uo_Change(Sender: TObject);
procedure uo_ReadOnly1Click(Sender: TObject);
procedure uo_ReadWrite1Click(Sender: TObject);
procedure uo_Fastupdates1Click(Sender: TObject);
procedure uo_Standardupdates1Click(Sender: TObject);
procedure uo_SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
FOnModified: TNotifyEvent;
FModifiedLocked: Boolean;
FSQLGenerator: Boolean;
FTableOptions: Boolean;
procedure SetSQLGenerator(const AValue: Boolean);
procedure SetTableOptions(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
procedure LoadFrom(AOpts: TFDUpdateOptions);
procedure SaveTo(AOpts: TFDUpdateOptions);
published
property SQLGenerator: Boolean read FSQLGenerator write SetSQLGenerator
default False;
property TableOptions: Boolean read FTableOptions write SetTableOptions
default True;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
end;
implementation
{$R *.dfm}
uses
Data.DB;
{ --------------------------------------------------------------------------- }
constructor TfrmFDGUIxFormsUpdateOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTableOptions := True;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.LoadFrom(AOpts: TFDUpdateOptions);
var
lBottom: Boolean;
begin
FModifiedLocked := True;
try
lBottom := AOpts is TFDBottomUpdateOptions;
if not FSQLGenerator then begin
uo_Label5.Enabled := lBottom;
uo_edtUpdateTableName.Enabled := lBottom;
uo_Label6.Enabled := lBottom;
uo_edtKeyFields.Enabled := lBottom;
uo_Label9.Enabled := lBottom;
uo_edtAutoIncFields.Enabled := lBottom;
end;
if uo_cbEnableDelete.Enabled then
uo_cbEnableDelete.Checked := AOpts.EnableDelete;
if uo_cbEnableInsert.Enabled then
uo_cbEnableInsert.Checked := AOpts.EnableInsert;
if uo_cbEnableUpdate.Enabled then
uo_cbEnableUpdate.Checked := AOpts.EnableUpdate;
if uo_cbxLockMode.Enabled then
uo_cbxLockMode.ItemIndex := Integer(AOpts.LockMode);
if uo_cbxLockPoint.Enabled then
uo_cbxLockPoint.ItemIndex := Integer(AOpts.LockPoint);
if uo_cbLockWait.Enabled then
uo_cbLockWait.Checked := AOpts.LockWait;
if uo_cbUpdateChangedFields.Enabled then
uo_cbUpdateChangedFields.Checked := AOpts.UpdateChangedFields;
if uo_cbUpdateNonBaseFields.Enabled then
uo_cbUpdateNonBaseFields.Checked := AOpts.UpdateNonBaseFields;
if uo_cbxUpdateMode.Enabled then
uo_cbxUpdateMode.ItemIndex := Integer(AOpts.UpdateMode);
if uo_cbCountUpdatedRecords.Enabled then
uo_cbCountUpdatedRecords.Checked := AOpts.CountUpdatedRecords;
if uo_cbRefreshMode.Enabled then
uo_cbRefreshMode.ItemIndex := Integer(AOpts.RefreshMode);
if uo_edtUpdateTableName.Enabled and lBottom then
uo_edtUpdateTableName.Text := TFDBottomUpdateOptions(AOpts).UpdateTableName;
if uo_edtKeyFields.Enabled and lBottom then
uo_edtKeyFields.Text := TFDBottomUpdateOptions(AOpts).KeyFields;
if uo_cbxFetchGeneratorsPoint.Enabled then
uo_cbxFetchGeneratorsPoint.ItemIndex := Integer(AOpts.FetchGeneratorsPoint);
if uo_edtGeneratorName.Enabled then
uo_edtGeneratorName.Text := AOpts.GeneratorName;
if uo_edtAutoIncFields.Enabled and lBottom then
uo_edtAutoIncFields.Text := TFDBottomUpdateOptions(AOpts).AutoIncFields;
if uo_cbCheckRequired.Enabled then
uo_cbCheckRequired.Checked := AOpts.CheckRequired;
if uo_cbCheckReadOnly.Enabled then
uo_cbCheckReadOnly.Checked := AOpts.CheckReadOnly;
finally
FModifiedLocked := False;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.SaveTo(AOpts: TFDUpdateOptions);
begin
if uo_cbEnableDelete.Enabled and (AOpts.EnableDelete <> uo_cbEnableDelete.Checked) then
AOpts.EnableDelete := uo_cbEnableDelete.Checked;
if uo_cbEnableInsert.Enabled and (AOpts.EnableInsert <> uo_cbEnableInsert.Checked) then
AOpts.EnableInsert := uo_cbEnableInsert.Checked;
if uo_cbEnableUpdate.Enabled and (AOpts.EnableUpdate <> uo_cbEnableUpdate.Checked) then
AOpts.EnableUpdate := uo_cbEnableUpdate.Checked;
if uo_cbxLockMode.Enabled and (AOpts.LockMode <> TFDLockMode(uo_cbxLockMode.ItemIndex)) then
AOpts.LockMode := TFDLockMode(uo_cbxLockMode.ItemIndex);
if uo_cbxLockPoint.Enabled and (AOpts.LockPoint <> TFDLockPoint(uo_cbxLockPoint.ItemIndex)) then
AOpts.LockPoint := TFDLockPoint(uo_cbxLockPoint.ItemIndex);
if uo_cbLockWait.Enabled and (AOpts.LockWait <> uo_cbLockWait.Checked) then
AOpts.LockWait := uo_cbLockWait.Checked;
if uo_cbUpdateChangedFields.Enabled and (AOpts.UpdateChangedFields <> uo_cbUpdateChangedFields.Checked) then
AOpts.UpdateChangedFields := uo_cbUpdateChangedFields.Checked;
if uo_cbUpdateNonBaseFields.Enabled and (AOpts.UpdateNonBaseFields <> uo_cbUpdateNonBaseFields.Checked) then
AOpts.UpdateNonBaseFields := uo_cbUpdateNonBaseFields.Checked;
if uo_cbxUpdateMode.Enabled and (AOpts.UpdateMode <> TUpdateMode(uo_cbxUpdateMode.ItemIndex)) then
AOpts.UpdateMode := TUpdateMode(uo_cbxUpdateMode.ItemIndex);
if uo_cbCountUpdatedRecords.Enabled and (AOpts.CountUpdatedRecords <> uo_cbCountUpdatedRecords.Checked) then
AOpts.CountUpdatedRecords := uo_cbCountUpdatedRecords.Checked;
if uo_cbRefreshMode.Enabled and (AOpts.RefreshMode <> TFDRefreshMode(uo_cbRefreshMode.ItemIndex)) then
AOpts.RefreshMode := TFDRefreshMode(uo_cbRefreshMode.ItemIndex);
if uo_edtUpdateTableName.Enabled and (AOpts is TFDBottomUpdateOptions) and
(TFDBottomUpdateOptions(AOpts).UpdateTableName <> uo_edtUpdateTableName.Text) then
TFDBottomUpdateOptions(AOpts).UpdateTableName := uo_edtUpdateTableName.Text;
if uo_edtKeyFields.Enabled and (AOpts is TFDBottomUpdateOptions) and
(TFDBottomUpdateOptions(AOpts).KeyFields <> uo_edtKeyFields.Text) then
TFDBottomUpdateOptions(AOpts).KeyFields := uo_edtKeyFields.Text;
if uo_cbxFetchGeneratorsPoint.Enabled and (AOpts.FetchGeneratorsPoint <> TFDFetchGeneratorsPoint(uo_cbxFetchGeneratorsPoint.ItemIndex)) then
AOpts.FetchGeneratorsPoint := TFDFetchGeneratorsPoint(uo_cbxFetchGeneratorsPoint.ItemIndex);
if uo_edtGeneratorName.Enabled and (AOpts.GeneratorName <> uo_edtGeneratorName.Text) then
AOpts.GeneratorName := uo_edtGeneratorName.Text;
if uo_edtAutoIncFields.Enabled and (AOpts is TFDBottomUpdateOptions) and
(TFDBottomUpdateOptions(AOpts).AutoIncFields <> uo_edtAutoIncFields.Text) then
TFDBottomUpdateOptions(AOpts).AutoIncFields := uo_edtAutoIncFields.Text;
if uo_cbCheckRequired.Enabled and (uo_cbCheckRequired.Checked <> AOpts.CheckRequired) then
AOpts.CheckRequired := uo_cbCheckRequired.Checked;
if uo_cbCheckReadOnly.Enabled and (uo_cbCheckReadOnly.Checked <> AOpts.CheckReadOnly) then
AOpts.CheckReadOnly := uo_cbCheckReadOnly.Checked;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_Change(Sender: TObject);
begin
if not FModifiedLocked and Assigned(FOnModified) then
FOnModified(Self);
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.SetSQLGenerator(const AValue: Boolean);
begin
if FSQLGenerator <> AValue then begin
FSQLGenerator := AValue;
FModifiedLocked := True;
try
uo_Label2.Enabled := not AValue;
uo_cbxLockPoint.Enabled := not AValue;
uo_cbUpdateChangedFields.Enabled := not AValue;
uo_cbUpdateChangedFields.Checked := False;
uo_cbCheckRequired.Enabled := not AValue;
uo_cbCheckReadOnly.Enabled := not AValue;
uo_cbUpdateNonBaseFields.Enabled := not AValue;
uo_cbUpdateNonBaseFields.Checked := False;
uo_cbCountUpdatedRecords.Enabled := not AValue;
uo_cbCountUpdatedRecords.Checked := True;
uo_Label5.Enabled := not AValue;
uo_edtUpdateTableName.Enabled := not AValue;
uo_edtUpdateTableName.Text := '';
uo_Label6.Enabled := not AValue;
uo_edtKeyFields.Enabled := not AValue;
uo_edtKeyFields.Text := '';
uo_Label7.Enabled := not AValue;
uo_cbxFetchGeneratorsPoint.Enabled := not AValue;
uo_cbxFetchGeneratorsPoint.ItemIndex := -1;
uo_Label8.Enabled := not AValue;
uo_edtGeneratorName.Enabled := not AValue;
uo_edtGeneratorName.Text := '';
uo_Label9.Enabled := not AValue;
uo_edtAutoIncFields.Enabled := not AValue;
uo_edtAutoIncFields.Text := '';
finally
FModifiedLocked := False;
end;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.SetTableOptions(const Value: Boolean);
begin
if FTableOptions <> Value then begin
FTableOptions := Value;
{
if FTableOptions then begin
uo_GroupBox5.Left := 2;
uo_GroupBox5.Top := 77;
uo_GroupBox4.Left := 277;
uo_GroupBox4.Top := 97;
uo_GroupBox5.Visible := True;
end
else begin
uo_GroupBox5.Visible := False;
uo_GroupBox4.Left := 2;
uo_GroupBox4.Top := 77;
end;
}
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_ReadOnly1Click(Sender: TObject);
begin
uo_cbEnableInsert.Checked := False;
uo_cbEnableUpdate.Checked := False;
uo_cbEnableDelete.Checked := False;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_ReadWrite1Click(Sender: TObject);
begin
uo_cbEnableInsert.Checked := True;
uo_cbEnableUpdate.Checked := True;
uo_cbEnableDelete.Checked := True;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_Fastupdates1Click(Sender: TObject);
begin
uo_cbUpdateChangedFields.Checked := False;
uo_cbxUpdateMode.ItemIndex := 2;
uo_cbxLockMode.ItemIndex := 2;
uo_cbRefreshMode.ItemIndex := 0;
uo_cbCheckRequired.Checked := False;
uo_cbCheckReadOnly.Checked := False;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_Standardupdates1Click(Sender: TObject);
begin
uo_cbUpdateChangedFields.Checked := True;
uo_cbxUpdateMode.ItemIndex := 0;
uo_cbxLockMode.ItemIndex := 2;
uo_cbRefreshMode.ItemIndex := 1;
uo_cbCheckRequired.Checked := True;
uo_cbCheckReadOnly.Checked := True;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUpdateOptions.uo_SpeedButton1Click(Sender: TObject);
var
P: TPoint;
begin
P := uo_Panel6.ClientToScreen(uo_SpeedButton1.BoundsRect.TopLeft);
uo_PopupMenu1.Popup(P.X, P.Y);
end;
end.
|
unit udatajual;
interface
const
NMadata : integer = 100;
type
dataJual = record
KdKategori:string;{ Kode kategori produk }
KdProduk:string;{ Kode produk }
Hasil:integer; { Hasil Penjualan }
end;
tabPenjualan = record
TJual : array [1..101] of dataJual;
Neff : integer; { 0..100, nilai efektif, 0 jika tabel kosong }
end;
function EOP (rek : dataJual) : boolean;
{ Menghasilkan true jika rek = mark }
procedure LoadDataJual (filename : string; var T : tabPenjualan);
{ I.S. : filename terdefinisi, T sembarang }
{ F.S. : Tabel T terisi data hasil penjualan dengan data yang dibaca
dari file dg nama = filename
T.Neff = 0 jika tidak ada file kosong;
T diisi dengan seluruh isi file atau sampai T penuh. }
procedure UrutKategoriAsc (var T : tabPenjualan);
{ I.S. : T terdefinisi; T mungkin kosong }
{ F.S. : Isi tabel T terurut membesar menurut KdKategori. T tetap jika T kosong. }
{ Proses : Gunakan salah satu algoritma sorting yang diajarkan di kelas.
Tuliskan nama algoritmanya dalam bentuk komentar. }
procedure HitungRataRata (T : tabPenjualan);
{ I.S. : T terdefinisi; T mungkin kosong }
{ F.S. : Menampilkan KdKategori dan hasil penjualan rata-rata per KdKategori
yang ada dalam tabel dengan format: <KdKategori>=<rata-rata>
Nilai rata-rata dibulatkan ke integer terdekat. Gunakan fungsi round. }
{ Proses : Menggunakan ide algoritma konsolidasi tanpa separator pada file
eksternal, hanya saja diberlakukan pada tabel. }
procedure SaveDataJual (filename : string; T : tabPenjualan);
{ I.S. : T dan filename terdefinisi; T mungkin kosong }
{ F.S. : Isi tabel T dituliskan pada file dg nama = filename }
implementation
function EOP (rek : dataJual) : boolean;
begin
if (rek.KdKategori='99999999') and (rek.KdProduk='datadata9999') and (rek.Hasil=-999) then
EOP:=true
else
EOP:=false;
end;
procedure LoadDataJual (filename : string; var T : tabPenjualan);
var
stream:file of dataJual;
data:dataJual;
begin
assign(stream,filename);
reset(stream);
read(stream,data);
T.Neff:=0;
while (not(EOP(data))) do
begin
T.Neff:=T.Neff+1;
T.TJual[T.Neff]:=data;
read(stream,data);
end;
close(stream);
end;
procedure UrutKategoriAsc (var T : tabPenjualan);
//bubble
var
i,j:integer;
temp:dataJual;
begin
if (T.Neff>=2) then
begin
for i:=T.Neff downto 2 do
begin
for j:=1 to i-1 do
begin
if T.TJual[j].KdKategori>T.TJual[j+1].KdKategori then
begin
temp := T.TJual[j+1];
T.TJual[j+1] :=T.TJual[j];
T.TJual[j] :=temp;
end;
end;
end;
end;
end;
procedure HitungRataRata (T : tabPenjualan);
var
sum,cnt,i:integer;
begin
if (T.Neff=0) then
begin
writeln('Data kosong');
end
else
begin
sum:=0;
cnt:=0;
T.TJual[T.Neff+1].KdKategori:='99999999';
T.TJual[T.Neff+1].KdProduk:='datadata9999';
T.TJual[T.Neff+1].Hasil:=-999;
for i:= 1 to T.Neff do
begin
sum:=sum+T.TJual[i].hasil;
cnt:=cnt+1;
if (T.TJual[i].KdKategori<>T.TJual[i+1].KdKategori) then
begin
writeln(T.TJual[i].KdKategori,'=',round(sum/cnt));
sum:=0;
cnt:=0;
end
end;
end;
end;
procedure SaveDataJual (filename : string; T : tabPenjualan);
var
stream:file of dataJual;
i:integer;
data:dataJual;
begin
assign(stream,filename);
rewrite(stream);
for i:=1 to T.Neff do
begin
write(stream,T.TJual[i]);
end;
data.KdKategori:='99999999';
data.KdProduk:='datadata9999';
data.Hasil:=-999;
write(stream,data);
close(stream);
end;
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileDAE<p>
COLLADA DAE file format implementation.<p>
<b>History :</b><font size=-1><ul>
<li>17/01/14 - PW - Bugfixed for XE5
<li>16/01/14 - PW - Added $I GLScene.inc
<li>15/01/14 - PW - Creation
</ul></font>
}
unit GLFileDAE;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
GLVectorFileObjects, GLApplicationFileIO {, Fmx.FileDAE};
type
// TGLDAEVectorFile
//
{: The DAE vector file (COLLADA actor file).<p>
Stores a set of "frames" describing the different postures of the actor,
it may be animated by TGLActor. The "Skin" must be loaded indepentendly
(the whole mesh uses a single texture bitmap).<p>}
TGLDAEVectorFile = class(TVectorFile)
public
{ Public Declarations }
class function Capabilities : TDataFileCapabilities; override;
procedure LoadFromStream(aStream : TStream); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLDAEVectorFile ------------------
// ------------------
// Capabilities
//
class function TGLDAEVectorFile.Capabilities : TDataFileCapabilities;
begin
Result:=[dfcRead];
end;
// LoadFromStream
//
procedure TGLMD2VectorFile.LoadFromStream(aStream : TStream);
var
i, j : Integer;
DAEFile : TFileDAE;
mesh : TMorphableMeshObject;
faceGroup : TFGIndexTexCoordList;
morphTarget : TMeshMorphTarget;
begin
DAEFile:=TFileDAE.Create;
DAEFile.LoadFromStream(aStream);
try
// retrieve mesh data
mesh:=TMorphableMeshObject.CreateOwned(Owner.MeshObjects);
with mesh, DAEFile do begin
Mode:=momFaceGroups;
faceGroup:=TFGIndexTexCoordList.CreateOwned(FaceGroups);
with faceGroup do begin
MaterialName:='';
VertexIndices.Capacity:=iTriangles*3;
TexCoords.Capacity:=iTriangles*3;
// copy the face list
for i:=0 to iTriangles-1 do with IndexList[i] do begin
Add(a, a_s, -a_t);
Add(b, b_s, -b_t);
Add(c, c_s, -c_t);
end;
end;
// retrieve frames data (morph targets)
for i:=0 to iFrames-1 do begin
morphTarget:=TMeshMorphTarget.CreateOwned(MorphTargets);
with morphTarget do begin
Name:='Frame'+IntToStr(i);
Vertices.Capacity:=iVertices;
for j:=0 to iVertices-1 do
Vertices.Add(VertexList[i][j]);
BuildNormals(faceGroup.VertexIndices, momTriangles);
end;
end;
end;
if GetOwner is TGLActor then with TGLActor(GetOwner).Animations do begin
Clear;
with DAEFile do for i:=0 to frameNames.Count-1 do with Add do begin
Name:=frameNames[i];
Reference:=aarMorph;
StartFrame:=Integer(frameNames.Objects[i]);
if i<frameNames.Count-1 then
EndFrame:=Integer(frameNames.Objects[i+1])-1
else EndFrame:=iFrames-1;
end;
end;
if mesh.MorphTargets.Count>0 then
mesh.MorphTo(0);
finally
DAEFile.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('dae', 'COLLADA model files', TGLDAEVectorFile);
end.
|
unit MediaServer.Stream.Source.VideoCapture;
interface
uses Windows, SysUtils, Classes, SyncObjs, VFW,
MediaServer.Stream.Source,
MediaProcessing.Definitions;
type
//Класс, выполняющий непосредственно получение данных (видеопотока) из камеры
TMediaServerSourceCapture = class (TMediaServerSource)
private
FCaptureWnd: HWND;
FCurrentBmpInfo: TBitmapInfo;
procedure OnFrameReceived(aMediaType: TMediaType;
aData: pointer; aDataSize:cardinal;
const aFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal);
public
constructor Create; overload;
destructor Destroy; override;
procedure Open(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Name: string; override;
function VideoStreamType: TStreamType; override;
function AudioStreamType: TStreamType; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
//property Framer: TStreamFramer read FFramer;
end;
implementation
uses Math,Forms,uWorkspace,uTrace,MediaStream.FramerFactory,IdGlobal;
{ TMediaServerSourceCapture }
constructor TMediaServerSourceCapture.Create();
begin
Create(-1);
end;
destructor TMediaServerSourceCapture.Destroy;
begin
inherited;
end;
function TMediaServerSourceCapture.DeviceType: string;
begin
result:='Capture';
end;
function TMediaServerSourceCapture.Name: string;
begin
result:='Capture';
end;
procedure TMediaServerSourceCapture.OnFrameReceived(aMediaType: TMediaType;
aData: pointer; aDataSize:cardinal;
const aFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal);
var
aLSCP : TDateTime;
aStatisticsFrameLength: int64;
begin
Lock;
try
Inc(FBytesReceived, aDataSize);
Inc(FFramesReceived);
if aMediaType=mtAudio then
inc(FAFramesReceived)
else if ffKeyFrame in aFormat.biFrameFlags then
inc(FVIFramesReceived)
else
inc(FVPFramesReceived);
FAverageFrameSize:=FBytesReceived div FFramesReceived;
FMaxFrameSize := max(FMaxFrameSize,aDataSize);
if FMinFrameSize<0 then
FMinFrameSize:=aDataSize
else
FMinFrameSize := min(FMinFrameSize,aDataSize);
FLastStreamDateTime:=Now;
aLSCP:=Now;
aStatisticsFrameLength:=Trunc((aLSCP-FLastStatisticsCheckpoint)*SecsPerDay);
if (aStatisticsFrameLength>10) then
begin
FBytesReceivedSpeed:=(FBytesReceived-FBytesReceivedCheckPoint) div aStatisticsFrameLength;
FBytesReceivedCheckPoint:=FBytesReceived;
FLastStatisticsCheckpoint:=aLSCP;
end;
DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize);
finally
Unlock;
end;
end;
function CaptureCallback(hWnd: HWND; lpVHdr: PVIDEOHDR): DWORD; stdcall;
begin
result:=0;
end;
procedure TMediaServerSourceCapture.Open(aSync: boolean);
begin
if Opened then
exit;
Close;
FCurrentBmpInfo.bmiHeader.biBitCount:=24;
FCurrentBmpInfo.bmiHeader.biClrImportant:=0;
FCurrentBmpInfo.bmiHeader.biClrUsed:=0;
FCurrentBmpInfo.bmiHeader.biCompression:=BI_RGB;
FCurrentBmpInfo.bmiHeader.biHeight:=240;
FCurrentBmpInfo.bmiHeader.biPlanes:=1;
FCurrentBmpInfo.bmiHeader.biSize:=sizeof(BITMAPINFOHEADER);
FCurrentBmpInfo.bmiHeader.biSizeImage:=0;
FCurrentBmpInfo.bmiHeader.biWidth:=320;
FCurrentBmpInfo.bmiHeader.biXPelsPerMeter:=0;
FCurrentBmpInfo.bmiHeader.biYPelsPerMeter:=0;
FCaptureWnd:=capCreateCaptureWindow('Capture Window',WS_VISIBLE or WS_CHILD,0,0,320,240,Application.MainFormHandle,1);
if FCaptureWnd=0 then
RaiseLastOSError;
SetWindowLong(FCaptureWnd,GWL_USERDATA,integer(self));
capDriverConnect(FCaptureWnd,0);
//set the video format
capSetVideoFormat(FCaptureWnd,@FCurrentBmpInfo,sizeof(FCurrentBmpInfo));
capPreviewRate(FCaptureWnd,40);
// capDlgVideoFormat(this->m_hWndCapture);
capPreview(FCaptureWnd,TRUE);
capSetCallbackOnFrame(FCaptureWnd,@CaptureCallback);
if Assigned(OnConnectionOk) then
OnConnectionOk(self);
end;
procedure TMediaServerSourceCapture.DoClose;
begin
capDriverDisconnect(FCaptureWnd);
end;
function TMediaServerSourceCapture.ConnectionString: string;
begin
result:='';
end;
function TMediaServerSourceCapture.Opened: Boolean;
begin
result:=FCaptureWnd<>0;
end;
function TMediaServerSourceCapture.StreamInfo: TBytes;
begin
Lock;
try
CheckConnected;
result:=RawToBytes(FCurrentBmpInfo.bmiHeader,sizeof(FCurrentBmpInfo.bmiHeader));
finally
Unlock;
end;
end;
function TMediaServerSourceCapture.VideoStreamType: TStreamType;
begin
result:=stRGB;
end;
function TMediaServerSourceCapture.AudioStreamType: TStreamType;
begin
result:=0;
end;
function TMediaServerSourceCapture.PtzSupported: boolean;
begin
result:=false;
end;
procedure TMediaServerSourceCapture.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
end;
end.
|
unit cparserexp;
interface
uses
SysUtils, cparsertypes;
const
CIdentClose : array [TIdentType] of string = ('', ']',')', '', '');
CIdentOpen : array [TIdentType] of string = ('', '[','(', '.', '->');
function ParseCExprEx(p: TTextParser): TExp;
function isCTypeCast(exp: TExp; tinfo: TCTypeInfo): Boolean;
implementation
function isCTypeCast(exp: TExp; tinfo: TCTypeInfo): Boolean;
var
hasType: Boolean;
begin
Result:=false;
while Assigned(exp) do begin
if exp.dir = edPostfix then begin
exp:=exp.left;
end else if exp.dir = edPrefix then begin
exp:=exp.right;
end else if (exp.dir = edValue) then begin
if isStdCType(exp.val) then
hastype:=true
else begin
hasType:=Assigned(tinfo) and (tinfo.isType(exp.val));
if not hasType then Exit // an identify that's not a type
end;
exp:=nil;
end else begin
// nothing else os allowed in typecast
Exit;
end;
end;
Result:=hasType;
end;
function _Rotate(core: TExp): TExp;
begin
if Assigned(core.right) and (core.right.dir<>edValue) and (core.right.pr>=core.pr) then
begin
Result:=core.right;
core.right:=Result.left;
Result.left:=core;
// additional rotate
Result.left:=_Rotate(core);
end else
Result:=core;
end;
function isIdentSep(const t: string; var it: TIdentType): Boolean;
begin
Result:=true;
if t='(' then it:=itFuncCall
else if t = '[' then it:=itIndex
else if t = '.' then it:=itField
else if t = '->' then it:=itSubSel
else Result:=false;
end;
function level2(p: TTextParser): TExp;
var
exp : TExp;
res : Boolean;
it : TIdentType;
e : TExp;
begin
Result:=nil;
if p.TokenType=tt_Numeric then begin
exp := TExp.Create(2, '', edValue);
exp.val:=p.Token;
p.NextToken;
Result:=exp;
end else if p.TokenType=tt_Ident then begin
exp := TExp.Create(2, '', edValue);
exp.val:=p.Token;
p.NextToken;
res:=isIdentSep(p.Token, it);
if res then begin
e:=TExp.Create(2, p.Token, edPostfix);
e.left:=exp;
e.identtype:=it;
exp:=e;
p.NextToken;
if it in [itField, itSubSel] then
exp.right:=level2(p)
else if it in [itFuncCall, itIndex] then begin
exp.inner:=ParseCExprEx(p);
if p.Token = CIdentClose[it] then
p.NextToken
else begin
// error!
end;
end;
end else if (p.Token='++') or (p.Token='--') then begin
e:=TExp.Create(2, p.Token, edPostfix);
e.left:=exp;
exp:=e;
p.NextToken;
end;
Result:=exp;
end;
end;
function level3(p: TTextParser): TExp;
var
exp : TExp;
ct : TExp;
begin
exp:=level2(p);
if not Assigned(exp) then begin
Result:=nil;
// typecast
if (p.Tokentype=tt_Symbol) and (p.Token='(') then begin
p.NextToken;
ct:=ParseCExprEx(p);
if (p.TokenType=tt_Symbol) and (p.Token = ')') then
p.NextToken;
if not isCTypeCast(ct, p.CTypeInfo) then begin
// not a typecast!
ct.pr:=1;
Result:=ct;
end else begin
Result:=TExp.Create(3, 'typecast', edInfix);
Result.inner:=ct;
Result.right:=ParseCExprEx(p);
//Result:=Rotate(REsult);
end;
end else if (p.Token='sizeof') or (p.Token='++') or (p.Token='--')
or ((length(p.Token) = 1) and (p.Token[1] in ['&','*','~','!','-','+']))
then begin
Result:=TExp.Create(3, p.Token, edPrefix);
p.NextToken;
Result.right:=ParseCExprEx(p);
//Result:=Rotate(Result);
end
end else
Result:=exp;
end;
function level5(p: TTextParser): TExp;
var
e : TExp;
begin
Result :=level3(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and ( (length(p.Token)=1) and (p.Token[1] in ['*','/','%'])) do begin
e:=Result;
Result:=TExp.Create(5, p.Token, edInfix);
p.NextToken;
Result.left:=e;
Result.right:=level3(p);
end;
end;
function level6(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level5(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and ( (length(p.Token)=1) and (p.Token[1] in ['+','-'])) do begin
e:=Result;
Result:=TExp.Create(6, p.Token, edInfix);
p.NextToken;
Result.left:=e; // a * b + c
Result.right:=level5(p);
end;
end;
function level7(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level6(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and ( (p.Token = '<<') or (p.Token='>>')) do begin
e:=Result;
Result:=TExp.Create(7, p.Token, edInfix);
p.NextToken;
Result.left:=e;
Result.right:=level6(p);
end;
end;
function level8(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level7(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and ((p.Token='<') or (p.Token='<=') or (p.Token='>=') or (p.Token='>')) do begin
e:=Result;
Result:=TExp.Create(8, p.Token, edInfix);
p.NextToken;
Result.left:=e;
Result.right:=level7(p);
end;
end;
function level9(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level8(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and ((p.Token='==') or (p.Token='!=')) do begin
e := Result;
Result:=TExp.Create(9, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level8(p);
end;
end;
function level10(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level9(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and (p.Token='&') do begin
e:=Result;
Result:=TExp.Create(10, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level9(p);
end;
end;
function level11(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level10(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and (p.Token='^') do begin
e := Result;
Result:=TExp.Create(11, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level10(p);
end;
end;
function level12(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level11(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and (p.Token='|') do begin
e := Result;
Result:=TExp.Create(12, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level11(p);
end;
end;
function level13(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level12(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and (p.Token='&&') do begin
e := Result;
Result:=TExp.Create(13, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level12(p);
end;
end;
function level14(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level13(p);
while Assigned(Result) and (p.TokenType = tt_Symbol) and (p.Token='||') do begin
e := Result;
Result:=TExp.Create(14, p.Token, edInfix);
Result.left:=e;
p.NextToken;
Result.right:=level13(p);
//Result:=Rotate(Result);
end;
end;
function level15(p: TTextParser): TExp;
var
e : TExp;
begin
Result:=level14(p);
while Assigned(result) and (p.Token='?') do
begin
p.NextToken;
e:=Result;
Result:=TExp.Create(15, '?', edTernary);
Result.main:=e;
Result.left:=level14(p);
if p.Token = ':' then p.NextToken;
Result.right:=level14(p);
end;
end;
function level16(p: TTextParser): TExp;
var
tk : string;
e : TExp;
begin
Result:=level15(p);
while Assigned(Result) and ((tk='=')
or (tk='+=') or (tk='-=') or (tk='*=') or (tk='/=')
or (tk='%=') or (tk='<<=') or (tk='>>=') or (tk='&=')
or (tk='^=') or (tk='|=')) do
begin
e:=Result;
Result:=TExp.Create(16, tk, edInfix);
Result.right:=e;
p.NextToken;
Result.left:=level15(p);
end;
end;
function level17(p: TTextParser): TExp;
var
tk : string;
e : TExp;
begin
Result:=level16(p);
while Assigned(Result) and (p.TokenType=tt_Symbol) and (p.Token=',') do begin
e:=Result;
p.NextToken;
Result:=TExp.Create(17, ',', edSequence);
Result.left:=e;
Result.right:=level16(p);
end;
end;
function ParseCExprEx(p: TTextParser): TExp;
begin
Result:=level17(p);
end;
end.
|
object SaveAttributesAs: TSaveAttributesAs
Left = 426
Top = 119
BorderStyle = bsDialog
Caption = 'Save %s attributes as'
ClientHeight = 119
ClientWidth = 274
ParentFont = True
Position = poScreenCenter
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Bevel1: TBevel
Left = 2
Top = 8
Width = 183
Height = 105
Shape = bsFrame
end
object Label1: TLabel
Left = 10
Top = 16
Width = 88
Height = 13
Caption = '&Attribute set name:'
FocusControl = AttributeNameEdit
end
object Label2: TLabel
Left = 10
Top = 64
Width = 48
Height = 13
Caption = '&Based on:'
FocusControl = BasedOnList
end
object BasedOnList: TComboBox
Left = 10
Top = 80
Width = 167
Height = 21
ItemHeight = 13
TabOrder = 1
end
object AttributeNameEdit: TEdit
Left = 10
Top = 32
Width = 167
Height = 21
TabOrder = 0
end
object OKBtn: TButton
Left = 192
Top = 8
Width = 75
Height = 25
Caption = 'OK'
Default = True
TabOrder = 2
OnClick = OKBtnClick
end
object CancelBtn: TButton
Left = 192
Top = 40
Width = 75
Height = 25
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 3
OnClick = CancelBtnClick
end
object HelpBtn: TButton
Left = 192
Top = 72
Width = 75
Height = 25
Caption = '&Help'
TabOrder = 4
OnClick = HelpBtnClick
end
end
|
unit Command.Button2;
interface
uses
System.Classes,
System.SysUtils,
Vcl.StdCtrls,
Pattern.Command;
type
TButon2Command = class (TCommand)
private
FMemo: TMemo;
FEdit: TEdit;
protected
procedure DoGuard; override;
procedure DoExecute; override;
published
property Memo: TMemo read FMemo write FMemo;
property Edit: TEdit read FEdit write FEdit;
end;
implementation
procedure TButon2Command.DoGuard;
begin
Assert(Memo<>nil);
Assert(Edit<>nil);
end;
procedure TButon2Command.DoExecute;
begin
Memo.Lines.Add('[2] Getting info from Edit and put it here ...');
Memo.Lines.Add('[2] Edit.Text = "'+Edit.Text+'"');
Memo.Lines.Add('--- ---');
end;
end.
|
unit uRatingBijdrage;
interface
type
TRatingBijdrage = class
private
FPositie: String;
FMid_PM: double;
FCD_GK: double;
FCD_DEF: double;
FWB_GK: double;
FWB_DEF: double;
FCA_PASS: double;
FCA_SC: double;
FWA_PASS: double;
FWA_SC_OTHER: double;
FWA_WING: double;
FWA_SC: double;
procedure SetPositie(const Value: String);
function GetCount: integer;
public
procedure LoadFromXLS(aWorkSheet: Variant; aRow: integer);
procedure ExportToXLS(aWorkSheet: Variant; var aRow: integer);
property Count:integer read GetCount;
property MID_PM: double read FMid_PM write FMid_PM;
property CD_GK: double read FCD_GK write FCD_GK;
property CD_DEF: double read FCD_DEF write FCD_DEF;
property WB_GK: double read FWB_GK write FWB_GK;
property WB_DEF: double read FWB_DEF write FWB_DEF;
property CA_PASS: double read FCA_PASS write FCA_PASS;
property CA_SC: double read FCA_SC write FCA_SC;
property WA_PASS: double read FWA_PASS write FWA_PASS;
property WA_WING: double read FWA_WING write FWA_WING;
property WA_SC: double read FWA_SC write FWA_SC;
property WA_SC_OTHER: double read FWA_SC_OTHER write FWA_SC_OTHER;
property Positie:String read FPositie write SetPositie;
end;
implementation
uses
SysUtils;
{ TRatingBijdrage }
{-----------------------------------------------------------------------------
Procedure: SetPositie
Author: Harry
Date: 18-apr-2012
Arguments: const Value: String
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrage.SetPositie(const Value: String);
begin
FPositie := UpperCase(Value);
end;
{-----------------------------------------------------------------------------
Procedure: GetCount
Author: Harry
Date: 18-apr-2012
Arguments: None
Result: integer
-----------------------------------------------------------------------------}
function TRatingBijdrage.GetCount: integer;
begin
result := 0;
if (MID_PM > 0) then
inc(result);
if (CD_GK > 0) then
inc(result);
if (CD_DEF > 0) then
inc(result);
if (WB_GK > 0) then
inc(result);
if (WB_DEF > 0) then
inc(result);
if (CA_PASS > 0) then
inc(result);
if (CA_SC > 0) then
inc(result);
if (WA_PASS > 0) then
inc(result);
if (WA_WING > 0) then
inc(result);
if (WA_SC > 0) then
inc(result);
if (WA_SC_OTHER > 0) then
inc(result);
end;
{-----------------------------------------------------------------------------
Procedure: ExportToXLS
Author: Harry
Date: 24-apr-2012
Arguments: aWorkSheet: Varian; aRow: integer
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrage.ExportToXLS(aWorkSheet: Variant; var aRow: integer);
begin
aWorksheet.Activate;
if (aRow = 0) then
begin
aWorksheet.Range['A1'].Value := 'POSITIE';
aWorksheet.Range['B1'].Value := 'Mid-PM';
aWorksheet.Range['C1'].Value := 'CD-GK';
aWorksheet.Range['D1'].Value := 'CD-Def';
aWorksheet.Range['E1'].Value := 'WB-GK';
aWorksheet.Range['F1'].Value := 'WB-Def';
aWorksheet.Range['G1'].Value := 'CA-Pass';
aWorksheet.Range['H1'].Value := 'CA-Scor';
aWorksheet.Range['I1'].Value := 'WI-Pass';
aWorksheet.Range['J1'].Value := 'WI-Wing';
aWorksheet.Range['K1'].Value := 'WI-Scor';
aWorksheet.Range['L1'].Value := 'WI-Scor(other)';
inc(aRow);
end;
inc(aRow);
aWorksheet.Range[Format('A%d',[aRow])].Value := Positie;
if (MID_PM > 0) then
aWorksheet.Range[Format('B%d',[aRow])].Value := MID_PM;
if (CD_GK > 0) then
aWorksheet.Range[Format('C%d',[aRow])].Value := CD_GK;
if (CD_DEF > 0) then
aWorksheet.Range[Format('D%d',[aRow])].Value := CD_DEF;
if (WB_GK > 0) then
aWorksheet.Range[Format('E%d',[aRow])].Value := WB_GK;
if (WB_DEF > 0) then
aWorksheet.Range[Format('F%d',[aRow])].Value := WB_DEF;
if (CA_PASS > 0) then
aWorksheet.Range[Format('G%d',[aRow])].Value := CA_PASS;
if (CA_SC > 0) then
aWorksheet.Range[Format('H%d',[aRow])].Value := CA_SC;
if (WA_PASS > 0) then
aWorksheet.Range[Format('I%d',[aRow])].Value := WA_PASS;
if (WA_WING > 0) then
aWorksheet.Range[Format('J%d',[aRow])].Value := WA_WING;
if (WA_SC > 0) then
aWorksheet.Range[Format('K%d',[aRow])].Value := WA_SC;
if (WA_SC_OTHER > 0) then
aWorksheet.Range[Format('L%d',[aRow])].Value := WA_SC_OTHER;
end;
{-----------------------------------------------------------------------------
Procedure: LoadFromXLS
Author: Harry
Date: 25-apr-2012
Arguments: aWorkSheet: Variant; var aRow: integer
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrage.LoadFromXLS(aWorkSheet: Variant;
aRow: integer);
begin
MID_PM := aWorksheet.Range[Format('B%d',[aRow])];
CD_GK := aWorksheet.Range[Format('C%d',[aRow])];
CD_DEF := aWorksheet.Range[Format('D%d',[aRow])];
WB_GK := aWorksheet.Range[Format('E%d',[aRow])];
WB_DEF := aWorksheet.Range[Format('F%d',[aRow])];
CA_PASS := aWorksheet.Range[Format('G%d',[aRow])];
CA_SC := aWorksheet.Range[Format('H%d',[aRow])];
WA_PASS := aWorksheet.Range[Format('I%d',[aRow])];
WA_WING := aWorksheet.Range[Format('J%d',[aRow])];
WA_SC := aWorksheet.Range[Format('K%d',[aRow])];
WA_SC_OTHER := aWorksheet.Range[Format('L%d',[aRow])];
end;
end.
|
unit FrmAutobusy;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, ClassData, ExtCtrls;
type
TFormAutobusy = class(TForm)
ComboBox: TComboBox;
CheckBox: TCheckBox;
TrackBar: TTrackBar;
ListView: TListView;
procedure FormCreate(Sender: TObject);
procedure ComboBoxChange(Sender: TObject);
procedure TrackBarChange(Sender: TObject);
procedure CheckBoxClick(Sender: TObject);
procedure ListViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure ListViewDblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
VybranySpoj : PSpoj;
VybranaZastavka : PZastavka;
Prilepeny : integer; {-1 - nie je; 0 - left; 1 - right}
procedure InitComboBox;
procedure UpdateListBox;
procedure Moving( var Message : TMessage );message WM_MOVING;
procedure ZrusPrilepenie;
public
{ Public declarations }
end;
var
FormAutobusy: TFormAutobusy;
implementation
uses ClassMapa, FrmZastavka, FormHlavneOkno;
{$R *.DFM}
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
procedure TFormAutobusy.InitComboBox;
var I : integer;
begin
ComboBox.Clear;
for I := 0 to Data.SpojeInfo.Count-1 do
if TSpojInfo( Data.SpojeInfo[I]^ ).Spoj <> nil then
if TSpojInfo( Data.SpojeInfo[I]^ ).Spoj^.Typ = 0 then
ComboBox.Items.Add( IntToStr( TSpojInfo( Data.SpojeInfo[I]^ ).Spoj^.Cislo ) );
ComboBox.ItemIndex := 0;
end;
procedure TFormAutobusy.FormCreate(Sender: TObject);
begin
VybranySpoj := nil;
VybranaZastavka := nil;
Prilepeny := -1;
// OrigRect := HlavneOkno.PanelDock.BoundsRect;
InitComboBox;
UpdateListBox;
end;
//==============================================================================
//==============================================================================
//
// Show
//
//==============================================================================
//==============================================================================
procedure TFormAutobusy.FormShow(Sender: TObject);
begin
Left := ((HlavneOkno.ClientRect.Left + HlavneOkno.ClientRect.Right) div 2) - (Width div 2);
end;
//==============================================================================
//==============================================================================
//
// Close
//
//==============================================================================
//==============================================================================
procedure TFormAutobusy.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if Action <> caNone then
ZrusPrilepenie;
end;
//==============================================================================
//==============================================================================
//
// Windows messages
//
//==============================================================================
//==============================================================================
procedure TFormAutobusy.ZrusPrilepenie;
begin
Prilepeny := -1;
{ HlavneOkno.PanelDock.Visible := False;
HlavneOkno.PanelDock.Left := OrigRect.Left;
HlavneOkno.PanelDock.Width := OrigRect.Right - OrigRect.Left;}
end;
procedure TFormAutobusy.Moving( var Message : TMessage );
begin
{ Rect := Pointer( Message.LParam );
case Prilepeny of
0 : begin
if Rect^.Left >= MARGIN then
begin
ZrusPrilepenie;
exit;
end;
end;
1 : begin
if (HlavneOkno.BoundsRect.Right - Rect^.Right) >= MARGIN then
begin
ZrusPrilepenie;
exit;
end;
end;
end;
if (Rect^.Left < MARGIN) and
((Prilepeny = -1) or
(Prilepeny = 0)) then
begin
Rect^.Left := 2;
Rect^.Right := Rect^.Left + (BoundsRect.Right - BoundsRect.Left);
if Prilepeny = -1 then
begin
HlavneOkno.PanelDock.Left := 1;
HlavneOkno.PanelDock.Top := HlavneOkno.ClientRect.Top;
HlavneOkno.PanelDock.Height := HlavneOkno.ClientHeight - HlavneOkno.StatusBar.Height;
HlavneOkno.PanelDock.Width := Rect^.Right;
end;
if Rect^.Top <= HlavneOkno.PanelDock.ClientOrigin.y then
begin
Rect^.Top := HlavneOkno.PanelDock.ClientOrigin.y + 1;
Rect^.Bottom := Rect^.Top + (BoundsRect.Bottom - BoundsRect.Top);
end;
if Rect^.Bottom >= HlavneOkno.PanelDock.ClientOrigin.y + HlavneOkno.PanelDock.ClientHeight then
begin
Rect^.Bottom := HlavneOkno.PanelDock.ClientOrigin.y + HlavneOkno.PanelDock.ClientHeight - 1;
Rect^.Top := Rect^.Bottom - (BoundsRect.Bottom - BoundsRect.Top);
end;
if Prilepeny = -1 then
begin
I := HlavneOkno.PanelDock.BoundsRect.Right;
HlavneOkno.PanelDock.Left := HlavneOkno.PanelDock.BoundsRect.Right + 1;
HlavneOkno.PanelDock.ClientWidth := I - HlavneOkno.PanelDock.Left;
HlavneOkno.PanelDock.Visible := True;
Prilepeny := 0;
end;
exit;
end;
if (HlavneOkno.BoundsRect.Right - Rect^.Right < MARGIN) and
((Prilepeny = -1) or
(Prilepeny = 1)) then
begin
if Prilepeny = -1 then
begin
HlavneOkno.PanelDock.Left := HlavneOkno.ClientRect.Right - (BoundsRect.Right - BoundsRect.Left) - 2;
HlavneOkno.PanelDock.Top := HlavneOkno.ClientRect.Top;
HlavneOkno.PanelDock.Height := HlavneOkno.ClientHeight - HlavneOkno.StatusBar.Height;
HlavneOkno.PanelDock.Width := Rect^.Right - Rect^.Left + 2;
end;
Rect^.Left := HlavneOkno.PanelDock.BoundsRect.Left + 1;
Rect^.Right := Rect^.Left + (BoundsRect.Right - BoundsRect.Left);
if Rect^.Top <= HlavneOkno.PanelDock.ClientOrigin.y then
begin
Rect^.Top := HlavneOkno.PanelDock.ClientOrigin.y + 1;
Rect^.Bottom := Rect^.Top + (BoundsRect.Bottom - BoundsRect.Top);
end;
if Rect^.Bottom >= HlavneOkno.PanelDock.ClientOrigin.y + HlavneOkno.PanelDock.ClientHeight then
begin
Rect^.Bottom := HlavneOkno.PanelDock.ClientOrigin.y + HlavneOkno.PanelDock.ClientHeight - 1;
Rect^.Top := Rect^.Bottom - (BoundsRect.Bottom - BoundsRect.Top);
end;
if Prilepeny = -1 then
begin
HlavneOkno.PanelDock.ClientWidth := HlavneOkno.PanelDock.BoundsRect.Left - HlavneOkno.PanelDock.Left - 2;
HlavneOkno.PanelDock.Visible := True;
Prilepeny := 1;
end;
end; }
inherited;
end;
//==============================================================================
//==============================================================================
//
// Komponenty
//
//==============================================================================
//==============================================================================
procedure TFormAutobusy.UpdateListBox;
var I : integer;
Active : PSpoj;
PNewListItem : TListItem;
begin
if (ComboBox.ItemIndex = -1) then exit;
Active := nil;
for I := 0 to Data.SpojeInfo.Count-1 do
if TSpojInfo( Data.SpojeInfo[I]^ ).Spoj^.Cislo = StrToInt( ComboBox.Items[ ComboBox.ItemIndex ] ) then
begin
case TrackBar.Position of
0 : Active := TSpojInfo( Data.SpojeInfo[I]^ ).Spoj;
1 : Active := TSpojInfo( Data.SpojeInfo[I]^ ).OpacnySpoj;
end;
if Active = VybranySpoj then exit;
VybranySpoj := Active;
break;
end;
ListView.Items.Clear;
while Active <> nil do
begin
PNewListItem := ListView.Items.Add;
PNewListItem.Caption := Active^.NaZastavke^.Nazov;
Active := Active^.Next;
end;
end;
procedure TFormAutobusy.ComboBoxChange(Sender: TObject);
begin
UpdateListBox;
if CheckBox.Checked then Mapa.UkazSpoj := VybranySpoj;
end;
procedure TFormAutobusy.TrackBarChange(Sender: TObject);
begin
UpdateListBox;
if CheckBox.Checked then Mapa.UkazSpoj := VybranySpoj;
end;
procedure TFormAutobusy.CheckBoxClick(Sender: TObject);
begin
if not CheckBox.Checked then Mapa.UkazSpoj := nil
else Mapa.UkazSpoj := VybranySpoj;
end;
procedure TFormAutobusy.ListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var Active : PSpoj;
begin
if not Selected then
begin
VybranaZastavka := nil;
exit;
end;
Active := VybranySpoj;
while (Active^.NaZastavke^.Nazov <> Item.Caption) and
(Active <> nil) do
Active := Active^.Next;
VybranaZastavka := Active^.NaZastavke;
if CheckBox.Checked then Mapa.PozriSaNaZastavku( Active^.NaZastavke );
end;
procedure TFormAutobusy.ListViewDblClick(Sender: TObject);
begin
if ListView.Selected = nil then exit;
FormZastavka.MyShow( BoundsRect , VybranaZastavka );
end;
end.
|
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, rkVistaPanel, rkAeroTabs,
Vcl.ComCtrls, Vcl.ExtCtrls, dxGDIPlusClasses, TaskBar, System.Win.Registry, System.IniFiles,
Vcl.Buttons, W7Classes, W7Images;
type
TMainForm = class(TForm)
rkAeroTabs1: TrkAeroTabs;
rkpnlMainPanel: TrkVistaPanel;
lblInfoText: TLabel;
pgcMainControl: TPageControl;
TaskBar1: TTaskBar;
btnBack: TSpeedButton;
btnNext: TSpeedButton;
btnCancel: TSpeedButton;
W7Image1: TW7Image;
W7Image2: TW7Image;
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure CreateStartPage;
procedure CreateOpenFirmware;
procedure CreateGitHubPage;
procedure CreateCompileFirmware;
procedure CreateAddonsPage;
procedure CreateFinishPage;
procedure btnNextClick(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure W7Image2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
WorkDir, AddonsDir, FirmwareFile, DataDir, aAppsDir, JavaHome, OTAUpdateServer, GitHubRepository:string;
AddonsChck:Boolean;
AddonItegrateScriptList, AddonIntegateList:TStringList;
PasswordList:TStringList;
AddonsChecked: array[0..9] of Boolean;
GitHubs:TStringList;
procedure AddToLog(State, LogValue:string);
procedure SetProgress(Progress:Integer; Marquee:boolean=False);
procedure ShowHelp(HelpIndex:string);
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses StartFrame, GitHubChooiser, OpenFirmware, CompileFirmware, AddonFrame, HelpUnit, FinishFrame,
CryModule;
procedure TMainForm.ShowHelp(HelpIndex: string);
begin
if FileExists(DataDir+'Help\'+HelpIndex+'.rtf') then begin
HelpForm.HelpContent.Clear;
HelpForm.HelpContent.Lines.LoadFromFile(DataDir+'Help\'+HelpIndex+'.rtf');
HelpForm.Show;
end else ShowMessage('Для данного раздела ещё не написана справка');
end;
procedure TMainForm.W7Image2Click(Sender: TObject);
begin
if ParamStr(1)='-google' then
CryMode.Show;
end;
procedure TMainForm.SetProgress(Progress: Integer; Marquee:boolean=False);
begin
TaskBar1.ProgressValue:=Progress;
if Marquee then TaskBar1.ProgressState:=TBPF_INDETERMINATE
else TaskBar1.ProgressState:=TBPF_NORMAL;
Application.ProcessMessages;
end;
procedure TMainForm.AddToLog(State, LogValue:string);
var
Log:TStringList;
begin
Log:=TStringList.Create;
Log.Clear;
if FileExists(WorkDir+'Log.log') then Log.LoadFromFile(WorkDir+'Log.log');
Log.Add(State+'\ | '+FormatDateTime('dd.MM.yyyy hh.mm.ss', Now)+' | '+LogValue);
Log.SaveToFile(WorkDir+'Log.log');
end;
procedure TMainForm.btnBackClick(Sender: TObject);
begin
if (pgcMainControl.ActivePageIndex-1)>=0 then begin
pgcMainControl.ActivePageIndex:=pgcMainControl.ActivePageIndex-1;
lblInfoText.Caption:=pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Caption;
end;
if (pgcMainControl.ActivePageIndex)>=(pgcMainControl.PageCount-1) then
btnNext.Caption:='Финиш' else btnNext.Caption:='Далее';
if pgcMainControl.ActivePageIndex<=0 then btnBack.Enabled:=False
else btnBack.Enabled:=True;
btnNext.Enabled:=True;
end;
procedure TMainForm.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.CreateStartPage;
var
TS : TTabsheet;
frmStartPage:TfrmStartPage;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmStartPage:=TfrmStartPage.Create(TS);
frmStartPage.Parent:= TS;
TS.Caption:='Начало';
frmStartPage.Align:= alClient;
end;
procedure TMainForm.CreateGitHubPage;
var
TS : TTabsheet;
frmGitPage:TGitHubRepositories;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmGitPage:=TGitHubRepositories.Create(TS);
frmGitPage.Parent:= TS;
TS.Caption:='Настройка GitHub';
frmGitPage.cbbGitHubs.Items.LoadFromFile(WorkDir+'Settings\GitHub-names.conf');
frmGitPage.cbbGitHubs.ItemIndex:=-1;
if not Assigned(GitHubs) then
GitHubs:=TStringList.Create;
GitHubs.Clear;
GitHubs.LoadFromFile(WorkDir+'Settings\GitHub-gits.conf');
frmGitPage.Align:= alClient;
end;
procedure TMainForm.CreateOpenFirmware;
var
TS : TTabsheet;
frmOpenFirmware:TfrmOpenFirmware;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmOpenFirmware:=TfrmOpenFirmware.Create(TS);
frmOpenFirmware.Parent:= TS;
TS.Caption:='Открытие прошивки и дополнения';
frmOpenFirmware.Align:= alClient;
end;
procedure TMainForm.CreateFinishPage;
var
TS : TTabsheet;
frmFinishFrame:TfrmFinish;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmFinishFrame:=TfrmFinish.Create(TS);
frmFinishFrame.Parent:= TS;
TS.Caption:='Готово';
frmFinishFrame.Align:= alClient;
end;
procedure TMainForm.CreateAddonsPage;
var
TS : TTabsheet;
frmAddons:TfrmAddons;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmAddons:=TfrmAddons.Create(TS);
frmAddons.Parent:= TS;
TS.Caption:='Интеграция дополнений и удаление программ';
frmAddons.Align:= alClient;
end;
procedure TMainForm.CreateCompileFirmware;
var
TS : TTabsheet;
frmCompileFirmware:TfrmCompileFirmware;
begin
TS := TTabSheet.Create(pgcMainControl);
TS.PageControl := pgcMainControl;
TS.TabVisible := False;
frmCompileFirmware:=TfrmCompileFirmware.Create(TS);
frmCompileFirmware.Parent:= TS;
TS.Caption:='Открытие прошивки и дополнения';
frmCompileFirmware.Align:= alClient;
frmCompileFirmware.UbuntuProgress1.Align:=alBottom
end;
procedure TMainForm.btnNextClick(Sender: TObject);
var
frmCompileFirmware:TfrmCompileFirmware;
frmAddons:TfrmAddons;
IniFiles:TIniFile;
FirmwareVersion, ID1, ID2:string;
begin
btnBack.Repaint;
btnBack.Refresh;
if (pgcMainControl.ActivePageIndex+1)<pgcMainControl.PageCount then begin
pgcMainControl.ActivePageIndex:=pgcMainControl.ActivePageIndex+1;
lblInfoText.Caption:=pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Caption;
end else Close;
btnNext.Enabled:=False;
if (pgcMainControl.ActivePageIndex)=(pgcMainControl.PageCount-1) then begin
btnNext.Caption:='Финиш';
btnNext.Enabled:=True;
end;
if pgcMainControl.ActivePageIndex<=0 then btnBack.Enabled:=False
else btnBack.Enabled:=True;
if pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Controls[0].Name='frmCompileFirmware' then begin
frmCompileFirmware:=pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Controls[0] as TfrmCompileFirmware;
frmCompileFirmware.Memo1.Lines.Clear;
IniFiles:=TIniFile.Create(MainForm.DataDir+'Language.conf');
FirmwareVersion:=IniFiles.ReadString('Language','Version','');
ID1:=IniFiles.ReadString('Language','ID1','ru');
ID2:=IniFiles.ReadString('Language','ID2','RU');
IniFiles.Free;
if FileExists(MainForm.DataDir+'\LanguageFiles_Git\Language.conf') then begin
IniFiles:=TIniFile.Create(MainForm.DataDir+'\LanguageFiles_Git\Language.conf');
FirmwareVersion:=IniFiles.ReadString('Language','Version','')+'-git';
IniFiles.Free;
end;
frmCompileFirmware.Memo1.Lines.Add('Прошивка:');
frmCompileFirmware.Memo1.Lines.Add(#9'Используется перевод для версии: '+ FirmwareVersion+' ('+ID1+'_'+ID2+')');
frmCompileFirmware.Memo1.Lines.Add(#9'Имя файла прошивки: '+ FirmwareFile);
if AddonsChck then
frmCompileFirmware.Memo1.Lines.Add(#9'Папка для дополнений: '+ AddonsDir);
frmCompileFirmware.Memo1.Lines.Add(#9);
frmCompileFirmware.Memo1.Lines.Add('Дополнения:');
if MainForm.AddonsChecked[0] then frmCompileFirmware.Memo1.Lines.Add(#9'CPU Control');
if MainForm.AddonsChecked[1] then frmCompileFirmware.Memo1.Lines.Add(#9'Дополнения KDG');
if MainForm.AddonsChecked[2] then frmCompileFirmware.Memo1.Lines.Add(#9'Шрифт Android 4.0');
if MainForm.AddonsChecked[3] then frmCompileFirmware.Memo1.Lines.Add(#9'Sony Bravia Engine');
if MainForm.AddonsChecked[4] then frmCompileFirmware.Memo1.Lines.Add(#9'Sony XLoud');
if MainForm.AddonsChecked[5] then frmCompileFirmware.Memo1.Lines.Add(#9'Тема с дополнительными значками');
if MainForm.AddonsChecked[6] then frmCompileFirmware.Memo1.Lines.Add(#9'Подготовка к OTA');
if MainForm.AddonsChecked[7] then frmCompileFirmware.Memo1.Lines.Add(#9'Перевод 4WayReboot');
if MainForm.AddonsChecked[8] then frmCompileFirmware.Memo1.Lines.Add(#9'MineField mode');
frmCompileFirmware.Memo1.Lines.Add(#9);
frmCompileFirmware.Memo1.Lines.Add('Все готово для компиляции!');
btnNext.Enabled:=False;
btnBack.Enabled:=False;
end;
if pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Controls[0].Name='frmAddons' then begin
frmAddons:=pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Controls[0] as TfrmAddons;
if FileExists(WorkDir+'Settings\FilesToDelete.conf') then frmAddons.lstDelete.Items.LoadFromFile(WorkDir+'Settings\FilesToDelete.conf')
else begin
ForceDirectories(WorkDir+'Settings');
frmAddons.lstDelete.Items.Add('AppShare.apk');
frmAddons.lstDelete.Items.Add('SimpleLiveWallpaper.apk');
frmAddons.lstDelete.Items.Add('MIUIStats.apk');
frmAddons.lstDelete.Items.Add('Compass.apk');
frmAddons.lstDelete.Items.SaveToFile(WorkDir+'Settings\FilesToDelete.conf');
end;
btnNext.Enabled:=True;
end;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
GitHubs.Free;
AddonItegrateScriptList.Free;
AddonIntegateList.Free;
PasswordList.Free;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
JavaVersion:string;
Registry:TRegistry;
i:Integer;
IniFile:TIniFile;
begin
IniFile:=TIniFile.Create(WorkDir+'Settings\Settings.conf');
GitHubRepository:='git://github.com/miuirussia/miui-russian-translation.git';
OTAUpdateServer:=IniFile.ReadString('Server', 'DownloadServer', 'http://ota.miuirussia.com/OTAS/')+IniFile.ReadString('Server', 'WorkName', 'Noned')+'/update.php';
//OTAUpdateServer:='http://ota.miuirussia.com/KDG/update.php';
if CheckWin32Version(5,4) then rkAeroTabs1.ColorBackground := clBlack;
JavaHome:='Null';
with TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY) do
begin
try
RootKey:=HKEY_LOCAL_MACHINE;
if OpenKey('SOFTWARE\JavaSoft\Java Runtime Environment',False) then
begin
JavaVersion:=ReadString('CurrentVersion');
end;
CloseKey;
if OpenKey('SOFTWARE\JavaSoft\Java Runtime Environment\'+JavaVersion,False) then
begin
JavaHome:=ReadString('JavaHome');
end;
CloseKey;
finally
free;
end;
end;
WorkDir:=ExtractFilePath(Application.ExeName);
DataDir:=IncludeTrailingBackslash(IncludeTrailingBackslash(WorkDir)+'Data');
aAppsDir:=IncludeTrailingBackslash(IncludeTrailingBackslash(DataDir)+'aApps');
for i := 0 to 9 do AddonsChecked[i]:=False;
AddToLog('I', 'WorkDir: '+WorkDir);
AddToLog('I', 'DataDir: '+DataDir);
AddToLog('I', 'aAppsDir: '+aAppsDir);
AddToLog('I', 'JavaHome: '+JavaHome);
if JavaHome='Null' then begin
ShowMessage('Failed to initialize JVM. Please reinstall Java');
Application.Terminate;
Exit;
end;
rkAeroTabs1.Tabs.Clear;
rkAeroTabs1.Tabs.Add(MainForm.Caption);
lblInfoText.Caption:='Начало';
CreateStartPage;
CreateGitHubPage;
CreateOpenFirmware;
CreateAddonsPage;
CreateCompileFirmware;
CreateFinishPage;
pgcMainControl.ActivePageIndex:=0;
AddonsChck:=False;
btnBack.Enabled:=False;
AddonItegrateScriptList:=TStringList.Create;
AddonIntegateList:=TStringList.Create;
PasswordList:=TStringList.Create;
PasswordList.Add({„обавить свои пароли});
end;
procedure TMainForm.Image1Click(Sender: TObject);
begin
ShowHelp(pgcMainControl.Pages[pgcMainControl.ActivePageIndex].Controls[0].Name);
end;
end.
|
unit mcpUtilsUnit;
interface
{
*************************************************************************
prj: MinexBank Profit Calculator
ver: 0.3
wtf address : inbox2@zoho.com
donate MNX : XLJ2FXXB7gRLFiThd7WGyVgerhXje5FqBR
Used components\libs:
DevExpress VCL 17.1.5 (http://devexpress.com)
ICS V8.51 (http://wiki.overbyte.eu)
Synopse mORMot (http://synopse.info)
*************************************************************************
}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Math,
Dialogs, System.StrUtils, SynCommons;
function lc_microparse(src, _begin, _end: string): string;
function parse_mnxexplorerbalance(s: string): Double;
function GetTotalProfitFromExistingDeposit(const depamount, bankrate: Extended; rounds: Integer; inc_round_profit: Boolean): Extended;
function GetDepositForExpectingProfit(const expamount, bankrate: Extended; maxrounds: Integer; inc_round_profit, biqORequal: Boolean): Extended;
function GetPeriodCountForExpectingProfit(const existing_amount, expamount, bankrate: Extended; inc_round_profit, biqORequal: Boolean): Integer;
procedure procCalc(am: Extended; rate: Extended; rounds: Integer; incprofit: Boolean; var r_profit: Extended);
procedure procCalc2(const exp: Extended; biqORequal: Boolean; rate: Extended; maxRounds: Integer; incprofit: Boolean; var r_deposit, r_profit: Extended);
procedure procCalc3(am, exp: Extended; rate: Extended; biqORequal: Boolean; var rounds: Integer; var r_profit: Extended);
implementation
function GetTotalProfitFromExistingDeposit(const depamount, bankrate: Extended; rounds: Integer; inc_round_profit: Boolean): Extended;
var
I: Integer;
round_profit, p_amount : Extended;
begin
result := 0;
if bankrate = 0 then Exit;
p_amount := depamount;
for I := 1 to rounds do
begin
round_profit := p_amount / 100 * bankrate; //Профит раунда
result := result + round_profit; //Сумма всех профитов
if inc_round_profit then p_amount := round_profit + p_amount;
end;
end;
function GetDepositForExpectingProfit(const expamount, bankrate: Extended; maxrounds: Integer; inc_round_profit, biqORequal: Boolean): Extended;
var
tmpdep: Extended;
tmpTotalProfit: Extended;
begin
result := 0;
if (bankrate = 0) or (expamount = 0) then Exit;
result := ( expamount / (bankrate*maxrounds) ) * 100;
tmpTotalProfit := GetTotalProfitFromExistingDeposit(result, bankrate, maxrounds, inc_round_profit);
if expamount = tmpTotalProfit then Exit;
if not inc_round_profit then Exit;
tmpdep := Result;
while tmpTotalProfit > expamount do
begin
tmpdep := tmpdep - 0.001;
tmpTotalProfit := GetTotalProfitFromExistingDeposit(tmpdep, bankrate, maxrounds, true);
end;
if biqORequal then Result := tmpdep+ 0.001;
end;
function GetPeriodCountForExpectingProfit(const existing_amount, expamount, bankrate: Extended; inc_round_profit, biqORequal: Boolean): Integer;
var prof: Extended;
begin
Result := 0;
prof := 0;
if bankrate =0 then Exit;
if biqORequal then
begin
while not (prof >= expamount) do
begin
Inc(Result);
prof := GetTotalProfitFromExistingDeposit(existing_amount, bankrate, Result, inc_round_profit);
end;
end
else
begin
while (prof <= expamount) do
begin
Inc(Result);
prof := GetTotalProfitFromExistingDeposit(existing_amount, bankrate, Result, inc_round_profit);
end;
end;
{ SetRoundMode(rmNearest);
if expamount < existing_amount then
begin
if biqORequal then
Result := Round(expamount / ((existing_amount) / 100 * bankrate) )
else
Result := Round(expamount / ((existing_amount+expamount) / 100 * bankrate) );
if Result < 1 then Result := 1;
end; }
end;
function lc_microparse(src, _begin, _end: string): string;
var i_begin, i_end: Integer;
begin
i_begin := Pos( _begin, src);
i_end := System.StrUtils.PosEx(_end, src, i_begin);
Result := Trim( Copy(src, i_begin + _begin.Length, i_end-(i_begin + _begin.Length) ) );
end;
function parse_mnxexplorerbalance(s: string): Double;
const substr_mark_begin1 = '<td>Total balance</td>';
substr_mark_begin2 = '<td>';
substr_mark_end = '</td>';
var i_begin, i_end: Integer;
tms: string;
begin
result := -1;
i_begin := Pos( substr_mark_begin1, s);
if i_begin < 1 then Exit;
i_begin := System.StrUtils.PosEx(substr_mark_begin2, s, i_begin+substr_mark_begin1.Length+1);
i_end := System.StrUtils.PosEx(substr_mark_end, s, i_begin+1);
tms := Copy( s, i_begin+substr_mark_begin2.Length, i_end -(i_begin + substr_mark_begin2.Length) );
//Result := tms;
i_end := Pos(' ', tms);
FormatSettings.DecimalSeparator := '.';
tms := Trim(Copy(tms, 1, i_end));
tms := ReplaceStr(tms, ',', '');
result := StrToFloat( Trim(tms) );
// result := StrToFloat( Trim(Copy(tms, 1, i_end)) );
FormatSettings.DecimalSeparator := ','; {}
end;
// calculate profit from existing amount of mnx
procedure procCalc(am: Extended; rate: Extended; rounds: Integer; incprofit: Boolean; var r_profit: Extended);
var
I: Integer;
round_profit, p_amount : Extended;
begin
r_profit := 0;
p_amount := am;
for I := 1 to rounds do
begin
round_profit := p_amount / 100 * rate; //Профит раунда
r_profit := r_profit + round_profit; //Сумма всех профитов
if incprofit then p_amount := round_profit + p_amount;
end;
end;
// calculate deposit for expecting profit amount [with parks limit]
procedure procCalc2(const exp: Extended; biqORequal: Boolean; rate: Extended; maxRounds: Integer; incprofit: Boolean;
var r_deposit, r_profit: Extended);
var tmpdep: Extended;
begin
r_deposit := ( exp / (rate*maxRounds) ) * 100;
procCalc(r_deposit, rate, maxRounds, incprofit, r_profit);
if not incprofit then Exit;
if exp = r_profit then Exit;
tmpdep := r_deposit;
while r_profit > exp do
begin
tmpdep := tmpdep - 0.001;
procCalc(tmpdep, rate, maxRounds, true, r_profit);
end;
if biqORequal then r_deposit := tmpdep+ 0.001;
procCalc(r_deposit, rate, maxRounds, true, r_profit);
end;
// calculate period for expecting profit amount from existing amount of mnx
procedure procCalc3(am, exp: Extended; rate: Extended; biqORequal: Boolean; var rounds: Integer; var r_profit: Extended);
begin
{
calt time
rate 2%:
wEightOne Needs 6 mnx
rounds 3
}
end;
end.
|
unit uController.Cliente;
interface
uses
DB,
DBClient,
Classes,
System.JSON,
uDM,
uController.Base,
DataSet.Serialize,
Horse;
type
TControllerCliente = class(TControllerBase)
public
procedure Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Store(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
end;
var
ControllerCliente: TControllerCliente;
implementation
uses
System.SysUtils;
{ TControllerCliente }
procedure TControllerCliente.Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
begin
Res.Send<TJSONArray>(DM.cdsCliente.ToJSONArray());
end;
procedure TControllerCliente.Store(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Body: TJSONObject;
begin
Body := Req.Body<TJSONObject>;
//------------------------------------------------------------------------------
// Valida parâmetros obrigatórios
//------------------------------------------------------------------------------
if not Assigned(Body.Values['name']) then
raise EHorseException.Create('O parâmetro "name" é obrigatório.');
if not Assigned(Body.Values['user_id']) then
raise EHorseException.Create('O parâmetro "user_id" é obrigatório.');
//------------------------------------------------------------------------------
// Valida chave estrangeira
//------------------------------------------------------------------------------
if not DM.cdsUsuario.Locate('ID', Body.Values['user_id'].Value.ToInteger, []) then
raise EHorseException.Create('Usuário não encontrado.');
DM.cdsCliente.Append;
DM.cdsCliente.FieldByName('NOME').AsString := Body.Values['name'].Value;
DM.cdsCliente.FieldByName('USUARIO_ID').AsInteger := Body.Values['user_id'].Value.ToInteger;
DM.cdsCliente.FieldByName('ENDERECO').AsString := Body.Values['address'].Value;
DM.cdsCliente.FieldByName('DATE_CAD').AsDateTime := Now;
DM.cdsCliente.Post;
Salvar;
Res.Status(200);
end;
procedure TControllerCliente.Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Id: Integer;
Body: TJSONObject;
begin
Id := Req.Params.Items['id'].ToInteger;
Body := Req.Body<TJSONObject>;
//------------------------------------------------------------------------------
// Valida
//------------------------------------------------------------------------------
if not DM.cdsCliente.Locate('ID', Id, []) then
raise EHorseException.Create('Cliente não encontrado.');
//------------------------------------------------------------------------------
// Salva
//------------------------------------------------------------------------------
DM.cdsCliente.Edit;
if Assigned(Body.Values['name']) then
DM.cdsCliente.FieldByName('NOME').AsString := Body.Values['name'].Value;
if Assigned(Body.Values['user_id']) then
begin
if not DM.cdsUsuario.Locate('ID', Body.Values['user_id'].Value.ToInteger, []) then
begin
Res.Send(TJSONObject.Create(TJSONPair.Create('error', 'Usuário não encontrado'))).Status(400);
Exit;
end;
DM.cdsCliente.FieldByName('USUARIO_ID').AsInteger := Body.Values['user_id'].Value.ToInteger;
end;
if Assigned(Body.Values['address']) then
DM.cdsCliente.FieldByName('ENDERECO').AsString := Body.Values['address'].Value;
DM.cdsCliente.FieldByName('DATE_UPDATE').AsDateTime := Now;
DM.cdsCliente.Post;
Salvar;
Res.Status(200);
end;
procedure TControllerCliente.Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Id: Integer;
begin
Id := Req.Params.Items['id'].ToInteger;
//------------------------------------------------------------------------------
// Valida
//------------------------------------------------------------------------------
if not DM.cdsCliente.Locate('ID', Id, []) then
raise EHorseException.Create('Cliente não encontrado.');
//------------------------------------------------------------------------------
// Salva
//------------------------------------------------------------------------------
DM.cdsCliente.Delete;
Salvar;
Res.Status(200);
end;
end.
|
{ ***************************************************************************
SPELL (Simple Programming Language)
Инструкция к языку расположена в файле spell.doc.
Машина при старте скрипта запускает функцию void main().
*************************************************************************** }
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, XPMan;
type
TfrmMain = class(TForm)
XPManifest: TXPManifest;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
mnuMain: TMainMenu;
mniFile: TMenuItem;
mniFileNew: TMenuItem;
mniFileOpen: TMenuItem;
mniFileSave: TMenuItem;
mniFileBreak1: TMenuItem;
mniFileExit: TMenuItem;
mniProject: TMenuItem;
mniProjectRun: TMenuItem;
memMain: TMemo;
mniFileSaveAs: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure mniFileNewClick(Sender: TObject);
procedure mniFileOpenClick(Sender: TObject);
procedure mniFileSaveClick(Sender: TObject);
procedure mniFileSaveAsClick(Sender: TObject);
procedure mniFileExitClick(Sender: TObject);
procedure mniProjectRunClick(Sender: TObject);
procedure memMainChange(Sender: TObject);
private
FFileName: String;
FModify: Boolean;
function FileTitle: String;
function SaveQuery: Boolean;
procedure SetFileName(const Value: String);
procedure SetModify(const Value: Boolean);
public
property FileName: String read FFileName write SetFileName;
property Modify: Boolean read FModify write SetModify;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
Scripts, Codes;
const
FILENAME_NEW = '';
{ TfrmMain }
{ published }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FileName := FILENAME_NEW;
Modify := False;
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := SaveQuery;
end;
procedure TfrmMain.mniFileNewClick(Sender: TObject);
begin
if not SaveQuery then
Exit;
memMain.Clear;
FileName := FILENAME_NEW;
Modify := False;
end;
procedure TfrmMain.mniFileOpenClick(Sender: TObject);
begin
if not SaveQuery then
Exit;
if dlgOpen.Execute then
begin
FileName := dlgOpen.FileName;
memMain.Lines.LoadFromFile(FFileName);
Modify := False;
end;
end;
procedure TfrmMain.mniFileSaveClick(Sender: TObject);
begin
if FFileName = FILENAME_NEW then
mniFileSaveAs.Click
else
begin
memMain.Lines.SaveToFile(FFileName);
Modify := False;
end;
end;
procedure TfrmMain.mniFileSaveAsClick(Sender: TObject);
var
lExt, lFileName: String;
begin
dlgSave.FileName := FFileName;
if dlgSave.Execute then
begin
lFileName := dlgSave.FileName;
lExt := AnsiLowerCase(ExtractFileExt(lFileName));
if lExt = '' then
lFileName := lFileName + '.spl';
FileName := lFileName;
memMain.Lines.SaveToFile(FFileName);
Modify := False;
end;
end;
procedure TfrmMain.mniFileExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.mniProjectRunClick(Sender: TObject);
var
lScript: TScript;
lCode: TCode;
begin
lScript := TScript.Create;
lScript.Compile(memMain.Text);
lCode := TCode.Create;
lScript.Attach(lCode);
lCode.Compile('main();');
lCode.Run().Free;
lCode.Free;
lScript.Free;
end;
procedure TfrmMain.memMainChange(Sender: TObject);
begin
Modify := True;
end;
{ private }
function TfrmMain.FileTitle: String;
begin
if FFileName = FILENAME_NEW then
Result := 'SPELL - Новый проект'
else
Result := 'SPELL - ' + ExtractFileName(FFileName);
if FModify then
Result := Result + ' (изменён)';
end;
function TfrmMain.SaveQuery: Boolean;
begin
if FModify then
case Application.MessageBox('Вы хотите сохранить изменения?',
'Найдены изменения', MB_ICONWARNING or MB_YESNOCANCEL) of
IDYES:
begin
mniFileSave.Click;
Result := True;
end;
IDNO: Result := True;
IDCANCEL: Result := False;
else
Result := False;
end
else
Result := True;
end;
procedure TfrmMain.SetFileName(const Value: String);
begin
FFileName := Value;
Caption := FileTitle;
Application.Title := Caption;
end;
procedure TfrmMain.SetModify(const Value: Boolean);
begin
FModify := Value;
Caption := FileTitle;
Application.Title := Caption;
end;
end.
|
unit ncCustoSaver;
interface
type
TncCustoData = class
Produto : Integer;
TipoTran : Byte;
Cancelado : Boolean;
CustoU : Currency;
function Igual(B: TncCustoData): Boolean;
function AlterouProduto(B: TncCustoData): Boolean;
function AlteraCusto: Boolean;
constructor Create(aProduto: Integer; aTipoTran: Byte; aCancelado: Boolean; aCustoU: Currency);
end;
TncCustoSaver = class
FAntigo : TncCustoData;
FNovo : TncCustoData;
function RefreshCustoAntigo: Boolean;
function RefreshCustoNovo: Boolean;
constructor Create(aProduto: Integer; aTipoTran: Byte; aCancelado: Boolean; aCustoU: Currency);
destructor Destroy; override;
procedure setAntigo(aProduto: Integer; aTipoTran: Byte; aCancelado: Boolean; aCustoU: Currency);
end;
implementation
uses ncClassesBase;
{ TncCustoData }
function TncCustoData.AlteraCusto: Boolean;
begin
Result := (TipoTran in [trEstCompra, trAjustaCusto]) and (not Cancelado) and (CustoU>0);
end;
function TncCustoData.AlterouProduto(B: TncCustoData): Boolean;
begin
Result := (Produto<>B.Produto);
end;
constructor TncCustoData.Create(aProduto: Integer; aTipoTran: Byte;
aCancelado: Boolean; aCustoU: Currency);
begin
Produto := aProduto;
TipoTran := aTipoTran;
Cancelado := aCancelado;
CustoU := aCustoU;
end;
function TncCustoData.Igual(B: TncCustoData): Boolean;
begin
Result := (Produto=B.Produto) and (TipoTran=B.TipoTran) and (Cancelado=B.Cancelado) and (CustoU=B.CustoU);
end;
{ TncCustoSaver }
constructor TncCustoSaver.Create(aProduto: Integer; aTipoTran: Byte;
aCancelado: Boolean; aCustoU: Currency);
begin
FNovo := TncCustoData.Create(aProduto, aTipoTran, aCancelado, aCustoU);
FAntigo := nil;
end;
destructor TncCustoSaver.Destroy;
begin
if Assigned(FAntigo) then FAntigo.Free;
FNovo.Free;
inherited;
end;
function TncCustoSaver.RefreshCustoAntigo: Boolean;
begin
Result := (FAntigo<>nil) and FAntigo.AlterouProduto(FNovo) and FAntigo.AlteraCusto;
end;
function TncCustoSaver.RefreshCustoNovo: Boolean;
begin
if FAntigo<>nil then begin
Result := False;
if FAntigo.Igual(FNovo) then Exit;
if (not FAntigo.AlteraCusto) and (not FNovo.AlteraCusto) then Exit;
if FAntigo.AlterouProduto(FNovo) and (not FNovo.AlteraCusto) then Exit;
Result := True;
end else
Result := FNovo.AlteraCusto;
end;
procedure TncCustoSaver.setAntigo(aProduto: Integer; aTipoTran: Byte;
aCancelado: Boolean; aCustoU: Currency);
begin
if Assigned(FAntigo) then FAntigo.Free;
FAntigo := TncCustoData.Create(aProduto, aTipoTran, aCancelado, aCustoU);
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
SysUtils, LazFileUtils, LazUTF8, Forms, EditBtn, StdCtrls, Buttons,
ExtCtrls, Classes, Controls;
type
{ TfrmFileConvertor }
TfrmFileConvertor = class(TForm)
ApplicationProperties1: TApplicationProperties;
BitBtn1: TBitBtn;
edtFilename: TFileNameEdit;
Label1: TLabel;
mmoTextPreview: TMemo;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
procedure ApplicationProperties1DropFiles(Sender: TObject;
const FileNames: array of String);
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormDropFiles(Sender: TObject; const FileNames: array of String);
private
{ private declarations }
procedure ConvertFile(FileName: string);
public
{ public declarations }
end;
var
frmFileConvertor: TfrmFileConvertor;
implementation
{$R *.lfm}
{ TfrmFileConvertor }
procedure TfrmFileConvertor.FormCreate(Sender: TObject);
begin
end;
procedure TfrmFileConvertor.ApplicationProperties1DropFiles(Sender: TObject;
const FileNames: array of String);
begin
if FileExistsUTF8(FileNames[0]) then
ConvertFile(FileNames[0]);
end;
procedure TfrmFileConvertor.BitBtn1Click(Sender: TObject);
begin
if FileExistsUTF8(edtFilename.FileName) then
ConvertFile(edtFilename.FileName);
end;
procedure TfrmFileConvertor.FormDropFiles(Sender: TObject;
const FileNames: array of String);
begin
if FileExistsUTF8(FileNames[0]) then
ConvertFile(FileNames[0]);
end;
procedure TfrmFileConvertor.ConvertFile(FileName: string);
var
myFile : TextFile;
textLn, replacedLine, newFileName : string;
begin
edtFilename.Text := FileName;
mmoTextPreview.Lines.Clear;
newFileName := StringReplace(FileName, 'txt', 'csv', [rfReplaceAll, rfIgnoreCase]);
AssignFile(myFile, FileName);
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
ReadLn(myFile, textLn);
replacedLine := StringReplace(textLn, ';', ',', [rfReplaceAll, rfIgnoreCase]);
mmoTextPreview.Lines.Add(replacedLine);
end;
mmoTextPreview.Lines.SaveToFile(newFileName);
end;
end.
|
program add;
{ Simple program to add 2 integer arrays element by element. }
const
size = 5;
type
color = (red, blue, yellow, green, white, black, orange);
colors = set of color;
var
i: integer;
a: intarray;
{ adder }
procedure adder(var a,b : intarray);
var
i: integer;
begin
i := a + b;
end;
{ main }
begin
writeln('The array before call to adder:');
adder(a,a);
writeln('The array after call to adder:');
end.
|
{Implementation for class Statistic which write in file our statistics}
Unit Statist;
Interface
const _NUMBER_OF_ITERATION_ = 11;
type
p_Statistic = ^StatisticObj;
StatisticObj = object
private
{quantity request of source for everyone _NUMBER_OF_ITERATION_}
kol : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
{quantity requst of source have processed for everyone _NUMBER_OF_ITERATION_}
kobr : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
{quantity request of source have got reject for everyone _NUMBER_OF_ITERATION_}
kotk : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
{probability of reject}
probabilityOfReject : array[1..2,0.._NUMBER_OF_ITERATION_] of real;
{common probability Of Reject}
commonProbabilityOfReject : array[0.._NUMBER_OF_ITERATION_] of real;
{counter quantity of request sent in buffer}
quantityOfRequestInBuffer : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
{average processing time}
averageQuantityRequestInBuffer : array[1..2] of longint;
{average expection time}
averageExpectionTime : array[1..2,1.._NUMBER_OF_ITERATION_] of real;
{common average expection time}
commonAverageExpectionTime : array[1.._NUMBER_OF_ITERATION_] of real;
{request Reached Device}
requestReachedDevice : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
{request going in device instantly}
requestGoingInstantlyToDevice : array[1..2,1.._NUMBER_OF_ITERATION_] of longint;
public
{initialization our the massive for statistics}
constructor Init(probabilityOfReject_ : real);
{increment quantity request of source}
procedure incrementKol(i, numberOfIteration: longint);
{increment quantity request of source have processed}
procedure incrementKobr(i, numberOfIteration: longint);
{increment quantity request of source have got reject}
procedure incrementKotk(i, numberOfIteration: longint);
{calculate probability of reject}
procedure calculateProbabilityOfReject(numberOfIteration : longint);
{change average processing time after new request in buffer}
procedure calculateAverageQuantityRequestInBuffer(i : longint);
{change average expection time after new request in buffer}
procedure newAverageExpectionTime(i, iteration : longint; newTime : real);
{calculate common average expection time}
procedure calculateAverageExpectionTime(numberOfIteration : longint);
{increment quantityOfRequestInBuffer}
procedure incrementQuantityRequestInBuffer(i, iteration : longint);
{increment quantityOfRequestInBuffer}
procedure incrementRequestGoingInstantlyToDevice(i, iteration : longint);
{reset all field}
procedure resetField;
{getters for all field of class}
function getKol(i, numberOfIteration : longint) : longint;
function getKobr(i, numberOfIteration : longint) : longint;
function getKotk(i, numberOfIteration : longint) : longint;
function getProbabilityOfReject(i, numberOfIteration : longint) : real;
function getCommonProbabilityOfReject(numberOfIteration : longint) : real;
function getAverageQuantityRequestInBuffer(i : longint) : longint;
function getAverageExpectionTime(i, numberOfIteration : longint) : real;
function getCommonAvExpTime(numberOfIteration : longint) : real;
function getQuantityRequestInBuffer(i, numberOfIteration : longint) : longint;
function getRequestGoingInstantlyToDevice(i, numberOfIteration : longint) : longint;
end;
Implementation
constructor StatisticObj.Init;
begin
probabilityOfReject[1,0] := probabilityOfReject_;
probabilityOfReject[2,0] := probabilityOfReject_;
commonProbabilityOfReject[0] := probabilityOfReject_;
end;
procedure StatisticObj.resetField;
var
i, j : longint;
begin
for i := 1 to 2 do
begin
for j := 1 to _NUMBER_OF_ITERATION_ do
begin
kol[i,j] := 0;
kobr[i,j] := 0;
kotk[i,j] := 0;
averageQuantityRequestInBuffer[i] := 0;
averageExpectionTime[i,j] := 0;
quantityOfRequestInBuffer[i,j] := 0;
probabilityOfReject[i,j] := 0;
commonProbabilityOfReject[j] := 0;
commonAverageExpectionTime[j] := 0;
requestReachedDevice[i,j] := 0;
requestGoingInstantlyToDevice[i,j] := 0;
end;
end;
end;
procedure StatisticObj.incrementKol;
begin
inc(kol[i, numberOfIteration]);
end;
procedure StatisticObj.incrementKobr;
begin
inc(kobr[i, numberOfIteration]);
end;
procedure StatisticObj.incrementKotk;
begin
inc(kotk[i, numberOfIteration]);
end;
procedure StatisticObj.calculateProbabilityOfReject;
var
i : longint;
begin
for i := 1 to 2 do
probabilityOfReject[i, numberOfIteration] :=
kotk[i, numberOfIteration] / kol[i, numberOfIteration];
commonProbabilityOfReject[numberOfIteration] :=
(probabilityOfReject[1, numberOfIteration] + probabilityOfReject[2, numberOfIteration]) / 2;
end;
procedure StatisticObj.calculateAverageQuantityRequestInBuffer;
var
temp : longint;
j : longint;
begin
temp := 0;
for j := 1 to _NUMBER_OF_ITERATION_ do
temp :=temp + quantityOfRequestInBuffer[i, j];
averageQuantityRequestInBuffer[i] := round(temp / _NUMBER_OF_ITERATION_);
end;
procedure StatisticObj.newAverageExpectionTime;
begin
averageExpectionTime[i, iteration] := (averageExpectionTime[i, iteration] *
requestReachedDevice[i, iteration] + newTime) / (requestReachedDevice[i, iteration] + 1);
inc(requestReachedDevice[i, iteration]);
end;
procedure StatisticObj.calculateAverageExpectionTime;
begin
commonAverageExpectionTime[numberOfIteration] := (averageExpectionTime[1, numberOfIteration] +
averageExpectionTime[2, numberOfIteration]) / 2;
end;
procedure StatisticObj.incrementQuantityRequestInBuffer;
begin
inc(quantityOfRequestInBuffer[i, iteration]);
end;
procedure StatisticObj.incrementRequestGoingInstantlyToDevice;
begin
inc(requestGoingInstantlyToDevice[i, iteration]);
end;
function StatisticObj.getKol;
begin
getKol := kol[i, numberOfIteration];
end;
function StatisticObj.getKobr;
begin
getKobr := kobr[i, numberOfIteration];
end;
function StatisticObj.getKotk;
begin
getKotk := kotk[i, numberOfIteration];
end;
function StatisticObj.getProbabilityOfReject;
begin
getProbabilityOfReject := kotk[i, numberOfIteration] / kol[i, numberOfIteration];
end;
function StatisticObj.getAverageExpectionTime;
begin
getAverageExpectionTime := averageExpectionTime[i, numberOfIteration];
end;
function StatisticObj.getQuantityRequestInBuffer;
begin
getQuantityRequestInBuffer := quantityOfRequestInBuffer[i, numberOfIteration];
end;
function StatisticObj.getAverageQuantityRequestInBuffer;
begin
calculateAverageQuantityRequestInBuffer(i);
getAverageQuantityRequestInBuffer := averageQuantityRequestInBuffer[i];
end;
function StatisticObj.getCommonAvExpTime;
begin
calculateAverageExpectionTime(numberOfIteration);
getCommonAvExpTime := commonAverageExpectionTime[numberOfIteration];
end;
function StatisticObj.getCommonProbabilityOfReject(numberOfIteration : longint) : real;
begin
getCommonProbabilityOfReject := commonProbabilityOfReject[numberOfIteration];
end;
function StatisticObj.getRequestGoingInstantlyToDevice;
begin
getRequestGoingInstantlyToDevice := requestGoingInstantlyToDevice[i, numberOfIteration];
end;
BEGIN
END. |
unit PrimesSieve;
interface
type
TNumberValue = Cardinal; //Cardinal compatible with D7, else must be - NativeUInt - compiler depended size (x32 or x64) or partial arrays in sieve for UInt64
TPrimesSieve = class
private
FSieve: array of Boolean;
FCurrent: TNumberValue;
FSize: TNumberValue;
public
constructor Create(ASize: TNumberValue);
function GetNext(out ANumber: TNumberValue): Boolean;
end;
implementation
{ TPrimesSieve }
constructor TPrimesSieve.Create(ASize: TNumberValue);
var
l, k: TNumberValue;
begin
FCurrent := 1;
FSize := ASize;
SetLength(FSieve, FSize - 1);
k := 2;
while (FSize >= (k * k)) do
begin
if not FSieve[k] then
begin
l := k * k;
while FSize >= l do
begin
FSieve[l] := True;
l := l + k;
end;
end;
Inc(k);
end;
end;
function TPrimesSieve.GetNext(out ANumber: TNumberValue): Boolean;
begin
while (FCurrent < FSize) do
begin
Inc(FCurrent);
if not FSieve[FCurrent] then
begin
ANumber := FCurrent;
Result := True;
Exit;
end;
end;
Result := False;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный клас-переходник между библиотечным интерфейсом
предоставления данных для чарта (ISCInputDataCollection) и
выборкой данных (IStockDataQuery)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.DataQueryToInputDataCollectionMediator;
{$I Compiler.inc}
interface
uses BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,FC.Definitions, StockChart.Obj;
type
//----------------------------------------------------------------------------
TStockDataQueryToInputDataCollectionMediator = class (TSCInputDataCollection)
private
FDS : IStockDataQuery;
procedure CheckDataLoadedFor(index: integer);
public
constructor Create(aDS:IStockDataQuery; AOwner: ISCChangeNotifier);
destructor Destroy; override;
function ISCInputDataCollection_GetItem(Index: Integer): ISCInputData; override;
function DirectGetItem_DataDateTime(index: integer):TDateTime; override;
function DirectGetItem_DataClose(index: integer): TStockRealNumber; override;
function DirectGetItem_DataHigh(index: integer): TStockRealNumber; override;
function DirectGetItem_DataLow(index: integer): TStockRealNumber; override;
function DirectGetItem_DataOpen(index: integer): TStockRealNumber; override;
function DirectGetItem_DataVolume(index: integer): integer; override;
function Count: integer; override;
procedure SetDataQuery(aDS: IStockDataQuery);
function GetDataQuery: IStockDataQuery;
end;
implementation
uses Math;
{ TStockDataQueryToInputDataCollectionMediator }
constructor TStockDataQueryToInputDataCollectionMediator.Create(aDS: IStockDataQuery; AOwner: ISCChangeNotifier);
begin
inherited Create(AOwner,aDS.StockSymbol.GetTimeIntervalValue/MinsPerDay);
SetDataQuery(aDS);
end;
destructor TStockDataQueryToInputDataCollectionMediator.Destroy;
begin
inherited;
end;
procedure TStockDataQueryToInputDataCollectionMediator.CheckDataLoadedFor(index: integer);
begin
if (Index < 0) or (Index >= Count) then
raise ESCListIndexError.Create(Index);
if Index>=FList.Count then
while Index<>FList.Count-1 do
begin
AddItemInternal(FDS.GetDataDateTime,FDS.GetDataOpen,FDS.GetDataHigh,FDS.GetDataLow,FDS.GetDataClose,FDS.GetDataVolume);
FDS.Next;
end;
end;
function TStockDataQueryToInputDataCollectionMediator.Count: integer;
begin
if FDS=nil then
result:=0
else
result:=FDS.RecordCount;
end;
function TStockDataQueryToInputDataCollectionMediator.ISCInputDataCollection_GetItem(Index: Integer): ISCInputData;
begin
CheckDataLoadedFor(index);
result:=inherited ISCInputDataCollection_GetItem(index);
end;
procedure TStockDataQueryToInputDataCollectionMediator.SetDataQuery(aDS: IStockDataQuery);
begin
if FDS<>aDS then
begin
FDS:=aDS;
if aDS.StockSymbol.IsInfoAvailable then
begin
SetPricePrecision(aDS.StockSymbol.GetInfo.Digits);
SetPricesInPoint(Round(1/aDS.StockSymbol.GetInfo.Point));
end;
OnItemsChanged;
end;
end;
function TStockDataQueryToInputDataCollectionMediator.GetDataQuery: IStockDataQuery;
begin
result:=FDS;
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataOpen(index: integer): TStockRealNumber;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataOpen(index)
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataHigh(index: integer): TStockRealNumber;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataHigh(index)
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataDateTime(index: integer): TDateTime;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataDateTime(index)
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataVolume(index: integer): integer;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataVolume(index)
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataClose(index: integer): TStockRealNumber;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataClose(index)
end;
function TStockDataQueryToInputDataCollectionMediator.DirectGetItem_DataLow(index: integer): TStockRealNumber;
begin
CheckDataLoadedFor(index);
result:=inherited DirectGetItem_DataLow(index)
end;
end.
|
unit Test.Devices.Logica.SPT941.ReqCreator;
interface
uses Windows, TestFrameWork, Devices.Logica.SPT941, GMGlobals, Test.Devices.Base.ReqCreator, GmSqlQuery, Test.Devices.Base.ReqParser;
type
TSPT941ReqCreatorFortest = class(TSPT941ReqCreator)
protected
function CanRequestPack(): bool; override;
end;
TLogicaSPT941ReqCreatorTest = class(TDeviceReqCreatorTestBase)
private
procedure DropDevStates;
procedure LastReqTimeStates_CheckPeriod(n: int);
protected
procedure SetUp; override;
procedure TearDown; override;
function GetDevType(): int; override;
procedure DoCheckRequests(); override;
published
procedure LastReqTimeStates();
end;
implementation
uses DateUtils, SysUtils, GMConst, Threads.ResponceParser, UsefulQueries;
{ TLogicaReqCreatorTest }
procedure TLogicaSPT941ReqCreatorTest.DoCheckRequests;
var n: int;
begin
Check(ReqList.Count >= 3, 'Count = ' + IntToStr(ReqList.Count));
CheckReqHexString(0, 'FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF'); // инициализация линии
CheckReqHexString(1, '10 21 90 0 0 5 0 3F 0 0 0 0 12 21'); // запрос сеанса
CheckReqHexString(2, '10 21 90 01 00 74 00 ' + // заголовок
'72 ' + // FNC
'4A 3 0 3 4 4A 3 0 4 4 4A 3 0 5 4 4A 3 0 6 4 4A 3 0 7 4 4A 3 0 8 4 4A 3 0 9 4 4A 3 0 A 4 4A 3 0 B 4 ' + // DATA
'4A 3 0 C 4 4A 3 0 D 4 4A 3 0 E 4 4A 3 0 F 4 4A 3 0 10 4 4A 3 0 11 4 4A 3 0 12 4 4A 3 0 13 4 ' + // DATA cont.
'4A 3 0 0 8 4A 3 0 1 8 4A 3 0 2 8 4A 3 0 3 8 4A 3 0 4 8 4A 3 0 5 8 ' + // DATA cont.
'88 C9'); // CRC
Check(ReqList[2].ReqID = 1, 'ReqList[2].ReqID');
Check(ReqList[2].rqtp = rqtSPT941, 'ReqList[2].rqtp');
Check(ReqList[2].ReqLinkCount = 23, 'ReqList[2].ReqLinkCount');
n := StrToIntDef(QueryResult('select LastReqNumber from ObjectStates where ID_Obj = (select ID_Obj from Devices where ID_Device = ' + IntToStr(GetID_Device()) + ')'), 0);
Check(n >= 2, 'ObjectStates');
end;
function TLogicaSPT941ReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_SPT_941;
end;
procedure TLogicaSPT941ReqCreatorTest.LastReqTimeStates_CheckPeriod(n: int);
var ut: ULong;
i: int;
begin
ReqList.Clear();
ReqCreator.AddDeviceToSendBuf();
for i := High(FSPT941ArchReqPeriodTypes) downto n do
begin
ut := StrToIntDef(SQLReq_GetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[i].NameWithChannel(0)), 0);
Check(Abs(NowGM - ut) < UTC_MINUTE);
end;
end;
procedure TLogicaSPT941ReqCreatorTest.LastReqTimeStates;
begin
LastReqTimeStates_CheckPeriod(0);
Check(ReqList.Count > 400, 'FullCount = ' + IntToStr(ReqList.Count));
DropDevStates();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 40 * UTC_DAY);
LastReqTimeStates_CheckPeriod(0);
Check(ReqList.Count > 400, 'FullCount2 = ' + IntToStr(ReqList.Count));
DropDevStates();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 10 * UTC_DAY);
LastReqTimeStates_CheckPeriod(1);
Check(ReqList.Count > 100, 'MonthCount = ' + IntToStr(ReqList.Count));
DropDevStates();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 10 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[1].NameWithChannel(0), NowGM() - 8 * UTC_DAY);
LastReqTimeStates_CheckPeriod(2);
Check(ReqList.Count > 100, 'MonthCount2 = ' + IntToStr(ReqList.Count));
DropDevStates();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 10 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[1].NameWithChannel(0), NowGM() - 5 * UTC_DAY);
LastReqTimeStates_CheckPeriod(2);
Check(ReqList.Count > 5, 'DayCount = ' + IntToStr(ReqList.Count));
DropDevStates();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 10 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[1].NameWithChannel(0), NowGM() - 5 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[2].NameWithChannel(0), NowGM() - 2 * UTC_HOUR);
LastReqTimeStates_CheckPeriod(2);
Check(ReqList.Count > 5, 'DayCount2 = ' + IntToStr(ReqList.Count));
DropDevStates();
ReqList.Clear();
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[0].NameWithChannel(0), NowGM() - 10 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[1].NameWithChannel(0), NowGM() - 5 * UTC_DAY);
SQLReq_SetDevState(ReqCreator.ReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[2].NameWithChannel(0), NowGM() - 5 * UTC_MINUTE);
ReqCreator.AddDeviceToSendBuf();
Check(ReqList.Count = 3, 'NoRecCount = ' + IntToStr(ReqList.Count));
end;
procedure TLogicaSPT941ReqCreatorTest.DropDevStates();
begin
ExecSQL(Format('delete from DevStates where ID_Device = %d', [ReqCreator.ReqDetails.ID_Device]));
end;
procedure TLogicaSPT941ReqCreatorTest.SetUp;
begin
inherited SetUp;
DropDevStates();
end;
procedure TLogicaSPT941ReqCreatorTest.TearDown;
begin
inherited;
end;
{ TSPT941ReqCreatorFortest }
function TSPT941ReqCreatorFortest.CanRequestPack: bool;
begin
Result := true;
end;
initialization
RegisterTest('GMIOPSrv/Devices/Logica', TLogicaSPT941ReqCreatorTest.Suite);
end.
|
unit FC.Trade.Trader.Pips;
{$I Compiler.inc}
interface
uses
Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList,
Collections.Map, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage,
StockChart.Definitions.Drawing,Graphics;
type
IStockTraderPips = interface
['{E8728AFA-2446-4072-8C03-786D3640A09D}']
end;
//Свойства ордера
TStockOrderProperties=class;
IStockOrderProperties = interface (ISCAttribute)
['{051E6BF5-46FC-4A83-A365-D5B421CF6A89}']
function GetObject:TStockOrderProperties;
end;
TStockOrderProperties = class (TNameValuePersistentObjectRefCounted,IStockOrderProperties,ISCAttribute)
public
//Когда перевернулся 1H - тренд не в нашу сторону
H1TrendTurnTime:TDateTime;
//from IStockOrderProperties
function GetObject:TStockOrderProperties;
end;
TStockTraderPips = class (TStockTraderBase,IStockTraderPips)
private
//Это временные переменные, испольщуемые при трейдинге
FMA: ISCIndicatorMA;
FMAIndex: integer;
FPassedTimes:TMap<TDateTime,Boolean>;
FPassedTimes2:TMap<TDateTime,Boolean>;
protected
//Отрубаем стандартные механизмы установки ST TP
procedure SetTrailingStopAccordingProperty(aOrder: IStockOrder); override;
procedure SetStopLossAccordingProperty(aOrder: IStockOrder); override;
function CreateIndicatorMA(const aChart: IStockChart): ISCIndicatorMA;
procedure InitMA(const aMA:ISCIndicatorMA; it:TStockTimeInterval);
//форма для тестирования
function TestBenchDialogClass: TClass; override;
function Spread: TSCRealNumber;
function ToPrice(aPoints: integer): TSCRealNumber;
procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string);
procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string);
public
procedure SetProject(const aValue : IStockProject); override;
procedure OnBeginWorkSession; override;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
implementation
uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory,
FC.DataUtils;
const
TrendToOrderKind : array [TSCTrendType] of TStockOrderKind = (okBuy,okSell,okBuy);
const
aOrderMargin=0.0005;
{ TStockTraderPips }
constructor TStockTraderPips.Create;
begin
inherited Create;
UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]);
FPassedTimes:=TMap<TDateTime,Boolean>.Create;
FPassedTimes2:=TMap<TDateTime,Boolean>.Create;
end;
destructor TStockTraderPips.Destroy;
begin
inherited;
FreeAndNil(FPassedTimes);
FreeAndNil(FPassedTimes2);
end;
procedure TStockTraderPips.Dispose;
begin
inherited;
end;
function TStockTraderPips.CreateIndicatorMA(const aChart: IStockChart): ISCIndicatorMA;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'MA-'+aChart.StockSymbol.GetTimeIntervalName,true,aCreated) as ISCIndicatorMA;
if aCreated then
begin
InitMA(result,aChart.StockSymbol.TimeInterval);
end;
end;
procedure TStockTraderPips.OnBeginWorkSession;
begin
inherited;
FPassedTimes.Clear;
FPassedTimes2.Clear;
end;
procedure TStockTraderPips.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string);
begin
AddMarkToCharts(GetBroker.GetCurrentTime,
GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid),
aMarkType,aMessage);
end;
procedure TStockTraderPips.SetProject(const aValue: IStockProject);
begin
if GetProject=aValue then
exit;
inherited;
if aValue=nil then
while ExpertCount>0 do
DeleteExpert(0);
if aValue <> nil then
begin
FMA:=CreateIndicatorMA(aValue.GetStockChart(sti60));
end;
end;
procedure TStockTraderPips.SetStopLossAccordingProperty(aOrder: IStockOrder);
begin
//Ничего!
end;
procedure TStockTraderPips.SetTrailingStopAccordingProperty(aOrder: IStockOrder);
begin
//Ничего!
end;
function TStockTraderPips.TestBenchDialogClass: TClass;
begin
result:=nil;
end;
function TStockTraderPips.ToPrice(aPoints: integer): TSCRealNumber;
begin
result:=GetBroker.PointToPrice(GetSymbol,1);
end;
function TStockTraderPips.Spread: TSCRealNumber;
begin
result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread);
end;
procedure TStockTraderPips.UpdateStep2(const aTime: TDateTime);
var
i: integer;
aOrder: IStockOrder;
aBid{,aAsk}: TStockRealNumber;
aOpen : TStockRealNumber;
begin
for i := 0 to GetOrders.Count - 1 do
begin
aOrder:=GetOrders.Items[i];
if aOrder.GetState=osPending then
if MinutesBetween(aTime,aOrder.GetCreateTime)>60 then
aOrder.RevokePending();
end;
RemoveClosedOrders;
if LastOrderType<>lotNone then
exit;
FMAIndex:=FMA.GetInputData.FindExactMatched(aTime);
if FMAIndex=-1 then
raise EAlgoError.Create;
//Раньше нельзя начинать
if FMAIndex<max(FMA.GetPeriod,4) then
exit;
aBid:=GetBroker.GetCurrentPrice(GetSymbol,bpkBid);
//aAsk:=GetBroker.GetCurrentPrice(GetSymbol,bpkAsk);
if (FMA.GetValue(FMAIndex-2)<FMA.GetValue(FMAIndex-1)) and
(FMA.GetValue(FMAIndex-1)<FMA.GetValue(FMAIndex)) then
begin
aOpen:=aBid+Spread*2;//+ToPrice(1);
OpenOrderAt(okSell,
aOpen,
PropLotDefaultRateSize.Value,
aOpen+Spread*2,
aOpen-Spread*2,
0
);
end;
end;
procedure TStockTraderPips.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string);
begin
GetBroker.AddMessage(aOrder,aMessage);
AddMarkToCharts(GetBroker.GetCurrentTime,
GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid),
aMarkType,aMessage);
end;
procedure TStockTraderPips.InitMA(const aMA:ISCIndicatorMA; it:TStockTimeInterval);
begin
aMA.SetMAMethod(mamSimple);
aMA.SetShift(0);
aMA.SetPeriod(34);
aMA.SetApplyTo(atClose);
end;
{ TStockOrderProperties }
function TStockOrderProperties.GetObject: TStockOrderProperties;
begin
result:=self;
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','Pips',TStockTraderPips,IStockTraderPips);
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Menus, StdCtrls, Windows, ShellAPI;
type
{ TForm1 }
TForm1 = class(TForm)
btnHide: TButton;
btnSelectFolder: TButton;
Button1: TButton;
edtFind: TEdit;
edtCopyFilter: TEdit;
edtFolder: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Memo1: TMemo;
menuExit: TMenuItem;
menuShow: TMenuItem;
PopupMenu1: TPopupMenu;
dlgSelect: TSelectDirectoryDialog;
Timer1: TTimer;
TrayIcon1: TTrayIcon;
procedure btnHideClick(Sender: TObject);
procedure btnSelectFolderClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure menuExitClick(Sender: TObject);
procedure menuShowClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ private declarations }
public
{ private declarations }
end;
var
Form1: TForm1;
list: DWORD;
first_show:boolean=true;
const
MIN_FREE_SPACE = 200*1024*1024;
WAIT_AFTER_FINDED = 15*1000;
WAIT_BETWEEN_SCAN = 60*1000;
HIDE_AT_START = true;
implementation
{$R *.lfm}
{ TForm1 }
function GetDiskSize(drive: Char; var free_size, total_size: Int64): Boolean;
var
RootPath: array[0..4] of Char;
RootPtr: PChar;
current_dir: string;
begin
RootPath[0] := Drive;
RootPath[1] := ':';
RootPath[2] := '\';
RootPath[3] := #0;
RootPtr := RootPath;
current_dir := GetCurrentDir;
if SetCurrentDir(drive + ':\') then
begin
GetDiskFreeSpaceEx(RootPtr, Free_size, Total_size, nil);
// this to turn back to original dir
SetCurrentDir(current_dir);
Result := True;
end
else
begin
Result := False;
Free_size := -1;
Total_size := -1;
end;
end;
function CopyAllFiles(sFrom, sTo: string; Protect: boolean): boolean;
{ Copies files or directory to another directory. }
var
F: TShFileOpStruct;
ResultVal: integer;
tmp1, tmp2: string;
begin
FillChar(F{%H-}, SizeOf(F), #0);
Screen.Cursor := crHourGlass;
try
F.Wnd := 0;
F.wFunc := FO_COPY;
{ Add an extra null char }
tmp1 := sFrom + #0;
tmp2 := sTo + #0;
F.pFrom := PChar(tmp1);
F.pTo := PChar(tmp2);
if Protect then
F.fFlags := FOF_SIMPLEPROGRESS or FOF_NOCONFIRMATION or
FOF_SILENT or FOF_NOERRORUI //or FOF_RENAMEONCOLLISION
else
F.fFlags := FOF_SIMPLEPROGRESS;
F.fAnyOperationsAborted := False;
F.hNameMappings := nil;
Resultval := ShFileOperation(F);
Result := (ResultVal = 0);
finally
Screen.Cursor := crDefault;
end;
end;
procedure TForm1.menuExitClick(Sender: TObject);
begin
Form1.Close();
end;
procedure TForm1.menuShowClick(Sender: TObject);
begin
Form1.Show;
end;
function check1bit(ld: DWORD; i: integer):boolean;
begin
if (ld and (1 shl i)) <> 0 then
Result:=true
else
Result:=false;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
ld: DWORD;
i: integer;
tsr: TSearchRec;
finded: boolean;
free_size_read, total_size_read: Int64;
free_size_write, total_size_write: Int64;
cur_disk_letter: Char;
copyPath, copyFilter, findFilter: String;
begin
Timer1.Enabled:=false;
//Memo1.Lines.Add('work in');
ld:= GetLogicalDrives;
copyPath := UTF8ToAnsi(edtFolder.Text);
copyFilter := UTF8ToAnsi(edtCopyFilter.Text);
findFilter := UTF8ToAnsi(edtFind.Text);
for i:= 0 to 25 do begin
if (check1bit(ld,i) and (not check1bit(list,i))) then begin
cur_disk_letter:=Char(Ord('A')+i);
Memo1.Lines.Add( 'Added ' + cur_disk_letter + ':\' );
Memo1.Lines.Add('wait '+FloatToStr(WAIT_AFTER_FINDED / 1000)+' sec');
sleep(WAIT_AFTER_FINDED);
finded:=false;
if FindFirst( cur_disk_letter + ':\' + findFilter, faAnyFile,tsr) = 0
then begin
finded:=true;
end;
SysUtils.FindClose(tsr);
if finded then begin
if GetDiskSize(cur_disk_letter,free_size_read{%H-},total_size_read{%H-})
and GetDiskSize(copyPath[1],free_size_write{%H-},total_size_write{%H-})
then begin
if (free_size_write-MIN_FREE_SPACE) < (total_size_read-free_size_read)
then begin
Memo1.Lines.Add('disk is full, stopped');
Timer1.Enabled:=false;
end;
end
else begin
Memo1.Lines.Add('error at get space at disk '+cur_disk_letter);
end;
//copy
if CopyAllFiles( cur_disk_letter + ':\' + copyFilter, copyPath, true)
then Memo1.Lines.Add('ok')
else Memo1.Lines.Add('fail');
end;
end;
end;
list:=ld;
//Memo1.Lines.Add('work out');
Timer1.Enabled:=true;
end;
procedure TForm1.btnSelectFolderClick(Sender: TObject);
begin
if dlgSelect.Execute then
edtFolder.Caption:=dlgSelect.FileName;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ld: DWORD;
i: integer;
begin
ld:= GetLogicalDrives;
for i:= 0 to 25 do begin
if (ld and (1 shl i)) <> 0 then
Memo1.Lines.Text:=Memo1.Lines.Text+Char(Ord('A') + i);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
list:=GetLogicalDrives;
edtFolder.Text:=AnsiToUTF8(ExtractFilePath(Application.ExeName));
Timer1.Interval:=WAIT_BETWEEN_SCAN;
Timer1.Enabled:=true;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
if first_show then begin
if HIDE_AT_START then Form1.Hide;
first_show:=false;
end;
end;
procedure TForm1.btnHideClick(Sender: TObject);
begin
Form1.Hide;
end;
end.
|
unit ClasseCS;
interface
uses
Classes,
Db,
SysUtils,
SyncObjs,
CacheProp;
type
{$M+}
TClasseCS = class
private
FCacheProp : TCacheProp;
protected
function GetChave: Variant; virtual; abstract;
public
constructor Create;
destructor Destroy; override;
function HaAlteracoes: Boolean;
procedure AtualizaCache; // Salva valores propriedads para cache
procedure Reverte; // Salva valores em cache p/ propriedades
procedure LimpaCache; // Todos valores serao considerados alterados
procedure LeStream(S: TStream); virtual;
procedure LeReader(R: TCPReader; S: TStream); virtual;
procedure SalvaWriter(W: TCPWriter; SoAlterados: Boolean); virtual;
procedure SalvaStream(S: TStream; SoAlterados: Boolean); virtual;
procedure LeDataset(Tab: TDataset); virtual;
procedure SalvaDataset(Tab: TDataset); virtual;
procedure Assign(ObjFonte: TClasseCS); virtual;
function PropriedadesAlteradas: String;
property Chave: Variant
read GetChave;
end;
{$M-}
TCriaClasseCSFunc = function (TipoClasse: Integer): TClasseCS of Object;
TListaClasseCS = class
private
FTipoClasse : Integer;
FItens : TList;
FCriaClasse : TCriaClasseCSFunc;
FSyncObj : TCriticalSection;
protected
function GetItem(I: Integer): TClasseCS;
function GetItemPorChave(V: Variant): TClasseCS;
function GetCount: Integer; virtual;
public
constructor Create(aTipoClasse: Integer);
destructor Destroy; override;
procedure Limpa;
procedure Lock;
procedure Unlock;
procedure AtualizaCache;
procedure LeDataset(Tab: TDataset);
procedure SalvaDataset(Tab: TDataset);
procedure LeStream(S: TStream);
procedure SalvaStream(S: TStream);
procedure SalvaArquivo(Nome: String); virtual;
procedure LeArquivo(Nome: String); virtual;
procedure Add(Obj: TClasseCS);
function Remove(Obj: TClasseCS): Integer;
property Itens[I: Integer]: TClasseCS
read GetItem; default;
property ItemPorChave[V: Variant]: TClasseCS
read GetItemPorChave;
property Count: Integer
read GetCount;
property CriaClasse: TCriaClasseCSFunc
read FCriaClasse write FCriaClasse;
end;
implementation
{ TClasseCS }
procedure TClasseCS.AtualizaCache;
begin
FCacheProp.LeProps;
end;
constructor TClasseCS.Create;
begin
inherited;
FCacheProp := TCacheProp.Create(Self);
end;
destructor TClasseCS.Destroy;
begin
FCacheProp.Free;
inherited;
end;
procedure TClasseCS.LeReader(R: TCPReader; S: TStream);
begin
FCacheProp.LeReader(R, S);
end;
procedure TClasseCS.LeStream(S: TStream);
begin
FCacheProp.LeStream(S);
end;
procedure TClasseCS.Reverte;
begin
FCacheProp.Reverte;
end;
procedure TClasseCS.LimpaCache;
begin
FCacheProp.Limpa;
end;
procedure TClasseCS.SalvaDataset(Tab: TDataset);
var F: TField;
begin
FCacheProp.SalvaDataset(Tab);
F := Tab.FindField('ObjectInt');
if Assigned(F) then
F.AsInteger := Integer(Self);
end;
procedure TClasseCS.LeDataset(Tab: TDataset);
begin
FCacheProp.LeDataset(Tab);
end;
procedure TClasseCS.SalvaStream(S: TStream; SoAlterados: Boolean);
begin
try
FCacheProp.SalvaStream(S, SoAlterados);
except
on E: Exception do
Raise Exception.Create('TClasseCS.SalvaStream - Exception: ' + E.Message);
end;
end;
procedure TClasseCS.SalvaWriter(W: TCPWriter; SoAlterados: Boolean);
begin
try
FCacheProp.SalvaWriter(W, SoAlterados);
except
on E: Exception do
raise Exception.Create('TClasseCS.SalvaWriter - Exception: '+ E.Message);
end;
end;
procedure TClasseCS.Assign(ObjFonte: TClasseCS);
begin
FCacheProp.Assign(ObjFonte);
end;
function TClasseCS.HaAlteracoes: Boolean;
begin
Result := FCacheProp.Alterou;
end;
function TClasseCS.PropriedadesAlteradas: String;
begin
Result := FCacheProp.PropertiesAlteradas;
end;
procedure TListaClasseCS.LeArquivo(Nome: String);
var S: TStream;
begin
if not FileExists(Nome) then Exit;
S := TFileStream.Create(Nome, fmOpenRead);
try
LeStream(S);
finally
S.Free;
end;
end;
procedure TListaClasseCS.SalvaArquivo(Nome: String);
var S: TStream;
begin
S := TFileStream.Create(Nome, fmCreate);
try
SalvaStream(S);
finally
S.Free;
end;
end;
{ TListaClasseCS }
constructor TListaClasseCS.Create(aTipoClasse: Integer);
begin
inherited Create;
FTipoClasse := aTipoClasse;
FItens := TList.Create;
FCriaClasse := nil;
FSyncObj := TCriticalSection.Create;
end;
destructor TListaClasseCS.Destroy;
begin
Limpa;
FItens.Free;
FSyncObj.Free;
inherited;
end;
procedure TListaClasseCS.Limpa;
var Obj: TClasseCS;
begin
Lock;
try
while Count > 0 do begin
Obj := Itens[0];
FItens.Remove(Obj);
Obj.Free;
end;
finally
Unlock;
end;
end;
function TListaClasseCS.GetCount: Integer;
begin
Lock;
try
Result := FItens.Count;
finally
Unlock;
end;
end;
function TListaClasseCS.GetItem(I: Integer): TClasseCS;
begin
Lock;
try
Result := FItens[I];
finally
Unlock;
end;
end;
function TListaClasseCS.GetItemPorChave(V: Variant): TClasseCS;
var I : Integer;
begin
Lock;
try
for I := 0 to pred(Count) do
if Itens[I].Chave = V then begin
Result := Itens[I];
Exit;
end;
finally
Unlock;
end;
Result := nil;
end;
procedure TListaClasseCS.LeDataset(Tab: TDataset);
var Obj: TClasseCS;
begin
Lock;
try
Tab.First;
while not Tab.Eof do begin
Obj := FCriaClasse(FTipoClasse);
Obj.LeDataset(Tab);
FItens.Add(Obj);
Tab.Next;
end;
finally
Unlock;
end;
end;
procedure TListaClasseCS.LeStream(S: TStream);
var
R : TCPReader;
Obj : TClasseCS;
begin
Lock;
try
Limpa;
R := TCPReader.Create(S, 8192);
try
R.ReadListBegin;
while (not R.EndOfList) and (R.Position<(S.Size-1)) do begin
Obj := FCriaClasse(FTipoClasse);
Obj.LeReader(R, S);
FItens.Add(Obj);
end;
R.ReadListEnd;
finally
R.Free;
end;
finally
Unlock;
end;
end;
procedure TListaClasseCS.SalvaDataset(Tab: TDataset);
var I : Integer;
begin
Lock;
try
for I := 0 to pred(Count) do begin
Tab.Append;
Itens[I].SalvaDataset(Tab);
Tab.Post;
end;
finally
Unlock;
end;
end;
procedure TListaClasseCS.SalvaStream(S: TStream);
var
W : TCPWriter;
I : Integer;
P : String;
begin
P := '0';
try
W := TCPWriter.Create(S, 8192);
P := '1';
Lock;
P := '2';
try
P := '3';
W.WriteListBegin;
try
P := '4';
for I := 0 to pred(Count) do begin
P := '4-'+IntToStr(I);
Itens[I].SalvaWriter(W, False);
end;
P := '5';
finally
W.WriteListEnd;
end;
P := '6';
finally
Unlock;
W.Free;
end;
except
on E: Exception do begin
// DebugMsgEsp('TListaClasseCS.SalvaStream - P: '+P+' - Exception: '+ E.Message, False, True);
Raise;
end;
end;
end;
procedure TListaClasseCS.Add(Obj: TClasseCS);
begin
Lock;
try
if FItens.IndexOf(Obj) = -1 then
FItens.Add(Obj);
finally
Unlock;
end;
end;
function TListaClasseCS.Remove(Obj: TClasseCS): Integer;
begin
Lock;
try
Result := FItens.Remove(Obj);
finally
Unlock;
end;
end;
procedure TListaClasseCS.Lock;
begin
// FSyncObj.Enter;
end;
procedure TListaClasseCS.Unlock;
begin
// FSyncObj.Leave;
end;
procedure TListaClasseCS.AtualizaCache;
var
I : Integer;
begin
Lock;
try
for I := 0 to pred(Count) do Itens[I].AtualizaCache;
finally
Unlock;
end;
end;
end.
|
{
GMHeatmap unit
ES: contiene las clases bases necesarias para mostrar mapas de calor en un
mapa de Google Maps mediante el componente TGMHeatmap
EN: includes the base classes needed to show head maps on Google Map map using
the component TGMHeatmap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los
datos a mostrar. Añadir una entrada en el registro de Windows en la clave
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\MiAplicacion.exe = (DWORD) xxxxxx
donde xxxxxx es un valor según la tabla http://msdn.microsoft.com/en-us/library/ie/ee330730%28v=vs.85%29.aspx#browser_emulation
EN: put the component into a form, link to a TGMMap and put the data to
show. Add a registry entry at the key
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\MiAplicacion.exe = (DWORD) xxxxxx
where xxxxxx is a value according to this table http://msdn.microsoft.com/en-us/library/ie/ee330730%28v=vs.85%29.aspx#browser_emulation
=========================================================================
History:
ver 1.3.0
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
unit GMHeatmap;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMMap, GMClasses, GMConstants;
type
{*------------------------------------------------------------------------------
Base class for heat map.
More information at https://developers.google.com/maps/documentation/javascript/reference#HeatmapLayer
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para los mapas de calor.
Más información en https://developers.google.com/maps/documentation/javascript/reference#HeatmapLayer
-------------------------------------------------------------------------------}
TGMHeatmap = class(TGMObjects, ILinePoint)
private
FOpacity: Real;
FRadius: Integer;
FDissipating: Boolean;
FShow: Boolean;
FMaxIntensity: Real;
FData: TLinePoints;
FGradient: TGradient;
function GetItems(I: Integer): TLinePoint;
procedure SetShow(const Value: Boolean);
function GetCount: Integer;
procedure SetDissipating(const Value: Boolean);
procedure SetMaxIntensity(const Value: Real);
procedure SetOpacity(const Value: Real);
procedure SetRadius(const Value: Integer);
procedure SetGradient(const Value: TGradient);
protected
procedure HideHeapmap; virtual;
procedure ShowHeapmap; virtual;
function PolylineToStr: string;
function GetAPIUrl: string; override;
procedure DeleteMapObjects; override;
procedure ShowElements; override;
procedure EventFired(EventType: TEventType; Params: array of const); override;
{ ILinePoint }
procedure LinePointChanged;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure LoadFromCSV(LatColumn, LngColumn: Integer; FileName: string;
Delimiter: Char = ','; DeleteBeforeLoad: Boolean = True;
WithRownTitle: Boolean = True);
procedure Clear;
property Count: Integer read GetCount;
property Items[I: Integer]: TLinePoint read GetItems; default;
published
property Show: Boolean read FShow write SetShow default False;
property Data: TLinePoints read FData write FData;
property Dissipating: Boolean read FDissipating write SetDissipating default False;
property MaxIntensity: Real read FMaxIntensity write SetMaxIntensity;
property Opacity: Real read FOpacity write SetOpacity;
property Radius: Integer read FRadius write SetRadius default 15;
property Gradient: TGradient read FGradient write SetGradient default grHot;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
Lang, GMFunctions;
{ TGMHeatmap }
procedure TGMHeatmap.Clear;
begin
FData.Clear;
end;
constructor TGMHeatmap.Create(aOwner: TComponent);
begin
inherited;
FData := TLinePoints.Create(Self, TLinePoint);
FDissipating := False;
FMaxIntensity := 0;
FOpacity := 0.6;
FRadius := 15;
FGradient := grHot;
end;
procedure TGMHeatmap.DeleteMapObjects;
begin
//inherited;
end;
destructor TGMHeatmap.Destroy;
begin
if Assigned(FData) then FreeAndNil(FData);
inherited;
end;
procedure TGMHeatmap.EventFired(EventType: TEventType;
Params: array of const);
begin
//inherited;
end;
function TGMHeatmap.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#HeatmapLayer';
end;
function TGMHeatmap.GetCount: Integer;
begin
Result := FData.Count;
end;
function TGMHeatmap.GetItems(I: Integer): TLinePoint;
begin
Result := TLinePoint(FData[i]);
end;
procedure TGMHeatmap.HideHeapmap;
begin
ExecuteScript('HeapmapHide', IntToStr(IdxList));
end;
procedure TGMHeatmap.LinePointChanged;
begin
Show := False;
end;
procedure TGMHeatmap.LoadFromCSV(LatColumn, LngColumn: Integer;
FileName: string; Delimiter: Char; DeleteBeforeLoad, WithRownTitle: Boolean);
var
L1, L2: TStringList;
i: Integer;
Point: TLinePoint;
begin
if not FileExists(FileName) then
raise Exception.Create(GetTranslateText('El fichero no existe', Language));
if DeleteBeforeLoad then Clear;
L1 := TStringList.Create;
L2 := TStringList.Create;
try
L1.LoadFromFile(FileName);
if WithRownTitle then L1.Delete(0);
L2.Delimiter := Delimiter;
{$IFDEF DELPHI2005}
L2.StrictDelimiter := True;
{$ENDIF}
for i := 0 to L1.Count - 1 do
begin
L2.DelimitedText := L1[i];
if (LatColumn > L2.Count) or (LngColumn > L2.Count) then
raise Exception.Create(GetTranslateText('El número de columna es incorrecto', Language));
Point := FData.Add;
Point.Lat := Point.StringToReal(L2[LatColumn]);
Point.Lng := Point.StringToReal(L2[LngColumn]);
end;
if FShow then ShowHeapmap;
finally
if Assigned(L1) then FreeAndNil(L1);
if Assigned(L2) then FreeAndNil(L2);
end;
end;
function TGMHeatmap.PolylineToStr: string;
var
Points: array of TLatLng;
i: Integer;
begin
Result := '';
if not Assigned(Map) then Exit;
SetLength(Points, Count);
for i := 0 to FData.Count - 1 do
Points[i] := FData[i].GetLatLng;
Result := TGMGenFunc.PointsToStr(Points, GetMapPrecision);
end;
procedure TGMHeatmap.SetDissipating(const Value: Boolean);
begin
if FDissipating = Value then Exit;
FDissipating := Value;
Show := False;
end;
procedure TGMHeatmap.SetGradient(const Value: TGradient);
begin
if FGradient = Value then Exit;
FGradient := Value;
Show := False;
end;
procedure TGMHeatmap.SetMaxIntensity(const Value: Real);
begin
if FMaxIntensity = Value then Exit;
FMaxIntensity := Value;
Show := False;
end;
procedure TGMHeatmap.SetOpacity(const Value: Real);
begin
if FOpacity = Value then Exit;
FOpacity := Value;
if FOpacity < 0 then FOpacity := 0;
if FOpacity > 1 then FOpacity := 1;
FOpacity := Trunc(FOpacity * 100) / 100;
Show := False;
end;
procedure TGMHeatmap.SetRadius(const Value: Integer);
begin
if FRadius = Value then Exit;
FRadius := Value;
Show := False;
end;
procedure TGMHeatmap.SetShow(const Value: Boolean);
begin
if FShow = Value then Exit;
FShow := Value;
if FShow then ShowHeapmap
else HideHeapmap;
end;
procedure TGMHeatmap.ShowElements;
begin
//inherited;
end;
procedure TGMHeatmap.ShowHeapmap;
const
StrParams = '%s,%s,%s,%s,%s,%s';
var
Params: string;
begin
if csDesigning in ComponentState then Exit;
if not Assigned(Map) then
raise Exception.Create(GetTranslateText('Mapa no asignado', Language));
Params := Format(StrParams, [
IntToStr(IdxList),
QuotedStr(PolylineToStr),
LowerCase(TCustomTransform.GMBoolToStr(FDissipating, True)),
StringReplace(FloatToStr(FMaxIntensity), ',', '.', [rfReplaceAll]),
StringReplace(FloatToStr(FOpacity), ',', '.', [rfReplaceAll]),
IntToStr(FRadius),
QuotedStr(TCustomTransform.GradientToStr(FGradient))
]);
ExecuteScript('HeapmapShow', Params);
end;
end.
|
{*********************************************}
{ TeeGrid Software Library }
{ VirtualData from Records and Objects }
{ Copyright (c) 2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit Tee.Grid.Data.Rtti;
interface
{
Several classes to automatically link a TeeGrid with arrays or TList of
records and classes.
Example using arrays:
type
TPerson=record ... end; // <-- or class
var
MyData : TArray<TPerson>;
SetLength(MyData,10);
... fill MyData ....
TeeGrid1.Data:= TVirtualArrayData<TPerson>.Create(MyData);
Example using TList:
var
MyData : TList<TPerson>;
TeeGrid1.Data:= TVirtualListData<TPerson>.Create(MyData);
}
uses
Tee.Grid.Data, Tee.Grid.Columns, Tee.Painter,
System.Generics.Collections, System.Rtti, System.TypInfo;
type
TVirtualDataRtti=class(TVirtualData)
private
var
Parents : Array[0..99] of TColumn;
class function Add(const AColumns:TColumns;
const AMember:TRttiMember;
const AType:TRttiType):TColumn; overload; static;
class procedure DoSetValue(const AMember:TRttiMember; const P:Pointer; const Value:TValue); overload; static;
class procedure DoSetValue(const AColumn:TColumn; const P:Pointer; const Value:TValue); overload; static;
//function FinalPointer(AParent: TColumn; P:Pointer):Pointer;
function FinalValue(const AColumn: TColumn; const AValue:TValue):TValue; overload;
class function IsBoolean(const AType:TRttiType):Boolean; static;
class function IsDate(const AType:TRttiType):Boolean; static;
class function IsTime(const AType:TRttiType):Boolean; static;
class function IsDateTime(const AType:TRttiType):Boolean; static;
class function IsNumeric(const AType:TRttiType):Boolean; overload; static;
class function MemberOf(const AColumn:TColumn):TRttiMember; inline; static;
class function PointerOf(const AValue:TValue):Pointer; static;
class function TypeOf(const AColumn: TColumn): TRttiType; static;
class function ValueOf(const AMember:TRttiMember; const P:Pointer):TValue; overload; static;
class function ValueOf(const AColumn:TColumn; const P:Pointer):TValue; overload; static; inline;
end;
TVisibility=set of TMemberVisibility;
TRttiMembers=(Both, Fields, Properties);
TVirtualData<T>=class(TVirtualDataRtti)
private
class var
Context : TRttiContext;
var
FMembers : TRttiMembers;
FTypeInfo : PTypeInfo;
FVisibility : TVisibility;
procedure AddFields(const AColumns:TColumns; const AType:TRttiType);
procedure AddProperties(const AColumns:TColumns; const AType:TRttiType);
procedure DoAddColumns(const AColumns:TColumns; const AType:TRttiType);
procedure InternalAddType(const AColumns:TColumns;
const AMember:TRttiMember;
const AType:TRttiType);
function IsVisible(const AMember:TRttiMember):Boolean; inline;
class function NameOf(const AType:TRttiOrdinalType):String; overload; static;
class function NameOf(const AType:TRttiFloatType):String; overload; static;
public
Constructor Create(const AType:PTypeInfo;
const AVisibility:TVisibility=[mvPublic,mvPublished];
const AMembers:TRttiMembers=TRttiMembers.Both);
procedure AddColumns(const AColumns:TColumns); override;
function AutoWidth(const APainter:TPainter; const AColumn:TColumn):Single; override;
procedure Load; override;
end;
TVirtualArrayData<T>=class(TVirtualData<T>)
private
FArray : TArray<T>;
function FinalValue(const AColumn: TColumn; const ARow: Integer): TValue; overload;
procedure TryInt64(const AColumn: TColumn; const ARow: Integer; const AText: String);
procedure TryFloat(const AColumn: TColumn; const ARow: Integer; const AText: String);
public
Constructor Create(var Value: TArray<T>);
function AsString(const AColumn:TColumn; const ARow:Integer):String; override;
function Count:Integer; override;
procedure SetValue(const AColumn:TColumn; const ARow:Integer; const AText:String); override;
end;
TVirtualListData<T>=class(TVirtualData<T>)
private
FList : TList<T>;
public
Constructor Create(const Value: TList<T>);
function AsString(const AColumn:TColumn; const ARow:Integer):String; override;
function Count:Integer; override;
procedure SetValue(const AColumn:TColumn; const ARow:Integer; const AText:String); override;
end;
implementation
|
unit uXplPluginEngine;
{$Define DEBUG}
interface
uses MemMap, XPLMDataAccess, uXplCommon;
type
TXplEngine = class (TObject)
fMM: TMemMap;
fPosCountDown: Integer;
fLatitudeRef: XPLMDataRef;
fLongitudeRef: XPLMDataRef;
fHeadingRef: XPLMDataRef;
fHeightRef: XPLMDataRef;
pBuffer: PXplComRecord;
procedure DebugLog(Value: String);
function GetArrayLength(pDataRef: XPLMDataRef ;pDataType: XPLMDataTypeID): Integer;
procedure ProcessSlot(pSlot: PXplComSlot);
public
{ Public declarations }
constructor Create;
destructor Destroy; Override;
procedure XplTick;
end;
implementation
uses SysUtils, Windows, XPLMUtilities;
{ TXplEngine }
constructor TXplEngine.Create;
begin
pBuffer := nil;
fPosCountDown := -1;
fMM := TMemMap.Create(XPL_MEM_FILE, SizeOf(TXplComRecord));
if fMM.Memory <> nil then
begin
pBuffer := fMM.Memory;
//DebugLog(Format('pBuffer addr is %s.', [IntToStr(ULong(pBuffer))]));
//DebugLog(Format('Slot size: %d, mem size: %d', [SizeOf(TXplComSlot), SizeOf(TXplComRecord)]));
if pBuffer^.HdmConnected > 0 then
begin
DebugLog('Hidmacros already connected to shared memory.');
fPosCountDown := pBuffer^.PosInterval;
end
else
DebugLog('Hidmacros not yet connected to shared memory.');
pBuffer^.XplConnected := 1;
pBuffer^.XplRequestFlag := 0;
end
else
DebugLog('FATAL: Shared memory not created.');
end;
procedure TXplEngine.DebugLog(Value: String);
var
tmp: PChar;
lVal: String;
logFile: TextFile;
begin
{$IfNDef DEBUG}
if pBuffer = nil then
exit;
if not pBuffer^.Debug then
exit;
{$Endif}
lVal := 'XPLHDMplugin:'+ Value;
{$IFDEF OUTPUTDEBUGSTRING}
GetMem(tmp, Length(lVal) + 1);
try
StrPCopy(tmp, lVal);
OutputDebugString(tmp);
finally
FreeMem(tmp);
end;
{$ELSE}
// to file
AssignFile(logFile, 'debug.log');
if FileExists('debug.log') then
Append(logFile)
else
Rewrite(logFile);
WriteLn(logFile, lVal);
CloseFile(logFile);
{$ENDIF}
end;
destructor TXplEngine.Destroy;
begin
if pBuffer <> nil then
pBuffer^.XplConnected := 0;
fMM.Free;
inherited;
end;
function TXplEngine.GetArrayLength(pDataRef: XPLMDataRef ;pDataType: XPLMDataTypeID): Integer;
begin
Result := 0;
if (pDataType = xplmType_IntArray) then
Result := XPLMGetDatavi(pDataRef, nil, 0, 0);
if (pDataType = xplmType_FloatArray) then
Result := XPLMGetDatavf(pDataRef, nil, 0, 0);
if (pDataType = xplmType_Data) then
Result := XPLMGetDatab(pDataRef, nil, 0, 0);
end;
procedure TXplEngine.XplTick;
var
i: Integer;
lAllDone : Boolean;
begin
//DebugLog('Tick');
if pBuffer = nil then
exit;
if pBuffer^.XplRequestFlag = 1 then
begin
for I := 0 to COM_SLOTS_COUNT - 1 do
if pBuffer^.ComSlots[i].XplRequestFlag = 1 then
ProcessSlot(@pBuffer^.ComSlots[i]);
lAllDone := True;
for I := 0 to COM_SLOTS_COUNT - 1 do
lAllDone := lAllDone and (pBuffer^.ComSlots[i].XplRequestFlag = 0);
if lAllDone then
pBuffer^.XplRequestFlag := 0;
end;
if (pBuffer^.HdmConnected > 0) and (fPosCountDown > 0) then
begin
Dec(fPosCountDown);
if (fPosCountDown = 0) then
begin
// refresh pos values
if fLatitudeRef = nil then
fLatitudeRef := XPLMFindDataRef('sim/flightmodel/position/latitude');
if fLongitudeRef = nil then
fLongitudeRef := XPLMFindDataRef('sim/flightmodel/position/longitude');
if fHeadingRef = nil then
fHeadingRef := XPLMFindDataRef('sim/flightmodel/position/psi');
if fHeightRef = nil then
fHeightRef := XPLMFindDataRef('sim/flightmodel/position/elevation');
if fLatitudeRef <> nil then
pBuffer^.Latitude := XPLMGetDatad(fLatitudeRef);
if fLongitudeRef <> nil then
pBuffer^.Longitude := XPLMGetDatad(fLongitudeRef);
if fHeadingRef <> nil then
pBuffer^.Heading := XPLMGetDataf(fHeadingRef);
if fHeightRef <> nil then
pBuffer^.Height := XPLMGetDataf(fHeightRef);
fPosCountDown := pBuffer^.PosInterval;
//DebugLog('Pos: lat ' + FloatToStr(pBuffer^.Latitude) +
// ', lon ' + FloatToStr(pBuffer^.Longitude) +
// ', heading ' + FloatToStr(pBuffer^.Heading));
end;
end;
end;
procedure TXplEngine.ProcessSlot(pSlot: PXplComSlot);
var
lInt: Integer;
lFloat: Single;
lBuff: PChar;
lMakeChecks: Boolean;
begin
if pSlot^.XplRequestFlag = 1 then
begin
// check command
if (pSlot^.HDMcommand = HDMC_GET_VAR) or (pSlot^.HDMcommand = HDMC_SET_VAR) then
begin
// is already registered?
if pSlot^.DataRef = 0 then
begin
// register first
DebugLog('Finding ref for ' + pSlot^.ValueName);
pSlot^.DataRef := Pointer2Pointer8b(XPLMFindDataRef(pSlot^.ValueName));
if pSlot^.DataRef <> 0 then
begin
DebugLog(Format('Got valid pointer %x.', [pSlot^.DataRef]));
pSlot^.Writable := (XPLMCanWriteDataRef(Pointer8b2Pointer(pSlot^.DataRef)) <> 0);
if (pSlot^.Writable) then
DebugLog('Variable is writable.')
else
DebugLog('Variable is not writable.');
pSlot^.DataType := XPLMGetDataRefTypes(Pointer8b2Pointer(pSlot^.DataRef));
DebugLog('Data type is ' + IntToStr(Ord(pSlot^.DataType)));
pSlot^.Length := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType);
end
else
DebugLog('Ref not found.');
lMakeChecks := True; // we can make check only when all pBuffer items
// were just filled
end
else
lMakeChecks := False;
if pSlot^.DataRef <> 0 then
begin
DebugLog(Format('Using data ref %x.', [pSlot^.DataRef]));
if (pSlot^.HDMcommand = HDMC_SET_VAR) then
begin
// convert from string to appropriate value
case pSlot^.DataType of
xplmType_Float,
xplmType_FloatArray:
pSlot^.Value.floatData := StrToFloat(pSlot^.ValueUntyped);
xplmType_Double:
pSlot^.Value.doubleData := StrToFloat(pSlot^.ValueUntyped);
xplmType_Int,
xplmType_IntArray:
pSlot^.Value.intData := StrToint(pSlot^.ValueUntyped);
end;
end;
if lMakeChecks and (pSlot^.HDMcommand = HDMC_SET_VAR) and (not pSlot^.Writable) then
begin
DebugLog('Can''t set variable which is read only, chenging to get.');
pSlot^.HDMcommand := HDMC_GET_VAR;
end;
case pSlot^.DataType of
xplmType_Float:
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.floatData := XPLMGetDataf(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDataf(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.floatData);
end;
DebugLog('Got/set value ' + FloatToStr(pSlot^.Value.floatData));
end;
xplmType_Double:
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.doubleData := XPLMGetDatad(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDatad(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.doubleData);
end;
DebugLog('Got/set value ' + FloatToStr(pSlot^.Value.doubleData));
end;
xplmType_Int:
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.intData := XPLMGetDatai(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDatai(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.intData);
end;
DebugLog('Got/set value ' + IntToStr(pSlot^.Value.intData));
end;
xplmType_IntArray:
begin
// check range
if pSlot^.Index < 0 then
pSlot^.Value.intData := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType)
else if (not lMakeChecks) or (pSlot^.Index < (pSlot^.Length - 1)) then
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatavi(Pointer8b2Pointer(pSlot^.DataRef), @lInt,
pSlot^.Index, 1);
pSlot^.Value.intData := lInt;
end;
HDMC_SET_VAR:
begin
lInt := pSlot^.Value.intData;
XPLMSetDatavi(Pointer8b2Pointer(pSlot^.DataRef), @lInt, pSlot^.Index, 1);
end;
end;
DebugLog('Got/Set value ' + IntToStr(pSlot^.Value.intData));
end else
DebugLog('Index for int array too high ' + IntToStr(pSlot^.Index));
end;
xplmType_FloatArray:
begin
// check range
if pSlot^.Index < 0 then
pSlot^.Value.intData := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType)
else if (not lMakeChecks) or (pSlot^.Index < (pSlot^.Length - 1)) then
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatavf(Pointer8b2Pointer(pSlot^.DataRef), @lFloat,
pSlot^.Index, 1);
pSlot^.Value.floatData := lFloat;
end;
HDMC_SET_VAR:
begin
lFloat := pSlot^.Value.floatData;
XPLMSetDatavf(Pointer8b2Pointer(pSlot^.DataRef), @lFloat, pSlot^.Index, 1);
end;
end;
DebugLog('Got/Set value ' + FloatToStr(pSlot^.Value.floatData));
end else
DebugLog('Index for array too high ' + IntToStr(pSlot^.Index));
end;
xplmType_Data:
begin
if (pSlot^.Length > XPL_MAX_STRING_SIZE) then
pSlot^.Length := XPL_MAX_STRING_SIZE;
lBuff := pSlot^.StringBuffer;
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatab(Pointer8b2Pointer(pSlot^.DataRef), lBuff, 0, pSlot^.Length);
end;
HDMC_SET_VAR:
begin
lInt := StrLen(lBuff)+1; // copy also end str char
XPLMSetDatab(Pointer8b2Pointer(pSlot^.DataRef), lBuff, 0, lInt);
end;
end;
DebugLog('Got/Set value ' + lBuff);
end;
end;
end;
end;
if (pSlot^.HDMcommand = HDMC_EXEC_COMMAND) or
(pSlot^.HDMcommand = HDMC_COMMAND_BEGIN) or
(pSlot^.HDMcommand = HDMC_COMMAND_END)
then
begin
// is already registered?
if pSlot^.CommandRef = 0 then
begin
// register first
DebugLog('Finding ref for command ' + pSlot^.ValueName);
pSlot^.CommandRef := Pointer2Pointer8b(XPLMFindCommand(pSlot^.ValueName));
if pSlot^.CommandRef <> 0 then
begin
DebugLog(Format('Got valid pointer %p.', [Pointer8b2Pointer(pSlot^.CommandRef)]));
end;
end;
if pSlot^.CommandRef <> 0 then
begin
DebugLog(Format('Sending command for %p.', [Pointer8b2Pointer(pSlot^.CommandRef)]));
case pSlot^.HDMcommand of
HDMC_EXEC_COMMAND: XPLMCommandOnce(Pointer8b2Pointer(pSlot^.CommandRef));
HDMC_COMMAND_BEGIN: XPLMCommandBegin(Pointer8b2Pointer(pSlot^.CommandRef));
HDMC_COMMAND_END: XPLMCommandEnd(Pointer8b2Pointer(pSlot^.CommandRef));
end;
end;
end;
if (pSlot^.HDMcommand = HDMC_SET_POSINTERVAL) then
fPosCountDown := pBuffer^.PosInterval;
pSlot^.XplRequestFlag := 0;
end;
end;
end.
|
(* StackADT1: SWa, 2020-04-15 *)
(* ---------- *)
(* Stack abstract data type - version 1. *)
(* ========================================================================= *)
UNIT StackADT1;
INTERFACE
CONST
MAX = 100;
TYPE
Stack = RECORD
top: INTEGER;
data: ARRAY [1..MAX] OF INTEGER;
END; (* Stack *)
FUNCTION NewStack: Stack;
PROCEDURE Push(VAR s: Stack; value: INTEGER);
FUNCTION Pop(VAR s: Stack): INTEGER;
FUNCTION Empty(s: Stack): BOOLEAN;
IMPLEMENTATION
FUNCTION NewStack: Stack;
VAR
s: Stack;
BEGIN (* NewStack *)
s.top := 0;
NewStack := s;
END; (* NewStack *)
PROCEDURE Push(VAR s: Stack; value: INTEGER);
BEGIN (* Push *)
IF (s.top = MAX) THEN BEGIN
WriteLn('ERROR: stack full');
HALT;
END; (* IF *)
s.top := s.top + 1;
s.data[s.top] := value;
END; (* Push *)
FUNCTION Pop(VAR s: Stack): INTEGER;
VAR
value: INTEGER;
BEGIN (* Pop *)
IF (s.top = 0) THEN BEGIN
WriteLn('ERROR: stack empty');
HALT;
END; (* IF *)
value := s.data[s.top];
s.top := s.top - 1;
Pop := value;
END; (* Pop *)
FUNCTION Empty(s: Stack): BOOLEAN;
BEGIN (* Empty *)
Empty := (s.top = 0);
END; (* Empty *)
END. (* StackADT1 *)
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ Support for high-precision timing utilities }
{*******************************************************}
unit System.Diagnostics;
interface
{$HPPEMIT LEGACYHPP}
uses System.Classes, System.TimeSpan;
type
TStopwatch = record
strict private
class var FFrequency: Int64;
class var FIsHighResolution: Boolean;
class var TickFrequency: Double;
strict private
FElapsed: Int64;
FRunning: Boolean;
FStartTimeStamp: Int64;
function GetElapsed: TTimeSpan;
function GetElapsedDateTimeTicks: Int64;
function GetElapsedMilliseconds: Int64;
function GetElapsedTicks: Int64;
class procedure InitStopwatchType; static;
public
class function Create: TStopwatch; static;
class function GetTimeStamp: Int64; static;
procedure Reset;
procedure Start;
class function StartNew: TStopwatch; static;
procedure Stop;
property Elapsed: TTimeSpan read GetElapsed;
property ElapsedMilliseconds: Int64 read GetElapsedMilliseconds;
property ElapsedTicks: Int64 read GetElapsedTicks;
class property Frequency: Int64 read FFrequency;
class property IsHighResolution: Boolean read FIsHighResolution;
property IsRunning: Boolean read FRunning;
end;
implementation
{$IF defined(MSWINDOWS)}
uses Winapi.Windows;
{$ELSEIF defined(MACOS)}
uses Macapi.Mach;
{$ELSEIF defined(POSIX)}
uses Posix.Time;
{$ENDIF}
{ TStopwatch }
class function TStopwatch.Create: TStopwatch;
begin
InitStopwatchType;
Result.Reset;
end;
function TStopwatch.GetElapsed: TTimeSpan;
begin
Result := TTimeSpan.Create(GetElapsedDateTimeTicks);
end;
function TStopwatch.GetElapsedDateTimeTicks: Int64;
begin
Result := ElapsedTicks;
if FIsHighResolution then
Result := Trunc(Result * TickFrequency);
end;
function TStopwatch.GetElapsedMilliseconds: Int64;
begin
Result := GetElapsedDateTimeTicks div TTimeSpan.TicksPerMillisecond;
end;
function TStopwatch.GetElapsedTicks: Int64;
begin
Result := FElapsed;
if FRunning then
Result := Result + GetTimeStamp - FStartTimeStamp;
end;
class function TStopwatch.GetTimeStamp: Int64;
{$IF defined(POSIX) and not defined(MACOS)}
var
res: timespec;
{$ENDIF}
begin
{$IF defined(MSWINDOWS)}
if FIsHighResolution then
QueryPerformanceCounter(Result)
else
Result := GetTickCount * Int64(TTimeSpan.TicksPerMillisecond);
{$ELSEIF defined(MACOS)}
Result := Int64(AbsoluteToNanoseconds(mach_absolute_time) div 100);
{$ELSEIF defined(POSIX)}
clock_gettime(CLOCK_MONOTONIC, @res);
Result := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 100;
{$ENDIF}
end;
class procedure TStopwatch.InitStopwatchType;
begin
if FFrequency = 0 then
begin
{$IF defined(MSWINDOWS)}
if not QueryPerformanceFrequency(FFrequency) then
begin
FIsHighResolution := False;
FFrequency := TTimeSpan.TicksPerSecond;
TickFrequency := 1.0;
end else
begin
FIsHighResolution := True;
TickFrequency := 10000000.0 / FFrequency;
end;
{$ELSEIF defined(POSIX)}
FIsHighResolution := True;
FFrequency := 10000000; // 100 Nanosecond resolution
TickFrequency := 10000000.0 / FFrequency;
{$ENDIF}
end;
end;
procedure TStopwatch.Reset;
begin
FElapsed := 0;
FRunning := False;
FStartTimeStamp := 0;
end;
procedure TStopwatch.Start;
begin
if not FRunning then
begin
FStartTimeStamp := GetTimeStamp;
FRunning := True;
end;
end;
class function TStopwatch.StartNew: TStopwatch;
begin
InitStopwatchType;
Result.Reset;
Result.Start;
end;
procedure TStopwatch.Stop;
begin
if FRunning then
begin
FElapsed := FElapsed + GetTimeStamp - FStartTimeStamp;
FRunning := False;
end;
end;
end.
|
unit lib_interface;
interface
uses
Classes, WinInet, Dialogs, Windows, Forms,
IdBaseComponent, IdComponent, IdRawBase, IdRawClient, IdIcmpClient,
cxButtons, SysUtils, cxGraphics, Buttons,
Controls, ExtCtrls, StdCtrls, Messages, Menus;
type
TInterface = Class(TPersistent)
// private
// protected
public
procedure ArredondarComponente(Componente: TWinControl; const Radius: SmallInt);
procedure OrganizaScrollBox(ScrollBox: TScrollBox; inTop: Integer);
procedure CriaButtonScrollBox(ScrollBox: TScrollBox; stCaption: String; stOnClick: TNotifyEvent;
inHeight, inWidth: Integer; intag: Integer = 0; TmpImageList: TcxImageList = Nil;
inImagePos: Integer = 0; pum: TPopUpMenu = Nil);
// published
end;
const
{ Panel de button }
QTDECOLUNS_PANEL = 0; {QTDECOLUNS_PANEL for 0, pega o limite de botões possiveis}
// BUTTON_WIDTH = 200;
// BUTTON_HEIGHT = 80;
// BUTTON_TOP = 1;
implementation
{ Interface }
{ TInterface }
procedure TInterface.ArredondarComponente(Componente: TWinControl;
const Radius: SmallInt);
var
R: TRect;
Rgn: HRGN;
begin
with Componente do
begin
R := ClientRect;
Rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, Radius, Radius);
Perform(EM_GETRECT, 0, lParam(@R));
InflateRect(R, -5, -5);
Perform(EM_SETRECTNP, 0, lParam(@R));
SetWindowRgn(Handle, Rgn, True);
Invalidate;
end;
end;
procedure TInterface.CriaButtonScrollBox(ScrollBox: TScrollBox; stCaption: String;
stOnClick: TNotifyEvent; inHeight, inWidth: Integer; intag: Integer = 0; TmpImageList: TcxImageList = Nil;
inImagePos: Integer = 0; pum: TPopUpMenu = Nil);
var
btn: TcxButton;
begin
btn := TcxButton.Create(nil);
btn.Visible := False;
btn.Parent := ScrollBox;
btn.Name := 'btn'+ScrollBox.Name+IntToStr(ScrollBox.ControlCount);
btn.Caption := stCaption;
btn.Height := inHeight;
btn.Width := inWidth;
btn.OnClick := stOnClick;
btn.Visible := True;
btn.Tag := intag;
btn.SpeedButtonOptions.CanBeFocused := False;
btn.SpeedButtonOptions.Flat := True;
btn.SpeedButtonOptions.Transparent := True;
btn.PopupMenu := pum;
try
if TmpImageList <> Nil then
TmpImageList.GetImage(inImagePos, btn.Glyph);
btn.Layout := blGlyphTop;
except
//Cala a boca
end;
ArredondarComponente(btn,10);
end;
procedure TInterface.OrganizaScrollBox(ScrollBox: TScrollBox; inTop: Integer);
var
iComp, iCompLinha, iCompDaLn, iPrButton: Integer;
iRestDimen: Double;
boMudaLinha: Boolean;
begin
iCompDaLn := 0;
iPrButton := 0;
iCompLinha := (ScrollBox.Width div ScrollBox.Controls[iPrButton].Width);
if (QTDECOLUNS_PANEL > 0) and (iCompLinha > QTDECOLUNS_PANEL) then
iCompLinha := QTDECOLUNS_PANEL;
iRestDimen := (ScrollBox.Width-(ScrollBox.Controls[iPrButton].Width * iCompLinha))/(iCompLinha+1);
for iComp := 0 to pred(ScrollBox.ControlCount) do begin
if iCompDaLn < iCompLinha then
boMudaLinha := False
else
boMudaLinha := True;
if boMudaLinha then begin
ScrollBox.Controls[iComp].Left := Trunc(iRestDimen);
ScrollBox.Controls[iComp].Top := ScrollBox.Controls[iComp-1].Top+inTop+
ScrollBox.Controls[iComp].Height;
iCompDaLn := 0;
end else begin
if iComp = 0 then begin
ScrollBox.Controls[iComp].Left := Trunc(iRestDimen);
ScrollBox.Controls[iComp].Top := inTop;
end else begin
ScrollBox.Controls[iComp].Left := ScrollBox.Controls[iComp-1].Left+ScrollBox.Controls[iComp].width+Trunc(iRestDimen);
ScrollBox.Controls[iComp].Top := ScrollBox.Controls[iComp-1].Top;
end;
end;
inc(iCompDaLn);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.