text stringlengths 14 6.51M |
|---|
unit StyleEditorExampleKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы StyleEditorExample }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Settings\StyleEditorExampleKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "StyleEditorExampleKeywordsPack" MUID: (509C799A0733)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3IntfUses
{$If Defined(Nemesis)}
, nscTextSource
{$IfEnd} // Defined(Nemesis)
, vtPanel
, eeEditorWithoutOperations
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, StyleEditorExample_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_StyleEditorExample = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы StyleEditorExample
----
*Пример использования*:
[code]
'aControl' форма::StyleEditorExample TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_StyleEditorExample
Tkw_StyleEditorExample_Component_TextSource = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола TextSource
----
*Пример использования*:
[code]
компонент::TextSource TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorExample_Component_TextSource
Tkw_StyleEditorExample_Control_EditorPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола EditorPanel
----
*Пример использования*:
[code]
контрол::EditorPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorExample_Control_EditorPanel
Tkw_StyleEditorExample_Control_EditorPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола EditorPanel
----
*Пример использования*:
[code]
контрол::EditorPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorExample_Control_EditorPanel_Push
Tkw_StyleEditorExample_Control_Editor = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола Editor
----
*Пример использования*:
[code]
контрол::Editor TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorExample_Control_Editor
Tkw_StyleEditorExample_Control_Editor_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола Editor
----
*Пример использования*:
[code]
контрол::Editor:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorExample_Control_Editor_Push
TkwStyleEditorExampleFormTextSource = {final} class(TtfwPropertyLike)
{* Слово скрипта .TStyleEditorExampleForm.TextSource }
private
function TextSource(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TnscTextSource;
{* Реализация слова скрипта .TStyleEditorExampleForm.TextSource }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwStyleEditorExampleFormTextSource
TkwStyleEditorExampleFormEditorPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TStyleEditorExampleForm.EditorPanel }
private
function EditorPanel(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TvtPanel;
{* Реализация слова скрипта .TStyleEditorExampleForm.EditorPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwStyleEditorExampleFormEditorPanel
TkwStyleEditorExampleFormEditor = {final} class(TtfwPropertyLike)
{* Слово скрипта .TStyleEditorExampleForm.Editor }
private
function Editor(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TeeEditorWithoutOperations;
{* Реализация слова скрипта .TStyleEditorExampleForm.Editor }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwStyleEditorExampleFormEditor
function Tkw_Form_StyleEditorExample.GetString: AnsiString;
begin
Result := 'StyleEditorExampleForm';
end;//Tkw_Form_StyleEditorExample.GetString
class function Tkw_Form_StyleEditorExample.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::StyleEditorExample';
end;//Tkw_Form_StyleEditorExample.GetWordNameForRegister
function Tkw_StyleEditorExample_Component_TextSource.GetString: AnsiString;
begin
Result := 'TextSource';
end;//Tkw_StyleEditorExample_Component_TextSource.GetString
class procedure Tkw_StyleEditorExample_Component_TextSource.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTextSource);
end;//Tkw_StyleEditorExample_Component_TextSource.RegisterInEngine
class function Tkw_StyleEditorExample_Component_TextSource.GetWordNameForRegister: AnsiString;
begin
Result := 'компонент::TextSource';
end;//Tkw_StyleEditorExample_Component_TextSource.GetWordNameForRegister
function Tkw_StyleEditorExample_Control_EditorPanel.GetString: AnsiString;
begin
Result := 'EditorPanel';
end;//Tkw_StyleEditorExample_Control_EditorPanel.GetString
class procedure Tkw_StyleEditorExample_Control_EditorPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_StyleEditorExample_Control_EditorPanel.RegisterInEngine
class function Tkw_StyleEditorExample_Control_EditorPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::EditorPanel';
end;//Tkw_StyleEditorExample_Control_EditorPanel.GetWordNameForRegister
procedure Tkw_StyleEditorExample_Control_EditorPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('EditorPanel');
inherited;
end;//Tkw_StyleEditorExample_Control_EditorPanel_Push.DoDoIt
class function Tkw_StyleEditorExample_Control_EditorPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::EditorPanel:push';
end;//Tkw_StyleEditorExample_Control_EditorPanel_Push.GetWordNameForRegister
function Tkw_StyleEditorExample_Control_Editor.GetString: AnsiString;
begin
Result := 'Editor';
end;//Tkw_StyleEditorExample_Control_Editor.GetString
class procedure Tkw_StyleEditorExample_Control_Editor.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TeeEditorWithoutOperations);
end;//Tkw_StyleEditorExample_Control_Editor.RegisterInEngine
class function Tkw_StyleEditorExample_Control_Editor.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Editor';
end;//Tkw_StyleEditorExample_Control_Editor.GetWordNameForRegister
procedure Tkw_StyleEditorExample_Control_Editor_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('Editor');
inherited;
end;//Tkw_StyleEditorExample_Control_Editor_Push.DoDoIt
class function Tkw_StyleEditorExample_Control_Editor_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Editor:push';
end;//Tkw_StyleEditorExample_Control_Editor_Push.GetWordNameForRegister
function TkwStyleEditorExampleFormTextSource.TextSource(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TnscTextSource;
{* Реализация слова скрипта .TStyleEditorExampleForm.TextSource }
begin
Result := aStyleEditorExampleForm.TextSource;
end;//TkwStyleEditorExampleFormTextSource.TextSource
class function TkwStyleEditorExampleFormTextSource.GetWordNameForRegister: AnsiString;
begin
Result := '.TStyleEditorExampleForm.TextSource';
end;//TkwStyleEditorExampleFormTextSource.GetWordNameForRegister
function TkwStyleEditorExampleFormTextSource.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTextSource);
end;//TkwStyleEditorExampleFormTextSource.GetResultTypeInfo
function TkwStyleEditorExampleFormTextSource.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwStyleEditorExampleFormTextSource.GetAllParamsCount
function TkwStyleEditorExampleFormTextSource.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TStyleEditorExampleForm)]);
end;//TkwStyleEditorExampleFormTextSource.ParamsTypes
procedure TkwStyleEditorExampleFormTextSource.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству TextSource', aCtx);
end;//TkwStyleEditorExampleFormTextSource.SetValuePrim
procedure TkwStyleEditorExampleFormTextSource.DoDoIt(const aCtx: TtfwContext);
var l_aStyleEditorExampleForm: TStyleEditorExampleForm;
begin
try
l_aStyleEditorExampleForm := TStyleEditorExampleForm(aCtx.rEngine.PopObjAs(TStyleEditorExampleForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aStyleEditorExampleForm: TStyleEditorExampleForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(TextSource(aCtx, l_aStyleEditorExampleForm));
end;//TkwStyleEditorExampleFormTextSource.DoDoIt
function TkwStyleEditorExampleFormEditorPanel.EditorPanel(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TvtPanel;
{* Реализация слова скрипта .TStyleEditorExampleForm.EditorPanel }
begin
Result := aStyleEditorExampleForm.EditorPanel;
end;//TkwStyleEditorExampleFormEditorPanel.EditorPanel
class function TkwStyleEditorExampleFormEditorPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TStyleEditorExampleForm.EditorPanel';
end;//TkwStyleEditorExampleFormEditorPanel.GetWordNameForRegister
function TkwStyleEditorExampleFormEditorPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwStyleEditorExampleFormEditorPanel.GetResultTypeInfo
function TkwStyleEditorExampleFormEditorPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwStyleEditorExampleFormEditorPanel.GetAllParamsCount
function TkwStyleEditorExampleFormEditorPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TStyleEditorExampleForm)]);
end;//TkwStyleEditorExampleFormEditorPanel.ParamsTypes
procedure TkwStyleEditorExampleFormEditorPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству EditorPanel', aCtx);
end;//TkwStyleEditorExampleFormEditorPanel.SetValuePrim
procedure TkwStyleEditorExampleFormEditorPanel.DoDoIt(const aCtx: TtfwContext);
var l_aStyleEditorExampleForm: TStyleEditorExampleForm;
begin
try
l_aStyleEditorExampleForm := TStyleEditorExampleForm(aCtx.rEngine.PopObjAs(TStyleEditorExampleForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aStyleEditorExampleForm: TStyleEditorExampleForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(EditorPanel(aCtx, l_aStyleEditorExampleForm));
end;//TkwStyleEditorExampleFormEditorPanel.DoDoIt
function TkwStyleEditorExampleFormEditor.Editor(const aCtx: TtfwContext;
aStyleEditorExampleForm: TStyleEditorExampleForm): TeeEditorWithoutOperations;
{* Реализация слова скрипта .TStyleEditorExampleForm.Editor }
begin
Result := aStyleEditorExampleForm.Editor;
end;//TkwStyleEditorExampleFormEditor.Editor
class function TkwStyleEditorExampleFormEditor.GetWordNameForRegister: AnsiString;
begin
Result := '.TStyleEditorExampleForm.Editor';
end;//TkwStyleEditorExampleFormEditor.GetWordNameForRegister
function TkwStyleEditorExampleFormEditor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TeeEditorWithoutOperations);
end;//TkwStyleEditorExampleFormEditor.GetResultTypeInfo
function TkwStyleEditorExampleFormEditor.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwStyleEditorExampleFormEditor.GetAllParamsCount
function TkwStyleEditorExampleFormEditor.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TStyleEditorExampleForm)]);
end;//TkwStyleEditorExampleFormEditor.ParamsTypes
procedure TkwStyleEditorExampleFormEditor.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Editor', aCtx);
end;//TkwStyleEditorExampleFormEditor.SetValuePrim
procedure TkwStyleEditorExampleFormEditor.DoDoIt(const aCtx: TtfwContext);
var l_aStyleEditorExampleForm: TStyleEditorExampleForm;
begin
try
l_aStyleEditorExampleForm := TStyleEditorExampleForm(aCtx.rEngine.PopObjAs(TStyleEditorExampleForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aStyleEditorExampleForm: TStyleEditorExampleForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Editor(aCtx, l_aStyleEditorExampleForm));
end;//TkwStyleEditorExampleFormEditor.DoDoIt
initialization
Tkw_Form_StyleEditorExample.RegisterInEngine;
{* Регистрация Tkw_Form_StyleEditorExample }
Tkw_StyleEditorExample_Component_TextSource.RegisterInEngine;
{* Регистрация Tkw_StyleEditorExample_Component_TextSource }
Tkw_StyleEditorExample_Control_EditorPanel.RegisterInEngine;
{* Регистрация Tkw_StyleEditorExample_Control_EditorPanel }
Tkw_StyleEditorExample_Control_EditorPanel_Push.RegisterInEngine;
{* Регистрация Tkw_StyleEditorExample_Control_EditorPanel_Push }
Tkw_StyleEditorExample_Control_Editor.RegisterInEngine;
{* Регистрация Tkw_StyleEditorExample_Control_Editor }
Tkw_StyleEditorExample_Control_Editor_Push.RegisterInEngine;
{* Регистрация Tkw_StyleEditorExample_Control_Editor_Push }
TkwStyleEditorExampleFormTextSource.RegisterInEngine;
{* Регистрация StyleEditorExampleForm_TextSource }
TkwStyleEditorExampleFormEditorPanel.RegisterInEngine;
{* Регистрация StyleEditorExampleForm_EditorPanel }
TkwStyleEditorExampleFormEditor.RegisterInEngine;
{* Регистрация StyleEditorExampleForm_Editor }
TtfwTypeRegistrator.RegisterType(TypeInfo(TStyleEditorExampleForm));
{* Регистрация типа TStyleEditorExampleForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTextSource));
{* Регистрация типа TnscTextSource }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TeeEditorWithoutOperations));
{* Регистрация типа TeeEditorWithoutOperations }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
end.
|
//
// IsoCity - Isometric City Builder
// Written by Mitchell Williamson
// April-June 2016
//
//=============================================================================
// GameMain.pas
//=============================================================================
//
// The core game file, calls all other units and maintains the game variables
//
//=============================================================================
program GameMain;
uses SwinGame, sgTypes, gInput, gMap, gTypes, gRender, gResources, gUnit, gUnitAI, gGUI, Math;
procedure Main();
var
game: GameData;
x,y, tX, tY,idx, i : Integer;
pos : Point2D;
begin
DebugMsg('Game starting in debug mode...');
DebugMsg('----- Isometric City Builder -----');
DebugMsg('-- Written by Mitchell Williamson --');
DebugMsg('Init: Starting Game Initialising...');
InitResources(game); // Load the resources...
InitRendering(); // Start the rendering...
Randomize(); // Seed randomness
GenerateMap(game); // Generate the game map
game.mouseLoc.mouseStatus := MOUSE_NORMAL;
game.power := 0; // Set the base power
game.money := 50000; // Set the base money
game.guiStatus := STARTUP_MODE;
game.menuStatus := MAIN_SCREEN;
game.zoningType := TERRAIN_ZONE;
DebugMsg('Init: Game Init Complete.');
PlayMusic('MainThemeOne'); // Play the game music
if SHOW_SPLASHSCREEN then
ShowSwinGameSplashScreen(); // Play the SwinGame intro splashscreen
if game.guiStatus = MAIN_MENU then
begin
DebugMsg('UI: Starting Menu Rendering...');
repeat
ProcessEvents();
DrawMainMenu(game);
until (WindowCloseRequested()) or (game.guiStatus <> MAIN_MENU);
DebugMsg('UI: Stopping Menu Rendering...');
end;
if game.guiStatus = IN_GAME then
begin
MoveCameraTo(Point(340,-340));
DebugMsg('Init: Starting Game Rendering...');
repeat;
ProcessEvents();
HandleInput(game); // gInput.pas
AITick(game); // gUnitAI.pas
RenderGame(game); // gRender.pas
// Manage income
if TimerTicks(game.moneyTimer) > (PAY_TIME*1000) then
begin
ResetTimer(game.moneyTimer);
StartTimer(game.moneyTimer);
game.money += Length(game.citizens) * 50;
PlaySoundEffect('PaidNotif');
end;
until WindowCloseRequested();
DebugMsg('Init: Stopping Game Rendering...');
end;
DebugMsg('Resources: Releasing Resources...');
ReleaseAllResources();
DebugMsg('Resources: Releasing Resources... done.');
DebugMsg('--Game Shutdown--')
end;
begin
Main();
end.
|
program basicAlgorithms(input, output);
const
MIN = 1;
MAX = 10;
type
sequence = array [MIN .. MAX] of integer;
bits = 0 .. 1;
bitString = array [MIN .. MAX] of bits;
var
s : sequence;
b : bitString;
exercise : integer;
procedure populateSequence();
begin
s[1] := 9;
s[2] := 45;
s[3] := 56;
s[4] := -4;
s[5] := 99;
s[6] := 1;
s[7] := 65;
s[8] := 0;
s[9] := 45;
s[10] := 5
end;
procedure populateBits();
begin
b[1] := 1;
b[2] := 0;
b[3] := 1;
b[4] := 1;
b[5] := 0;
b[6] := 0;
b[7] := 1;
b[8] := 0;
b[9] := 1;
b[10] := 1
end;
procedure printSequence(var s : sequence);
var i : integer;
begin
for i := MIN to MAX do
write(s[i], ' ');
writeln;
end;
{ Corresponds to 1.2.1 }
procedure smallestValueWhile(var s : sequence);
var ans, i : integer;
begin
i := MIN;
ans := s[i];
while i <= MAX do begin
if s[i] < ans then
ans := s[i];
i := i + 1
end;
writeln(ans)
end;
{ Corresponds to 1.2.2 }
procedure smallestValueFor(var s : sequence);
var ans, i : integer;
begin
ans := s[MIN];
for i := MIN to MAX do
if s[i] < ans then
ans := s[i];
writeln(ans)
end;
{ Corresponds to 1.2.3 }
procedure largestPair(var s : sequence);
var max1, max2, i : integer;
begin
if s[MIN] > s[MIN + 1] then begin
max1 := s[MIN]; max2 := s[MIN + 1]
end
else begin
max1 := s[MIN + 1]; max2 := s[MIN];
end;
for i := MIN + 2 to MAX do begin
if s[i] > max2 then begin
if s[i] > max1 then begin
max2 := max1; max1 := s[i]
end
else max2 := s[i]
end
end;
writeln(max1, ' ', max2)
end;
{ Correspnds to 1.2.4 }
procedure smallestPair(var s : sequence);
var min1, min2, i : integer;
begin
if s[MIN] > s[MIN + 1] then begin
min1 := s[MIN + 1]; min2 := s[MIN]
end
else begin
min1 := s[MIN]; min2 := s[MIN + 1]
end;
for i := MIN + 2 to MAX do begin
if s[i] < min2 then begin
if s[i] < min1 then begin
min2 := min1; min1 := s[i]
end
else
min2 := s[i]
end
end;
writeln(min1, ' ', min2)
end;
{ Corresponds to 1.2.5 }
procedure smallestLargest(var s : sequence);
var small, big, i : integer;
begin
i := MIN; small := s[i]; big := s[i];
for i := MIN to MAX do begin
if s[i] < small then
small := s[i]
else if s[i] > big then
big := s[i]
end;
writeln(small, ' ', big)
end;
{ Corresponds to 1.2.6 }
procedure firstIndexOfLargest(var s : sequence);
var big, i, ans : integer;
begin
big := s[MIN]; ans := MIN;
for i := MIN to MAX do begin
if s[i] > big then begin
ans := i; big := s[i]
end
end;
writeln(ans)
end;
{ Corresponds to 1.2.7 }
procedure lastIndexOfLargest(var s : sequence);
var big, i, ans : integer;
begin
big := s[MIN]; ans := MIN;
for i := MIN to MAX do begin
if s[i] >= big then begin
ans := i; big := s[i]
end
end;
writeln(ans)
end;
{ Corresponds to 1.2.8 }
procedure firstIndexOf(var s : sequence; key : integer);
label final;
var i, ans : integer;
begin
ans := 0;
for i := MIN to MAX do
if s[i] = key then begin
ans := i;
goto final
end;
final:
writeln(ans)
end;
{ Corresponds to 1.2.9 }
procedure lastIndexOf(var s : sequence; key : integer);
var i, ans : integer;
begin
ans := 0;
for i := MIN to MAX do
if s[i] = key then
ans := i;
writeln(ans)
end;
{ Corresponds to 1.2.10 }
procedure indexOfFirstDecreasingItem1(var s : sequence);
var i, ans : integer; flag : boolean;
begin
i := MIN;
ans := 0;
flag := false;
while (i < MAX) and (not flag) do begin
if s[i] > s[i + 1] then begin
ans := i + 1; flag := true
end;
i := i + 1
end;
writeln(ans);
end;
procedure indexOfFirstDecreasingItem2(var s : sequence);
label final;
var i, ans : integer;
begin
ans := 0;
for i := 2 to MAX do
if s[i] < s[i - 1] then begin
h
end;
final:
writeln(ans);
end;
{ Corresponds to 1.2.11 }
procedure reverseSequence(var s : sequence);
var aux : sequence; i : integer;
begin
for i := MAX downto MIN do
aux[i] := s[MAX - i + 1];
printSequence(aux);
end;
{ Corresponds to 1.2.12 NOT }
{ Corresponds to 1.2.13 Bubble-sort like }
procedure sortBitString1(var b : bitString);
var i, j : integer;
procedure swap(var b : bitString; i, j : integer);
var temp : bits;
begin
temp := b[i]; b[i] := b[j]; b[j] := temp
end;
begin
for i := 0 to (MAX - 1) do
for j := 0 to (MAX - 2) do
if b[j] > b[j + 1] then
swap(b, j, j + 1);
printBits(b);
end;
procedure sortBitString2(var b : bitString);
var i, j : integer;
procedure swap(var b : bitString; i, j : integer);
var temp : bits;
begin
temp := b[i]; b[i] := b[j]; b[j] := temp
end;
begin
i := 1;
j := MAX;
while i < j do begin
while (i < j) and (b[i] = 0) do
i := i + 1;
while (i < j) and (b[j] = 1) do
j := j - 1;
swap(b, i, j)
end;
printBits(b)
end;
begin
populateSequence();
populateBits();
write('Enter exercise number: '); read(exercise);
case exercise of
1 :
smallestValueWhile(s);
2 :
smallestValueFor(s);
3 :
largestPair(s);
4 :
smallestPair(s);
5 :
smallestLargest(s);
6 :
firstIndexOfLargest(s);
7 :
lastIndexOfLargest(s);
8 :
firstIndexOf(s, 99);
9 :
lastIndexOf(s, 99);
10:
indexOfFirstDecreasingItem1(s);
11:
reverseSequence(s);
13:
begin
printBits(b);
sortBitString1(b)
end;
else
exercise := 1
end
end. |
unit Dependencies;
interface
uses
System.SysUtils,
Quick.Commons,
Quick.IOC;
type
IMathService = interface
['{E8BEE282-3828-4F27-869D-C808296F8CA2}']
procedure IncNumsOperations;
function NumOperations : Integer;
end;
ISumService = interface(IMathService)
['{7580F5F6-0132-49F3-A22A-A2E93E53E8A7}']
function Sum(a, b : Integer) : Integer;
end;
IMultService = interface(IMathService)
['{56772C4B-70AF-4BB7-9DFE-E2D67912DDC1}']
function Mult(a, b : Integer) : Integer;
end;
TMathService = class(TInterfacedObject,IMathService)
private
fNumOperations : Integer;
public
constructor Create;
procedure IncNumsOperations;
function NumOperations : Integer;
end;
TSumService = class(TMathService,ISumService)
public
function Sum(a, b : Integer) : Integer;
end;
TMultService = class(TMathService,IMultService)
public
function Mult(a, b : Integer) : Integer;
end;
IBigService = interface
['{AE7E7617-02BD-48C9-A370-49566A563C38}']
function GetNumOperations : Integer;
function Sum(a, b : Integer) : Integer;
function Mult(a, b : Integer) : Integer;
function SumService : ISumService;
function MultService : IMultService;
property NumOperations : Integer read GetNumOperations;
end;
TBigService = class(TInterfacedObject,IBigService)
private
fSumService : ISumService;
fMultService : IMultService;
fNumOperations : Integer;
function GetNumOperations : Integer;
procedure IncNumOperations;
public
constructor Create(aSumService : ISumService; aMultService : IMultService);
function Sum(a, b : Integer) : Integer;
function Mult(a, b : Integer) : Integer;
function SumService : ISumService;
function MultService : IMultService;
property NumOperations : Integer read GetNumOperations;
end;
TDivideService = class
private
fNumOperations : Integer;
fRound : Boolean;
public
constructor Create(aRound : Boolean);
property NumOperations : Integer read fNumOperations;
function Divide(a,b : Integer) : Integer;
end;
implementation
{ TSumService }
function TSumService.Sum(a, b: Integer): Integer;
begin
Result := a + b;
IncNumsOperations;
end;
{ TMultService }
function TMultService.Mult(a, b: Integer): Integer;
begin
Result := a * b;
IncNumsOperations;
end;
{ TBigService }
constructor TBigService.Create(aSumService: ISumService; aMultService: IMultService);
begin
fSumService := aSumService;
fMultService := aMultService;
end;
function TBigService.Sum(a, b: Integer): Integer;
begin
Result := fSumService.Sum(a,b);
IncNumOperations;
end;
function TBigService.SumService: ISumService;
begin
Result := fSumService;
end;
function TBigService.GetNumOperations: Integer;
begin
Result := fNumOperations;
end;
procedure TBigService.IncNumOperations;
begin
Inc(fNumOperations);
end;
function TBigService.Mult(a, b: Integer): Integer;
begin
Result := fMultService.Mult(a,b);
IncNumOperations;
end;
function TBigService.MultService: IMultService;
begin
Result := fMultService;
end;
{ TMathService }
constructor TMathService.Create;
begin
fNumOperations := 0;
end;
procedure TMathService.IncNumsOperations;
begin
Inc(fNumOperations);
end;
function TMathService.NumOperations: Integer;
begin
Result := fNumOperations;
end;
{ TDivideService }
constructor TDivideService.Create(aRound : Boolean);
begin
fNumOperations := 0;
fRound := aRound;
end;
function TDivideService.Divide(a, b: Integer): Integer;
begin
if fRound then Result := Round(a / b)
else Result := Trunc(a / b);
Inc(fNumOperations);
end;
end.
|
unit ConvForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Types, StdCtrls, ConvUtils, StdConvs, StrUtils;
type
TForm1 = class(TForm)
ComboFamilies: TComboBox;
ListTypes: TListBox;
EditType: TEdit;
EditAmount: TEdit;
EditConverted: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
BtnSimple: TButton;
Label6: TLabel;
EditDestination: TEdit;
BtnConvert: TButton;
Label7: TLabel;
procedure FormCreate(Sender: TObject);
procedure ChangeFamily(Sender: TObject);
procedure BtnSimpleClick(Sender: TObject);
procedure DoConvert(Sender: TObject);
procedure EditTypeDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure EditTypeDragDrop(Sender, Source: TObject; X, Y: Integer);
private
aFamilies: TConvFamilyArray;
CurrFamily: TConvFamily;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
GetConvFamilies (aFamilies);
for i := Low(aFamilies) to High(aFamilies) do
ComboFamilies.Items.Add (
ConvFamilyToDescription (aFamilies[i]));
// get the first and fire event
ComboFamilies.ItemIndex := 0;
ChangeFamily (self);
end;
procedure TForm1.ChangeFamily(Sender: TObject);
var
aTypes: TConvTypeArray;
i: Integer;
begin
ListTypes.Clear;
CurrFamily := aFamilies [ComboFamilies.ItemIndex];
GetConvTypes (CurrFamily, aTypes);
for i := Low(aTypes) to High(aTypes) do
ListTypes.Items.Add (
ConvTypeToDescription (aTypes[i]));
end;
procedure TForm1.BtnSimpleClick(Sender: TObject);
begin
// samples
// convert temperatures: celsius to fahrenheit
ShowMessage ('31 Celsius -> ' + FloatToStr (
Convert (31, tuCelsius, tuFahrenheit)) + ' Fahrenheit');
// convert speed: miles per hour to meters per seconds
ShowMessage ('20 Miles/Hour -> ' + FloatToStr (
Convert(20, duMiles, tuHours, duMeters, tuSeconds)) +
' Meters/Second');
end;
procedure TForm1.DoConvert(Sender: TObject);
var
BaseType, DestType: TConvType;
begin
// get and check base type
if not DescriptionToConvType(CurrFamily, EditType.Text, BaseType) then
EditType.Font.Color := clRed
else
EditType.Font.Color := clBlack;
// get and check destination type
if not DescriptionToConvType(CurrFamily, EditDestination.Text, DestType) then
EditDestination.Font.Color := clRed
else
EditDestination.Font.Color := clBlack;
if (DestType = 0) or (BaseType = 0) then
EditConverted.Text := 'Invalid type'
else
EditConverted.Text := FloatToStr (Convert (
StrToFloat (EditAmount.Text), BaseType, DestType));
end;
procedure TForm1.EditTypeDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := True;
end;
procedure TForm1.EditTypeDragDrop(Sender, Source: TObject; X, Y: Integer);
begin
(Sender as TEdit).Text := (Source as TListBox).Items
[(Source as TListBox).ItemIndex];
end;
end.
|
unit Model.DestinosTransportes;
interface
uses Common.ENum, FireDAC.Comp.Client;
type
TDestinosTransporte = class
private
var
FDestino: Integer;
FDescricao: String;
FLog: String;
FAcao: TAcao;
public
property Destino: Integer read FDestino write FDestino;
property Descricao: String read FDescricao write FDescricao;
property Log : String read FLog write FLog;
property Acao: TAcao read FAcao write FAcao;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TDestinosTransportes }
uses DAO.DestinosTransporte;
function TDestinosTransporte.Gravar: Boolean;
var
destinosDAO : TDestinosTransporteDAO;
begin
try
Result := False;
destinosDAO := TDestinosTransporteDAO.Create;
case FAcao of
Common.ENum.tacIncluir: Result := destinosDAO.Insert(Self);
Common.ENum.tacAlterar: Result := destinosDAO.Update(Self);
Common.ENum.tacExcluir: Result := destinosDAO.Delete(Self);
end;
finally
destinosDAO.Free;
end;end;
function TDestinosTransporte.Localizar(aParam: array of variant): TFDQuery;
var
destinosDAO : TDestinosTransporteDAO;
begin
try
destinosDAO := TDestinosTransporteDAO.Create;
Result := destinosDAO.Find(aParam);
finally
destinosDAO.Free;
end;
end;
end.
|
unit tipocombustivel;
interface
type
T_TipoCombustivel = class(TObject)
private
F_Id: Integer;
F_Nome: String;
F_ValorPorLitro: Double;
F_PercentualDeImposto: Double;
// F_Id
procedure setId(pId: Integer);
function getId(): Integer;
// F_Nome
procedure setNome(pNome: String);
function getNome(): String;
// F_ValorPorLitro
procedure setValorPorLitro(pValorPorLitro: Double);
function getValorPorLitro(): Double;
// F_PercentualDeImposto
procedure setPercentualDeImposto(pPercentualDeImposto: Double);
function getPercentualDeImposto(): Double;
public
constructor Create(
pId: Integer;
pNome: String;
pValorPorLitro: Double;
pPercentualDeImposto: Double
); overload;
constructor Create(); overload;
published
property Id: Integer read getId write setId;
property Nome: String read getNome write setNome;
property ValorPorLitro: Double read getValorPorLitro write setValorPorLitro;
property PercentualDeImposto: Double read getPercentualDeImposto write setPercentualDeImposto;
end;
implementation
constructor T_TipoCombustivel.Create(
pId: Integer;
pNome: String;
pValorPorLitro: Double;
pPercentualDeImposto: Double
);
begin
F_Id := pId;
F_Nome := pNome;
F_ValorPorLitro := pValorPorLitro;
F_PercentualDeImposto := pPercentualDeImposto;
end;
constructor T_TipoCombustivel.Create();
begin
//
end;
// F_Id
procedure T_TipoCombustivel.setId(pId: Integer);
begin
F_Id := pId;
end;
function T_TipoCombustivel.getId(): Integer;
begin
result := F_Id;
end;
// F_Nome
procedure T_TipoCombustivel.setNome(pNome: String);
begin
F_Nome := pNome;
end;
function T_TipoCombustivel.getNome(): String;
begin
result := F_Nome;
end;
// F_ValorPorLitro
procedure T_TipoCombustivel.setValorPorLitro(pValorPorLitro: Double);
begin
F_ValorPorLitro := pValorPorLitro;
end;
function T_TipoCombustivel.getValorPorLitro(): Double;
begin
result := F_ValorPorLitro;
end;
// F_PercentualDeImposto
procedure T_TipoCombustivel.setPercentualDeImposto(pPercentualDeImposto: Double);
begin
F_PercentualDeImposto := pPercentualDeImposto;
end;
function T_TipoCombustivel.getPercentualDeImposto(): Double;
begin
result := F_PercentualDeImposto;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clBodyEdit;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Messages, Forms, Menus, Classes, Controls, StdCtrls, ExtCtrls, ComCtrls,
SysUtils, TypInfo, Graphics, Dialogs, Windows, Types, Grids,
{$ELSE}
Winapi.Messages, Vcl.Forms, Vcl.Menus, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
System.SysUtils, System.TypInfo, Vcl.Graphics, Vcl.Dialogs, Winapi.Windows, System.Types, Vcl.Grids,
{$ENDIF}
clBodyChooser, clMailMessage;
type
TclItemEditor = class
private
FItem: TclMessageBody;
FParent: TWinControl;
FContentTypeLabel: TLabel;
FEncodingLabel: TLabel;
FContentType: TEdit;
FEncoding: TComboBox;
protected
procedure FillControls; virtual;
procedure FillData; virtual;
procedure CreateControls; virtual;
procedure DestroyControls; virtual;
function GetMaxLabelWidth: Integer; virtual;
function GetControlsVertivalPos: Integer;
public
constructor Create(AItem: TclMessageBody; AParent: TWinControl); virtual;
destructor Destroy; override;
procedure AlignControls; virtual;
property Item: TclMessageBody read FItem;
property Parent: TWinControl read FParent;
end;
TclItemEditorClass = class of TclItemEditor;
TclTextItemEditor = class(TclItemEditor)
private
FRichEdit: TRichEdit;
protected
procedure FillControls; override;
procedure FillData; override;
procedure CreateControls; override;
procedure DestroyControls; override;
public
procedure AlignControls; override;
end;
TclMultipartItemEditor = class(TclItemEditor)
private
FButton: TButton;
procedure ButtonClick(Sender: TObject);
protected
procedure CreateControls; override;
procedure DestroyControls; override;
public
procedure AlignControls; override;
end;
TclFileItemEditor = class(TclItemEditor)
private
FFileNameLabel: TLabel;
FFileName: TEdit;
FBrowseButton: TButton;
procedure DoOnBrowseClick(Sender: TObject);
protected
procedure FillControls; override;
procedure FillData; override;
procedure CreateControls; override;
procedure DestroyControls; override;
function GetMaxLabelWidth: Integer; override;
public
procedure AlignControls; override;
end;
TclMessageBodyEditorDlg = class(TForm)
Panel4: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel1: TPanel;
PageControl: TPageControl;
tsBodies: TTabSheet;
Panel5: TPanel;
Panel6: TPanel;
Panel8: TPanel;
pnButtons: TPanel;
btnAdd: TButton;
btnDelete: TButton;
btnUp: TButton;
btnDown: TButton;
BodyList: TListBox;
pmHeaders: TPopupMenu;
miAdd: TMenuItem;
miDelete: TMenuItem;
miUp: TMenuItem;
miDown: TMenuItem;
tsContent: TTabSheet;
Panel7: TPanel;
btnOK: TButton;
btnCancel: TButton;
pDetails: TPanel;
procedure FormResize(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BodyListDblClick(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure FormHide(Sender: TObject);
private
FBodyEditor: TclItemEditor;
FMailMessage: TclMailMessage;
procedure SetMessageBodies(const Value: TclMessageBodies);
procedure LoadBodyList(ASelectedIndex: Integer);
procedure AddBodyToList(AMessageBody: TclMessageBody);
function CurrentBody: TclMessageBody;
procedure StoreBodies;
function GetMessageBodies: TclMessageBodies;
protected
function CreateBodyEditor(AMessageBody: TclMessageBody;
AParent: TWinControl): TclItemEditor; virtual;
public
property MessageBodies: TclMessageBodies read GetMessageBodies write SetMessageBodies;
end;
function ModifyMessageBodies(AMessageBodies: TclMessageBodies): Boolean;
implementation
uses
clEncoder;
{$R *.DFM}
function ModifyMessageBodies(AMessageBodies: TclMessageBodies): Boolean;
var
Dlg: TclMessageBodyEditorDlg;
begin
Dlg := TclMessageBodyEditorDlg.Create(nil);
try
Dlg.MessageBodies := AMessageBodies;
Result := Dlg.ShowModal() = mrOK;
if (Result) then
begin
AMessageBodies.Assign(Dlg.MessageBodies);
end;
finally
Dlg.Free();
end;
end;
procedure SetFocusControl(AControl: TWinControl);
begin
if AControl.CanFocus() then
begin
AControl.SetFocus();
end;
end;
{ TclMessageBodyEditorDlg }
function TclMessageBodyEditorDlg.CreateBodyEditor(AMessageBody: TclMessageBody;
AParent: TWinControl): TclItemEditor;
const
BodyCount = 3;
Bodies: array[0..BodyCount - 1] of TclMessageBodyClass = (
TclTextBody, TclAttachmentBody, TclMultipartBody);
Editors: array[0..BodyCount - 1] of TclItemEditorClass = (
TclTextItemEditor, TclFileItemEditor, TclMultipartItemEditor);
var
i: Integer;
begin
Result := nil;
if (AMessageBody = nil) then Exit;
for i := Low(Bodies) to High(Bodies) do
begin
if (Bodies[i] = AMessageBody.ClassType) then
begin
Result := Editors[i].Create(AMessageBody, AParent);
Break;
end;
end;
end;
procedure TclMessageBodyEditorDlg.FormResize(Sender: TObject);
begin
if (FBodyEditor <> nil) then
begin
FBodyEditor.AlignControls();
end;
end;
procedure TclMessageBodyEditorDlg.btnDeleteClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := BodyList.ItemIndex;
if (Ind > - 1) then
begin
MessageBodies.Delete(Ind);
if (Ind = MessageBodies.Count) then
begin
Dec(Ind);
end;
LoadBodyList(Ind);
end;
end;
procedure TclMessageBodyEditorDlg.btnUpClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := BodyList.ItemIndex;
if (Ind > 0) and (Ind < MessageBodies.Count) then
begin
MessageBodies.Move(Ind, Ind - 1);
LoadBodyList(Ind - 1);
end;
end;
procedure TclMessageBodyEditorDlg.btnDownClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := BodyList.ItemIndex;
if (Ind > -1) and (Ind < MessageBodies.Count - 1) then
begin
MessageBodies.Move(Ind, Ind + 1);
LoadBodyList(Ind + 1);
end;
end;
procedure TclMessageBodyEditorDlg.SetMessageBodies(const Value: TclMessageBodies);
begin
MessageBodies.Assign(Value);
LoadBodyList(0);
end;
procedure TclMessageBodyEditorDlg.FormCreate(Sender: TObject);
begin
FMailMessage := TclMailMessage.Create(nil);
PageControl.ActivePage := tsBodies;
end;
procedure TclMessageBodyEditorDlg.FormDestroy(Sender: TObject);
begin
StoreBodies();
FMailMessage.Free();
end;
procedure TclMessageBodyEditorDlg.AddBodyToList(AMessageBody: TclMessageBody);
begin
BodyList.Items.AddObject(AMessageBody.ClassName, AMessageBody);
end;
procedure TclMessageBodyEditorDlg.LoadBodyList(ASelectedIndex: Integer);
var
i: Integer;
begin
BodyList.Clear();
for i := 0 to MessageBodies.Count - 1 do
begin
AddBodyToList(MessageBodies[i]);
end;
if (BodyList.Items.Count > ASelectedIndex) then
begin
BodyList.ItemIndex := ASelectedIndex;
end;
end;
procedure TclMessageBodyEditorDlg.BodyListDblClick(Sender: TObject);
begin
PageControl.ActivePage := tsContent;
PageControlChange(PageControl);
end;
function TclMessageBodyEditorDlg.CurrentBody: TclMessageBody;
begin
if (BodyList.ItemIndex > -1) then
begin
Result := TclMessageBody(BodyList.Items.Objects[BodyList.ItemIndex]);
end else
begin
Result := nil;
end;
end;
procedure TclMessageBodyEditorDlg.PageControlChange(Sender: TObject);
begin
FBodyEditor.Free();
FBodyEditor := nil;
if (PageControl.ActivePage = tsBodies) then
begin
SetFocusControl(BodyList);
end else
if (PageControl.ActivePage = tsContent) then
begin
FBodyEditor := CreateBodyEditor(CurrentBody(), pDetails);
end;
end;
procedure TclMessageBodyEditorDlg.FormHide(Sender: TObject);
begin
StoreBodies();
end;
procedure TclMessageBodyEditorDlg.StoreBodies();
begin
FBodyEditor.Free();
FBodyEditor := nil;
end;
procedure TclMessageBodyEditorDlg.btnAddClick(Sender: TObject);
begin
if TclMessageBodyChooser.AddSingleBody(MessageBodies) then
begin
LoadBodyList(MessageBodies.Count - 1);
end;
end;
function TclMessageBodyEditorDlg.GetMessageBodies: TclMessageBodies;
begin
Result := FMailMessage.Bodies;
end;
{ TclItemEditor }
procedure TclItemEditor.AlignControls;
var
w: Integer;
begin
FContentTypeLabel.Top := 3;
FEncodingLabel.Top := FContentTypeLabel.Top + FContentType.Height + 3;
FContentType.Top := 0;
FEncoding.Top := FContentType.Top + FContentType.Height + 3;
w := GetMaxLabelWidth();
FContentType.Left := w;
FEncoding.Left := w;
FContentType.Width := Parent.ClientWidth - FContentType.Left;
FEncoding.Width := Parent.ClientWidth - FEncoding.Left;
end;
constructor TclItemEditor.Create(AItem: TclMessageBody; AParent: TWinControl);
begin
inherited Create();
FItem := AItem;
FParent := AParent;
CreateControls();
AlignControls();
FillControls();
SetFocusControl(FContentType);
end;
type
TDummyEncodeMethod = class(TPersistent)
private
FEncodeMethod: TclEncodeMethod;
published
property EncodeMethod: TclEncodeMethod read FEncodeMethod;
end;
procedure TclItemEditor.CreateControls;
var
TypeInfo : PPropInfo;
i : TclEncodeMethod;
begin
FContentTypeLabel := TLabel.Create(nil);
FEncodingLabel := TLabel.Create(nil);
FContentType := TEdit.Create(nil);
FEncoding := TComboBox.Create(nil);
FContentTypeLabel.Parent := Parent;
FEncodingLabel.Parent := Parent;
FContentType.Parent := Parent;
FEncoding.Parent := Parent;
FContentTypeLabel.Caption := 'Content Type';
FEncodingLabel.Caption := 'Encoding';
TypeInfo := GetPropInfo(TDummyEncodeMethod.ClassInfo, 'EncodeMethod');
for i := Low(TclEncodeMethod) to High(TclEncodeMethod) do
begin
FEncoding.Items.AddObject(GetEnumName(TypeInfo^.PropType^, Integer(i)), Pointer(i));
end;
end;
destructor TclItemEditor.Destroy;
begin
FillData();
DestroyControls();
inherited Destroy();
end;
procedure TclItemEditor.DestroyControls;
begin
FEncoding.Free();
FContentType.Free();
FEncodingLabel.Free();
FContentTypeLabel.Free();
end;
procedure TclItemEditor.FillControls;
begin
FContentType.Text := Item.ContentType;
FEncoding.ItemIndex := Integer(Item.Encoding);
end;
procedure TclItemEditor.FillData;
begin
Item.ContentType := FContentType.Text;
Item.Encoding := TclEncodeMethod(FEncoding.ItemIndex);
end;
function TclItemEditor.GetControlsVertivalPos: Integer;
begin
Result := FEncoding.Top + FEncoding.Height + 5;
end;
function TclItemEditor.GetMaxLabelWidth: Integer;
begin
Result := FContentTypeLabel.Width;
if (Result < FEncodingLabel.Width) then
begin
Result := FEncodingLabel.Width;
end;
Result := Result + 4;
end;
{ TclTextItemEditor }
procedure TclTextItemEditor.AlignControls;
begin
inherited AlignControls();
FRichEdit.Top := GetControlsVertivalPos();
FRichEdit.Left := 0;
FRichEdit.Width := Parent.ClientWidth;
FRichEdit.Height := Parent.ClientHeight - FRichEdit.Top;
FRichEdit.Anchors := [akTop, akLeft, akRight, akBottom];
end;
procedure TclTextItemEditor.CreateControls;
begin
inherited CreateControls();
FRichEdit := TRichEdit.Create(nil);
FRichEdit.Parent := Parent;
FRichEdit.WordWrap := False;
end;
procedure TclTextItemEditor.DestroyControls;
begin
FRichEdit.Free();
inherited DestroyControls();
end;
procedure TclTextItemEditor.FillControls;
begin
inherited FillControls();
FRichEdit.Lines.Assign((Item as TclTextBody).Strings);
end;
procedure TclTextItemEditor.FillData;
begin
inherited FillData();
(Item as TclTextBody).Strings.Assign(FRichEdit.Lines);
end;
{ TclFileItemEditor }
procedure TclFileItemEditor.AlignControls;
begin
inherited AlignControls();
FFileNameLabel.Top := GetControlsVertivalPos() + 3;
FFileName.Top := GetControlsVertivalPos();
FBrowseButton.Top := FFileName.Top;
FFileName.Left := GetMaxLabelWidth();
FBrowseButton.Height := FFileName.Height;
FBrowseButton.Width := FBrowseButton.Height;
FBrowseButton.Left := Parent.ClientWidth - FBrowseButton.Width;
FFileName.Width := Parent.ClientWidth - FFileName.Left - FBrowseButton.Width;
end;
procedure TclFileItemEditor.CreateControls;
begin
inherited CreateControls();
FFileNameLabel := TLabel.Create(nil);
FFileName := TEdit.Create(nil);
FBrowseButton := TButton.Create(nil);
FFileNameLabel.Parent := Parent;
FFileName.Parent := Parent;
FBrowseButton.Parent := Parent;
FFileNameLabel.Caption := 'File Name';
FBrowseButton.Caption := '...';
FBrowseButton.OnClick := DoOnBrowseClick;
end;
procedure TclFileItemEditor.DoOnBrowseClick(Sender: TObject);
var
dlg: TOpenDialog;
begin
dlg := TOpenDialog.Create(nil);
try
dlg.Filename := FFileName.Text;
dlg.InitialDir := ExtractFilePath(dlg.Filename);
dlg.Filter := '*.*';
dlg.Options := dlg.Options + [ofEnableSizing];
if dlg.Execute then FFileName.Text := dlg.Filename;
finally
dlg.Free();
end;
end;
procedure TclFileItemEditor.FillControls;
begin
inherited FillControls();
FFileName.Text := (Item as TclAttachmentBody).FileName;
end;
procedure TclFileItemEditor.FillData;
begin
inherited FillData();
(Item as TclAttachmentBody).FileName := FFileName.Text;
end;
procedure TclFileItemEditor.DestroyControls;
begin
FBrowseButton.Free();
FFileName.Free();
FFileNameLabel.Free();
inherited DestroyControls();
end;
function TclFileItemEditor.GetMaxLabelWidth: Integer;
begin
Result := inherited GetMaxLabelWidth();
if (Result < FFileNameLabel.Width) then
begin
Result := FFileNameLabel.Width;
end;
Result := Result + 4;
end;
{ TclMultipartItemEditor }
procedure TclMultipartItemEditor.AlignControls;
begin
inherited AlignControls();
FButton.Top := GetControlsVertivalPos();
FButton.Left := 0;
FButton.Width := Parent.ClientWidth;
end;
procedure TclMultipartItemEditor.CreateControls;
begin
inherited CreateControls();
FButton := TButton.Create(nil);
FButton.Parent := Parent;
FButton.Caption := 'Edit Multipart Body Content...';
FButton.OnClick := ButtonClick;
end;
procedure TclMultipartItemEditor.DestroyControls;
begin
FButton.Free();
inherited DestroyControls();
end;
procedure TclMultipartItemEditor.ButtonClick(Sender: TObject);
begin
ModifyMessageBodies((Item as TclMultipartBody).Bodies);
end;
end.
|
unit psapi;
{$WEAKPACKAGEUNIT ON}
interface
uses Windows;
type
PHInst = ^HInst;
TModuleInfo = record
lpBaseOfDll : pointer;
SizeOfImage : Integer;
EntryPoint : pointer
end;
TPSAPIWsWatchInformation = record
FaultingPc : pointer;
FaultingVa : pointer
end;
TProcessMemoryCounters = record
cb : Integer;
PageFaultCount : Integer;
PeakWorkingSetSize : Integer;
WorkingSetSize : Integer;
QuotaPeakPagedPoolUsage : Integer;
QuotaPagedPoolUsage : Integer;
QuotaPeakNonPagedPoolUsage : Integer;
QuotaNonPagedPoolUsage : Integer;
PagefileUsage : Integer;
PeakPagefileUsage : Integer
end;
function EnumProcesses (pidList : PInteger; cb : Integer; var cbNeeded : Integer): boolean; stdcall;
function EnumProcessModules (hProcess : THandle; moduleList : PHInst; cb : Integer; var cbNeeded : Integer) : boolean; stdcall;
function GetModuleBaseName (hProcess : THandle; module : HInst; BaseName : Pchar; size : Integer) : Integer; stdcall;
function GetModuleFileNameEx (hProcess : THandle; module : HInst; FileName : PChar; size : Integer) : Integer; stdcall;
function GetModuleInformation(hProcess : THandle; module : HInst; var info : TModuleInfo; size : Integer) : boolean; stdcall;
function EmptyWorkingSet (hProcess : THandle) : boolean; stdcall;
function QueryWorkingSet (hProcess : THandle; var pv; size : Integer) : boolean; stdcall;
function InitializeProcessForWsWatch (hProcess : THandle) : boolean; stdcall;
function GetWsChanges (hProcess : THandle; var WatchInfo : TPSAPIWsWatchInformation; size : Integer) : boolean; stdcall;
function GetMappedFileName (hProcess : THandle; pv : pointer; FileName : PChar; size : Integer) : Integer; stdcall;
function EnumDeviceDrivers (var ImageBase : Integer; cb : Integer; var cbNeeded : Integer) : boolean; stdcall;
function GetDeviceDriverBaseName (ImageBase : Integer; BaseName : PChar; size : Integer) : Integer; stdcall;
function GetDeviceDriverFileName (ImageBase : Integer; FileName : PChar; size : Integer) : Integer; stdcall;
function GetProcessMemoryInfo (hProcess : THandle; var ProcessMemoryCounters : TProcessMemoryCounters; size : Integer) : boolean; stdcall;
implementation
const psapidll = 'psapi.dll';
function EnumProcesses; external psapidll;
function EnumProcessModules; external psapidll;
function GetModuleBaseName; external psapidll name 'GetModuleBaseNameA';
function GetModuleFileNameEx; external psapidll name 'GetModuleFileNameExA';
function GetModuleInformation; external psapidll;
function EmptyWorkingSet; external psapidll;
function QueryWorkingSet; external psapidll;
function InitializeProcessForWsWatch; external psapidll;
function GetWsChanges; external psapidll;
function GetMappedFileName; external psapidll name 'GetMappedFileNameA';
function EnumDeviceDrivers; external psapidll;
function GetDeviceDriverBaseName; external psapidll name 'GetDeviceDriverBaseNameA';
function GetDeviceDriverFileName; external psapidll name 'GetDeviceDriverFileNameA';
function GetProcessMemoryInfo; external psapidll;
end.
|
unit Controller.ListagemAssinantesJornal;
interface
uses System.SysUtils, FireDAC.Comp.Client, Common.ENum, Controller.Sistema, Model.ListagemAssinantesJornal,
Controller.PlanilhaListagemJornal, Generics.Collections, Model.PlanilhaListagemJornal, System.Classes;
type
TListagemAssinantesJornalControl = class
private
FListagem : TListagemAssinantesJornal;
fdAssinaturas: TFDQuery;
public
constructor Create();
destructor Destroy(); override;
property Lista: TListagemAssinantesJornal read FListagem write FListagem;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
function ImportData(sFile: String; dateData: TDate): Boolean;
function DeleteEdicao(): Boolean;
function DeleteAll(): Boolean;
end;
implementation
{ TListagemAssinantesJornalControl }
uses dataModule, Common.Utils;
constructor TListagemAssinantesJornalControl.Create;
begin
FListagem := TListagemAssinantesJornal.Create;
end;
function TListagemAssinantesJornalControl.DeleteAll: Boolean;
begin
if not Flistagem.DeleteAll() then
begin
TUtils.Dialog('Atenção', 'Erro ao limpar o banco de dados!', 0);
end;
end;
function TListagemAssinantesJornalControl.DeleteEdicao: Boolean;
begin
if not Flistagem.DeleteEdicao() then
begin
TUtils.Dialog('Atenção', 'Erro ao excluir a data do banco de dados!', 0);
end;
end;
destructor TListagemAssinantesJornalControl.Destroy;
begin
FListagem.Free;
inherited;
end;
function TListagemAssinantesJornalControl.Gravar: Boolean;
begin
Result := False;
Result := FListagem.Gravar;
end;
function TListagemAssinantesJornalControl.ImportData(sFile: String; dateData: TDate): Boolean;
var
FPlanilha: TPlanilhaListagemJornalControl;
idiaSemana : Integer;
FDados: TObjectList<TPlanilhaListagemJornal>;
i: Integer;
fdAssinaturas : TFDQuery;
begin
try
try
Result := False;
FPlanilha := TPlanilhaListagemJornalControl.Create;
fdAssinaturas := FListagem.QueryInsertMode();
idiaSemana := DayOfWeek(dateData);
if idiaSemana in [3,4,5,6,7] then
begin
FListagem.DeleteAll();
end
else
begin
Flistagem.Edicao := dateData;;
FListagem.DeleteEdicao();
end;
FDados := TObjectList<TPlanilhaListagemJornal>.Create;
FDados := FPlanilha.GetPlanilha(sFile);
if FDados = nil then Exit;
if FDados.Count = 0 then Exit;
for i := 0 to FDados.Count - 1 do
begin
fdAssinaturas.Params.ArraySize := i + 1;
fdAssinaturas.ParamByName('pcod_agente').AsIntegers[i] := StrToIntDef(FDados[i].Agente,0);
fdAssinaturas.ParamByName('pdat_edicao').AsDateTimes[i] := dateData;
fdAssinaturas.ParamByName('pcod_assinatura').AsStrings[i] := FDados[i].Codigo;
fdAssinaturas.ParamByName('pnom_assinante').AsStrings[i] := FDados[i].Nome;
fdAssinaturas.ParamByName('pdes_endereco').AsStrings[i] := FDados[i].Endereco;
fdAssinaturas.ParamByName('pnum_endereco').AsStrings[i] := FDados[i].Numero;
fdAssinaturas.ParamByName('pdes_complemento').AsStrings[i] := FDados[i].Complemento;
fdAssinaturas.ParamByName('pdes_bairro').AsStrings[i] := FDados[i].Bairro;
fdAssinaturas.ParamByName('pnum_cep').AsStrings[i] := FDados[i].CEP;
fdAssinaturas.ParamByName('pdes_referencia').AsStrings[i] := FDados[i].Referencia;
fdAssinaturas.ParamByName('pdes_produto').AsStrings[i] := FDados[i].Produto;
fdAssinaturas.ParamByName('pcod_modalidade').AsIntegers[i] := StrToIntDef(FDados[i].Modalidade,1);
fdAssinaturas.ParamByName('pdes_modalidade').AsStrings[i] := FDados[i].DescricaoModalidade;
fdAssinaturas.ParamByName('pqtd_exemplares').AsIntegers[i] := StrToIntDef(FDados[i].Quantidade,1);
end;
fdAssinaturas.Execute(i,0);
Result := True;
Except
on E: Exception do
begin
TUtils.Dialog('Erro', 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message, 0);
end;
end;
finally
FPlanilha.Free;
fdAssinaturas.Free;
end;
end;
function TListagemAssinantesJornalControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FListagem.Localizar(aParam);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clCookieManager;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SyncObjs,
{$ELSE}
System.Classes, System.SyncObjs,
{$ENDIF}
clHeaderFieldList, clWUtils;
type
TclCookieFormat = (cfNetscape, cfRFC2109, cfRFC2965);
TclCookieItem = class(TCollectionItem)
private
FSecure: Boolean;
FValue: string;
FExpires: TDateTime;
FName: string;
FDomain: string;
FPath: string;
FCookieData: string;
FDiscard: Boolean;
FMaxAge: Int64;
FVersion: Integer;
FPort: string;
FCommentURL: string;
FComment: string;
FFormat: TclCookieFormat;
procedure SetMaxAge(const Value: Int64);
function GetIsPersistent: Boolean;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
procedure Load(AStream: TStream); virtual;
procedure Save(AStream: TStream); virtual;
property Format: TclCookieFormat read FFormat write FFormat;
property Name: string read FName write FName;
property Value: string read FValue write FValue;
property Expires: TDateTime read FExpires write FExpires;
property Domain: string read FDomain write FDomain;
property Path: string read FPath write FPath;
property Secure: Boolean read FSecure write FSecure;
property Comment: string read FComment write FComment;
property MaxAge: Int64 read FMaxAge write SetMaxAge;
property Version: Integer read FVersion write FVersion;
property CommentURL: string read FCommentURL write FCommentURL;
property Discard: Boolean read FDiscard write FDiscard;
property Port: string read FPort write FPort;
property CookieData: string read FCookieData write FCookieData;
property IsPersistent: Boolean read GetIsPersistent;
end;
TclCookieList = class;
TclCompareCookies = function(AList: TclCookieList; Index1, Index2: Integer): Integer of object;
TclCookieList = class(TOwnedCollection)
private
function GetItem(Index: Integer): TclCookieItem;
procedure SetItem(Index: Integer; const Value: TclCookieItem);
procedure RemoveCookies(AFieldList: TclHeaderFieldList);
function GetExpires(AFieldList: TclHeaderFieldList; const ACookieData: string): string;
function CheckLexem(const ASource, ALexem: string): Boolean;
procedure InternalSort(L, R: Integer; ACompare: TclCompareCookies);
procedure ExchangeItems(Index1, Index2: Integer);
function CompareCookies(AList: TclCookieList; Index1, Index2: Integer): Integer;
protected
function BuildRequestCookie(ACookieItem: TclCookieItem): string; virtual;
procedure ParseResponseCookie(AFieldList: TclHeaderFieldList; AFieldIndex: Integer;
const ADomain, APath: string; APort: Integer); virtual;
public
procedure SetRequestCookies(ARequestHeader: TStrings); virtual;
procedure GetResponseCookies(AResponseHeader: TStrings; const ADomain, APath: string; APort: Integer); virtual;
procedure Sort;
function Add: TclCookieItem; overload;
function Add(const AName, AValue, AUrl: string): TclCookieItem; overload;
function Add(const AName, AValue, ADomain, APath: string): TclCookieItem; overload;
function CookieByName(const AName: string; AStartFrom: Integer = 0): TclCookieItem;
procedure Load(AStream: TStream); virtual;
procedure Save(AStream: TStream); virtual;
property Items[Index: Integer]: TclCookieItem read GetItem write SetItem; default;
end;
TclCookieEvent = procedure (Sender: TObject; ACookie: TclCookieItem; var Allow: Boolean) of object;
TclUpdateCookieEvent = procedure (Sender: TObject; AOldCookie, ANewCookie: TclCookieItem;
var Allow: Boolean) of object;
TclAcceptCookieEvent = procedure (Sender: TObject; ACookie: TclCookieItem;
const ADomain, APath: string; APort: Integer; ASecure: Boolean; var Allow: Boolean) of object;
TclCookieManager = class(TComponent)
private
FCookies: TclCookieList;
FAccessor: TCriticalSection;
FOnAddCookie: TclCookieEvent;
FOnDeleteCookie: TclCookieEvent;
FOnUpdateCookie: TclUpdateCookieEvent;
FOnAcceptCookie: TclAcceptCookieEvent;
function GetCookie: TclCookieList;
procedure InternalCleanup;
function IsExpired(ACookie: TclCookieItem): Boolean;
function FindCookie(ATemplate: TclCookieItem): TclCookieItem;
procedure DeleteCookie(ACookie: TclCookieItem);
procedure AddCookie(ACookie: TclCookieItem);
procedure UpdateCookie(AOldCookie, ANewCookie: TclCookieItem);
function IsMatch(ACookie: TclCookieItem; const ADomain, APath: string; APort: Integer; ASecure: Boolean): Boolean;
function IsDomainMatch(const ACookieDomain, AUrlDomain: string): Boolean;
function IsPathMatch(const ACookiePath, AUrlPath: string): Boolean;
function IsPortMatch(const ACookiePort: string; AUrlPort: Integer): Boolean;
protected
procedure DoAddCookie(ACookie: TclCookieItem; var Allow: Boolean); virtual;
procedure DoDeleteCookie(ACookie: TclCookieItem; var Allow: Boolean); virtual;
procedure DoUpdateCookie(AOldCookie, ANewCookie: TclCookieItem; var Allow: Boolean); virtual;
procedure DoAcceptCookie(ACookie: TclCookieItem; const ADomain, APath: string;
APort: Integer; ASecure: Boolean; var Accept: Boolean); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddCookies(ACookies: TclCookieList);
procedure GetCookies(ACookies: TclCookieList; const ADomain, APath: string; APort: Integer; ASecure: Boolean);
procedure Clear;
procedure ClearExpired;
procedure ClearNonPersistent;
procedure BeginUpdate;
procedure EndUpdate;
property Cookies: TclCookieList read GetCookie;
published
property OnAddCookie: TclCookieEvent read FOnAddCookie write FOnAddCookie;
property OnDeleteCookie: TclCookieEvent read FOnDeleteCookie write FOnDeleteCookie;
property OnUpdateCookie: TclUpdateCookieEvent read FOnUpdateCookie write FOnUpdateCookie;
property OnAcceptCookie: TclAcceptCookieEvent read FOnAcceptCookie write FOnAcceptCookie;
end;
function NormalizeDomain(const ADomain: string): string;
function NormalizePath(const APath: string): string;
implementation
uses
{$IFNDEF DELPHIXE2}
SysUtils,
{$ELSE}
System.SysUtils,
{$ENDIF}
clUtils, clUriUtils, clSocket, clHttpHeader;
function NormalizeDomain(const ADomain: string): string;
begin
Result := Trim(ADomain);
if (Result <> '') and (Result[1] <> '.') then
begin
Result := '.' + Result;
end;
end;
function NormalizePath(const APath: string): string;
begin
Result := Trim(APath);
if (Result = '') then
begin
Result := '/';
end;
end;
{ TclCookieList }
function TclCookieList.Add: TclCookieItem;
begin
Result := TclCookieItem(inherited Add());
end;
function TclCookieList.GetItem(Index: Integer): TclCookieItem;
begin
Result := TclCookieItem(inherited GetItem(Index));
end;
procedure TclCookieList.GetResponseCookies(AResponseHeader: TStrings;
const ADomain, APath: string; APort: Integer);
var
i: Integer;
fieldList: TclHeaderFieldList;
begin
Clear();
fieldList := TclHeaderFieldList.Create();
try
fieldList.Parse(0, AResponseHeader);
for i := 0 to fieldList.FieldList.Count - 1 do
begin
if SameText('set-cookie', fieldList.FieldList[i]) or SameText('set-cookie2', fieldList.FieldList[i]) then
begin
ParseResponseCookie(fieldList, i, ADomain, APath, APort);
end;
end;
finally
fieldList.Free();
end;
end;
procedure TclCookieList.Save(AStream: TStream);
var
i: Integer;
writer: TWriter;
begin
writer := TWriter.Create(AStream, 1024);
try
writer.WriteInteger(Count);
finally
writer.Free();
end;
for i := 0 to Count - 1 do
begin
Items[i].Save(AStream);
end;
end;
procedure TclCookieList.SetItem(Index: Integer; const Value: TclCookieItem);
begin
inherited SetItem(Index, Value);
end;
procedure TclCookieList.RemoveCookies(AFieldList: TclHeaderFieldList);
var
i: Integer;
begin
for i := AFieldList.FieldList.Count - 1 downto 0 do
begin
if SameText('cookie', AFieldList.FieldList[i]) then
begin
AFieldList.RemoveField(i);
end;
end;
end;
procedure TclCookieList.SetRequestCookies(ARequestHeader: TStrings);
const
cookieDelimiter = '; ';
var
i: Integer;
s: string;
fieldList: TclHeaderFieldList;
begin
fieldList := TclHeaderFieldList.Create();
try
fieldList.Parse(0, ARequestHeader);
RemoveCookies(fieldList);
s := '';
for i := 0 to Count - 1 do
begin
s := s + BuildRequestCookie(Items[i]) + cookieDelimiter;
end;
if (s <> '') then
begin
SetLength(s, Length(s) - Length(cookieDelimiter));
end;
fieldList.AddField('Cookie', s);
finally
fieldList.Free();
end;
end;
function TclCookieList.BuildRequestCookie(ACookieItem: TclCookieItem): string;
begin
Result := ACookieItem.Name + '=' + ACookieItem.Value;
end;
function TclCookieList.GetExpires(AFieldList: TclHeaderFieldList; const ACookieData: string): string;
const
lexem = 'expires=';
var
ind: Integer;
begin
ind := system.Pos(lexem, LowerCase(ACookieData));
if (ind > 0) then
begin
Result := system.Copy(ACookieData, ind + Length(lexem), Length(ACookieData));
Result := StringReplace(Result, ',', '==', [rfReplaceAll]);
Result := AFieldList.GetFieldValueItem(Result, '');
Result := StringReplace(Result, '==', ',', [rfReplaceAll]);
Result := StringReplace(Result, '-', ' ', [rfReplaceAll]);
end else
begin
Result := '';
end;
end;
procedure TclCookieList.ParseResponseCookie(AFieldList: TclHeaderFieldList; AFieldIndex: Integer;
const ADomain, APath: string; APort: Integer);
var
ind: Integer;
item: TclCookieItem;
s, cookieHeader, cookieData: string;
begin
cookieHeader := AFieldList.FieldList[AFieldIndex];
cookieData := AFieldList.GetFieldValue(AFieldIndex);
if (cookieData = '') then Exit;
item := Add();
ind := system.Pos('=', cookieData);
if (ind > 0) then
begin
item.Name := Trim(system.Copy(cookieData, 1, ind - 1));
item.Value := AFieldList.GetFieldValueItem(cookieData, LowerCase(item.Name));
s := GetExpires(AFieldList, cookieData);
if (s <> '') then
begin
try
item.Expires := MimeTimeToDateTime(s);
except
end;
end;
item.Domain := AFieldList.GetFieldValueItem(cookieData, 'domain');
item.Path := AFieldList.GetFieldValueItem(cookieData, 'path');
item.Secure := CheckLexem(cookieData, 'secure');
item.Comment := AFieldList.GetFieldValueItem(cookieData, 'comment');
item.MaxAge := StrToInt64Def(AFieldList.GetFieldValueItem(cookieData, 'max-age'), -1);
item.Version := StrToIntDef(AFieldList.GetFieldValueItem(cookieData, 'version'), 0);
item.CommentURL := AFieldList.GetFieldValueItem(cookieData, 'commenturl');
item.Port := AFieldList.GetFieldValueItem(cookieData, 'port');
item.Discard := CheckLexem(cookieData, 'discard');
if (item.Port = '') and CheckLexem(cookieData, 'port') then
begin
item.Port := IntToStr(APort);
end;
end else
begin
item.Name := cookieData;
end;
item.CookieData := cookieData;
if SameText('set-cookie2', cookieHeader) then
begin
item.Format := cfRFC2965;
end else
if (item.Version = 1) then
begin
item.Format := cfRFC2109;
end;
if (item.Domain = '') then
begin
item.Domain := ADomain;
end;
item.Domain := NormalizeDomain(item.Domain);
if (item.Path = '') then
begin
item.Path := APath;
end;
item.Path := NormalizePath(item.Path);
end;
function TclCookieList.CheckLexem(const ASource, ALexem: string): Boolean;
function IsDelimiter(AChar: Char): Boolean;
begin
Result := CharInSet(AChar, [' ', ',', ';', #10, #9]);
end;
var
ind: Integer;
begin
ind := system.Pos(ALexem, LowerCase(ASource));
Result := ind > 0;
if (Result) then
begin
Result := IsDelimiter(ASource[ind - 1]);
end;
if (Result and (ind + Length(ALexem) < Length(ASource))) then
begin
Result := IsDelimiter(ASource[ind + Length(ALexem) + 1]);
end;
end;
function TclCookieList.CookieByName(const AName: string; AStartFrom: Integer): TclCookieItem;
var
i: Integer;
begin
for i := AStartFrom to Count - 1 do
begin
Result := Items[i];
if SameText(Result.Name, AName) then Exit;
end;
Result := nil;
end;
function TclCookieList.Add(const AName, AValue, ADomain, APath: string): TclCookieItem;
begin
Result := Add();
Result.Name := AName;
Result.Value := AValue;
Result.Domain := ADomain;
Result.Path := APath;
end;
function TclCookieList.CompareCookies(AList: TclCookieList; Index1, Index2: Integer): Integer;
begin
Result := CompareText(AList[Index1].Name, AList[Index2].Name);
if (Result = 0) then
begin
Result := CompareText(AList[Index2].Path, AList[Index1].Path);
end;
end;
procedure TclCookieList.Sort;
begin
BeginUpdate();
try
if (Count > 0) then
begin
InternalSort(0, Count - 1, CompareCookies);
end;
finally
EndUpdate();
end;
end;
procedure TclCookieList.InternalSort(L, R: Integer; ACompare: TclCompareCookies);
var
i, j, p: Integer;
begin
repeat
i := L;
j := R;
p := (L + R) shr 1;
repeat
while ACompare(Self, i, p) < 0 do Inc(i);
while ACompare(Self, j, p) > 0 do Dec(j);
if (i <= j) then
begin
ExchangeItems(i, j);
if (p = i) then
begin
p := j;
end else
if (p = j) then
begin
p := i;
end;
Inc(i);
Dec(j);
end;
until (i > j);
if (L < j) then
begin
InternalSort(L, j, ACompare);
end;
L := i;
until (i >= R);
end;
procedure TclCookieList.Load(AStream: TStream);
var
i, cnt: Integer;
reader: TReader;
begin
Clear();
reader := TReader.Create(AStream, 1024);
try
cnt := reader.ReadInteger();
finally
reader.Free();
end;
for i := 0 to cnt - 1 do
begin
Add().Load(AStream);
end;
end;
procedure TclCookieList.ExchangeItems(Index1, Index2: Integer);
var
item1, item2: TclCookieItem;
begin
item1 := Items[Index1];
item2 := Items[Index2];
item1.Index := Index2;
item2.Index := Index1;
end;
function TclCookieList.Add(const AName, AValue, AUrl: string): TclCookieItem;
var
host: string;
parser: TclUrlParser;
begin
parser := TclUrlParser.Create();
try
parser.Parse(AUrl);
host := parser.Host;
if SameText(host, 'localhost') then
begin
host := 'local';
end;
host := NormalizeDomain(host);
Result := Add(AName, AValue, host, NormalizePath(parser.AbsolutePath));
finally
parser.Free();
end;
end;
{ TclCookieItem }
procedure TclCookieItem.Assign(Source: TPersistent);
var
item: TclCookieItem;
begin
if (Source is TclCookieItem) then
begin
item := (Source as TclCookieItem);
FFormat := item.Format;
FName := item.Name;
FValue := item.Value;
FExpires := item.Expires;
FDomain := item.Domain;
FPath := item.Path;
FSecure := item.Secure;
FComment := item.Comment;
FMaxAge := item.MaxAge;
FVersion := item.Version;
FCommentURL := item.CommentURL;
FDiscard := item.Discard;
FPort := item.Port;
FCookieData := item.CookieData;
end else
begin
inherited Assign(Source);
end;
end;
constructor TclCookieItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FExpires := -1;
FMaxAge := -1;
end;
function TclCookieItem.GetIsPersistent: Boolean;
begin
Result := (Expires > 0) or (Expires < -1);
end;
procedure TclCookieItem.Load(AStream: TStream);
var
reader: TReader;
begin
reader := TReader.Create(AStream, 1024);
try
FFormat := TclCookieFormat(reader.ReadInteger());
FName := reader.ReadString();
FValue := reader.ReadString();
FExpires := reader.ReadDate();
FDomain := reader.ReadString();
FPath := reader.ReadString();
FSecure := reader.ReadBoolean();
FComment := reader.ReadString();
FMaxAge := reader.ReadInteger();
FVersion := reader.ReadInteger();
FCommentURL := reader.ReadString();
FDiscard := reader.ReadBoolean();
FPort := reader.ReadString();
FCookieData := reader.ReadString();
finally
reader.Free();
end;
end;
procedure TclCookieItem.Save(AStream: TStream);
var
writer: TWriter;
begin
writer := TWriter.Create(AStream, 1024);
try
writer.WriteInteger(Integer(FFormat));
writer.WriteString(FName);
writer.WriteString(FValue);
writer.WriteDate(FExpires);
writer.WriteString(FDomain);
writer.WriteString(FPath);
writer.WriteBoolean(FSecure);
writer.WriteString(FComment);
writer.WriteInteger(FMaxAge);
writer.WriteInteger(FVersion);
writer.WriteString(FCommentURL);
writer.WriteBoolean(FDiscard);
writer.WriteString(FPort);
writer.WriteString(FCookieData);
finally
writer.Free();
end;
end;
procedure TclCookieItem.SetMaxAge(const Value: Int64);
begin
if (FMaxAge <> Value) then
begin
FMaxAge := Value;
if (FMaxAge > 0) and (FExpires < 0) then
begin
FExpires := Now() + FMaxAge * 1000 / MSecsPerDay;
end;
end;
end;
{ TclCookieManager }
procedure TclCookieManager.AddCookies(ACookies: TclCookieList);
var
i: Integer;
item: TclCookieItem;
begin
BeginUpdate();
try
InternalCleanup();
for i := 0 to ACookies.Count - 1 do
begin
item := FindCookie(ACookies[i]);
if (item <> nil) then
begin
if IsExpired(ACookies[i]) then
begin
DeleteCookie(item);
end else
begin
UpdateCookie(item, ACookies[i]);
end;
end else
begin
AddCookie(ACookies[i]);
end;
end;
finally
EndUpdate();
end;
end;
constructor TclCookieManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
FCookies := TclCookieList.Create(Self, TclCookieItem);
end;
destructor TclCookieManager.Destroy;
begin
FCookies.Free();
FAccessor.Free();
inherited Destroy();
end;
function TclCookieManager.GetCookie: TclCookieList;
begin
Result := FCookies;
end;
procedure TclCookieManager.InternalCleanup;
var
i: Integer;
item: TclCookieItem;
begin
for i := Cookies.Count - 1 downto 0 do
begin
item := Cookies[i];
if IsExpired(item) then
begin
DeleteCookie(item);
end;
end;
end;
function TclCookieManager.IsExpired(ACookie: TclCookieItem): Boolean;
begin
Result := ACookie.MaxAge = 0;
if Result then Exit;
Result := ((ACookie.Expires > 0) or (ACookie.Expires < -1)) and (ACookie.Expires < Now());
end;
function TclCookieManager.FindCookie(ATemplate: TclCookieItem): TclCookieItem;
var
i: Integer;
begin
for i := 0 to Cookies.Count - 1 do
begin
Result := Cookies[i];
if SameText(Result.Name, ATemplate.Name) and SameText(Result.Domain, ATemplate.Domain)
and SameText(Result.Path, ATemplate.Path) then Exit;
end;
Result := nil;
end;
procedure TclCookieManager.DeleteCookie(ACookie: TclCookieItem);
var
accept: Boolean;
begin
accept := True;
DoDeleteCookie(ACookie, accept);
if accept then
begin
ACookie.Free();
end;
end;
procedure TclCookieManager.AddCookie(ACookie: TclCookieItem);
var
accept: Boolean;
begin
accept := True;
DoAddCookie(ACookie, accept);
if accept then
begin
Cookies.Add().Assign(ACookie);
end;
end;
procedure TclCookieManager.UpdateCookie(AOldCookie, ANewCookie: TclCookieItem);
var
accept: Boolean;
begin
accept := True;
DoUpdateCookie(AOldCookie, ANewCookie, accept);
if accept then
begin
AOldCookie.Assign(ANewCookie);
end;
end;
procedure TclCookieManager.GetCookies(ACookies: TclCookieList;
const ADomain, APath: string; APort: Integer; ASecure: Boolean);
var
i: Integer;
begin
BeginUpdate();
ACookies.BeginUpdate();
try
InternalCleanup();
ACookies.Clear();
for i := 0 to Cookies.Count - 1 do
begin
if IsMatch(Cookies[i], ADomain, APath, APort, ASecure) then
begin
ACookies.Add().Assign(Cookies[i]);
end;
end;
ACookies.Sort();
finally
ACookies.EndUpdate();
EndUpdate();
end;
end;
function TclCookieManager.IsDomainMatch(const ACookieDomain, AUrlDomain: string): Boolean;
var
ind: Integer;
cDomain, uDomain: string;
begin
cDomain := LowerCase(NormalizeDomain(ACookieDomain));
uDomain := LowerCase(NormalizeDomain(AUrlDomain));
Result := (cDomain = '.local');
if not Result then
begin
Result := (cDomain = uDomain);
if not Result then
begin
Result := (RTextPos(cDomain, uDomain) > 0);
end;
if Result then
begin
Result := False;
if (Length(cDomain) > 1) then
begin
ind := TextPos('.', cDomain, 2);
Result := ((ind = 0) or (ind > 2)) and (ind < Length(cDomain));
end;
end;
end;
end;
function TclCookieManager.IsPathMatch(const ACookiePath, AUrlPath: string): Boolean;
var
cPath, uPath: string;
begin
cPath := LowerCase(NormalizePath(ACookiePath));
uPath := LowerCase(NormalizePath(AUrlPath));
Result := (system.Pos(cPath, uPath) > 0);
end;
function TclCookieManager.IsPortMatch(const ACookiePort: string; AUrlPort: Integer): Boolean;
var
i: Integer;
uPort: string;
begin
if (ACookiePort = '') then
begin
Result := True;
Exit;
end;
uPort := IntToStr(AUrlPort);
for i := 1 to WordCount(ACookiePort, [',']) do
begin
Result := (ExtractWord(i, ACookiePort, [',']) = uPort);
if Result then Exit;
end;
Result := False;
end;
function TclCookieManager.IsMatch(ACookie: TclCookieItem; const ADomain, APath: string;
APort: Integer; ASecure: Boolean): Boolean;
begin
Result := IsDomainMatch(ACookie.Domain, ADomain) and IsPathMatch(ACookie.Path, APath)
and IsPortMatch(ACookie.Port, APort);
if Result and ACookie.Secure then
begin
Result := ASecure;
end;
DoAcceptCookie(ACookie, ADomain, APath, APort, ASecure, Result);
end;
procedure TclCookieManager.BeginUpdate;
begin
FAccessor.Enter();
Cookies.BeginUpdate();
end;
procedure TclCookieManager.EndUpdate;
begin
Cookies.EndUpdate();
FAccessor.Leave();
end;
procedure TclCookieManager.Clear;
var
i: Integer;
begin
BeginUpdate();
try
for i := Cookies.Count - 1 downto 0 do
begin
DeleteCookie(Cookies[i]);
end;
finally
EndUpdate();
end;
end;
procedure TclCookieManager.ClearExpired;
begin
BeginUpdate();
try
InternalCleanup();
finally
EndUpdate();
end;
end;
procedure TclCookieManager.ClearNonPersistent;
var
i: Integer;
item: TclCookieItem;
begin
BeginUpdate();
try
for i := Cookies.Count - 1 downto 0 do
begin
item := Cookies[i];
if not ((item.Expires > 0) or (item.Expires < -1)) then
begin
DeleteCookie(item);
end;
end;
finally
EndUpdate();
end;
end;
procedure TclCookieManager.DoAddCookie(ACookie: TclCookieItem; var Allow: Boolean);
begin
if Assigned(OnAddCookie) then
begin
OnAddCookie(Self, ACookie, Allow);
end;
end;
procedure TclCookieManager.DoDeleteCookie(ACookie: TclCookieItem; var Allow: Boolean);
begin
if Assigned(OnDeleteCookie) then
begin
OnDeleteCookie(Self, ACookie, Allow);
end;
end;
procedure TclCookieManager.DoUpdateCookie(AOldCookie, ANewCookie: TclCookieItem; var Allow: Boolean);
begin
if Assigned(OnUpdateCookie) then
begin
OnUpdateCookie(Self, AOldCookie, ANewCookie, Allow);
end;
end;
procedure TclCookieManager.DoAcceptCookie(ACookie: TclCookieItem; const ADomain, APath: string;
APort: Integer; ASecure: Boolean; var Accept: Boolean);
begin
if Assigned(OnAcceptCookie) then
begin
OnAcceptCookie(Self, ACookie, ADomain, APath, APort, ASecure, Accept);
end;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 2015-02-03 ¿ÀÈÄ 9:32:39
//
unit ClientClassesUnit1;
interface
uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect;
type
IDSRestCachedTFDJSONDataSets = interface;
TServerMethods1Client = class(TDSAdminRestClient)
private
FGetCustomersCommand: TDSRestCommand;
FGetCustomersCommand_Cache: TDSRestCommand;
FUpdateCustomersCommand: TDSRestCommand;
public
constructor Create(ARestConnection: TDSRestConnection); overload;
constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function GetCustomers(const ARequestFilter: string = ''): TFDJSONDataSets;
function GetCustomers_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
procedure UpdateCustomers(ADeltas: TFDJSONDeltas);
end;
IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>)
end;
TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand)
end;
const
TServerMethods1_GetCustomers: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods1_GetCustomers_Cache: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods1_UpdateCustomers: array [0..0] of TDSRestParameterMetaData =
(
(Name: 'ADeltas'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas')
);
implementation
function TServerMethods1Client.GetCustomers(const ARequestFilter: string): TFDJSONDataSets;
begin
if FGetCustomersCommand = nil then
begin
FGetCustomersCommand := FConnection.CreateCommand;
FGetCustomersCommand.RequestType := 'GET';
FGetCustomersCommand.Text := 'TServerMethods1.GetCustomers';
FGetCustomersCommand.Prepare(TServerMethods1_GetCustomers);
end;
FGetCustomersCommand.Execute(ARequestFilter);
if not FGetCustomersCommand.Parameters[0].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FGetCustomersCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FGetCustomersCommand.Parameters[0].Value.GetJSONValue(True)));
if FInstanceOwner then
FGetCustomersCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethods1Client.GetCustomers_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FGetCustomersCommand_Cache = nil then
begin
FGetCustomersCommand_Cache := FConnection.CreateCommand;
FGetCustomersCommand_Cache.RequestType := 'GET';
FGetCustomersCommand_Cache.Text := 'TServerMethods1.GetCustomers';
FGetCustomersCommand_Cache.Prepare(TServerMethods1_GetCustomers_Cache);
end;
FGetCustomersCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FGetCustomersCommand_Cache.Parameters[0].Value.GetString);
end;
procedure TServerMethods1Client.UpdateCustomers(ADeltas: TFDJSONDeltas);
begin
if FUpdateCustomersCommand = nil then
begin
FUpdateCustomersCommand := FConnection.CreateCommand;
FUpdateCustomersCommand.RequestType := 'POST';
FUpdateCustomersCommand.Text := 'TServerMethods1."UpdateCustomers"';
FUpdateCustomersCommand.Prepare(TServerMethods1_UpdateCustomers);
end;
if not Assigned(ADeltas) then
FUpdateCustomersCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDSRestCommand(FUpdateCustomersCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCustomersCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltas), True);
if FInstanceOwner then
ADeltas.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCustomersCommand.Execute;
end;
constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection);
begin
inherited Create(ARestConnection);
end;
constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean);
begin
inherited Create(ARestConnection, AInstanceOwner);
end;
destructor TServerMethods1Client.Destroy;
begin
FGetCustomersCommand.DisposeOf;
FGetCustomersCommand_Cache.DisposeOf;
FUpdateCustomersCommand.DisposeOf;
inherited;
end;
end.
|
program mebdd_worker;
{$MODE OBJFPC}
{$R manifest.rc}
{$R mebdd_worker.rc}
uses Sysutils, Classes, RegExpr, mebdd_worker_reg, mebdd_worker_proc, mebdd_worker_groups;
const
RETRIES = 3;
var
path_mebdd: AnsiString='';
path_diskpart: AnsiString='';
path_cmd: AnsiString='';
path_image: AnsiString='';
path_drives: Tdrive_string_arr;
path_drive_count: Word=0;
switch_verify: Boolean=False;
function file_is_readable(file_path:AnsiString):boolean;
var
_result:boolean=true;
f:TextFile;
buffer:AnsiString;
begin
{$I+}
try
AssignFile(f, file_path);
Reset(f);
read(f, buffer);
CloseFile(f);
except
on EInOutError do
_result := false;
end;
file_is_readable := _result;
end;
function get_file_size(file_path:AnsiString):Int64;
var
_result:Int64;
f:File of Byte;
begin
{$I+}
try
Assign(f,file_path);
Reset(f);
_result := FileSize(f);
Close(f);
except
_result := 0;
end;
get_file_size := _result;
end;
function is_worker_already_running():Boolean;
var
registry_pid:Integer;
_result:Boolean;
begin
_result := false;
registry_pid := read_registry_hkcu_value_int('Software\MEB Finland\mebdd', 'running_pid');
if registry_pid <= 0 then
begin
// Key was not found
_result := false;
end
else
begin
if is_pid_alive(registry_pid, 'iexplore.exe') then
_result := true;
end;
is_worker_already_running := _result;
end;
function devicepath_to_disknumber(devicepath:AnsiString):AnsiString;
var
RegexObj: TRegExpr;
str_devicepath_disknumber: AnsiString;
_result: AnsiString;
begin
// Default result 'not found'
_result := '';
RegexObj := TRegExpr.Create;
RegexObj.Expression := '^\\\\\.\\PHYSICALDRIVE(\d+)$';
RegexObj.ModifierI := True;
if RegexObj.Exec(devicepath) then
begin
str_devicepath_disknumber := RegexObj.Match[1];
If str_devicepath_disknumber <> '' Then
_result := str_devicepath_disknumber;
end;
devicepath_to_disknumber := _result;
end;
function drive_paths_are_usb(drive_count:Word; drives:Tdrive_string_arr):Boolean;
var
cmdline:Texec_params_array;
diskpart_script:AnsiString;
parameters:TStringList;
process_output:Tproc_output_arr;
n, match_count:Word;
f: TextFile;
RegexObj: TRegExpr;
begin
diskpart_script := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+'mebdd_worker_'+IntToStr(GetProcessID)+'.txt';
// Open DISKPART script file
AssignFile(f, diskpart_script);
ReWrite(f);
for n:=0 to drive_count-1 do
begin
// Create DISKPART script for this drive
If devicepath_to_disknumber(drives[n]) = '' Then
begin
proc_log_writeln('Device path "'+drives[n]+'" does not resolve to a disk number');
drive_paths_are_usb := False;
Exit;
end;
writeln(f, 'SELECT DISK '+devicepath_to_disknumber(drives[n]));
writeln(f, 'DETAIL DISK');
end;
writeln(f, 'EXIT');
CloseFile(f);
// Set process executable + parameters
cmdline[0].executable := path_diskpart;
parameters := TStringList.Create;
parameters.Add('/s');
parameters.Add(diskpart_script);
cmdline[0].parameters := parameters;
// Run processes
process_output := run_processes(1, cmdline);
// Delete DISKPART script
If not DeleteFile(diskpart_script) Then
proc_log_string('Warning: failed to delete temporary file "'+diskpart_script+'"');
// Check process output
RegexObj := TRegExpr.Create;
RegexObj.Expression := ': USB\r';
if RegexObj.Exec(process_output[0]) then
begin
// We have at least one match
match_count := 1;
while RegexObj.ExecNext do
Inc(match_count);
if match_count = drive_count then
drive_paths_are_usb := True
else
drive_paths_are_usb := False;
end;
RegexObj.Free;
end;
function get_file_digest(path_image:AnsiString):AnsiString;
var
image_details, image_details_this: AnsiString;
image_filedate: LongInt;
digest: AnsiString;
cmdline:Texec_params_array;
parameters:TStringList;
process_output:Tproc_output_arr;
RegexObj: TRegExpr;
begin
// Try to read an existing digest
image_details := read_registry_hkcu_value_string('Software\MEB Finland\mebdd', 'image_details');
digest := read_registry_hkcu_value_string('Software\MEB Finland\mebdd', 'image_md5');
image_filedate := FileAge(path_image);
if image_filedate = -1 then
image_details_this := path_image + ':' + IntToStr(get_file_size(path_image))
else
image_details_this := path_image + ':' + IntToStr(get_file_size(path_image)) + ':' + DateTimeToStr(FileDateTodateTime(image_filedate));
if image_details <> image_details_this then
begin
// The digest does not belong to this file
digest := '';
end;
// If we did not find a digest, calculate it
if digest = '' then
begin
// Run MD5 as an external process
cmdline[0].executable := IncludeTrailingPathDelimiter(path_mebdd)+'mebmd5.exe';
parameters := TStringList.Create;
parameters.Add(path_image);
cmdline[0].parameters := parameters;
process_output := run_processes(1, cmdline);
// Search the MD5 digest from the output
RegexObj := TRegExpr.Create;
RegexObj.Expression := '^([0123456789abcdef]+)';
RegexObj.ModifierI := True;
if RegexObj.Exec(process_output[0]) then
begin
digest := RegexObj.Match[1];
// Store digest to registry
if not write_registry_hkcu_value_string('Software\MEB Finland\mebdd', 'image_details', image_details_this) then
proc_log_writeln('Warning: Could not store digest to registry - image_details');
if not write_registry_hkcu_value_string('Software\MEB Finland\mebdd', 'image_md5', digest) then
proc_log_writeln('Warning: Could not store digest to registry - image_md5');
end;
end;
get_file_digest := digest;
end;
function clear_partition_tables(drive_count:Word; drives:Tdrive_string_arr):Boolean;
var
cmdline:Texec_params_array;
diskpart_script:AnsiString;
parameters:TStringList;
finished_processes:Word;
n:Word;
f: TextFile;
retry_counter: Integer;
begin
diskpart_script := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+'mebdd_worker_'+IntToStr(GetProcessID)+'.txt';
// Open DISKPART script file
AssignFile(f, diskpart_script);
ReWrite(f);
for n:=0 to drive_count-1 do
begin
// Create DISKPART script for this drive
If devicepath_to_disknumber(drives[n]) = '' Then
begin
proc_log_writeln('Device path "'+drives[n]+'" does not resolve to a disk number');
clear_partition_tables := False;
Exit;
end;
writeln(f, 'SELECT DISK '+devicepath_to_disknumber(drives[n]));
writeln(f, 'CLEAN');
end;
writeln(f, 'EXIT');
CloseFile(f);
// Set process executable + parameters
cmdline[0].executable := path_diskpart;
parameters := TStringList.Create;
parameters.Add('/s');
parameters.Add(diskpart_script);
cmdline[0].parameters := parameters;
// Run processes in a repeat loop
retry_counter := 0;
repeat
// Increase retry counter + write to log
Inc(retry_counter);
proc_log_string('Retry '+IntToStr(retry_counter)+':');
// Run process
finished_processes := run_processes_count(1, cmdline, 'exit_code:0', '');
if finished_processes = 1 then
clear_partition_tables := True
else
clear_partition_tables := False;
until ((retry_counter > RETRIES) or clear_partition_tables);
if (not clear_partition_tables) then
proc_log_string('All retries failed.');
// Delete DISKPART script
If not DeleteFile(diskpart_script) Then
proc_log_string('Warning: failed to delete temporary file "'+diskpart_script+'"');
end;
function create_fat_disk(drive_count:Word; drives:Tdrive_string_arr):Boolean;
var
cmdline:Texec_params_array;
diskpart_script:AnsiString;
parameters:TStringList;
finished_processes:Word;
n:Word;
f: TextFile;
retry_counter,automount_setting: Integer;
begin
// Read initial AUTOMOUNT setting
automount_setting := read_registry_hklm_value_int('SYSTEM\CurrentControlSet\Services\mountmgr', 'NoAutoMount');
If automount_setting = -1 Then
begin
proc_log_writeln('Could not read AUTOMOUNT setting from registry');
create_fat_disk := False;
Exit;
end;
diskpart_script := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+'mebdd_worker_'+IntToStr(GetProcessID)+'.txt';
// Open DISKPART script file
AssignFile(f, diskpart_script);
ReWrite(f);
// Disable AUTOMOUNT if it was enabled
If automount_setting = 0 Then
begin
writeln(f, 'AUTOMOUNT DISABLE');
end;
for n:=0 to drive_count-1 do
begin
// Create DISKPART script for this drive
If devicepath_to_disknumber(drives[n]) = '' Then
begin
proc_log_writeln('Device path "'+drives[n]+'" does not resolve to a disk number');
create_fat_disk := False;
Exit;
end;
writeln(f, 'SELECT DISK '+devicepath_to_disknumber(drives[n]));
writeln(f, 'CLEAN');
writeln(f, 'CREATE PARTITION PRIMARY');
writeln(f, 'FORMAT QUICK');
end;
// Enable AUTOMOUNT if it was originaly enabled
If automount_setting = 0 Then
begin
writeln(f, 'AUTOMOUNT ENABLE');
end;
writeln(f, 'EXIT');
CloseFile(f);
// Set process executable + parameters
cmdline[0].executable := path_diskpart;
parameters := TStringList.Create;
parameters.Add('/s');
parameters.Add(diskpart_script);
cmdline[0].parameters := parameters;
// Run processes in a repeat loop
retry_counter := 0;
repeat
// Increase retry counter + write to log
Inc(retry_counter);
proc_log_string('Retry '+IntToStr(retry_counter)+':');
// Run process
finished_processes := run_processes_count(1, cmdline, 'exit_code:0', '');
if finished_processes = 1 then
create_fat_disk := True
else
create_fat_disk := False;
until ((retry_counter > RETRIES) or create_fat_disk);
if (not create_fat_disk) then
proc_log_string('All retries failed.');
// Delete DISKPART script
If not DeleteFile(diskpart_script) Then
proc_log_string('Warning: failed to delete temporary file "'+diskpart_script+'"');
end;
function write_disk_image(drive_count:Word; drives:Tdrive_string_arr; image_file:AnsiString):Boolean;
var
dd_cmdline:Texec_params_array;
parameters:TStringList;
finished_processes:Word;
n:Word;
retry_counter: Integer;
begin
for n:=0 to drive_count-1 do
begin
dd_cmdline[n].executable := IncludeTrailingPathDelimiter(path_mebdd)+'dd.exe';
parameters := TStringList.Create;
parameters.Add('if="'+image_file+'"');
parameters.Add('of="'+drives[n]+'"');
parameters.Add('bs=1M');
dd_cmdline[n].parameters := parameters;
end;
// Run processes in a repeat loop
retry_counter := 0;
repeat
// Increase retry counter + write to log
Inc(retry_counter);
proc_log_string('Retry '+IntToStr(retry_counter)+':');
// Run processes
finished_processes := run_processes_count(drive_count, dd_cmdline, '', '.*Error.*');
if finished_processes = drive_count then
write_disk_image := True
else
write_disk_image := False;
until ((retry_counter > RETRIES) or write_disk_image);
if (not write_disk_image) then
proc_log_string('All retries failed.');
end;
function verify_disk_image(drive_count:Word; drives:Tdrive_string_arr; image_path: AnsiString; digest:AnsiString):Boolean;
var
dd_cmdline:Texec_params_array;
parameters:TStringList;
finished_processes:Word;
temporary_filename: Tdrive_string_arr;
n:Word;
file_size: Int64;
retry_counter: Integer;
begin
// Calculate image size in order to know how many bytes we read from the USB
file_size := get_file_size(image_path);
for n:=0 to drive_count-1 do
begin
dd_cmdline[n].executable := IncludeTrailingPathDelimiter(path_mebdd)+'mebdd_read.exe';
parameters := TStringList.Create;
parameters.Add(drives[n]);
parameters.Add(IntToStr(file_size));
parameters.Add(digest);
dd_cmdline[n].parameters := parameters;
end;
// Run processes in a repeat loop
retry_counter := 0;
repeat
// Increase retry counter + write to log
Inc(retry_counter);
proc_log_string('Retry '+IntToStr(retry_counter)+':');
// Run processes
finished_processes := run_processes_count(drive_count, dd_cmdline, 'exit_code:1', '');
if finished_processes = drive_count then
verify_disk_image := True
else
verify_disk_image := False;
until ((retry_counter > RETRIES) or verify_disk_image);
if (not verify_disk_image) then
proc_log_string('All retries failed.');
end;
Procedure write_image(path_drive_count:Word; path_drives:Tdrive_string_arr; path_image:AnsiString; switch_verify:Boolean);
var
image_digest:AnsiString;
begin
if path_image = '' then
begin
proc_log_writeln('Error: image path missing');
proc_log_halt(5);
end;
if not file_is_readable(path_image) then
begin
proc_log_writeln('Error: image file "'+path_image+'" is not readable');
proc_log_halt(6);
end;
// Make sure that path_drives resolve to USB memory sticks
proc_log_writeln('Checking drive path(s):');
if drive_paths_are_usb(path_drive_count, path_drives) then
begin
proc_log_writeln('Success! ');
end
else
begin
proc_log_writeln('Error: Drive path check failed');
proc_log_halt(8);
end;
// Count/create file MD5 digest
if (switch_verify) then
begin
proc_log_writeln('Getting image file digest:');
image_digest := get_file_digest(path_image);
if (image_digest = '') then
begin
proc_log_writeln('Error: Could not get image digest');
proc_log_halt(13);
end
else
proc_log_writeln('Success! ');
end
else
image_digest := '';
// Clear partition tables
proc_log_writeln('Clearing master boot record(s) and partition table(s):');
if clear_partition_tables(path_drive_count, path_drives) then
begin
proc_log_writeln('Success! ');
// Sleep 3 seconds to wait all pending disk activity to end
Sleep(3000);
end
else
begin
proc_log_writeln('Error: Failed to clear partition table');
proc_log_halt(9);
end;
// Write image
proc_log_writeln('Writing disk image(s):');
if write_disk_image(path_drive_count, path_drives, path_image) then
begin
proc_log_writeln('Success! ');
end
else
begin
proc_log_writeln('Error: Failed to write disk image');
proc_log_halt(10);
end;
// Verify image
if (switch_verify) then
if image_digest = '' then
begin
proc_log_writeln('Error: Image verify failed as MD5 was not calculated');
proc_log_halt(12);
end
else
begin
proc_log_writeln('Verifying disk image(s):');
if verify_disk_image(path_drive_count, path_drives, path_image, image_digest) then
begin
proc_log_writeln('Success! ');
end
else
begin
proc_log_writeln('Error: disk image verification failed');
proc_log_halt(13);
end;
end;
end;
Procedure create_disk(path_drive_count:Word; path_drives:Tdrive_string_arr);
begin
// Make sure that path_drives resolve to USB memory sticks
proc_log_writeln('Checking drive path(s):');
if drive_paths_are_usb(path_drive_count, path_drives) then
begin
proc_log_writeln('Success! ');
end
else
begin
proc_log_writeln('Error: Drive path check failed');
proc_log_halt(8);
end;
// Remove existing partitions and create FAT
proc_log_writeln('Clearing existiting partition table(s) and creating a new filesystem:');
if create_fat_disk(path_drive_count, path_drives) then
begin
proc_log_writeln('Success! ');
// Sleep 3 seconds to wait all pending disk activity to end
Sleep(3000);
end
else
begin
proc_log_writeln('Error: Failed to clear partition table and create a new filesystem');
proc_log_halt(9);
end;
end;
Procedure show_usage_and_exit;
begin
writeln('usage:');
writeln(' mebdd_worker -w [-v] image_to_write.iso device_to_write1 [device_to_writeN...]');
writeln(' mebdd_worker -c device_to_clear1 [device_to_clearN...]');
proc_log_halt(11);
end;
var
n:Word;
param_n:Word;
operation_mode:Word;
begin
operation_mode := 0;
// Init log file
proc_log_filename(IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP'))+'mebdd.txt');
proc_log_string('Execution started - mebdd_worker build ' + {$I %DATE%} + ' ' + {$I %TIME%});
// Check if user is admin
if not UserInGroup(DOMAIN_ALIAS_RID_ADMINS) then
begin
proc_log_writeln('Error: You have to have administrative privileges to run this program');
proc_log_halt(1);
end;
// Read paths from the registry
path_mebdd := read_registry_hklm_value_str('SOFTWARE\MEB Finland\mebdd', 'path_mebdd');
path_diskpart := read_registry_hklm_value_str('SOFTWARE\MEB Finland\mebdd', 'path_diskpart');
path_cmd := read_registry_hklm_value_str('SOFTWARE\MEB Finland\mebdd', 'path_cmd');
if path_mebdd = '' then
begin
proc_log_writeln('Error: MEB-DD installation path is not set');
proc_log_halt(2);
end;
if path_diskpart = '' then
begin
proc_log_writeln('Error: DISKPART path is not set');
proc_log_halt(3);
end;
if path_cmd = '' then
begin
proc_log_writeln('Error: CMD path is not set');
proc_log_halt(3);
end;
if is_worker_already_running() then
begin
proc_log_writeln('Error: mebdd_worker is already running');
proc_log_halt(4);
end;
// Read command line parameters
if (ParamCount = 0) then
begin
show_usage_and_exit();
end;
param_n := 1;
// Do we have -w = write image? (operation mode = 10)
If ParamStr(param_n) = '-w' Then
begin
Inc(param_n);
// Set operation mode to WRITE
operation_mode := 10;
// Do we have -v = verify?
if ParamStr(param_n) = '-v' then
begin
switch_verify := True;
Inc(param_n);
end
else
switch_verify := False;
// Read image parameter
path_image := ParamStr(param_n);
Inc(param_n);
end;
// Do we have -c = create FAT partition? (operation mode = 20)
If ParamStr(param_n) = '-c' Then
begin
Inc(param_n);
// Set operation mode to CREATE
operation_mode := 20;
end;
// No operation mode?
If (operation_mode = 0) Then
begin
show_usage_and_exit();
end;
// Read drive paths
for n:=param_n to ParamCount do
begin
path_drives[path_drive_count] := ParamStr(n);
path_drive_count := path_drive_count+1;
end;
// Set lock
if not write_registry_hkcu_value_int('Software\MEB Finland\mebdd', 'running_pid', GetProcessID) then
begin
proc_log_writeln('Error: PID write failed');
proc_log_halt(7);
end;
If operation_mode = 10 Then
write_image(path_drive_count, path_drives, path_image, switch_verify);
If operation_Mode = 20 Then
create_disk(path_drive_count, path_drives);
// Clear lock
write_registry_hkcu_value_int('Software\MEB Finland\mebdd', 'running_pid', 0);
proc_log_string('Normal termination');
proc_log_halt(255);
end.
|
program stringHandling(input, output);
type
str = array[0..20] of char;
{digits = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');}
var
test : str;
function lengthString(var reference : str) : integer;
var
i : 0 .. 20;
begin
i := 0;
while reference[i] <> '#' do
i := i + 1;
lengthString := i - 1
end;
procedure initializeString(var reference : str);
var
i : 0 .. 20;
begin
for i := 0 to 20 do
reference[i] := '#';
end;
procedure printString(var reference : str);
var
i, len : 0 .. 20;
begin
len := lengthString(reference);
for i := 0 to len do
write(reference[i]);
writeln;
end;
function power(n, b : integer) : integer;
var
ans, i : integer;
begin
ans := 1;
for i := 1 to b do
ans := ans * n;
power := ans;
end;
function atoi(var reference : str) : integer;
var
i : 0 .. 20;
ans, len, rep, p : integer;
begin
len := lengthString(reference);
ans := 0; rep := 0;
i := len;
while i <> 0 do begin
rep := ord(reference[i]) - 48;
p := len - i;
writeln(i, ' ', reference[i], ' ', rep, ' ', p);
ans := ans + rep * power(10, p);
i := i - 1;
end;
atoi := ans;
end;
begin
initializeString(test);
test[0] := 'N'; test[1] := 'i'; test[2] := 'k';
test[3] := 'l'; test[4] := 'a'; test[5] := 'u';
test[6] := 's'; test[7] := ' '; test[8] := 'W';
test[9] := 'i'; test[10] := 'r'; test[11] := 't';
test[12] := 'h'; test[13] := '.';
initializeString(test);
test[0] := '1'; test[1] := '0';
printString(test);
writeln(atoi(test));
end.
|
unit uGSSettingsMenu;
interface
uses
glr_gamescreens,
glr_utils,
glr_core,
glr_scene,
glr_gui,
glr_tween;
type
{ TglrSettingsMenu }
TglrSettingsMenu = class (TglrGameScreen)
protected
ActionManager: TglrActionManager;
GuiManager: TglrGuiManager;
Container: TglrNode;
ApplyBtn, BackBtn: TglrGuiButton;
MusicSlider, SoundSlider: TglrGuiSlider;
MusicSliderLabel, SoundSliderLabel: TglrGuiLabel;
ImportantCheckBox1, ImportantCheckBox2: TglrGuiCheckBox;
ICBLabel1, ICBLabel2: TglrGuiLabel;
procedure ButtonInit(var Button: TglrGuiButton);
procedure ButtonTween(aObject: TglrTweenObject; aValue: Single);
procedure ButtonClicked(Sender: TglrGuiElement; Event: PglrInputEvent);
procedure ButtonOver(Sender: TglrGuiElement; Event: PglrInputEvent);
procedure SliderAndLabelInit(var Slider: TglrGuiSlider;
var SLabel: TglrGuiLabel);
procedure SliderOver(Sender: TglrGuiElement; Event: PglrInputEvent);
procedure SliderValueChanged(Sender: TglrGuiElement; NewValue: Integer);
procedure CheckBoxAndLabelInit(var CheckBox: TglrGuiCheckBox;
var CBLabel: TglrGuiLabel);
procedure BackToMainMenu();
procedure Apply();
public
constructor Create(ScreenName: UnicodeString); override;
destructor Destroy; override;
procedure OnInput(Event: PglrInputEvent); override;
procedure OnRender; override;
procedure OnUpdate (const DeltaTime: Double); override;
procedure OnLoadStarted(); override;
procedure OnUnloadStarted(); override;
end;
implementation
uses
uGame,
uAssets,
glr_math,
glr_render;
{ TglrSettingsMenu }
procedure TglrSettingsMenu.ButtonInit(var Button: TglrGuiButton);
begin
Button := TglrGuiButton.Create();
with Button do
begin
SetVerticesColor(Colors.MenuButton);
SetSize(Sizes.ButtonSize);
TextLabel.Text := 'Button';
TextLabel.Position := Vec3f(Sizes.ButtonTextOffset, 0);
TextLabel.Color := Colors.MenuButtonText;
Position := Vec3f(Render.Width - Width / 2 - 50, Render.Height - Height - 80, 1);
OnClick := ButtonClicked;
OnMouseOver := ButtonOver;
OnMouseOut := ButtonOver;
Parent := Container;
end;
end;
procedure TglrSettingsMenu.ButtonTween(aObject: TglrTweenObject; aValue: Single);
var
v: TglrVec3f;
begin
v := Vec3f(1,1,1);
(aObject as TglrGuiButton).SetVerticesColor(Vec4f(v.Lerp(Vec3f(Colors.MenuButton), aValue), 1.0));
end;
procedure TglrSettingsMenu.ButtonClicked(Sender: TglrGuiElement;
Event: PglrInputEvent);
begin
Game.Tweener.AddTweenSingle(Sender, ButtonTween, tsExpoEaseIn, 0.0, 1.0, 2.0, 0.1);
if (Sender = BackBtn) then
ActionManager.AddIndependent(BackToMainMenu, 0.2);
if (Sender = ApplyBtn) then
begin
ActionManager.AddIndependent(Apply, 0.2);
end;
end;
procedure TglrSettingsMenu.ButtonOver(Sender: TglrGuiElement;
Event: PglrInputEvent);
begin
if (Sender.IsMouseOver) then
Sender.SetSize(Sizes.ButtonSizeOver)
else
Sender.SetSize(Sizes.ButtonSize);
end;
procedure TglrSettingsMenu.SliderAndLabelInit(var Slider: TglrGuiSlider;
var SLabel: TglrGuiLabel);
begin
Slider := TglrGuiSlider.Create();
with Slider do
begin
Position := Vec3f(Render.Width div 2, 150, 5);
SetVerticesColor(Colors.MenuSlider);
SetSize(200, 20);
Fill.SetSize(195, 15);
Fill.SetVerticesColor(Colors.MenuSlider);
Button.SetSize(25, 25);
Button.SetVerticesColor(Colors.MenuSlider);
Parent := Container;
OnValueChanged := SliderValueChanged;
OnMouseOver := SliderOver;
OnMouseOut := SliderOver;
ChangeTexCoords := True;
ValueLabel.Visible := False;
end;
SLabel := TglrGuiLabel.Create();
SLabel.SetFor(Slider, lpLeft, Vec2f(-15, 0));
SLabel.TextLabel.Color := Colors.MenuText;
end;
procedure TglrSettingsMenu.SliderOver(Sender: TglrGuiElement;
Event: PglrInputEvent);
begin
if (Sender.IsMouseOver) then
begin
TglrGuiSlider(Sender).Button.SetVerticesColor(Colors.MenuSliderOver);
TglrGuiSlider(Sender).Fill.SetVerticesColor(Colors.MenuSliderOver);
end
else
begin
TglrGuiSlider(Sender).Button.SetVerticesColor(Colors.MenuSlider);
TglrGuiSlider(Sender).Fill.SetVerticesColor(Colors.MenuSlider);
end;
end;
procedure TglrSettingsMenu.SliderValueChanged(Sender: TglrGuiElement;
NewValue: Integer);
begin
end;
procedure TglrSettingsMenu.CheckBoxAndLabelInit(var CheckBox: TglrGuiCheckBox;
var CBLabel: TglrGuiLabel);
begin
CheckBox := TglrGuiCheckBox.Create();
with CheckBox do
begin
SetSize(45, 45);
Check.SetSize(35, 35);
Position := Vec3f(Render.Width div 2, 250, 5);
SetVerticesColor(Colors.MenuSlider);
Check.SetVerticesColor(Colors.MenuSliderOver);
Parent := Container;
end;
CBLabel := TglrGuiLabel.Create();
CBLabel.SetFor(CheckBox, lpLeft, Vec2f(-145, 0));
CBLabel.TextLabel.Color := Colors.MenuText;
end;
procedure TglrSettingsMenu.BackToMainMenu;
begin
Game.GameScreenManager.Back();
end;
procedure TglrSettingsMenu.Apply;
begin
// Do some stuff
end;
constructor TglrSettingsMenu.Create(ScreenName: UnicodeString);
begin
inherited Create(ScreenName);
Container := TglrNode.Create();
ActionManager := TglrActionManager.Create();
ButtonInit(ApplyBtn);
ButtonInit(BackBtn);
SliderAndLabelInit(MusicSlider, MusicSliderLabel);
SliderAndLabelInit(SoundSlider, SoundSliderLabel);
SoundSlider.Position.y += 40;
MusicSlider.Value := 50;
SoundSlider.Value := 50;
MusicSliderLabel.TextLabel.Text := Texts.SettingsMusicVolume;
SoundSliderLabel.TextLabel.Text := Texts.SettingsSoundVolume;
ApplyBtn.TextLabel.Text := Texts.MenuApply;
BackBtn.TextLabel.Text := Texts.MenuBack;
BackBtn.Position.y += 70;
CheckBoxAndLabelInit(ImportantCheckBox1, ICBLabel1);
CheckBoxAndLabelInit(ImportantCheckBox2, ICBLabel2);
ICBLabel1.TextLabel.Text := 'Option 1';
ICBLabel2.TextLabel.Text := 'Option 2';
ImportantCheckBox2.Position.y += 50;
GuiManager := TglrGuiManager.Create(Assets.GuiMaterial, Assets.FontMain);
GuiManager.Add(ApplyBtn);
GuiManager.Add(BackBtn);
GuiManager.Add(MusicSlider);
GuiManager.Add(MusicSliderLabel);
GuiManager.Add(SoundSlider);
GuiManager.Add(SoundSliderLabel);
GuiManager.Add(ImportantCheckBox1);
GuiManager.Add(ImportantCheckBox2);
GuiManager.Add(ICBLabel1);
GuiManager.Add(ICBLabel2);
end;
destructor TglrSettingsMenu.Destroy;
begin
Container.Free();
ActionManager.Free();
GuiManager.Free(True);
inherited Destroy;
end;
procedure TglrSettingsMenu.OnInput(Event: PglrInputEvent);
begin
GuiManager.ProcessInput(Event, Assets.GuiCamera);
case Event.InputType of
itKeyDown:
case Event.Key of
kLeft: MusicSlider.Value := MusicSlider.Value - 5;
kRight: MusicSlider.Value := MusicSlider.Value + 5;
end;
end;
end;
procedure TglrSettingsMenu.OnRender;
begin
Assets.GuiCamera.Update();
GuiManager.Render();
end;
procedure TglrSettingsMenu.OnUpdate(const DeltaTime: Double);
begin
GuiManager.Update(DeltaTime);
ActionManager.Update(DeltaTime);
end;
procedure TglrSettingsMenu.OnLoadStarted;
begin
Game.Tweener.AddTweenPSingle(@Container.Position.x, tsExpoEaseIn, -Render.Width, 0, 2.5);
inherited OnLoadStarted;
end;
procedure TglrSettingsMenu.OnUnloadStarted;
begin
Game.Tweener.AddTweenPSingle(@Container.Position.x, tsExpoEaseIn, 0, -Render.Width, 1.0);
ActionManager.AddIndependent(UnloadCompleted, 0.5);
end;
end.
|
unit GX_EditorEnhancements;
{$I GX_CondDefine.inc}
interface
uses
GX_EditorFormServices, GX_ConfigurationInfo, Classes, Controls,
GX_HideNavbar;
type
TConfigurationSheet = (cfgEditor, cfgToolBar, cfgEditorExperts);
{ TEditorEnhancements needs to descend from TComponent as we install
a Notification hook that informs the object of disappearing editor
toolbars. }
type
TEditorEnhancements = class(TComponent)
private
FHideNavigationToolbarExpert: IHideNavigationToolbarExpert;
FToolBarAlign: TAlign;
FToolBarActionsList: TStringList;
FToolBarList: TList;
FButtons: Boolean;
FButtonsFlat: Boolean;
FMultiLine: Boolean;
FHotTrack: Boolean;
FToolBarVisible: Boolean;
FEnabled: Boolean;
FMiddleButtonClose: Boolean;
FHideNavbar: Boolean;
procedure AddToolBar;
procedure RemoveToolBar;
procedure EditorFormListener(EventCode: TEditFormEventCode; EditFormProxy: IGxEditFormProxy);
procedure SetToolBarActionsList(const Value: TStrings);
function GetToolBarActionsList: TStrings;
procedure LoadSettings;
procedure LoadToolBarSettings(const Settings: TGExpertsSettings);
procedure SaveToolBarSettings(const Settings: TGExpertsSettings);
function ShowConfigurationDialog(ActiveSheet: TConfigurationSheet): TModalResult;
procedure SetEnabled(const Value: Boolean);
procedure Install;
procedure Remove;
procedure SetHideNavbar(const _Value: Boolean);
protected
procedure Notification(Component: TComponent; Operation: TOperation); override;
function ConfigurationKey: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveSettings;
property Enabled: Boolean read FEnabled write SetEnabled;
// ToolBar code
procedure ApplyToolBarSettings;
property ToolBarActionsList: TStrings read GetToolBarActionsList write SetToolBarActionsList;
property ToolBarAlign: TAlign read FToolBarAlign write FToolBarAlign;
property ToolBarVisible: Boolean read FToolBarVisible write FToolBarVisible;
function ShowToolBarConfigurationDialog: TModalResult;
function ShowEditorConfigurationDialog: TModalResult;
// Tab properties
property MultiLine: Boolean read FMultiLine write FMultiLine;
property MiddleButtonClose: Boolean read FMiddleButtonClose write FMiddleButtonClose;
property HotTrack: Boolean read FHotTrack write FHotTrack;
property Buttons: Boolean read FButtons write FButtons;
property ButtonsFlat: Boolean read FButtonsFlat write FButtonsFlat;
property HideNavbar: Boolean read FHideNavbar write SetHideNavbar;
end;
function EditorEnhancements: TEditorEnhancements;
procedure FreeEditorEnhancements;
implementation
uses
{$IFOPT D+} GX_DbugIntf, GX_ActionBroker, {$ENDIF}
SysUtils, ExtCtrls, ComCtrls, Forms,
GX_GenericUtils, GX_OtaUtils, GX_Configure, GX_Toolbar, GX_ToolbarConfig,
GX_ToolBarDropDown, GX_GxUtils, GX_IdeUtils;
const
ToolBarActionsKey = 'EditorEnhancements' +PathDelim+ 'ToolBarActions';
ToolBarActionsCountValue = 'Count';
ToolBarActionsActionPrefixValue = 'Action';
{ TEditorEnhancements }
procedure TEditorEnhancements.AddToolBar;
const
GX_ToolBarComponentName = 'GX_ToolBar'; // Do not localize.
var
i: Integer;
EditorFormServices: IGxEditorFormServices;
EditorFormProxy: IGxEditFormProxy;
EditorForm: TCustomForm;
ToolBar: TGXToolBar;
EditControl: TControl;
EditControlPanel: TPanel;
begin
// Create list of toolbars on demand
if not Assigned(FToolBarList) then
FToolBarList := TList.Create;
EditControlPanel := nil;
EditorFormServices := GxEditorFormServices;
for i := 0 to EditorFormServices.EditorFormProxyCount - 1 do
begin
EditorFormProxy := EditorFormServices.EditorFormProxies[i];
Assert(Assigned(EditorFormProxy));
EditorForm := EditorFormProxy.EditorForm;
Assert(Assigned(EditorForm));
if EditorFormProxy.IsSourceEditor and (not Assigned(EditorForm.FindComponent(GX_ToolBarComponentName))) then
begin
ToolBar := TGXToolBar.Create(EditorForm);
FToolBarList.Add(ToolBar);
ToolBar.FreeNotification(Self);
ToolBar.Align := FToolBarAlign;
ToolBar.Name := GX_ToolBarComponentName;
EditControl := EditorFormProxy.EditControl;
Assert(Assigned(EditControl));
if RunningDelphi8OrGreater then begin
// There are toolbar focus problems when the Parent is EditorPanel in D8+
if Assigned(EditControl.Parent) then
EditControlPanel := EditControl.Parent.Parent as TPanel; // CodePanel
end
else
EditControlPanel := EditControl.Parent as TPanel; // EditorPanel
if not Assigned(EditControlPanel) then
Exit;
ToolBar.Parent := EditControlPanel;
ToolBar.Images := GxOtaGetIdeImageList;
ToolBar.BringToFront;
ToolBar.RecreateToolBarButtons;
// Finally make the toolbar visible depending on settings
ToolBar.Visible := ToolBarVisible;
ToolBar.SetEditorControls;
end;
end;
end;
procedure TEditorEnhancements.ApplyToolBarSettings;
var
i: Integer;
GExpertsToolBar: TGXToolBar;
begin
// Immediately exit if there are no toolbars around
if not Assigned(FToolBarList) then
Exit;
{$IFOPT D+} SendDebug(Format('Applying settings to %d toolbars', [FToolBarList.Count])); {$ENDIF}
for i := 0 to FToolBarList.Count - 1 do
begin
GExpertsToolBar := FToolBarList.Items[i];
{$IFOPT D+} SendDebug('Hiding GExpertsToolBar'); {$ENDIF}
GExpertsToolBar.Visible := False;
{$IFOPT D+} SendDebug('Aligning GExpertsToolBar'); {$ENDIF}
GExpertsToolBar.Align := FToolBarAlign;
GExpertsToolBar.RecreateToolBarButtons;
{$IFOPT D+} SendDebug('Setting GExpertsToolBar.Visible to ' + BooleanText(ToolBarVisible)); {$ENDIF}
GExpertsToolBar.Visible := ToolBarVisible;
GExpertsToolBar.SetEditorControls;
end;
{$IFOPT D+} SendDebug('Successfully applied toolbar settings'); {$ENDIF}
end;
function TEditorEnhancements.ConfigurationKey: string;
begin
Result := 'EditorEnhancements';
end;
constructor TEditorEnhancements.Create(AOwner: TComponent);
begin
// There have been some rather inexplicable problems (AVs)
// if AOwner <> nil; simply take no risks - we don't need an owner
Assert(AOwner = nil);
inherited Create(AOwner);
Name := 'GX_EditEnhance';
FHideNavigationToolbarExpert := CreateHideNavigationToolbarExpert;
// Editor tab control
FHotTrack := True;
// Toolbar settings
FToolBarVisible := True;
FToolBarAlign := alTop;
FToolBarActionsList := TStringList.Create;
InitializeGXToolBarDropdowns;
LoadSettings;
end;
destructor TEditorEnhancements.Destroy;
begin
{$IFOPT D+} SendDebug('Destroying Editor Enhancements'); {$ENDIF}
Remove;
FHideNavigationToolbarExpert := Nil;
FreeAndNil(FToolBarActionsList);
{$IFOPT D+} SendDebug('Editor Enhancements Destroyed'); {$ENDIF}
inherited Destroy;
end;
procedure TEditorEnhancements.EditorFormListener(
EventCode: TEditFormEventCode; EditFormProxy: IGxEditFormProxy);
begin
{$IFOPT D+} SendDebug('Got notification of editor form change'); {$ENDIF}
if EventCode = efAfterCreate then
AddToolBar;
end;
function TEditorEnhancements.GetToolBarActionsList: TStrings;
begin
Result := FToolBarActionsList;
end;
procedure TEditorEnhancements.Install;
begin
if not EditorEnhancementsPossible then
Exit;
AddToolBar;
GxEditorFormServices.AddListener(EditorFormListener);
end;
procedure TEditorEnhancements.LoadSettings;
var
Settings: TGExpertsSettings;
ExpSettings: TExpertSettings;
begin
Assert(ConfigInfo <> nil);
ExpSettings := nil;
Settings := TGExpertsSettings.Create;
try
LoadToolBarSettings(Settings);
ExpSettings := Settings.CreateExpertSettings(ConfigurationKey);
MiddleButtonClose := ExpSettings.ReadBool('MiddleButtonClose', MiddleButtonClose);
MultiLine := ExpSettings.ReadBool('MultiLine', MultiLine);
HotTrack := ExpSettings.ReadBool('HotTrack', HotTrack);
Buttons := ExpSettings.ReadBool('Buttons', Buttons);
ButtonsFlat := ExpSettings.ReadBool('ButtonsFlat', ButtonsFlat);
ToolBarVisible := ExpSettings.ReadBool('ToolBarVisible', ToolBarVisible);
HideNavbar := ExpSettings.ReadBool('HideNavbar', HideNavbar);
FToolBarAlign := TAlign(ExpSettings.ReadInteger('ToolBarAlign', Ord(ToolBarAlign)));
Assert(FToolBarAlign in [Low(TAlign)..High(TAlign)]);
finally
FreeAndNil(ExpSettings);
FreeAndNil(Settings);
end;
end;
procedure TEditorEnhancements.LoadToolBarSettings(const Settings: TGExpertsSettings);
const
// Do not localize default action names.
DefaultToolBarActions: array[0..4] of string =
('EditCutCommand', 'EditCopyCommand', 'EditPasteCommand', 'EditUndoCommand',
'EditRedoCommand');
var
i: Integer;
ActionData: string;
ToolBarButtonCount: Integer;
begin
ToolBarButtonCount := Settings.ReadInteger(ToolBarActionsKey, ToolBarActionsCountValue, 0);
for i := 0 to ToolBarButtonCount-1 do
begin
ActionData := Settings.ReadString(ToolBarActionsKey,
Format('%s%d', [ToolBarActionsActionPrefixValue, i]), SeparatorMenuItemString);
// Close just causes AVs, so we don't allow it
if not StrContains('FileClose', ActionData) then
FToolBarActionsList.Add(ActionData);
end;
if (ToolBarButtonCount = 0) and (not IsStandAlone) then
begin
for i := Low(DefaultToolBarActions) to High(DefaultToolBarActions) do
begin
{$IFOPT D+}
Assert(Assigned(GxActionBroker.FindAction(DefaultToolBarActions[i])),
'Could not locate default IDE action named ' + DefaultToolBarActions[i]);
{$ENDIF D+}
FToolBarActionsList.Add(DefaultToolBarActions[i]);
end;
SaveToolBarSettings(Settings);
end;
end;
procedure TEditorEnhancements.Notification(Component: TComponent; Operation: TOperation);
var
i: Integer;
begin
if Operation = opRemove then
begin
Assert(Assigned(FToolBarList));
i := FToolBarList.IndexOf(Component);
if i >= 0 then
FToolBarList.Delete(i);
end;
inherited Notification(Component, Operation);
end;
procedure TEditorEnhancements.Remove;
begin
if not EditorEnhancementsPossible then
Exit;
GxEditorFormServices.RemoveListener(EditorFormListener);
RemoveToolBar;
end;
procedure TEditorEnhancements.RemoveToolBar;
var
GExpertsToolBar: TGXToolBar;
begin
if not Assigned(FToolBarList) then
Exit;
{$IFOPT D+} SendDebug(Format('Editor Enhancements: Removing %d toolbar(s)', [FToolBarList.Count])); {$ENDIF}
// Note: Since we used FreeNotification on the toolbar
// to instruct it to notify ourselves of its very own
// deletion, GExpertsToolBar.Free will essentially
// call back into Notifcation where the toolbar is
// removed from the FToolBarList (.Delete).
// Hence the slightly weird structure of this loop.
while FToolBarList.Count > 0 do
begin
GExpertsToolBar := FToolBarList.Items[0];
FreeAndNil(GExpertsToolBar);
{$IFOPT D+} SendDebug('Editor Enhancements: Successfully freed a toolbar'); {$ENDIF}
end;
{$IFOPT D+} SendDebug('Freeing toolbar list'); {$ENDIF}
FreeAndNil(FToolBarList);
end;
procedure TEditorEnhancements.SaveSettings;
var
Settings: TGExpertsSettings;
ExpSettings: TExpertSettings;
begin
ExpSettings := nil;
Settings := TGExpertsSettings.Create;
try
ExpSettings := Settings.CreateExpertSettings(ConfigurationKey);
SaveToolBarSettings(Settings);
ExpSettings.WriteBool('MiddleButtonClose', MiddleButtonClose);
ExpSettings.WriteBool('MultiLine', MultiLine);
ExpSettings.WriteBool('HotTrack', HotTrack);
ExpSettings.WriteBool('Buttons', Buttons);
ExpSettings.WriteBool('ButtonsFlat', ButtonsFlat);
ExpSettings.WriteBool('ToolBarVisible', ToolBarVisible);
ExpSettings.WriteBool('HideNavbar', HideNavbar);
ExpSettings.WriteInteger('ToolBarAlign', Ord(ToolBarAlign));
finally
FreeAndNil(ExpSettings);
FreeAndNil(Settings);
end;
end;
procedure TEditorEnhancements.SaveToolBarSettings(const Settings: TGExpertsSettings);
var
i: Integer;
begin
Assert(Assigned(Settings));
Assert(Assigned(FToolBarActionsList));
Settings.WriteInteger(ToolBarActionsKey, ToolBarActionsCountValue, FToolBarActionsList.Count);
for i := 0 to FToolBarActionsList.Count - 1 do
Settings.WriteString(ToolBarActionsKey,
Format('%s%d', [ToolBarActionsActionPrefixValue, i]), FToolBarActionsList[i]);
end;
procedure TEditorEnhancements.SetEnabled(const Value: Boolean);
begin
if FEnabled = Value then
Exit;
FEnabled := Value;
if FEnabled then
Install
else
Remove;
end;
procedure TEditorEnhancements.SetHideNavbar(const _Value: Boolean);
begin
FHideNavbar := _Value;
FHideNavigationToolbarExpert.SetVisible(not FHideNavbar);
end;
procedure TEditorEnhancements.SetToolBarActionsList(const Value: TStrings);
begin
Assert(Assigned(FToolBarActionsList));
if Assigned(Value) then
FToolBarActionsList.Assign(Value)
else
FToolBarActionsList.Clear;
end;
function TEditorEnhancements.ShowConfigurationDialog(ActiveSheet: TConfigurationSheet): TModalResult;
var
Dlg: TfmConfiguration;
CurrentTabSheet: TTabSheet;
i: Integer;
begin
Dlg := TfmConfiguration.Create(nil);
try
Assert(Ord(High(TConfigurationSheet)) = 1);
case ActiveSheet of
cfgEditor: Dlg.pcConfig.ActivePage := Dlg.tshEditor;
end;
// Hide non-essential tab sheets.
for i := 0 to Dlg.pcConfig.PageCount - 1 do
begin
CurrentTabSheet := Dlg.pcConfig.Pages[i];
CurrentTabSheet.TabVisible := (CurrentTabSheet = Dlg.tshEditor);
end;
{ TODO 4 -oAnyone -cIssue:
This is horribly convoluted. From TEditorEnhancements we call that
dialog which, if mrOk, sets properties in TEditorEnhancements which
in turn will set properties on the toolbar and elsewhere.
Note that amazingly ShowConfigurationDialog here only ever is triggered
by the toolbar and by the editor local context menu appendix.
Probably ShowConfigurationDialog should be a member of, say GX_Toolbar?}
Result := Dlg.ShowModal;
finally
FreeAndNil(Dlg);
end;
end;
function TEditorEnhancements.ShowEditorConfigurationDialog: TModalResult;
begin
Result := ShowConfigurationDialog(cfgEditor);
end;
function TEditorEnhancements.ShowToolBarConfigurationDialog: TModalResult;
var
Dialog: TfmToolbarConfig;
begin
Dialog := TfmToolbarConfig.Create(nil);
try
Dialog.ToolBarActions := FToolBarActionsList;
Result := Dialog.ShowModal;
if Result = mrOk then
FToolBarActionsList.Assign(Dialog.ToolBarActions);
finally
FreeAndNil(Dialog);
end;
if Result = mrOk then
begin
SaveSettings;
ApplyToolBarSettings;
end;
end;
// ****************************************************************************
var
PrivateEditorEnhancements: TEditorEnhancements;
CanCreate: Boolean = True;
function EditorEnhancements: TEditorEnhancements;
begin
Assert(CanCreate, 'CanCreate must be true in EditorEnhancements');
if PrivateEditorEnhancements = nil then
PrivateEditorEnhancements := TEditorEnhancements.Create(nil);
Result := PrivateEditorEnhancements;
end;
procedure FreeEditorEnhancements;
begin
{$IFOPT D+} SendDebug('FreeEditorEnhancements CanCreate: ' + BooleanText(CanCreate)); {$ENDIF}
CanCreate := False;
FreeAndNil(PrivateEditorEnhancements);
end;
initialization
CanCreate := True;
finalization
FreeEditorEnhancements;
end.
|
// >< [&roel] I've add a new function Dec. 13th.
unit PidlUtils;
interface
uses
Windows, ShlObj, ActiveX, SysUtils;
//
// FUNCTIONS THAT DEAL WITH PIDLs
//
//Gets the next PIDL in the list
function Next( Pidl : PItemIDList ) : PItemIDList;
// Gets the size of the PIDL
function GetSize( Pidl : PItemIDList ): UINT;
//Allocates a PIDL
function Create( Size : UINT ) : PItemIDList;
//Concatenates two PIDLs
function ConcatPidls( Pidl1, Pidl2 : PItemIDList ) : PItemIDList;
//Copies the ITEMID
function CopyITEMID( Malloc : IMalloc; lpi : PItemIDList ) : PItemIDList;
//Gets the friendly name for the folder
function GetName ( lpsf : IShellFolder; lpi : PItemIDList; Flags : DWORD ) : pchar;
//Gets the Fully qualified Pidls for the folder
function GetFullyQualPidl( ShellFolder : IShellFolder; lpi : PItemIDList ) : PItemIDList;
function GetShellFolder( aPidl : PItemIDList ) : IShellFolder;
function GetPidl( aShellFolder : IShellFolder ) : PItemIDList;
function GetFileNamePidl( aFileName : string ) : PItemIDList;
procedure ReleasePidl( aPidl : PItemIDList );
function EqualPidl( Pidl1, Pidl2 : PItemIDList ) : boolean;
function RelativePidl( aPidl : PItemIDList ) : PItemIDList;
function GetShellFolderByPath( path : string ) : IShellFolder;
implementation
uses
ShellGUID, MiscUtils;
function Next( Pidl : PItemIDList ) : PItemIDList;
begin
Result := PItemIDList( pchar(Pidl) + Pidl^.mkID.cb );
end;
function GetSize( Pidl : PItemIDList ): UINT;
begin
Result := 0;
if Pidl <> nil
then
begin
Result := sizeof( Pidl^.mkID.cb );
while Pidl^.mkID.cb > 0 do
begin
Result := Result + Pidl^.mkID.cb;
Pidl := Next( Pidl );
end
end;
end;
function Create( Size : UINT ) : PItemIDList;
var
Malloc : IMalloc;
hr : HResult;
begin
Result := nil;
hr := SHGetMalloc( Malloc );
if hr = NO_ERROR
then
begin
Result := PItemIDList( Malloc.Alloc( Size ));
if Result <> nil
then fillchar( Result^, 0, Size );
Malloc := nil;
end;
end;
function ConcatPidls( Pidl1, Pidl2 : PItemIDList ) : PItemIDList;
var
cb1 : UINT;
cb2 : UINT;
begin
if Pidl1 <> nil
then cb1 := GetSize( Pidl1 ) - sizeof( Pidl1^.mkID.cb )
else cb1 := 0;
cb2 := GetSize( pidl2 );
Result := Create( cb1 + cb2 );
if Result <> nil
then
begin
if Pidl1 <> nil
then Move( Pidl1^, Result^, cb1 );
Move( Pidl2^, (pchar(Result) + cb1)^, cb2 );
end;
end;
function CopyITEMID(Malloc : IMalloc; lpi : PItemIDList ) : PItemIDList;
begin
Result := PItemIDList( Malloc.Alloc( lpi^.mkID.cb + sizeof(lpi^.mkID.cb )));
CopyMemory( Result, lpi, lpi^.mkID.cb + sizeof(lpi^.mkID.cb ));
end;
function GetName( lpsf : IShellFolder; lpi : PItemIDList; Flags : DWORD ) : pchar;
var
str : TSTRRET;
size : cardinal;
begin
Result := nil;
if lpsf.GetDisplayNameOf( lpi, Flags, str ) = NO_ERROR
then
case str.uType of
STRRET_WSTR :
begin
size := WideCharToMultiByte(
CP_ACP, // code page
0, // dwFlags
str.pOleStr, // lpWideCharStr
-1, // cchWideCharStr
nil, // lpMultiByteStr
0, // cchMultiByte
nil, // lpDefaultChar
nil); // lpUsedDefaultChar
if Size > 0
then
begin
getmem(Result, Size);
WideCharToMultiByte(CP_ACP, 0, str.pOleStr, -1, Result, Size - 1, nil, nil);
end;
end;
STRRET_OFFSET : Result := StrNew( pchar(lpi) + str.uOffset );
STRRET_CSTR : Result := StrNew(str.pStr);
end;
end;
function GetFullyQualPidl( ShellFolder : IShellFolder; lpi : PItemIDList ) : PItemIDList;
var
Buff : pchar;
OleChar : POleStr;
Desktop : IShellFolder;
Eaten, Attribs : ULONG;
begin
Buff := GetName( ShellFolder, lpi, SHGDN_FORPARSING );
if Buff <> nil
then
begin
SHGetDesktopFolder( Desktop );
getmem( Buff, MAX_PATH );
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
pchar( Buff ),
-1,
OleChar,
sizeof( OleChar ));
Desktop.ParseDisplayName( THandle( nil ), nil, OleChar, Eaten, Result, Attribs );
Desktop := nil;
end
else Result := nil;
end;
function GetShellFolder( aPidl : PItemIDList ) : IShellFolder;
function Desktop : boolean;
begin
Result := aPidl^.mkID.cb = 0;
end;
var
SH : IShellFolder;
begin
if SHGetDesktopFolder( SH )= NO_ERROR
then
if aPidl <> nil
then
if not Desktop
then
begin
Result := nil;
SH.BindToObject( aPidl, nil, IID_IShellFolder, Result );
SH := nil;
end
else Result := SH
else Result := nil
else Result := nil;
end;
function GetPidl( aShellFolder : IShellFolder ) : PItemIDList;
var
unk : ULONG;
begin
aShellFolder.GetAttributesOf( 1, Result, unk );
end;
function GetFileNamePidl( aFileName : string ) : PItemIDList;
var
OleChar : POleStr;
Desktop : IShellFolder;
Eaten, Attribs : ULONG;
hr : HResult;
begin
if pchar( aFileName ) <> nil
then
begin
SHGetDesktopFolder( Desktop );
getmem( OleChar, MAX_PATH );
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
pchar( aFileName ),
-1,
OleChar,
sizeof( OleChar ));
hr := Desktop.ParseDisplayName( THandle( nil ), nil, OleChar, Eaten, Result, Attribs );
if hr <> NO_ERROR
then Result := nil;
Desktop := nil;
end
else Result := nil;
end;
procedure ReleasePidl( aPidl : PItemIDList );
var
Malloc : IMalloc;
begin
if CoGetMalloc(1, Malloc ) = NO_ERROR
then
begin
Malloc.Free( aPidl );
Malloc := nil;
end;
end;
function EqualPidl( Pidl1, Pidl2 : PItemIDList ) : boolean;
var
Count1 : integer;
Count2 : integer;
begin
try
Count1 := GetSize( Pidl1 );
Count2 := GetSize( Pidl2 );
if Count1 = Count2
then Result := BufferEqual( Pidl1, Pidl2, Count1 )
else Result := false;
except
Result := false;
end;
end;
function RelativePidl( aPidl : PItemIDList ) : PItemIDList;
var
Malloc : IMalloc;
begin
if aPidl <> nil
then
begin
Result := aPidl;
aPidl := Next( aPidl );
while aPidl.mkID.cb > 0 do
begin
Result := aPidl;
aPidl := Next( aPidl );
end;
CoGetMalloc( 1, Malloc );
Result := CopyITEMID( Malloc, Result );
Malloc := nil;
end
else Result := nil;
end;
function GetShellFolderByPath( path : string ) : IShellFolder;
var
Pidl : PItemIDList;
begin
Pidl := GetFileNamePidl( path );
if Pidl <> nil
then
begin
Result := GetShellFolder( Pidl );
ReleasePidl( Pidl );
end
else Result := nil;
end;
end.
|
program carre_magique;
uses crt;
{ALGO carre magique
BUT faire un carre magique de taille impaire
SORTIE carre magique
CONST
MAX=7
procedure affichage(carre:tableau)
BUT afficher le tableau
VAR
i,j:ENTIER
DEBUT
POUR i DE 1 A MAX FAIRE
POUR j DE 1 A MAX FAIRE
SI carre[i,j]<10 ALORS
ECRIRE"0"&carre[i,j]&" "
SINON
ECRIRE carre[i,j]" "
FINSI
FINPOUR
FINPOUR
FINPROCEDURE
fonction initTab(carre:tableau):tableau
BUT initialiser le tableau avec des 0
VAR
i,j:ENTIER
DEBUT
POUR i DE 1 A MAX FAIRE
POUR j DE 1 A MAX FAIRE
carre[i,j]<-0
FINPOUR
FINPOUR
i<-(MAX div 2)
j<-(MAX div 2)+1
carre[i,j]<-1
initTab<-carre
FINFONCTION
fonction remplirTab(carre:tableau):tableau;
BUT remplir le carre magique
VAR
i,j,compteur:ENTIER
DEBUT
i<-(MAX div 2)
j<-(MAX div 2)+1
POUR compteur DE 2 A (MAX*MAX) FAIRE
SI j+1>MAX ALORS
j<-0
FINSI
SI i-1=0 ALORS
i<-MAX+1
FINSI
i<-i-1
j<-j+1
SI carre[i,j]<>0 ALORS
TANTQUE carre[i,j]<>0 FAIRE
SI j-1=0 ALORS
j<-MAX+1
FINSI
SI i-1=0 ALORS
i<-MAX+1
FINSI
i<-i-1
j<-j-1
FINTANTQUE
FINSI
carre[i,j]<-compteur
FINPOUR
remplirTab<-carre
FINFONCTION
VAR
carre:TABLEAU[1..MAX,1..MAX] D'ENTIER
DEBUT
carre<-initTab(carre)
carre<-remplirTab(carre)
affichage(carre)
FIN
}
CONST
MAX=5;{Taille du carre magique}
TYPE
Tab2dim=array[1..MAX,1..MAX] of integer;{creation du type Tab2dim utiliser pour pouvoir ce servir du Tableau carre dans les fonctions et procedure}
procedure affichage(carre:Tab2dim);{procedure permettant d'afficher le Tableau (ici la carre magique}
VAR
i,j:integer;{variables locales de la fonction permettant de parcourir le Tableau}
BEGIN
FOR i:=1 to MAX do
begin
for j:=1 to MAX do
begin
if carre[i,j]<10 then{Commande pour afficher un 0 devant la valeur si elle est inferieur a 10 afin de rendre le resltat plus lisible}
begin
write('0',carre[i,j],' ');
end
else
begin
write(carre[i,j],' ');{ecrire chaque ligne du Tableau}
end;
end;
writeln();{saut de ligne a la fin de chaque ligne du Tableau}
end;
END;
function initTab(carre:Tab2dim):Tab2dim;{fonction servant a initialiser le Tableau avec des 0}
VAR
i,j:integer;{variables locales de la fonction permettant de parcourir le Tableau}
BEGIN
FOR i:=1 to MAX DO
begin
FOR j:=1 to MAX DO
begin
carre[i,j]:=0;{commande pour mettre un 0 dans chaque case du Tableau}
end;
end;
i:=(MAX div 2);{coordonnee du 1}
j:=(MAX div 2)+1;{coordonnee du 1}
carre[i,j]:=1;{positioinnement du 1}
initTab:=carre;
END;
function remplirTab(carre:Tab2dim):Tab2dim;{fonction servant a remplir le Tableau}
VAR
i,j,compteur:integer;{variables locales de la fonction permettant de parcourir le Tableau compteur represente le chiffre qui sera placer dans la case}
BEGIN
i:=(MAX div 2);{coordonnee du 1}
j:=(MAX div 2)+1;{coordonnee du 1}
FOR compteur:=2 TO (MAX*MAX)DO
begin
IF j+1>MAX then{verification de i et j si jamais j est hors du Tableau il revient a 0 et si i sort du Tableau il revient a MAX+1 (+1 car il faut aussi remplir la derniere ligne)}
begin
j:=0;
end;
IF i-1=0 then
begin
i:=MAX+1;
end;
i:=i-1;{les coordonnee prennent leurs nouvelles valeurs se qui correspond aux deplacement}
j:=j+1;
IF carre[i,j]<>0 THEN{verification de l'interrieur de la case si il y a qqch alors...}
begin
WHILE carre[i,j]<>0 DO{... jusqu'a ce que la case soit vide faire Nord Ouest}
begin
IF j-1=0 then{verification de i et j si jamais j est hors du Tableau il revient a MAX+1 et si i sort du Tableau il revient a MAX+1 (+1 car il faut aussi remplir la derniere ligne et la derniere colonne)}
begin
j:=MAX+1;
end;
IF i-1=0 then
begin
i:=MAX+1;
end;
i:=i-1;{les coordonnee prennent leurs nouvelles valeurs}
j:=j-1;
end;
end;
carre[i,j]:=compteur;{remplissage du Tableau}
end;
remplirTab:=carre;
END;
VAR
carre:array[1..MAX,1..MAX] of integer;{Tableau correspondant au carre magique}
BEGIN
clrscr;{nettoyage d'ecran}
writeln('Programme du carre magique :');{nom du programme}
writeln('Appuyez sur entrer pour lancer le programme');{invitation a lancer le programme}
readln;
writeln('Voici un carre magique de ',MAX,' par ',MAX,' :');
writeln();
carre:=initTab(carre);{initialisation du carre avec des 0}
carre:=remplirTab(carre);{remplissage du carre}
affichage(carre);{affichage du carre}
writeln();
writeln('Appuiyez sur entrer pour quitter le programme.');
readln;
END. |
unit K363564248;
{* [Requestlink:363564248] }
// Модуль: "w:\archi\source\projects\Archi\Tests\K363564248.pas"
// Стереотип: "TestCase"
// Элемент модели: "K363564248" MUID: (4FAE352C0181)
// Имя типа: "TK363564248"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3IntfUses
{$If NOT Defined(NoScripts)}
, ArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
;
type
TK363564248 = class({$If NOT Defined(NoScripts)}
TArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
)
{* [Requestlink:363564248] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK363564248
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *4FAE352C0181impl_uses*
//#UC END# *4FAE352C0181impl_uses*
;
{$If NOT Defined(NoScripts)}
function TK363564248.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Text2TableTests';
end;//TK363564248.GetFolder
function TK363564248.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4FAE352C0181';
end;//TK363564248.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK363564248.Suite);
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
type
{ TMy }
TMy = class(TCustomControl)
private
FIsFocused: boolean;
FShowCaret: boolean;
FTimer: TTimer;
procedure TimerTick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
protected
procedure Paint; override;
procedure DoEnter; override;
procedure DoExit; override;
procedure Click; override;
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var
Ctl: TMy;
begin
Ctl:= TMy.Create(Self);
Ctl.Parent:= Self;
Ctl.Align:= alClient;
Ctl.Show;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
end;
{ TMy }
procedure TMy.TimerTick(Sender: TObject);
begin
FShowCaret:= not FShowCaret;
Invalidate;
end;
constructor TMy.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
TabStop:= true;
FIsFocused:= false;
FShowCaret:= true;
FTimer:= TTimer.Create(Self);
FTimer.Interval:= 500;
FTimer.OnTimer:= @TimerTick;
end;
procedure TMy.Paint;
var
C: TCanvas;
begin
C:= Canvas;
C.Brush.Color:= clCream;
C.FillRect(ClientRect);
C.Pen.Color:= clGray;
C.Rectangle(3, 3, ClientWidth-3, ClientHeight-3);
if not FIsFocused then
begin
C.Font.Name:= 'dafault';
C.Font.Size:= 12;
C.Font.Color:= clBlack;
C.TextOut(4, 4, '(not focused)')
end
else
if FShowCaret then
begin
C.Brush.Color:= clRed;
C.Fillrect(10, 6, 14, 30);
end;
end;
procedure TMy.DoEnter;
begin
inherited DoEnter;
FIsFocused:= true;
Invalidate;
end;
procedure TMy.DoExit;
begin
inherited DoExit;
FIsFocused:= false;
Invalidate;
end;
procedure TMy.Click;
begin
inherited Click;
if not FIsFocused then
begin
FIsFocused:= true;
Invalidate;
end;
end;
end.
|
unit calc_utils;
interface
uses Windows, SysUtils, graphics, Ap, mlpbase, mlptrain;
procedure NewEmptyMatrix(aWidth, aHeight: Integer; out lXY: TReal2DArray);
procedure ConstructMatrixFromLine(lX: TReal1DArray; aSubLineWidth, aStep, aCount: Integer; out lXY: TReal2DArray);
procedure CalcNeuroMatrix(aClassificator: boolean; aLevelCount: byte; lInCount, lOutCount: Integer; lXY: TReal2DArray;
out lNetwork: MultiLayerPerceptron);
procedure GetSubLine(aXSrc: TReal1DArray; aPosition, aSubLineWidth: Integer; var aXDest: TReal1DArray);
procedure PutImageToArrayLine(aImageIdx, aCharIdx: Integer; aCanvas: TCanvas; aWidth, aHeight: Integer;
var lXY: TReal2DArray);
procedure Get1DArrayFromImage(aCanvas: TCanvas; aWidth, aHeight: Integer; var lX: TReal1DArray);
function NeuroRegression(var lNetwork: MultiLayerPerceptron; lX: TReal1DArray; var lY: TReal1DArray): AlglibFloat;
implementation
uses Math;
procedure NewEmptyMatrix(aWidth, aHeight: Integer; out lXY: TReal2DArray);
var
x, y: Integer;
begin
SetLength(lXY, aHeight, aWidth);
for y := Low(lXY) to High(lXY) do
for x := Low(lXY[0]) to High(lXY[0]) do
lXY[y, x] := 0;
end;
procedure ConstructMatrixFromLine(lX: TReal1DArray; aSubLineWidth, aStep, aCount: Integer; out lXY: TReal2DArray);
var
x, y: Integer;
zYCount: Integer;
begin
//zYCount := Length(lX) - aSubLineWidth;
zYCount := aCount;
SetLength(lXY, zYCount, aSubLineWidth + 1);
y := 0;
while y < zYCount do
begin
for x := 0 to aSubLineWidth do
lXY[y, x] := lX[y + x];
inc(y, aStep);
end;
end;
procedure CalcNeuroMatrix(aClassificator: boolean; aLevelCount: byte; lInCount, lOutCount: Integer; lXY: TReal2DArray;
out lNetwork: MultiLayerPerceptron);
var
lMaxIts: Integer;
lMaxStep: Double;
lRestarts: Integer;
lDecay: Double;
lPoints: Integer;
lInfo: Integer;
lReport: MLPReport;
begin
Randomize;
lMaxIts := 500; // максимальное количество итераций обучения
lMaxStep := 0.001; // минимальный достигаемый шаг (ошибка)
lRestarts := 50; // количество рестартов обучения с рандомизацией весов
lDecay := 0.001; // точность обучения. Чем меньше - тем точнее
lPoints := Length(lXY); // количество обучающих выборок (в нашем лучае можно и поменьше)
// здесь можно использовать любую из функций MLPCreate
case aClassificator of
false:
case aLevelCount of
1:
MLPCreate0(lInCount, lOutCount, {0, 1,} lNetwork);
2:
MLPCreate1(lInCount, lInCount, lOutCount, {0, 1,} lNetwork);
else
MLPCreate2(lInCount, lInCount, lInCount, lOutCount, {0, 1,} lNetwork);
end;
true:
case aLevelCount of
1:
MLPCreateC0(lInCount, lOutCount, { 0, 50, } lNetwork);
2:
MLPCreateC1(lInCount, lInCount, lOutCount, { 0, 50, } lNetwork);
else
MLPCreateC2(lInCount, lInCount, lInCount, lOutCount, { 0, 50, } lNetwork);
end;
end;
// один из методов обучения. Можно использовать любой другой
//MLPTrainLBFGS_MT_Mod(lNetwork, lXY, lPoints, lRestarts, lMaxStep, 10, lMaxIts, lInfo, lReport);
MLPTrainLBFGS_MT(lNetwork, lXY, lPoints, lDecay, lRestarts, lMaxStep, lMaxIts, lInfo, lReport, 0);
//MLPTrainMonteCarlo(lNetwork, lXY, lPoints, 10, lRestarts, 0, lMaxIts, lInfo, lReport);
//MLPTrainLM(lNetwork, lXY, lPoints, lDecay, lRestarts, lInfo, lReport);
//MLPTrainES(lNetwork, lXY, lPoints, lXY, lPoints, lDecay, lRestarts, lInfo, lReport);
end;
// aSubLineWidth - длина строки с конечным обучающим значением
procedure GetSubLine(aXSrc: TReal1DArray; aPosition, aSubLineWidth: Integer; var aXDest: TReal1DArray); inline;
var
i: Integer;
begin
for i := 0 to aSubLineWidth - 1 do
aXDest[i] := aXSrc[i + aPosition];
end;
function NeuroRegression(var lNetwork: MultiLayerPerceptron; lX: TReal1DArray; var lY: TReal1DArray): AlglibFloat;
begin
MLPProcess(lNetwork, lX, lY);
Result := lY[0];
end;
function RgbToGray(RGBColor: TColor): AlglibFloat;
begin
Result := ((0.299 * GetRValue(RGBColor)) +
(0.587 * GetGValue(RGBColor)) +
(0.114 * GetBValue(RGBColor ))) * (1 / 255);
end;
procedure PutImageToArrayLine(aImageIdx, aCharIdx: Integer; aCanvas: TCanvas; aWidth, aHeight: Integer;
var lXY: TReal2DArray);
var
x, y, i: Integer;
begin
aCanvas.Lock;
try
i := 0;
for y := 0 to aHeight - 1 do
for x := 0 to aWidth - 1 do
begin
lXY[aImageIdx, i] := RgbToGray(aCanvas.Pixels[x, y]);
inc(i);
end;
// не указываем зарезервированные параметры
if (aCharIdx <> -1) then
lXY[aImageIdx, aWidth * aHeight] := aCharIdx;
finally
aCanvas.Unlock;
end;
end;
procedure Get1DArrayFromImage(aCanvas: TCanvas; aWidth, aHeight: Integer; var lX: TReal1DArray);
var
x, y, i: Integer;
begin
aCanvas.Lock;
try
i := 0;
for y := 0 to aHeight - 1 do
for x := 0 to aWidth - 1 do
begin
lX[i] := RgbToGray(aCanvas.Pixels[x, y]);
inc(i);
end;
finally
aCanvas.Unlock;
end;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_Vector2D
* Implements a 2D vector class
***********************************************************************************************************************
}
{$IFDEF OXYGENE}
namespace TERRA;
{$ELSE}
Unit TERRA_Vector2D;
{$I terra.inc}
{$ENDIF}
Interface
Uses TERRA_Vector3D, TERRA_Math;
Type
{$IFDEF OXYGENE}
Vector2D = Class
{$ELSE}
PVector2D=^Vector2D;
Vector2D=Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF}
{$ENDIF}
X,Y:Single;
{$IFDEF OXYGENE}
Constructor Create(X,Y:Single);
{$ENDIF}
Function Equals(Const B:Vector2D):Boolean;
Procedure Rotate(Const Angle:Single); Overload;
Procedure Rotate(Const Angle:Single; Const Center:Vector2D); Overload;
Procedure Add(Const B:Vector2D);
Procedure Subtract(Const B:Vector2D);
Procedure Scale(Const S:Single);Overload;
Procedure Scale(Const B:Vector2D);Overload;
Procedure Project(Const V:Vector2D);
Procedure Normalize;
Function Length:Single;
Function Distance(Const N:Vector2D):Single;
Function Dot(B:Vector2D):Single;
{$IFDEF BENCHMARK}
Function LengthSSE:Single;
Function DistanceSSE(Const N:Vector2D):Single;
{$ENDIF}
End;
Function VectorCreate2D(Const X,Y:Single):Vector2D;
Function VectorCross2D(Const A,B:Vector2D):Single;
Function VectorAdd2D(Const A,B:Vector2D):Vector2D;
Function VectorSubtract2D(Const A,B:Vector2D):Vector2D;
Function VectorAngle3D(Const A,B:Vector3D):Single;
Function VectorAngle2D(Const A,B:Vector2D):Single;
Implementation
{$IFDEF NEON_FPU}Uses TERRA_NEON;{$ENDIF}
Function VectorCreate2D(Const X,Y:Single):Vector2D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result.X := X;
Result.Y := Y;
End;
Function VectorCross2D(Const A,B:Vector2D):Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result := (A.X * B.Y) - (A.Y * B.X);
End;
Function Vector2D.Equals(Const B:Vector2D):Boolean; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result := (Self.X = B.X) And (Self.Y = B.Y);
End;
Function VectorAdd2D(Const A,B:Vector2D):Vector2D;
Begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
End;
Function VectorSubtract2D(Const A,B:Vector2D):Vector2D;
Begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
End;
Procedure Vector2D.Project(Const V:Vector2D);
Var
thisDotV:Single;
Begin
thisDotV := Self.Dot(V);
Self.X := V.X * thisDotV;
Self.Y := V.Y * thisDotV;
End;
Procedure Vector2D.Rotate(Const Angle:Single; Const Center:Vector2D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
Self.Subtract(Center);
Self.Rotate(Angle);
Self.Add(Center);
End;
Procedure Vector2D.Rotate(Const Angle:Single); {$IFDEF FPC} Inline;{$ENDIF}
Var
SX,SY:Single;
Sine,Cosine:Single;
Begin
SX := Self.X;
SY := Self.Y;
Sine := Sin(Angle);
Cosine := Cos(Angle);
X := (Sx * Cosine) - (Sy * Sine);
Y := (Sx * Sine) + (Sy * Cosine);
End;
Procedure Vector2D.Add(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X + B.X;
Y := Y + B.Y;
End;
{Procedure Vector2D.AddSSE(Const B:Vector2D);
Asm
movlps xmm0, [self] // xmm0 = (x,y)
movlps xmm1, [edx] // xmm1 = (b.x,b.y)
addps xmm0, xmm1
movlps [self], xmm0 // store result
End;
}
Procedure Vector2D.Subtract(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X - B.X;
Y := Y - B.Y;
End;
Procedure Vector2D.Scale(Const S:Single); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X * S;
Y := Y * S;
End;
Procedure Vector2D.Scale(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X * B.X;
Y := Y * B.Y;
End;
{$IFDEF SSE}
{$IFDEF BENCHMARK}
Function Vector2D.LengthSSE:Single;Register;
{$ELSE}
Function Vector2D.Length:Single;Register;
{$ENDIF}
Asm
movlps xmm0, [eax] // xmm0 = (x,y)
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y))
movaps xmm1, xmm0
shufps xmm1, xmm1, 85 // xmm1 = (sqr(y), sqr(y))
addps xmm0, xmm1 // add both
sqrtss xmm0, xmm0 // and finally, sqrt}
movss result, xmm0
End;
{$IFDEF BENCHMARK}
Function Vector2D.DistanceSSE(Const N:Vector2D):Single;Register;
{$ELSE}
Function Vector2D.Distance(Const N:Vector2D):Single;Register;
{$ENDIF}
Asm
movlps xmm0, [eax] // xmm0 = (x,y)
movlps xmm1, [edx] // xmm0 = (b.x,b.y)
subps xmm0, xmm1
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y))
movaps xmm1, xmm0
shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y))
addps xmm0, xmm1 // add both
sqrtss xmm1, xmm0 // and finally, sqrt
movss result, xmm1
End;
{$ENDIF}
{$IFDEF BENCHMARK} {$UNDEF SSE} {$ENDIF}
{$IFNDEF SSE}
Function Vector2D.Length:Single;
Begin
{$IFDEF OXYGENE}
Result := System.Math.Sqrt((X*X)+(Y*Y));
{$ELSE}
Result := Sqrt(Sqr(X)+Sqr(Y));
{$ENDIF}
End;
Function Vector2D.Distance(Const N:Vector2D):Single;
Var
A,B:Single;
Begin
A := Self.X - N.X;
B := Self.Y - N.Y;
{$IFDEF OXYGENE}
Result := System.Math.Sqrt((A*A)+(B*B));
{$ELSE}
Result := Sqrt(Sqr(A)+Sqr(B));
{$ENDIF}
End;
{$ENDIF}
Procedure Vector2D.Normalize;
Var
K:Single;
Begin
K := Length;
If (K<=1.0) Then
Exit;
X := X / K;
Y := Y / K;
End;
Function Vector2D.Dot(B:Vector2D):Single;
Begin
{$IFDEF NEON_FPU}
Result := dot2_neon_hfp(@Self,@B);
{$ELSE}
Result := (Self.X * B.X) + (Self.Y * B.Y);
{$ENDIF}
End;
{$IFDEF OXYGENE}
Constructor Vector2D.Create(X,Y:Single);
Begin
Self.X := X;
Self.Y := Y;
End;
{$ENDIF}
Function VectorAngle2D(Const A,B:Vector2D):Single;
Var
XDiff, YDiff: Single;
fpAngle: Single;
N:Vector2D;
begin
N := B;
N.Subtract(A);
N.Normalize();
fpAngle := Atan2(-N.Y, N.X);
Result := fpAngle + 90*RAD;
End;
Function VectorAngle3D(Const A,B:Vector3D):Single;
Var
PA, PB:Vector2D;
Begin
PA := VectorCreate2D(A.X, A.Z);
PB := VectorCreate2D(B.X, B.Z);
Result := VectorAngle2D(PA, PB);
End;
End. |
unit InfoUTLFTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoUTLFRecord = record
PTranID: String[5];
PModCount: Integer;
PLender: String[4];
PName: String[30];
PKeyDate: String[10];
PRecordType: String[1];
PEntryText: String[4];
PBatchDate: String[10];
PDocumentID: String[6];
PMailDate: String[10];
PLoanNumber: String[18];
PYear: String[2];
PDescription: String[12];
PVIN: String[17];
PAction: String[1];
PCompanyAgent: String[20];
PPolicy: String[15];
PEffDate: String[10];
PExpDate: String[10];
PUserID: String[6];
PComment: String[30];
PAddress: String[30];
PCompanyAddress: String[10];
PCompanyName: String[10];
End;
TInfoUTLFClass2 = class
public
PTranID: String[5];
PModCount: Integer;
PLender: String[4];
PName: String[30];
PKeyDate: String[10];
PRecordType: String[1];
PEntryText: String[4];
PBatchDate: String[10];
PDocumentID: String[6];
PMailDate: String[10];
PLoanNumber: String[18];
PYear: String[2];
PDescription: String[12];
PVIN: String[17];
PAction: String[1];
PCompanyAgent: String[20];
PPolicy: String[15];
PEffDate: String[10];
PExpDate: String[10];
PUserID: String[6];
PComment: String[30];
PAddress: String[30];
PCompanyAddress: String[10];
PCompanyName: String[10];
End;
// function CtoRInfoUTLF(AClass:TInfoUTLFClass):TInfoUTLFRecord;
// procedure RtoCInfoUTLF(ARecord:TInfoUTLFRecord;AClass:TInfoUTLFClass);
TInfoUTLFBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoUTLFRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoUTLF = (InfoUTLFPrimaryKey, InfoUTLFByName, InfoUTLFBatchDate, InfoUTLFSerial, InfoUTLFPolicy);
TInfoUTLFTable = class( TDBISAMTableAU )
private
FDFTranID: TStringField;
FDFModCount: TIntegerField;
FDFLender: TStringField;
FDFName: TStringField;
FDFKeyDate: TStringField;
FDFRecordType: TStringField;
FDFEntryText: TStringField;
FDFBatchDate: TStringField;
FDFDocumentID: TStringField;
FDFMailDate: TStringField;
FDFLoanNumber: TStringField;
FDFYear: TStringField;
FDFDescription: TStringField;
FDFVIN: TStringField;
FDFAction: TStringField;
FDFCompanyAgent: TStringField;
FDFPolicy: TStringField;
FDFEffDate: TStringField;
FDFExpDate: TStringField;
FDFUserID: TStringField;
FDFComment: TStringField;
FDFAddress: TStringField;
FDFCompanyAddress: TStringField;
FDFCompanyName: TStringField;
procedure SetPTranID(const Value: String);
function GetPTranID:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPKeyDate(const Value: String);
function GetPKeyDate:String;
procedure SetPRecordType(const Value: String);
function GetPRecordType:String;
procedure SetPEntryText(const Value: String);
function GetPEntryText:String;
procedure SetPBatchDate(const Value: String);
function GetPBatchDate:String;
procedure SetPDocumentID(const Value: String);
function GetPDocumentID:String;
procedure SetPMailDate(const Value: String);
function GetPMailDate:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPYear(const Value: String);
function GetPYear:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPVIN(const Value: String);
function GetPVIN:String;
procedure SetPAction(const Value: String);
function GetPAction:String;
procedure SetPCompanyAgent(const Value: String);
function GetPCompanyAgent:String;
procedure SetPPolicy(const Value: String);
function GetPPolicy:String;
procedure SetPEffDate(const Value: String);
function GetPEffDate:String;
procedure SetPExpDate(const Value: String);
function GetPExpDate:String;
procedure SetPUserID(const Value: String);
function GetPUserID:String;
procedure SetPComment(const Value: String);
function GetPComment:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCompanyAddress(const Value: String);
function GetPCompanyAddress:String;
procedure SetPCompanyName(const Value: String);
function GetPCompanyName:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoUTLF);
function GetEnumIndex: TEIInfoUTLF;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoUTLFRecord;
procedure StoreDataBuffer(ABuffer:TInfoUTLFRecord);
property DFTranID: TStringField read FDFTranID;
property DFModCount: TIntegerField read FDFModCount;
property DFLender: TStringField read FDFLender;
property DFName: TStringField read FDFName;
property DFKeyDate: TStringField read FDFKeyDate;
property DFRecordType: TStringField read FDFRecordType;
property DFEntryText: TStringField read FDFEntryText;
property DFBatchDate: TStringField read FDFBatchDate;
property DFDocumentID: TStringField read FDFDocumentID;
property DFMailDate: TStringField read FDFMailDate;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFYear: TStringField read FDFYear;
property DFDescription: TStringField read FDFDescription;
property DFVIN: TStringField read FDFVIN;
property DFAction: TStringField read FDFAction;
property DFCompanyAgent: TStringField read FDFCompanyAgent;
property DFPolicy: TStringField read FDFPolicy;
property DFEffDate: TStringField read FDFEffDate;
property DFExpDate: TStringField read FDFExpDate;
property DFUserID: TStringField read FDFUserID;
property DFComment: TStringField read FDFComment;
property DFAddress: TStringField read FDFAddress;
property DFCompanyAddress: TStringField read FDFCompanyAddress;
property DFCompanyName: TStringField read FDFCompanyName;
property PTranID: String read GetPTranID write SetPTranID;
property PModCount: Integer read GetPModCount write SetPModCount;
property PLender: String read GetPLender write SetPLender;
property PName: String read GetPName write SetPName;
property PKeyDate: String read GetPKeyDate write SetPKeyDate;
property PRecordType: String read GetPRecordType write SetPRecordType;
property PEntryText: String read GetPEntryText write SetPEntryText;
property PBatchDate: String read GetPBatchDate write SetPBatchDate;
property PDocumentID: String read GetPDocumentID write SetPDocumentID;
property PMailDate: String read GetPMailDate write SetPMailDate;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PYear: String read GetPYear write SetPYear;
property PDescription: String read GetPDescription write SetPDescription;
property PVIN: String read GetPVIN write SetPVIN;
property PAction: String read GetPAction write SetPAction;
property PCompanyAgent: String read GetPCompanyAgent write SetPCompanyAgent;
property PPolicy: String read GetPPolicy write SetPPolicy;
property PEffDate: String read GetPEffDate write SetPEffDate;
property PExpDate: String read GetPExpDate write SetPExpDate;
property PUserID: String read GetPUserID write SetPUserID;
property PComment: String read GetPComment write SetPComment;
property PAddress: String read GetPAddress write SetPAddress;
property PCompanyAddress: String read GetPCompanyAddress write SetPCompanyAddress;
property PCompanyName: String read GetPCompanyName write SetPCompanyName;
published
property Active write SetActive;
property EnumIndex: TEIInfoUTLF read GetEnumIndex write SetEnumIndex;
end; { TInfoUTLFTable }
TInfoUTLFQuery = class( TDBISAMQueryAU )
private
FDFTranID: TStringField;
FDFModCount: TIntegerField;
FDFLender: TStringField;
FDFName: TStringField;
FDFKeyDate: TStringField;
FDFRecordType: TStringField;
FDFEntryText: TStringField;
FDFBatchDate: TStringField;
FDFDocumentID: TStringField;
FDFMailDate: TStringField;
FDFLoanNumber: TStringField;
FDFYear: TStringField;
FDFDescription: TStringField;
FDFVIN: TStringField;
FDFAction: TStringField;
FDFCompanyAgent: TStringField;
FDFPolicy: TStringField;
FDFEffDate: TStringField;
FDFExpDate: TStringField;
FDFUserID: TStringField;
FDFComment: TStringField;
FDFAddress: TStringField;
FDFCompanyAddress: TStringField;
FDFCompanyName: TStringField;
procedure SetPTranID(const Value: String);
function GetPTranID:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPKeyDate(const Value: String);
function GetPKeyDate:String;
procedure SetPRecordType(const Value: String);
function GetPRecordType:String;
procedure SetPEntryText(const Value: String);
function GetPEntryText:String;
procedure SetPBatchDate(const Value: String);
function GetPBatchDate:String;
procedure SetPDocumentID(const Value: String);
function GetPDocumentID:String;
procedure SetPMailDate(const Value: String);
function GetPMailDate:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPYear(const Value: String);
function GetPYear:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPVIN(const Value: String);
function GetPVIN:String;
procedure SetPAction(const Value: String);
function GetPAction:String;
procedure SetPCompanyAgent(const Value: String);
function GetPCompanyAgent:String;
procedure SetPPolicy(const Value: String);
function GetPPolicy:String;
procedure SetPEffDate(const Value: String);
function GetPEffDate:String;
procedure SetPExpDate(const Value: String);
function GetPExpDate:String;
procedure SetPUserID(const Value: String);
function GetPUserID:String;
procedure SetPComment(const Value: String);
function GetPComment:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCompanyAddress(const Value: String);
function GetPCompanyAddress:String;
procedure SetPCompanyName(const Value: String);
function GetPCompanyName:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoUTLFRecord;
procedure StoreDataBuffer(ABuffer:TInfoUTLFRecord);
property DFTranID: TStringField read FDFTranID;
property DFModCount: TIntegerField read FDFModCount;
property DFLender: TStringField read FDFLender;
property DFName: TStringField read FDFName;
property DFKeyDate: TStringField read FDFKeyDate;
property DFRecordType: TStringField read FDFRecordType;
property DFEntryText: TStringField read FDFEntryText;
property DFBatchDate: TStringField read FDFBatchDate;
property DFDocumentID: TStringField read FDFDocumentID;
property DFMailDate: TStringField read FDFMailDate;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFYear: TStringField read FDFYear;
property DFDescription: TStringField read FDFDescription;
property DFVIN: TStringField read FDFVIN;
property DFAction: TStringField read FDFAction;
property DFCompanyAgent: TStringField read FDFCompanyAgent;
property DFPolicy: TStringField read FDFPolicy;
property DFEffDate: TStringField read FDFEffDate;
property DFExpDate: TStringField read FDFExpDate;
property DFUserID: TStringField read FDFUserID;
property DFComment: TStringField read FDFComment;
property DFAddress: TStringField read FDFAddress;
property DFCompanyAddress: TStringField read FDFCompanyAddress;
property DFCompanyName: TStringField read FDFCompanyName;
property PTranID: String read GetPTranID write SetPTranID;
property PModCount: Integer read GetPModCount write SetPModCount;
property PLender: String read GetPLender write SetPLender;
property PName: String read GetPName write SetPName;
property PKeyDate: String read GetPKeyDate write SetPKeyDate;
property PRecordType: String read GetPRecordType write SetPRecordType;
property PEntryText: String read GetPEntryText write SetPEntryText;
property PBatchDate: String read GetPBatchDate write SetPBatchDate;
property PDocumentID: String read GetPDocumentID write SetPDocumentID;
property PMailDate: String read GetPMailDate write SetPMailDate;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PYear: String read GetPYear write SetPYear;
property PDescription: String read GetPDescription write SetPDescription;
property PVIN: String read GetPVIN write SetPVIN;
property PAction: String read GetPAction write SetPAction;
property PCompanyAgent: String read GetPCompanyAgent write SetPCompanyAgent;
property PPolicy: String read GetPPolicy write SetPPolicy;
property PEffDate: String read GetPEffDate write SetPEffDate;
property PExpDate: String read GetPExpDate write SetPExpDate;
property PUserID: String read GetPUserID write SetPUserID;
property PComment: String read GetPComment write SetPComment;
property PAddress: String read GetPAddress write SetPAddress;
property PCompanyAddress: String read GetPCompanyAddress write SetPCompanyAddress;
property PCompanyName: String read GetPCompanyName write SetPCompanyName;
published
property Active write SetActive;
end; { TInfoUTLFTable }
procedure Register;
implementation
function TInfoUTLFTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoUTLFTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoUTLFTable.GenerateNewFieldName }
function TInfoUTLFTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoUTLFTable.CreateField }
procedure TInfoUTLFTable.CreateFields;
begin
FDFTranID := CreateField( 'TranID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFKeyDate := CreateField( 'KeyDate' ) as TStringField;
FDFRecordType := CreateField( 'RecordType' ) as TStringField;
FDFEntryText := CreateField( 'EntryText' ) as TStringField;
FDFBatchDate := CreateField( 'BatchDate' ) as TStringField;
FDFDocumentID := CreateField( 'DocumentID' ) as TStringField;
FDFMailDate := CreateField( 'MailDate' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFYear := CreateField( 'Year' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFVIN := CreateField( 'VIN' ) as TStringField;
FDFAction := CreateField( 'Action' ) as TStringField;
FDFCompanyAgent := CreateField( 'CompanyAgent' ) as TStringField;
FDFPolicy := CreateField( 'Policy' ) as TStringField;
FDFEffDate := CreateField( 'EffDate' ) as TStringField;
FDFExpDate := CreateField( 'ExpDate' ) as TStringField;
FDFUserID := CreateField( 'UserID' ) as TStringField;
FDFComment := CreateField( 'Comment' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCompanyAddress := CreateField( 'CompanyAddress' ) as TStringField;
FDFCompanyName := CreateField( 'CompanyName' ) as TStringField;
end; { TInfoUTLFTable.CreateFields }
procedure TInfoUTLFTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoUTLFTable.SetActive }
procedure TInfoUTLFTable.SetPTranID(const Value: String);
begin
DFTranID.Value := Value;
end;
function TInfoUTLFTable.GetPTranID:String;
begin
result := DFTranID.Value;
end;
procedure TInfoUTLFTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoUTLFTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TInfoUTLFTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoUTLFTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoUTLFTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoUTLFTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoUTLFTable.SetPKeyDate(const Value: String);
begin
DFKeyDate.Value := Value;
end;
function TInfoUTLFTable.GetPKeyDate:String;
begin
result := DFKeyDate.Value;
end;
procedure TInfoUTLFTable.SetPRecordType(const Value: String);
begin
DFRecordType.Value := Value;
end;
function TInfoUTLFTable.GetPRecordType:String;
begin
result := DFRecordType.Value;
end;
procedure TInfoUTLFTable.SetPEntryText(const Value: String);
begin
DFEntryText.Value := Value;
end;
function TInfoUTLFTable.GetPEntryText:String;
begin
result := DFEntryText.Value;
end;
procedure TInfoUTLFTable.SetPBatchDate(const Value: String);
begin
DFBatchDate.Value := Value;
end;
function TInfoUTLFTable.GetPBatchDate:String;
begin
result := DFBatchDate.Value;
end;
procedure TInfoUTLFTable.SetPDocumentID(const Value: String);
begin
DFDocumentID.Value := Value;
end;
function TInfoUTLFTable.GetPDocumentID:String;
begin
result := DFDocumentID.Value;
end;
procedure TInfoUTLFTable.SetPMailDate(const Value: String);
begin
DFMailDate.Value := Value;
end;
function TInfoUTLFTable.GetPMailDate:String;
begin
result := DFMailDate.Value;
end;
procedure TInfoUTLFTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoUTLFTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoUTLFTable.SetPYear(const Value: String);
begin
DFYear.Value := Value;
end;
function TInfoUTLFTable.GetPYear:String;
begin
result := DFYear.Value;
end;
procedure TInfoUTLFTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoUTLFTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoUTLFTable.SetPVIN(const Value: String);
begin
DFVIN.Value := Value;
end;
function TInfoUTLFTable.GetPVIN:String;
begin
result := DFVIN.Value;
end;
procedure TInfoUTLFTable.SetPAction(const Value: String);
begin
DFAction.Value := Value;
end;
function TInfoUTLFTable.GetPAction:String;
begin
result := DFAction.Value;
end;
procedure TInfoUTLFTable.SetPCompanyAgent(const Value: String);
begin
DFCompanyAgent.Value := Value;
end;
function TInfoUTLFTable.GetPCompanyAgent:String;
begin
result := DFCompanyAgent.Value;
end;
procedure TInfoUTLFTable.SetPPolicy(const Value: String);
begin
DFPolicy.Value := Value;
end;
function TInfoUTLFTable.GetPPolicy:String;
begin
result := DFPolicy.Value;
end;
procedure TInfoUTLFTable.SetPEffDate(const Value: String);
begin
DFEffDate.Value := Value;
end;
function TInfoUTLFTable.GetPEffDate:String;
begin
result := DFEffDate.Value;
end;
procedure TInfoUTLFTable.SetPExpDate(const Value: String);
begin
DFExpDate.Value := Value;
end;
function TInfoUTLFTable.GetPExpDate:String;
begin
result := DFExpDate.Value;
end;
procedure TInfoUTLFTable.SetPUserID(const Value: String);
begin
DFUserID.Value := Value;
end;
function TInfoUTLFTable.GetPUserID:String;
begin
result := DFUserID.Value;
end;
procedure TInfoUTLFTable.SetPComment(const Value: String);
begin
DFComment.Value := Value;
end;
function TInfoUTLFTable.GetPComment:String;
begin
result := DFComment.Value;
end;
procedure TInfoUTLFTable.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoUTLFTable.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoUTLFTable.SetPCompanyAddress(const Value: String);
begin
DFCompanyAddress.Value := Value;
end;
function TInfoUTLFTable.GetPCompanyAddress:String;
begin
result := DFCompanyAddress.Value;
end;
procedure TInfoUTLFTable.SetPCompanyName(const Value: String);
begin
DFCompanyName.Value := Value;
end;
function TInfoUTLFTable.GetPCompanyName:String;
begin
result := DFCompanyName.Value;
end;
procedure TInfoUTLFTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('TranID, String, 5, N');
Add('ModCount, Integer, 0, N');
Add('Lender, String, 4, N');
Add('Name, String, 30, N');
Add('KeyDate, String, 10, N');
Add('RecordType, String, 1, N');
Add('EntryText, String, 4, N');
Add('BatchDate, String, 10, N');
Add('DocumentID, String, 6, N');
Add('MailDate, String, 10, N');
Add('LoanNumber, String, 18, N');
Add('Year, String, 2, N');
Add('Description, String, 12, N');
Add('VIN, String, 17, N');
Add('Action, String, 1, N');
Add('CompanyAgent, String, 20, N');
Add('Policy, String, 15, N');
Add('EffDate, String, 10, N');
Add('ExpDate, String, 10, N');
Add('UserID, String, 6, N');
Add('Comment, String, 30, N');
Add('Address, String, 30, N');
Add('CompanyAddress, String, 10, N');
Add('CompanyName, String, 10, N');
end;
end;
procedure TInfoUTLFTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, TranID, Y, Y, N, N');
Add('ByName, Lender;Name, N, N, N, N');
Add('BatchDate, Lender;KeyDate;RecordType;EntryText, N, N, N, N');
Add('Serial, Lender, N, N, N, N');
Add('Policy, Lender;Policy, N, N, N, N');
end;
end;
procedure TInfoUTLFTable.SetEnumIndex(Value: TEIInfoUTLF);
begin
case Value of
InfoUTLFPrimaryKey : IndexName := '';
InfoUTLFByName : IndexName := 'ByName';
InfoUTLFBatchDate : IndexName := 'BatchDate';
InfoUTLFSerial : IndexName := 'Serial';
InfoUTLFPolicy : IndexName := 'Policy';
end;
end;
function TInfoUTLFTable.GetDataBuffer:TInfoUTLFRecord;
var buf: TInfoUTLFRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PTranID := DFTranID.Value;
buf.PModCount := DFModCount.Value;
buf.PLender := DFLender.Value;
buf.PName := DFName.Value;
buf.PKeyDate := DFKeyDate.Value;
buf.PRecordType := DFRecordType.Value;
buf.PEntryText := DFEntryText.Value;
buf.PBatchDate := DFBatchDate.Value;
buf.PDocumentID := DFDocumentID.Value;
buf.PMailDate := DFMailDate.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PYear := DFYear.Value;
buf.PDescription := DFDescription.Value;
buf.PVIN := DFVIN.Value;
buf.PAction := DFAction.Value;
buf.PCompanyAgent := DFCompanyAgent.Value;
buf.PPolicy := DFPolicy.Value;
buf.PEffDate := DFEffDate.Value;
buf.PExpDate := DFExpDate.Value;
buf.PUserID := DFUserID.Value;
buf.PComment := DFComment.Value;
buf.PAddress := DFAddress.Value;
buf.PCompanyAddress := DFCompanyAddress.Value;
buf.PCompanyName := DFCompanyName.Value;
result := buf;
end;
procedure TInfoUTLFTable.StoreDataBuffer(ABuffer:TInfoUTLFRecord);
begin
DFTranID.Value := ABuffer.PTranID;
DFModCount.Value := ABuffer.PModCount;
DFLender.Value := ABuffer.PLender;
DFName.Value := ABuffer.PName;
DFKeyDate.Value := ABuffer.PKeyDate;
DFRecordType.Value := ABuffer.PRecordType;
DFEntryText.Value := ABuffer.PEntryText;
DFBatchDate.Value := ABuffer.PBatchDate;
DFDocumentID.Value := ABuffer.PDocumentID;
DFMailDate.Value := ABuffer.PMailDate;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFYear.Value := ABuffer.PYear;
DFDescription.Value := ABuffer.PDescription;
DFVIN.Value := ABuffer.PVIN;
DFAction.Value := ABuffer.PAction;
DFCompanyAgent.Value := ABuffer.PCompanyAgent;
DFPolicy.Value := ABuffer.PPolicy;
DFEffDate.Value := ABuffer.PEffDate;
DFExpDate.Value := ABuffer.PExpDate;
DFUserID.Value := ABuffer.PUserID;
DFComment.Value := ABuffer.PComment;
DFAddress.Value := ABuffer.PAddress;
DFCompanyAddress.Value := ABuffer.PCompanyAddress;
DFCompanyName.Value := ABuffer.PCompanyName;
end;
function TInfoUTLFTable.GetEnumIndex: TEIInfoUTLF;
var iname : string;
begin
result := InfoUTLFPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoUTLFPrimaryKey;
if iname = 'BYNAME' then result := InfoUTLFByName;
if iname = 'BATCHDATE' then result := InfoUTLFBatchDate;
if iname = 'SERIAL' then result := InfoUTLFSerial;
if iname = 'POLICY' then result := InfoUTLFPolicy;
end;
function TInfoUTLFQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoUTLFQuery.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoUTLFQuery.GenerateNewFieldName }
function TInfoUTLFQuery.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoUTLFQuery.CreateField }
procedure TInfoUTLFQuery.CreateFields;
begin
FDFTranID := CreateField( 'TranID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFKeyDate := CreateField( 'KeyDate' ) as TStringField;
FDFRecordType := CreateField( 'RecordType' ) as TStringField;
FDFEntryText := CreateField( 'EntryText' ) as TStringField;
FDFBatchDate := CreateField( 'BatchDate' ) as TStringField;
FDFDocumentID := CreateField( 'DocumentID' ) as TStringField;
FDFMailDate := CreateField( 'MailDate' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFYear := CreateField( 'Year' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFVIN := CreateField( 'VIN' ) as TStringField;
FDFAction := CreateField( 'Action' ) as TStringField;
FDFCompanyAgent := CreateField( 'CompanyAgent' ) as TStringField;
FDFPolicy := CreateField( 'Policy' ) as TStringField;
FDFEffDate := CreateField( 'EffDate' ) as TStringField;
FDFExpDate := CreateField( 'ExpDate' ) as TStringField;
FDFUserID := CreateField( 'UserID' ) as TStringField;
FDFComment := CreateField( 'Comment' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCompanyAddress := CreateField( 'CompanyAddress' ) as TStringField;
FDFCompanyName := CreateField( 'CompanyName' ) as TStringField;
end; { TInfoUTLFQuery.CreateFields }
procedure TInfoUTLFQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoUTLFQuery.SetActive }
procedure TInfoUTLFQuery.SetPTranID(const Value: String);
begin
DFTranID.Value := Value;
end;
function TInfoUTLFQuery.GetPTranID:String;
begin
result := DFTranID.Value;
end;
procedure TInfoUTLFQuery.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoUTLFQuery.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TInfoUTLFQuery.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoUTLFQuery.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoUTLFQuery.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoUTLFQuery.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoUTLFQuery.SetPKeyDate(const Value: String);
begin
DFKeyDate.Value := Value;
end;
function TInfoUTLFQuery.GetPKeyDate:String;
begin
result := DFKeyDate.Value;
end;
procedure TInfoUTLFQuery.SetPRecordType(const Value: String);
begin
DFRecordType.Value := Value;
end;
function TInfoUTLFQuery.GetPRecordType:String;
begin
result := DFRecordType.Value;
end;
procedure TInfoUTLFQuery.SetPEntryText(const Value: String);
begin
DFEntryText.Value := Value;
end;
function TInfoUTLFQuery.GetPEntryText:String;
begin
result := DFEntryText.Value;
end;
procedure TInfoUTLFQuery.SetPBatchDate(const Value: String);
begin
DFBatchDate.Value := Value;
end;
function TInfoUTLFQuery.GetPBatchDate:String;
begin
result := DFBatchDate.Value;
end;
procedure TInfoUTLFQuery.SetPDocumentID(const Value: String);
begin
DFDocumentID.Value := Value;
end;
function TInfoUTLFQuery.GetPDocumentID:String;
begin
result := DFDocumentID.Value;
end;
procedure TInfoUTLFQuery.SetPMailDate(const Value: String);
begin
DFMailDate.Value := Value;
end;
function TInfoUTLFQuery.GetPMailDate:String;
begin
result := DFMailDate.Value;
end;
procedure TInfoUTLFQuery.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoUTLFQuery.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoUTLFQuery.SetPYear(const Value: String);
begin
DFYear.Value := Value;
end;
function TInfoUTLFQuery.GetPYear:String;
begin
result := DFYear.Value;
end;
procedure TInfoUTLFQuery.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoUTLFQuery.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoUTLFQuery.SetPVIN(const Value: String);
begin
DFVIN.Value := Value;
end;
function TInfoUTLFQuery.GetPVIN:String;
begin
result := DFVIN.Value;
end;
procedure TInfoUTLFQuery.SetPAction(const Value: String);
begin
DFAction.Value := Value;
end;
function TInfoUTLFQuery.GetPAction:String;
begin
result := DFAction.Value;
end;
procedure TInfoUTLFQuery.SetPCompanyAgent(const Value: String);
begin
DFCompanyAgent.Value := Value;
end;
function TInfoUTLFQuery.GetPCompanyAgent:String;
begin
result := DFCompanyAgent.Value;
end;
procedure TInfoUTLFQuery.SetPPolicy(const Value: String);
begin
DFPolicy.Value := Value;
end;
function TInfoUTLFQuery.GetPPolicy:String;
begin
result := DFPolicy.Value;
end;
procedure TInfoUTLFQuery.SetPEffDate(const Value: String);
begin
DFEffDate.Value := Value;
end;
function TInfoUTLFQuery.GetPEffDate:String;
begin
result := DFEffDate.Value;
end;
procedure TInfoUTLFQuery.SetPExpDate(const Value: String);
begin
DFExpDate.Value := Value;
end;
function TInfoUTLFQuery.GetPExpDate:String;
begin
result := DFExpDate.Value;
end;
procedure TInfoUTLFQuery.SetPUserID(const Value: String);
begin
DFUserID.Value := Value;
end;
function TInfoUTLFQuery.GetPUserID:String;
begin
result := DFUserID.Value;
end;
procedure TInfoUTLFQuery.SetPComment(const Value: String);
begin
DFComment.Value := Value;
end;
function TInfoUTLFQuery.GetPComment:String;
begin
result := DFComment.Value;
end;
procedure TInfoUTLFQuery.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoUTLFQuery.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoUTLFQuery.SetPCompanyAddress(const Value: String);
begin
DFCompanyAddress.Value := Value;
end;
function TInfoUTLFQuery.GetPCompanyAddress:String;
begin
result := DFCompanyAddress.Value;
end;
procedure TInfoUTLFQuery.SetPCompanyName(const Value: String);
begin
DFCompanyName.Value := Value;
end;
function TInfoUTLFQuery.GetPCompanyName:String;
begin
result := DFCompanyName.Value;
end;
function TInfoUTLFQuery.GetDataBuffer:TInfoUTLFRecord;
var buf: TInfoUTLFRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PTranID := DFTranID.Value;
buf.PModCount := DFModCount.Value;
buf.PLender := DFLender.Value;
buf.PName := DFName.Value;
buf.PKeyDate := DFKeyDate.Value;
buf.PRecordType := DFRecordType.Value;
buf.PEntryText := DFEntryText.Value;
buf.PBatchDate := DFBatchDate.Value;
buf.PDocumentID := DFDocumentID.Value;
buf.PMailDate := DFMailDate.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PYear := DFYear.Value;
buf.PDescription := DFDescription.Value;
buf.PVIN := DFVIN.Value;
buf.PAction := DFAction.Value;
buf.PCompanyAgent := DFCompanyAgent.Value;
buf.PPolicy := DFPolicy.Value;
buf.PEffDate := DFEffDate.Value;
buf.PExpDate := DFExpDate.Value;
buf.PUserID := DFUserID.Value;
buf.PComment := DFComment.Value;
buf.PAddress := DFAddress.Value;
buf.PCompanyAddress := DFCompanyAddress.Value;
buf.PCompanyName := DFCompanyName.Value;
result := buf;
end;
procedure TInfoUTLFQuery.StoreDataBuffer(ABuffer:TInfoUTLFRecord);
begin
DFTranID.Value := ABuffer.PTranID;
DFModCount.Value := ABuffer.PModCount;
DFLender.Value := ABuffer.PLender;
DFName.Value := ABuffer.PName;
DFKeyDate.Value := ABuffer.PKeyDate;
DFRecordType.Value := ABuffer.PRecordType;
DFEntryText.Value := ABuffer.PEntryText;
DFBatchDate.Value := ABuffer.PBatchDate;
DFDocumentID.Value := ABuffer.PDocumentID;
DFMailDate.Value := ABuffer.PMailDate;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFYear.Value := ABuffer.PYear;
DFDescription.Value := ABuffer.PDescription;
DFVIN.Value := ABuffer.PVIN;
DFAction.Value := ABuffer.PAction;
DFCompanyAgent.Value := ABuffer.PCompanyAgent;
DFPolicy.Value := ABuffer.PPolicy;
DFEffDate.Value := ABuffer.PEffDate;
DFExpDate.Value := ABuffer.PExpDate;
DFUserID.Value := ABuffer.PUserID;
DFComment.Value := ABuffer.PComment;
DFAddress.Value := ABuffer.PAddress;
DFCompanyAddress.Value := ABuffer.PCompanyAddress;
DFCompanyName.Value := ABuffer.PCompanyName;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoUTLFTable, TInfoUTLFQuery, TInfoUTLFBuffer ] );
end; { Register }
function TInfoUTLFBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..24] of string = ('TRANID','MODCOUNT','LENDER','NAME','KEYDATE','RECORDTYPE'
,'ENTRYTEXT','BATCHDATE','DOCUMENTID','MAILDATE','LOANNUMBER'
,'YEAR','DESCRIPTION','VIN','ACTION','COMPANYAGENT'
,'POLICY','EFFDATE','EXPDATE','USERID','COMMENT'
,'ADDRESS','COMPANYADDRESS','COMPANYNAME' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 24) and (flist[x] <> s) do inc(x);
if x <= 24 then result := x else result := 0;
end;
function TInfoUTLFBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftInteger;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
13 : result := ftString;
14 : result := ftString;
15 : result := ftString;
16 : result := ftString;
17 : result := ftString;
18 : result := ftString;
19 : result := ftString;
20 : result := ftString;
21 : result := ftString;
22 : result := ftString;
23 : result := ftString;
24 : result := ftString;
end;
end;
function TInfoUTLFBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PTranID;
2 : result := @Data.PModCount;
3 : result := @Data.PLender;
4 : result := @Data.PName;
5 : result := @Data.PKeyDate;
6 : result := @Data.PRecordType;
7 : result := @Data.PEntryText;
8 : result := @Data.PBatchDate;
9 : result := @Data.PDocumentID;
10 : result := @Data.PMailDate;
11 : result := @Data.PLoanNumber;
12 : result := @Data.PYear;
13 : result := @Data.PDescription;
14 : result := @Data.PVIN;
15 : result := @Data.PAction;
16 : result := @Data.PCompanyAgent;
17 : result := @Data.PPolicy;
18 : result := @Data.PEffDate;
19 : result := @Data.PExpDate;
20 : result := @Data.PUserID;
21 : result := @Data.PComment;
22 : result := @Data.PAddress;
23 : result := @Data.PCompanyAddress;
24 : result := @Data.PCompanyName;
end;
end;
end.
|
unit UIWrapper_DBTreeViewUnit;
interface
uses
FMX.TreeView, DBManager, SearchResult, SearchOption, DataFileSaver;
type
TBooleanEvent = procedure(Sender: TObject; val: Boolean) of object;
TUIWrapper_DBTreeView = class(TObject)
private
FDBManager: TAbsDBManager;
FTreeView: TTreeView;
FOnAfterSearch: TSearchResultEvent;
FOnFoundLogMsgData: TBooleanEvent;
procedure OnAfterSearch_Proc(schResult: IDataSetIterator);
procedure OnFoundLogMsgData_Proc(val: Boolean);
protected
function AddChild(childText: String): TTreeViewItem;
procedure AddChildOfChild(child: TTreeViewItem; childText: String);
function IsEventLog(tableName: String): Boolean;
function HasParentItem(listItem: TTreeViewItem): Boolean;
procedure TreeView_OnDblClick(Sender: TObject);
public
constructor Create(treeView: TTreeView);
destructor Destroy; override;
procedure AddDBFileInfo(filePath: String);
procedure RemoveDBFileInfo(fileName: String);
procedure SetDBManager(dbm: TAbsDBManager); virtual;
procedure ShowSearchOption;
published
property OnAfterSearch: TSearchResultEvent read FOnAfterSearch write FOnAfterSearch;
property OnFoundLogMsgData: TBooleanEvent read FOnFoundLogMsgData write FOnFoundLogMsgData;
end;
implementation
uses
Form_MainUnit, System.SysUtils, System.Classes, Form_SearchOptionUnit,
System.UITypes, Const_SearchOptionUnit, SimpleResult;
{ TEvent_DBTreeView }
function TUIWrapper_DBTreeView.AddChild(childText: String): TTreeViewItem;
var
child: TTreeViewItem;
begin
child := TTreeViewItem.Create( nil );
child.Text := childText;
//if FTreeView.ChildrenCount <= 0 then
FTreeView.AddObject( child );
//else
//FTreeView.InsertObject( 0, child );
result := child;
end;
procedure TUIWrapper_DBTreeView.AddChildOfChild(child: TTreeViewItem;
childText: String);
var
childchildItem: TTreeViewItem;
begin
childchildItem := TTreeViewItem.Create( nil );
childchildItem.Text := childText;
child.AddObject( childchildItem );
end;
procedure TUIWrapper_DBTreeView.AddDBFileInfo(filePath: String);
var
sRestoreName: string;
tvChild: TTreeViewItem;
sList_Tables: TStringList;
i: Integer;
begin
sRestoreName := ExtractFileName( filePath );
sRestoreName := StringReplace( sRestoreName, ExtractFileExt( filePath), '', [rfIgnoreCase] );
FDBManager.Restore( filePath, sRestoreName );
FDBManager.DBName := sRestoreName;
FDBManager.Open;
tvChild := AddChild( FDBManager.DBName );
sList_Tables := FDBManager.GetTableNames;
for i := 0 to sList_Tables.Count - 1 do
begin
AddChildOfChild( tvChild, sList_Tables[ i ] );
end;
end;
constructor TUIWrapper_DBTreeView.Create(treeView: TTreeView);
begin
FTreeView := treeView;
FTreeView.OnDblClick := TreeView_OnDblClick;
end;
destructor TUIWrapper_DBTreeView.Destroy;
begin
FDBManager.Free;
//FSearchOption.Free;
end;
function TUIWrapper_DBTreeView.HasParentItem(listItem: TTreeViewItem): Boolean;
begin
if listItem.ParentItem <> nil then
result := true
else
result := false;
end;
function TUIWrapper_DBTreeView.IsEventLog(tableName: String): Boolean;
var
i: Integer;
begin
for i := 0 to High( EVENT_LOG_TABLE ) do
begin
if LowerCase( tableName ) = EVENT_LOG_TABLE[ i ] then
begin
result := true; exit;
end;
end;
result := false;
end;
procedure TUIWrapper_DBTreeView.OnAfterSearch_Proc(schResult: IDataSetIterator);
begin
if Assigned( OnAfterSearch ) = true then
OnAfterSearch( self, schResult );
end;
procedure TUIWrapper_DBTreeView.OnFoundLogMsgData_Proc(val: Boolean);
begin
if Assigned( OnFoundLogMsgData ) = true then
OnFoundLogMsgData( self, val );
end;
procedure TUIWrapper_DBTreeView.RemoveDBFileInfo(fileName: String);
var
child: TTreeViewItem;
i: Integer;
begin
for i := 0 to FTreeView.Count - 1 do
begin
child := FTreeView.Items[ i ];
if child.Text = fileName then
begin
FTreeView.RemoveObject( child );
FDBManager.DropDB( fileName );
exit;
end;
end;
end;
procedure TUIWrapper_DBTreeView.SetDBManager(dbm: TAbsDBManager);
begin
FDBManager := dbm;
end;
procedure TUIWrapper_DBTreeView.ShowSearchOption;
var
modalRet: Integer;
sTableName: String;
begin
if FTreeView.Selected = nil then exit;
if HasParentItem( FTreeView.Selected ) = false then
begin
FTreeView.Selected.IsExpanded := not FTreeView.Selected.IsExpanded;
exit;
end;
FDBManager.DBName := FTreeView.Selected.ParentItem.Text;
sTableName := FtreeView.Selected.Text;
if IsEventLog( sTableName ) = true then
begin
OnFoundLogMsgData_Proc( true );
OnAfterSearch_Proc( TSimpleResult.Create( sTableName, FDBManager ) );
end
else
begin
modalRet := Form_SearchOption.ShowModalWithInitItems( sTableName, FDBManager );
if modalRet = mrOK then
begin
OnFoundLogMsgData_Proc( Form_SearchOption.IsDateTimeSplit );
OnAfterSearch_Proc( Form_SearchOption.GetSearchResult );
end;
end;
end;
procedure TUIWrapper_DBTreeView.TreeView_OnDblClick(Sender: TObject);
begin
ShowSearchOption;
end;
end.
|
unit UtilsHttp;
interface
uses
Windows, ActiveX, UrlMon, win.iobuffer;
type
PClientConnectSession = ^TClientConnectSession;
TClientConnectSession = record
Connection : Pointer;
SendTimeOut : Cardinal;
ConnectTimeOut : Cardinal;
ReceiveTimeOut : Cardinal;
end;
PHttpHeadParseSession = ^THttpHeadParseSession;
THttpHeadParseSession = record
RetCode : integer;
HeadEndPos : integer;
Transfer_Encoding : Integer;
Charset : Integer;
ContentLength : Integer;
Location : string;
end;
PHttpClientSession = ^THttpClientSession;
THttpClientSession = record
ConnectionSession: TClientConnectSession;
IsKeepAlive : Boolean;
HttpHeadSession : THttpHeadParseSession;
end;
PHttpUrlInfo = ^THttpUrlInfo;
THttpUrlInfo = record
Protocol : AnsiString;
Host : AnsiString;
Port : AnsiString;
PathName : AnsiString;
UserName : AnsiString;
Password : AnsiString;
end;
PHttpBuffer = ^THttpBuffer;
THttpBuffer = record
end;
function CheckOutHttpClientSession: PHttpClientSession;
procedure CheckInHttpClientSession(var ANetClientSession: PHttpClientSession);
{ 这里可能有问题
获取的数据 有些 Http 头 解析不正确
}
function GetHttpUrlData(AUrl: AnsiString; ANetSession: PHttpClientSession; ABuffer: PIOBuffer; ABufferSizeMode: Integer = SizeMode_16k): PIOBuffer; overload;
function GetHttpUrlData(AUrl: AnsiString; APost: AnsiString; ANetSession: PHttpClientSession; ABuffer: PIOBuffer; ABufferSizeMode: Integer = SizeMode_16k): PIOBuffer; overload;
function GetHttpUrlFile(AUrl: AnsiString; AOutputFile: AnsiString; ANetSession: PHttpClientSession): Boolean; overload;
function PostHttpUrlData(AUrl: AnsiString; APost: AnsiString; ANetSession: PHttpClientSession): PIOBuffer;
function GetDefaultUserAgent: AnsiString;
function ParseHttpUrlInfo(AUrl: AnsiString; AInfo: PHttpUrlInfo): Boolean;
procedure HttpBufferHeader_Parser(AHttpBuffer: PIOBuffer; AHttpHeadParseSession: PHttpHeadParseSession);
procedure SaveHttpResponseToFile(AHttpBuffer: PIOBuffer; AHttpHeadParseSession: PHttpHeadParseSession; AFileName: AnsiString);
{* 将 URL 中的特殊字符转换成 %XX 的形式}
function EncodeURL(const AUrl: string): string;
const
SAcceptEncoding = 'Accept-Encoding: gzip,deflate';
implementation
uses
Sysutils,
//UtilsHttp_Indy,
//win.diskfile,
UtilsHttp_Socket;
function CheckOutHttpClientSession: PHttpClientSession;
begin
Result := System.New(PHttpClientSession);
FillChar(Result^, SizeOf(THttpClientSession), 0);
Result.IsKeepAlive := True;
end;
procedure CheckInHttpClientSession(var ANetClientSession: PHttpClientSession);
begin
if nil <> ANetClientSession then
begin
if nil <> ANetClientSession.ConnectionSession.Connection then
begin
CheckInSocketConnection(ANetClientSession);
end;
FreeMem(ANetClientSession);
ANetClientSession := nil;
end;
end;
function EncodeURL(const AUrl: string): string;
const
UnsafeChars = ['*', '#', '%', '<', '>', '+', ' '];
var
i: Integer;
InStr, OutStr: AnsiString;
begin
InStr := AnsiString(AUrl);
OutStr := '';
for i := 1 to Length(InStr) do begin
if (InStr[i] in UnsafeChars) or (InStr[i] >= #$80) or (InStr[i] < #32) then
OutStr := OutStr + '%' + AnsiString(IntToHex(Ord(InStr[i]), 2))
else
OutStr := OutStr + InStr[i];
end;
Result := string(OutStr);
end;
function GetDefaultUserAgent: AnsiString;
var
s: AnsiString;
cbSize: Cardinal;
hRet: HRESULT;
begin
cbSize := MAX_PATH;
repeat
SetLength(s, cbSize);
hRet := UrlMon.ObtainUserAgentString(0, PAnsiChar(s), cbSize);
case hRet of
E_OUTOFMEMORY:
cbSize := cbSize * 2;
NOERROR:
SetLength(s, cbSize - 1);
else
SetLength(s, 0);
end;
until hRet <> E_OUTOFMEMORY;
Result := s;
end;
function ParseHttpUrlInfo(AUrl: AnsiString; AInfo: PHttpUrlInfo): Boolean;
var
Idx: Integer;
Buff: AnsiString;
function ExtractStr(var ASrc: AnsiString; ADelim: AnsiString; ADelete: Boolean = True): AnsiString;
var
Idx: Integer;
begin
Idx := Pos(ADelim, ASrc);
if Idx = 0 then
begin
Result := ASrc;
if ADelete then
ASrc := '';
end else
begin
Result := Copy(ASrc, 1, Idx - 1);
if ADelete then
ASrc := Copy(ASrc, Idx + Length(ADelim), MaxInt);
end;
end;
begin
Result := False;
AUrl := Trim(AUrl);
Idx := Pos('://', AUrl);
if Idx > 0 then
begin
AInfo.Protocol := Copy(AUrl, 1, Idx - 1);
Delete(AUrl, 1, Idx + 2);
if AUrl = '' then
Exit;
Buff := ExtractStr(AUrl, '/');
Idx := Pos('@', Buff);
AInfo.Password := Copy(Buff, 1, Idx - 1);
if Idx > 0 then
Delete(Buff, 1, Idx);
AInfo.UserName := ExtractStr(AInfo.Password, ':');
if Length(AInfo.UserName) = 0 then
AInfo.Password := '';
AInfo.Host := ExtractStr(Buff, ':');
AInfo.Port := Buff;
AInfo.PathName := '/' + AUrl;
Result := True;
end;
end;
function GetHttpUrlData(AUrl: AnsiString; ANetSession: PHttpClientSession; ABuffer: PIOBuffer; ABufferSizeMode: Integer = SizeMode_16k): PIOBuffer;
var
// tmpIConnection: PIndyConnectionSession;
tmpOwnedConnection: Boolean;
begin
tmpOwnedConnection := false;
if nil <> ANetSession then
begin
if nil = ANetSession.ConnectionSession.Connection then
begin
CheckOutSocketConnection(ANetSession);
if not ANetSession.IsKeepAlive then
tmpOwnedConnection := true;
end;
end;
//Result := Http_WinInet.Http_GetString(AUrl);
//Result := UtilsHttp_Indy.Http_GetString(AUrl, tmpConnection);
Result := UtilsHttp_Socket.Http_GetString(AUrl, '', ANetSession, ABuffer, ABufferSizeMode);
if tmpOwnedConnection then
begin
CheckInSocketConnection(ANetSession);
end;
end;
function GetHttpUrlFile(AUrl: AnsiString; AOutputFile: AnsiString; ANetSession: PHttpClientSession): Boolean;
begin
if nil <> ANetSession then
begin
if nil = ANetSession.ConnectionSession.Connection then
begin
//ANetSession.Connection := CheckOutIndyConnection;
CheckOutSocketConnection(ANetSession);
end;
end;
//Result := UtilsHttp_Indy.Http_GetFile(AUrl, AOutputFile, tmpConnection);
Result := UtilsHttp_Socket.Http_GetFile(AUrl, AOutputFile, ANetSession);
end;
function GetHttpUrlData(AUrl: AnsiString; APost: AnsiString; ANetSession: PHttpClientSession; ABuffer: PIOBuffer; ABufferSizeMode: Integer = SizeMode_16k): PIOBuffer;
var
// tmpIConnection: PIndyConnectionSession;
tmpOwnedConnection: Boolean;
begin
tmpOwnedConnection := false;
if nil <> ANetSession then
begin
if nil = ANetSession.ConnectionSession.Connection then
begin
CheckOutSocketConnection(ANetSession);
if not ANetSession.IsKeepAlive then
tmpOwnedConnection := true;
end;
end;
//Result := Http_WinInet.Http_GetString(AUrl);
//Result := UtilsHttp_Indy.Http_GetString(AUrl, tmpConnection);
Result := UtilsHttp_Socket.Http_GetString(AUrl, APost, ANetSession, ABuffer, ABufferSizeMode);
if tmpOwnedConnection then
begin
CheckInSocketConnection(ANetSession);
end;
end;
function PostHttpUrlData(AUrl: AnsiString; APost: AnsiString; ANetSession: PHttpClientSession): PIOBuffer;
var
// tmpIConnection: PIndyConnectionSession;
tmpOwnedConnection: Boolean;
begin
tmpOwnedConnection := false;
if nil <> ANetSession then
begin
if nil = ANetSession.ConnectionSession.Connection then
begin
CheckOutSocketConnection(ANetSession);
if not ANetSession.IsKeepAlive then
tmpOwnedConnection := true;
end;
end;
//Result := Http_WinInet.Http_GetString(AUrl);
//Result := UtilsHttp_Indy.Http_GetString(AUrl, tmpConnection);
Result := UtilsHttp_Socket.Http_GetString(AUrl, APost, ANetSession, nil);
if tmpOwnedConnection then
begin
CheckInSocketConnection(ANetSession);
end;
end;
procedure HttpBufferHeader_Parser(AHttpBuffer: PIOBuffer; AHttpHeadParseSession: PHttpHeadParseSession);
var
tmpHttpHeadBuffer: array[0..256 - 1] of AnsiChar;
i: integer;
tmpStr: AnsiString;
tmpValue: AnsiString;
tmpHead: AnsiString;
tmpPos: integer;
tmpLastPos_CRLF: integer;
tmpIsChecked: Boolean;
begin
if nil = AHttpBuffer then
exit;
FillChar(tmpHttpHeadBuffer, SizeOf(tmpHttpHeadBuffer), 0);
tmpLastPos_CRLF := 0;
for i := 0 to AHttpBuffer.BufferHead.TotalLength - 1 do
begin
if (#13 = AHttpBuffer.Data[i]) then
begin
//#13#10
if 0 = tmpLastPos_CRLF then
begin
CopyMemory(@tmpHttpHeadBuffer[0], @AHttpBuffer.Data[0], i);
tmpStr := tmpHttpHeadBuffer;
tmpPos := Pos(#32, tmpStr);
if tmpPos > 0 then
begin
tmpStr := Copy(tmpStr, tmpPos + 1, maxint);
tmpPos := Pos(#32, tmpStr);
if tmpPos > 0 then
begin
tmpStr := Copy(tmpStr, 1, tmpPos - 1);
AHttpHeadParseSession.RetCode := StrToIntDef(tmpStr, 0);
end;
end;
end else
begin
// Http Header Field Definitions
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
CopyMemory(@tmpHttpHeadBuffer[0], @AHttpBuffer.Data[tmpLastPos_CRLF + 1], i - tmpLastPos_CRLF - 1);
tmpStr := Trim(tmpHttpHeadBuffer);
if '' <> tmpStr then
begin
tmpPos := Pos(':', tmpStr);
if 0 < tmpPos then
begin
tmpHead := Copy(tmpStr, 1, tmpPos - 1);
if SameText('Server', tmpHead) then
begin
// web服务器软件名称
end;
if SameText('Allow', tmpHead) then
begin
// Allow: GET, HEAD 对某网络资源的有效的请求行为,不允许则返回405
end;
if SameText('Date', tmpHead) then
begin
end;
if SameText('Connection', tmpHead) then
begin
end;
if SameText('Accept-Ranges', tmpHead) then
begin
// 表明服务器是否支持指定范围请求及哪种类型的分段请求 Accept-Ranges: bytes
end;
if SameText('Set-Cookie', tmpHead) then
begin
end;
if SameText('Proxy-Authenticate', tmpHead) then
begin
// Proxy-Authenticate: Basic
// 它指出认证方案和可应用到代理的该URL上的参数
end;
if SameText('WWW-Authenticate', tmpHead) then
begin
// 表明客户端请求实体应该使用的授权方案 WWW-Authenticate: Basic
end;
if SameText('Cache-Control', tmpHead) then
begin
// Cache-Control: no-cache 告诉所有的缓存机制是否可以缓存及哪种类型
end;
if SameText('Location', tmpHead) then
begin
// Location: http://www.zcmhi.com/archives/94.html
// 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源
AHttpHeadParseSession.Location := Trim(Copy(tmpStr, tmpPos + 1, maxint));
end;
if SameText('Expires', tmpHead) then
begin
// 响应过期的日期和时间
end;
if SameText('Last-Modified', tmpHead) then
begin
// 请求资源的最后修改时间
end;
if SameText('ETag', tmpHead) then
begin
// 请求变量的实体标签的当前值
// ETag: “737060cd8c284d8af7ad3082f209582d”
end;
if SameText('Transfer-Encoding', tmpHead) then
begin
tmpStr := Trim(Copy(tmpStr, tmpPos + 1, maxint));
if SameText('chunked', tmpStr) then
begin
AHttpHeadParseSession.Transfer_Encoding := 1;
end;
end;
if SameText('Trailer', tmpHead) then
begin
//指出头域在分块传输编码的尾部存在 Trailer: Max-Forwards
end;
if SameText('Vary', tmpHead) then
begin
//告诉下游代理是使用缓存响应还是从原始服务器请求 Vary: *
end;
if SameText('Via', tmpHead) then
begin
//告知代理客户端响应是通过哪里发送的 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
end;
if SameText('Content-Encoding', tmpHead) then
begin
// Content-Encoding: gzip web服务器支持的返回内容压缩编码类型
end;
if SameText('Content-Language', tmpHead) then
begin
//响应体的语言 Content-Language: en,zh
end;
if SameText('Content-Length', tmpHead) then
begin
//响应体的长度 Content-Length: 348
AHttpHeadParseSession.ContentLength := 0;
end;
if SameText('Content-Location', tmpHead) then
begin
// 请求资源可替代的备用的另一地址 Content-Location: /index.htm
end;
if SameText('Content-MD5', tmpHead) then
begin
// 返回资源的MD5校验值 Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
end;
if SameText('Content-Range', tmpHead) then
begin
//在整个返回体中本部分的字节位置 Content-Range: bytes 21010-47021/47022
end;
if SameText('Content-Type', tmpHead) then
begin
// Content-Type: text/html; charset=utf-8
tmpStr := Trim(Copy(tmpStr, tmpPos + 1, maxint));
tmpPos := Pos('charset=', tmpStr);
if 0 < tmpPos then
begin
tmpValue := Copy(tmpStr, tmpPos + 8, maxint);
if '' <> tmpValue then
begin
if SameText('utf-8', tmpValue) then
begin
//AHttpHeadParseSession.Charset := ANSI_CHARSET;
AHttpHeadParseSession.Charset := CP_UTF8;
end;
end;
end;
end;
if SameText('Retry-After', tmpHead) then
begin
// 如果实体暂时不可取,通知客户端在指定时间之后再次尝试 Retry-After: 120
end;
if SameText('Warning', tmpHead) then
begin
// 警告实体可能存在的问题 Warning: 199 Miscellaneous warning
end;
end;
end;
end;
FillChar(tmpHttpHeadBuffer, SizeOf(tmpHttpHeadBuffer), 0);
if i - tmpLastPos_CRLF < 3 then
begin
AHttpHeadParseSession.HeadEndPos := i;
if #10 = AHttpBuffer.Data[i + 1] then
begin
AHttpHeadParseSession.HeadEndPos := i + 1;
end;
exit;
end;
tmpLastPos_CRLF := i;
end;
end;
end;
procedure SaveHttpResponseToFile(AHttpBuffer: PIOBuffer; AHttpHeadParseSession: PHttpHeadParseSession; AFileName: AnsiString);
var
tmpFileHandle: THandle;
tmpBytesWrite: DWORD;
tmpBytesWritten: DWORD;
begin
tmpFileHandle := Windows.CreateFileA(PAnsiChar(AFileName),
Windows.GENERIC_ALL, // GENERIC_READ
Windows.FILE_SHARE_READ or
Windows.FILE_SHARE_WRITE or
Windows.FILE_SHARE_DELETE,
nil,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, 0);
if (0 <> tmpFileHandle) and (INVALID_HANDLE_VALUE <> tmpFileHandle) then
begin
try
tmpBytesWrite := AHttpBuffer.BufferHead.BufDataLength - AHttpHeadParseSession.HeadEndPos;
if Windows.WriteFile(
tmpFileHandle, //hFile: THandle;
AHttpBuffer.Data[AHttpHeadParseSession.HeadEndPos + 1], // const Buffer;
tmpBytesWrite, //nNumberOfBytesToWrite: DWORD;
tmpBytesWritten, //var lpNumberOfBytesWritten: DWORD;
nil {lpOverlapped: POverlapped}) then
begin
end;
//Windows.WriteFileEx();
finally
Windows.CloseHandle(tmpFileHandle);
end;
end;
end;
end.
|
unit uEscalaVO;
interface
uses
System.SysUtils, uTableName, uKeyField;
type
[TableName('Escala')]
TEscalaVO = class
private
FIdUsuario: Integer;
FTotalHoras: Currency;
FId: Integer;
FHoraFim: string;
FData: string;
FHoraInicio: string;
procedure SetData(const Value: string);
procedure SetHoraFim(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
procedure SetTotalHoras(const Value: Currency);
procedure SetHoraInicio(const Value: string);
public
[KeyField('Esc_Id')]
property Id: Integer read FId write SetId;
[FieldName('Esc_Data')]
property Data: string read FData write SetData;
[FieldName('Esc_HoraInicio')]
property HoraInicio: string read FHoraInicio write SetHoraInicio;
[FieldName('Esc_HoraFim')]
property HoraFim: string read FHoraFim write SetHoraFim;
[FieldName('Esc_Usuario')]
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
[FieldName('Esc_TotalHoras')]
property TotalHoras: Currency read FTotalHoras write SetTotalHoras;
end;
TEscalaFiltro = class
private
FIdUsuario: string;
FId: Integer;
FDataFinal: string;
FDataInicial: string;
procedure SetDataFinal(const Value: string);
procedure SetDataInicial(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdUsuario(const Value: string);
public
property Id: Integer read FId write SetId;
property IdUsuario: string read FIdUsuario write SetIdUsuario;
property DataInicial: string read FDataInicial write SetDataInicial;
property DataFinal: string read FDataFinal write SetDataFinal;
end;
implementation
{ TEscalaVO }
procedure TEscalaVO.SetData(const Value: string);
begin
FData := Value;
end;
procedure TEscalaVO.SetHoraFim(const Value: string);
begin
FHoraFim := Value;
end;
procedure TEscalaVO.SetHoraInicio(const Value: string);
begin
FHoraInicio := Value;
end;
procedure TEscalaVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TEscalaVO.SetIdUsuario(const Value: Integer);
begin
FIdUsuario := Value;
end;
procedure TEscalaVO.SetTotalHoras(const Value: Currency);
begin
FTotalHoras := Value;
end;
{ TEscalaFiltro }
procedure TEscalaFiltro.SetDataFinal(const Value: string);
begin
FDataFinal := Value;
end;
procedure TEscalaFiltro.SetDataInicial(const Value: string);
begin
FDataInicial := Value;
end;
procedure TEscalaFiltro.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TEscalaFiltro.SetIdUsuario(const Value: string);
begin
FIdUsuario := Value;
end;
end.
|
unit PassNewForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, m_GlobalDefs, m_api, PasswordEditControl;
type
TfmPassNew = class(TForm)
Label1: TLabel;
Label2: TLabel;
edPass: TPasswordEdit;
edConf: TPasswordEdit;
Label3: TLabel;
bnCancel: TButton;
bnOK: TButton;
Label4: TLabel;
Image1: TImage;
Label5: TLabel;
Bevel1: TBevel;
procedure bnCancelClick(Sender: TObject);
procedure bnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure TranslateForm;
{ Private declarations }
public
{ Public declarations }
end;
var
fmPassNew: TfmPassNew;
implementation
{$I m_langpack.inc}
{$R *.DFM}
procedure TfmPassNew.bnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfmPassNew.bnOKClick(Sender: TObject);
begin
if edPass.Text <> edConf.Text then begin
MessageBox(Handle, Translate('Password and Confirm fields should be similar'),
Translate('Error'), MB_OK or MB_DEFBUTTON1 or MB_ICONEXCLAMATION);
exit;
end;
ModalResult := mrOK;
end;
procedure TfmPassNew.TranslateForm;
begin
Caption := Translate(PChar(Caption));
Label1.Caption := Translate(PChar(Label1.Caption));
Label5.Caption := Translate(PChar(Label5.Caption));
Label2.Caption := Translate(PChar(Label2.Caption));
Label3.Caption := Translate(PChar(Label3.Caption));
Label4.Caption := Translate(PChar(Label4.Caption));
bnOK.Caption := Translate(PChar(bnOK.Caption));
bnCancel.Caption := Translate(PChar(bnCancel.Caption));
end;
procedure TfmPassNew.FormCreate(Sender: TObject);
begin
TranslateForm;
end;
end.
|
unit mungo.components.bgrabitmap.BGRACanvas;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
BGRACanvas, BGRABitmapTypes, BGRAGraphics,
mungo.components.renderer,
mungo.components.geometry,
p3d.math;
type
{ TRendererFillColorBGRA }
TRendererFillColorBGRA = class ( TRendererFillColor )
procedure SetupPenBrush( ACanvas: TObject );
procedure RenderPoints( ACanvas: TObject; Points: TVec2List ); override;
procedure RenderBezier( ACanvas: TObject; Points: TVec2List ); override;
procedure RenderCircle( ACanvas: TObject; Position: TVec2; Radius: Float ); override;
procedure RenderRectangle( ACanvas: TObject; TopLeft: TVec2; BottomRight:TVec2 ); override;
end;
{ TRendererStrokeColorBGRA }
TRendererStrokeColorBGRA = class ( TRendererStrokeColor )
procedure SetupPenBrush( ACanvas: TObject );
procedure RenderPoints( ACanvas: TObject; Points: TVec2List ); override;
procedure RenderBezier( ACanvas: TObject; Points: TVec2List ); override;
procedure RenderCircle( ACanvas: TObject; Position: TVec2; Radius: Float ); override;
procedure RenderRectangle( ACanvas: TObject; TopLeft: TVec2; BottomRight:TVec2 ); override;
end;
implementation
{ TRendererStrokeColorBGRA }
procedure TRendererStrokeColorBGRA.SetupPenBrush( ACanvas: TObject );
var
C: TBGRACanvas absolute ACanvas;
Cl: TIVec4;
begin
Cl:= ivec4( Color * 255 );
C.Brush.Style:= bsClear;
C.Pen.BGRAColor:= BGRA( Cl.r, Cl.g, Cl.b, Cl.a );
C.Pen.Style:= psSolid;
C.Pen.Width:= round( Density );
end;
procedure TRendererStrokeColorBGRA.RenderPoints( ACanvas: TObject;
Points: TVec2List );
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.Polygon( Points.PtrTo( 0 ), Points.Count );
end;
end;
procedure TRendererStrokeColorBGRA.RenderBezier(ACanvas: TObject;
Points: TVec2List);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.PolyBezier( Points.PtrTo( 0 ), Points.Count );
end;
end;
procedure TRendererStrokeColorBGRA.RenderCircle(ACanvas: TObject;
Position: TVec2; Radius: Float);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.EllipseC( round( Position.X ), round( Position.Y ), round( Radius ), round( Radius ));
end;
end;
procedure TRendererStrokeColorBGRA.RenderRectangle(ACanvas: TObject;
TopLeft: TVec2; BottomRight: TVec2);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.Rectangle( round( TopLeft.X ), round( TopLeft.Y ), round( BottomRight.X ), round( BottomRight.Y ));
end;
end;
{ TRendererFillColorBGRA }
procedure TRendererFillColorBGRA.SetupPenBrush(ACanvas: TObject);
var
C: TBGRACanvas absolute ACanvas;
Cl: TIVec4;
begin
Cl:= ivec4( Color * 255 );
C.Brush.Style:= bsSolid;
C.Brush.BGRAColor:= BGRA( Cl.r, Cl.g, Cl.b, Cl.a );
C.Pen.Style:= psClear;
end;
procedure TRendererFillColorBGRA.RenderPoints(ACanvas: TObject;
Points: TVec2List);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.Polygon( Points.PtrTo( 0 ), Points.Count );
end;
end;
procedure TRendererFillColorBGRA.RenderBezier(ACanvas: TObject;
Points: TVec2List);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.PolyBezier( Points.PtrTo( 0 ), Points.Count, True );
end;
end;
procedure TRendererFillColorBGRA.RenderCircle(ACanvas: TObject;
Position: TVec2; Radius: Float);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.EllipseC( round( Position.X ), round( Position.Y ), round( Radius ), round( Radius ));
end;
end;
procedure TRendererFillColorBGRA.RenderRectangle(ACanvas: TObject;
TopLeft: TVec2; BottomRight: TVec2);
var
C: TBGRACanvas absolute ACanvas;
begin
if ( ACanvas is TBGRACanvas ) then begin
SetupPenBrush( ACanvas );
C.Rectangle( round( TopLeft.X ), round( TopLeft.Y ), round( BottomRight.X ), round( BottomRight.Y ));
end;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.VisionML;
interface
uses
System.Classes, System.JSON, System.SysUtils, System.SyncObjs,
System.Net.HttpClient, System.Net.URLClient, System.Generics.Collections,
REST.Types,
FB4D.Interfaces, FB4D.Response, FB4D.Request, FB4D.VisionMLDefinition;
type
TVisionML = class(TInterfacedObject, IVisionML)
private
fProjectID: string;
fApiKey: string;
fServerRegion: string;
fAuth: IFirebaseAuthentication;
function BaseURL: string;
function GetFeaturesJSONArr(Features: TVisionMLFeatures;
MaxResults: integer; Model: TVisionModel): TJSONArray;
procedure OnGetResponse(const RequestID: string;
Response: IFirebaseResponse);
public
constructor Create(const ProjectID, ApiKey: string;
Auth: IFirebaseAuthentication = nil;
const ServerRegion: string = cRegionUSCent1);
function AnnotateFileSynchronous(const FileAsBase64,
ContentType: string; Features: TVisionMLFeatures;
MaxResultsPerFeature: integer = 50;
Model: TVisionModel = vmStable): IVisionMLResponse;
procedure AnnotateFile(const FileAsBase64,
ContentType: string; Features: TVisionMLFeatures;
OnAnnotate: TOnAnnotate; OnAnnotateError: TOnRequestError;
const RequestID: string = ''; MaxResultsPerFeature: integer = 50;
Model: TVisionModel = vmStable);
function AnnotateStorageSynchronous(const RefStorageCloudURI,
ContentType: string; Features: TVisionMLFeatures;
MaxResultsPerFeature: integer = 50;
Model: TVisionModel = vmStable): IVisionMLResponse;
procedure AnnotateStorage(const RefStorageCloudURI,
ContentType: string; Features: TVisionMLFeatures;
OnAnnotate: TOnAnnotate; OnAnnotateError: TOnRequestError;
MaxResultsPerFeature: integer = 50;
Model: TVisionModel = vmStable);
end;
TVisionMLResponse = class(TInterfacedObject, IVisionMLResponse)
private
fResp: TJSONObject;
fPages: TList<TJSONObject>;
function GetAnnotations(PageNo: integer;
const AnnotationName: string): TAnnotationList;
public
constructor Create(Response: IFirebaseResponse);
destructor Destroy; override;
function GetFormatedJSON: string;
function GetNoPages: integer;
function GetError(PageNo: integer = 0): TErrorStatus;
function GetPageAsFormatedJSON(PageNo: integer = 0): string;
function LabelAnnotations(PageNo: integer = 0): TAnnotationList;
function LandmarkAnnotations(PageNo: integer = 0): TAnnotationList;
function LogoAnnotations(PageNo: integer = 0): TAnnotationList;
function TextAnnotations(PageNo: integer = 0): TAnnotationList;
function FullTextAnnotations(PageNo: integer = 0): TTextAnnotation;
function ImagePropAnnotation(
PageNo: integer = 0): TImagePropertiesAnnotation;
function CropHintsAnnotation(PageNo: integer = 0): TCropHintsAnnotation;
function WebDetection(PageNo: integer = 0): TWebDetection;
function SafeSearchAnnotation(PageNo: integer = 0): TSafeSearchAnnotation;
function FaceAnnotation(PageNo: integer = 0): TFaceAnnotationList;
function LocalizedObjectAnnotation(
PageNo: integer = 0): TLocalizedObjectList;
function ProductSearchAnnotation(
PageNo: integer = 0): TProductSearchAnnotation;
function ImageAnnotationContext(
PageNo: integer = 0): TImageAnnotationContext;
end;
implementation
uses
REST.Json,
FB4D.Helpers;
{ TVisionML }
const
VISION_API = 'https://vision.googleapis.com/v1';
// VISION_API = 'https://vision.googleapis.com/v1p4beta1';
resourcestring
rsFunctionCall = 'Function call %s';
rsUnexpectedResult = 'Unexpected result received: %s';
function TVisionML.BaseURL: string;
begin
result := VISION_API;
end;
constructor TVisionML.Create(const ProjectID, ApiKey: string;
Auth: IFirebaseAuthentication; const ServerRegion: string);
begin
fProjectID := ProjectID;
fApiKey := ApiKey;
fServerRegion := ServerRegion;
fAuth := Auth;
end;
function TVisionML.GetFeaturesJSONArr(Features: TVisionMLFeatures;
MaxResults: integer; Model: TVisionModel): TJSONArray;
function FeatureAsStr(Feature: TVisionMLFeature): string;
begin
case Feature of
vmlUnspecific:
result := 'TYPE_UNSPECIFIED';
vmlFaceDetection:
result := 'FACE_DETECTION';
vmlLandmarkDetection:
result := 'LANDMARK_DETECTION';
vmlLogoDetection:
result := 'LOGO_DETECTION';
vmlLabelDetection:
result := 'LABEL_DETECTION';
vmlTextDetection:
result := 'TEXT_DETECTION';
vmlDocTextDetection:
result := 'DOCUMENT_TEXT_DETECTION';
vmlSafeSearchDetection:
result := 'SAFE_SEARCH_DETECTION';
vmlImageProperties:
result := 'IMAGE_PROPERTIES';
vmlCropHints:
result := 'CROP_HINTS';
vmlWebDetection:
result := 'WEB_DETECTION';
vmlProductSearch:
result := 'PRODUCT_SEARCH';
vmlObjectLocalization:
result := 'OBJECT_LOCALIZATION';
else
raise Exception.Create('Unknown feature ' + ord(Feature).ToString);
end;
end;
function ModelAsStr: string;
begin
case Model of
vmStable:
result := 'builtin/stable';
vmLatest:
result := 'builtin/latest';
else
result := '';
end;
end;
var
Feature: TVisionMLFeature;
begin
result := TJSONArray.Create;
for Feature in Features do
if Model = vmUnset then
result.Add(TJSONObject.Create
.AddPair(TJSONPair.Create('type', FeatureAsStr(Feature)))
.AddPair(TJSONPair.Create('maxResults', TJSONNumber.Create(MaxResults))))
else
result.Add(TJSONObject.Create
.AddPair(TJSONPair.Create('type', FeatureAsStr(Feature)))
.AddPair(TJSONPair.Create('maxResults', TJSONNumber.Create(MaxResults)))
.AddPair(TJSONPair.Create('model', ModelAsStr)));
end;
function TVisionML.AnnotateFileSynchronous(const FileAsBase64,
ContentType: string; Features: TVisionMLFeatures;
MaxResultsPerFeature: integer; Model: TVisionModel): IVisionMLResponse;
var
Params: TQueryParams;
Request: IFirebaseRequest;
Body: TJSONObject;
begin
Body := TJSONObject.Create;
Params := TQueryParams.Create;
try
Request := TFirebaseRequest.Create(BaseURL, 'Vision ML Annotate');
Body.AddPair('requests',
TJSONArray.Create(
TJSONObject.Create
.AddPair('inputConfig',
TJSONObject.Create
.AddPair('content', FileAsBase64)
.AddPair('mimeType', ContentType))
.AddPair('features',
GetFeaturesJSONArr(Features, MaxResultsPerFeature, Model))));
Params.Add('key', [fApiKey]);
result := TVisionMLResponse.Create(Request.SendRequestSynchronous(
['files:annotate'], rmPost, Body, Params, tmNoToken));
finally
Params.Free;
Body.Free;
end;
end;
procedure TVisionML.AnnotateFile(const FileAsBase64, ContentType: string;
Features: TVisionMLFeatures; OnAnnotate: TOnAnnotate;
OnAnnotateError: TOnRequestError; const RequestID: string;
MaxResultsPerFeature: integer; Model: TVisionModel);
var
Params: TQueryParams;
Request: IFirebaseRequest;
Body: TJSONObject;
begin
Body := TJSONObject.Create;
Params := TQueryParams.Create;
try
Request := TFirebaseRequest.Create(BaseURL, RequestID);
Body.AddPair('requests',
TJSONArray.Create(
TJSONObject.Create
.AddPair('inputConfig',
TJSONObject.Create
.AddPair('content', FileAsBase64)
.AddPair('mimeType', ContentType))
.AddPair('features',
GetFeaturesJSONArr(Features, MaxResultsPerFeature, Model))));
Params.Add('key', [fApiKey]);
Request.SendRequest(['files:annotate'], rmPost, Body, Params, tmNoToken,
OnGetResponse, OnAnnotateError, TOnSuccess.CreateVisionML(OnAnnotate));
finally
Params.Free;
Body.Free;
end;
end;
procedure TVisionML.OnGetResponse(const RequestID: string;
Response: IFirebaseResponse);
var
Res: IVisionMLResponse;
begin
try
Res := TVisionMLResponse.Create(Response);
if assigned(Response.OnSuccess.OnAnnotate) then
Response.OnSuccess.OnAnnotate(Res);
except
on e: Exception do
begin
if assigned(Response.OnError) then
Response.OnError(RequestID, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['VisionML.OnGetResponse', RequestID, e.Message]);
end;
end;
end;
function TVisionML.AnnotateStorageSynchronous(const RefStorageCloudURI,
ContentType: string; Features: TVisionMLFeatures;
MaxResultsPerFeature: integer; Model: TVisionModel): IVisionMLResponse;
var
Params: TQueryParams;
Request: IFirebaseRequest;
Body: TJSONObject;
begin
Body := TJSONObject.Create;
Params := TQueryParams.Create;
try
Request := TFirebaseRequest.Create(BaseURL, 'Vision ML Annotate');
Body.AddPair('requests',
TJSONArray.Create(
TJSONObject.Create
.AddPair('inputConfig',
TJSONObject.Create
.AddPair('gcsSource',
TJSONObject.Create(TJSONPair.Create('uri', RefStorageCloudURI)))
.AddPair('mimeType', ContentType))
.AddPair('features',
GetFeaturesJSONArr(Features, MaxResultsPerFeature, Model))));
Params.Add('key', [fApiKey]);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('Storage.annotate: ' + Body.ToJSON);
{$ENDIF}
result := TVisionMLResponse.Create(Request.SendRequestSynchronous(
['files:annotate'], rmPost, Body, Params, tmBearer));
finally
Params.Free;
Body.Free;
end;
end;
procedure TVisionML.AnnotateStorage(const RefStorageCloudURI,
ContentType: string; Features: TVisionMLFeatures; OnAnnotate: TOnAnnotate;
OnAnnotateError: TOnRequestError; MaxResultsPerFeature: integer;
Model: TVisionModel);
var
Params: TQueryParams;
Request: IFirebaseRequest;
Body: TJSONObject;
begin
Body := TJSONObject.Create;
Params := TQueryParams.Create;
try
Request := TFirebaseRequest.Create(BaseURL, RefStorageCloudURI);
Body.AddPair('requests',
TJSONArray.Create(
TJSONObject.Create
.AddPair('inputConfig',
TJSONObject.Create
.AddPair('gcsSource',
TJSONObject.Create(TJSONPair.Create('uri', RefStorageCloudURI)))
.AddPair('mimeType', ContentType))
.AddPair('features',
GetFeaturesJSONArr(Features, MaxResultsPerFeature, Model))));
Params.Add('key', [fApiKey]);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('Storage.annotate: ' + Body.ToJSON);
{$ENDIF}
Request.SendRequest(['files:annotate'], rmPost, Body, Params, tmNoToken,
OnGetResponse, OnAnnotateError, TOnSuccess.CreateVisionML(OnAnnotate));
finally
Params.Free;
Body.Free;
end;
end;
{ TVisionMLResponse }
constructor TVisionMLResponse.Create(Response: IFirebaseResponse);
var
Responses, Pages: TJSONArray;
MainResp: TJSONObject;
c: cardinal;
begin
fPages := TList<TJSONObject>.Create;
Response.CheckForJSONObj;
fResp := Response.GetContentAsJSONObj;
Responses := fResp.GetValue('responses') as TJSONArray;
if Responses.Count <> 1 then
raise EFirebaseResponse.CreateFmt(
'ML Vision does not return one object as expected, but %d',
[Responses.Count]);
MainResp := Responses.Items[0] as TJSONObject;
Pages := MainResp.GetValue('responses') as TJSONArray;
for c := 0 to Pages.Count - 1 do
fPages.Add(Pages.Items[c].AsType<TJSONObject>);
end;
destructor TVisionMLResponse.Destroy;
begin
fResp.Free;
fPages.Free;
inherited;
end;
function TVisionMLResponse.GetFormatedJSON: string;
begin
result := fResp.Format;
end;
function TVisionMLResponse.GetNoPages: integer;
begin
result := fPages.Count;
end;
function TVisionMLResponse.GetPageAsFormatedJSON(PageNo: integer): string;
begin
result := '';
if PageNo < fPages.Count then
result := fPages[PageNo].Format;
end;
function TVisionMLResponse.GetError(PageNo: integer): TErrorStatus;
var
Error: TJSONObject;
begin
result.Init;
if PageNo < fPages.Count then
if fPages[PageNo].TryGetValue<TJSONObject>('error', Error) then
result.SetFromJSON(Error);
end;
function TVisionMLResponse.GetAnnotations(PageNo: integer;
const AnnotationName: string): TAnnotationList;
var
L: TJSONArray;
c: cardinal;
begin
SetLength(result, 0);
if PageNo < fPages.Count then
begin
if fPages[PageNo].TryGetValue<TJSONArray>(AnnotationName, L) then
begin
SetLength(result, L.Count);
for c := 0 to L.Count - 1 do
result[c].SetFromJSON(L.Items[c] as TJSONObject);
end;
end;
end;
function TVisionMLResponse.LabelAnnotations(PageNo: integer): TAnnotationList;
begin
result := GetAnnotations(PageNo, 'labelAnnotations');
end;
function TVisionMLResponse.LandmarkAnnotations(PageNo: integer): TAnnotationList;
begin
result := GetAnnotations(PageNo, 'landmarkAnnotations');
end;
function TVisionMLResponse.LogoAnnotations(PageNo: integer): TAnnotationList;
begin
result := GetAnnotations(PageNo, 'logoAnnotations');
end;
function TVisionMLResponse.TextAnnotations(PageNo: integer): TAnnotationList;
begin
result := GetAnnotations(PageNo, 'textAnnotations');
end;
function TVisionMLResponse.FaceAnnotation(PageNo: integer): TFaceAnnotationList;
var
A: TJSONArray;
c: cardinal;
begin
SetLength(result, 0);
if (PageNo < fPages.Count) and fPages[PageNo].
TryGetValue<TJSONArray>('faceAnnotations', A) then
begin
SetLength(result, A.Count);
for c := 0 to A.Count - 1 do
result[c].SetFromJSON(A.Items[c] as TJSONObject);
end;
end;
function TVisionMLResponse.LocalizedObjectAnnotation(
PageNo: integer): TLocalizedObjectList;
var
A: TJSONArray;
c: cardinal;
begin
SetLength(result, 0);
if (PageNo < fPages.Count) and fPages[PageNo].
TryGetValue<TJSONArray>('localizedObjectAnnotations', A) then
begin
SetLength(result, A.Count);
for c := 0 to A.Count - 1 do
result[c].SetFromJSON(A.Items[c] as TJSONObject);
end;
end;
function TVisionMLResponse.FullTextAnnotations(PageNo: integer): TTextAnnotation;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('fullTextAnnotation', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.ImagePropAnnotation(
PageNo: integer): TImagePropertiesAnnotation;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and fPages[PageNo].TryGetValue<TJSONObject>(
'imagePropertiesAnnotation', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.CropHintsAnnotation(
PageNo: integer): TCropHintsAnnotation;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('cropHintsAnnotation', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.WebDetection(PageNo: integer): TWebDetection;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('webDetection', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.SafeSearchAnnotation(
PageNo: integer): TSafeSearchAnnotation;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('safeSearchAnnotation', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.ProductSearchAnnotation(
PageNo: integer): TProductSearchAnnotation;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('productSearchResults', O) then
result.SetFromJSON(O);
end;
function TVisionMLResponse.ImageAnnotationContext(
PageNo: integer): TImageAnnotationContext;
var
O: TJSONObject;
begin
result.Init;
if (PageNo < fPages.Count) and
fPages[PageNo].TryGetValue<TJSONObject>('context', O) then
result.SetFromJSON(O);
end;
end.
|
unit PessoaLive.Model.Endereco;
interface
uses
PessoaLive.Interfaces;
type
TEndereco<T : IInterface> = class(TInterfacedObject, iEndereco<T>)
private
[Weak]
FParent : T;
FRua : String;
public
constructor Create(Parent : T);
destructor Destroy; override;
class function New(Parent : T) : iEndereco<T>;
function Rua ( aValue : String ) : iEndereco<T>; overload;
function Rua : String; overload;
function &End : T;
end;
implementation
{ TEndereco<T> }
function TEndereco<T>.&End: T;
begin
Result := FParent;
end;
constructor TEndereco<T>.Create(Parent : T);
begin
FParent := Parent;
end;
destructor TEndereco<T>.Destroy;
begin
inherited;
end;
class function TEndereco<T>.New(Parent : T): iEndereco<T>;
begin
Result := Self.Create(Parent);
end;
function TEndereco<T>.Rua(aValue: String): iEndereco<T>;
begin
Result := Self;
FRua := aValue;
end;
function TEndereco<T>.Rua: String;
begin
Result := FRua;
end;
end.
|
unit Model.Item;
interface
uses
Model.Interfaces;
type
TModelItem = class(TInterfacedObject, iModelItem)
private
[weak]
FParent : iModelVenda;
FCodigo : Integer;
public
constructor Create(Parent : iModelVenda);
destructor Destroy; override;
class function New(Parent : iModelVenda) : iModelItem;
function Codigo(Value : Integer) : iModelItem;
function Vender : iModelItem;
function &End : iModelVenda;
end;
implementation
uses
Controller.Observer.Interfaces;
function TModelItem.Codigo(Value: Integer): iModelItem;
begin
Result := Self;
FCodigo := Value;
end;
function TModelItem.&End: iModelVenda;
begin
Result := FParent;
end;
constructor TModelItem.Create(Parent : iModelVenda);
begin
FParent := Parent;
end;
destructor TModelItem.Destroy;
begin
inherited;
end;
class function TModelItem.New (Parent : iModelVenda) : iModelItem;
begin
Result := Self.Create(Parent);
end;
function TModelItem.Vender: iModelItem;
var
RI : TRecordItem;
begin
Result := Self;
case FCodigo of
1 : RI.Descricao := 'Arroz Branco';
2 : RI.Descricao := 'Feij„o Preto';
3 : RI.Descricao := 'Macarr„o';
end;
FParent.ObserverItem.Notify(RI);
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-21
描述: 数据模块
*******************************************************************************}
unit UDataModule;
interface
uses
Windows, SysUtils, Classes, DBClient, DB, SyncObjs, FZSale_Intf,
uROClient, uROBinMessage, uRODiscovery, uROIndyUDPChannel,
uROBroadcastChannel, uRODiscovery_Intf, XPMan, cxEdit, cxLookAndFeels;
type
PDataSetItem = ^TDataSetItem;
TDataSetItem = record
FUsed: Boolean; //是否使用
FDS: TClientDataSet; //数据集
end;
TDataSetArray = array of TDataSetItem;
//数据集列表
TFDM = class(TDataModule)
ROChannel: TROBroadcastChannel;
ROClient: TRODiscoveryClient;
ROMsg: TROBinMessage;
XPMan1: TXPManifest;
EditStyle1: TcxDefaultEditStyleController;
cxLF1: TcxLookAndFeelController;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure ROClientNewServiceFound(aSender: TObject; aName: String;
aDiscoveryOptions: TRODiscoveryOptions);
private
{ Private declarations }
FDSArray: TDataSetArray;
//数据集
FLock: TCriticalSection;
//同步锁
FClearing: Boolean;
//正在清理
FServerURL: string;
//服务地址
protected
procedure ClearDataSet;
//清理资源
function GetDataSet: TDataSet;
//获取数据集
public
{ Public declarations }
function FindServer: Boolean;
//定位服务
function LockDataSet(const nSQL: string; var nHint: string): TDataSet;
procedure ReleaseDataSet(const nDS: TDataSet);
//数据查询
function SQLExecute(const nSQL: string; var nHint: string): Integer; overload;
function SQLExecute(const nSQL: SQLItem; var nHint: string): Integer; overload;
//数据执行
function SQLUpdates(const nSQLList: SQLItems; const nAtomic: Boolean;
var nHint: string): Integer;
//批量执行
function SignIn(const nUser, nPwd: string; var nHint: string): Boolean;
//登录系统
end;
var
FDM: TFDM;
implementation
{$R *.dfm}
uses
Forms, ULibFun, UMgrChannel, uROBinaryHelpers, uROTypes, USysService,
USysConst;
procedure TFDM.DataModuleCreate(Sender: TObject);
begin
FClearing := False;
SetLength(FDSArray, 0);
FLock := TCriticalSection.Create;
end;
procedure TFDM.DataModuleDestroy(Sender: TObject);
begin
ClearDataSet;
FLock.Free;
inherited;
end;
procedure TFDM.ClearDataSet;
var nIdx: Integer;
begin
FLock.Enter;
try
FClearing := True;
for nIdx:=Low(FDSArray) to High(FDSArray) do
with FDSArray[nIdx] do
begin
if FUsed then
try
FLock.Leave;
while FUsed do Sleep(1);
finally
FLock.Enter;
end;
if Assigned(FDS) then FreeAndNil(FDS);
end;
SetLength(FDSArray, 0);
finally
FClearing := False;
FLock.Leave;
end;
end;
//Desc: 获取可用数据集
function TFDM.GetDataSet: TDataSet;
var nIdx: Integer;
begin
FLock.Enter;
try
Result := nil;
if FClearing then Exit;
for nIdx:=Low(FDSArray) to High(FDSArray) do
with FDSArray[nIdx] do
if not FUsed then
begin
FUsed := True;
Result := FDS; Exit;
end;
nIdx := Length(FDSArray);
SetLength(FDSArray, nIdx+1);
with FDSArray[nIdx] do
begin
FUsed := True;
FDS := TClientDataSet.Create(Self);
Result := FDS;
end;
finally
FLock.Leave;
end;
end;
//Desc: 查询数据并锁定数据集
function TFDM.LockDataSet(const nSQL: string; var nHint: string): TDataSet;
var nData: Binary;
nRes: SrvResult;
nChannel: PChannelItem;
begin
Result := nil;
nRes := nil;
nData := nil;
nChannel := gChannelManager.LockChannel(cChannel_DB);
try
if not Assigned(nChannel) then
begin
nHint := '无可用数据通道'; Exit;
end;
with nChannel^ do
begin
if not Assigned(FChannel) then
FChannel := CoSrvDB.Create(FMsg, FHttp);
//xxxxx
FHttp.TargetURL := gSysParam.FRemoteURL;
nRes := ISrvDB(FChannel).SQLQuery('', '', nSQL, nData);
//执行远程查询
if not Assigned(nRes) then
begin
nHint := '远程查询执行失败'; Exit;
end;
if not nRes.Re_sult then
begin
nHint := nRes.DataStr; Exit;
end;
if Assigned(nData) then
begin
Result := GetDataSet;
if not Assigned(Result) then
begin
nHint := '无可用的数据集'; Exit;
end;
TClientDataSet(Result).Data := VariantFromBinary(nData);
//数据有效
end;
end;
finally
nRes.Free;
nData.Free;
gChannelManager.ReleaseChannel(nChannel);
end;
end;
//Desc: 解锁指定数据集
procedure TFDM.ReleaseDataSet(const nDS: TDataSet);
var nIdx: Integer;
begin
if Assigned(nDS) then
begin
FLock.Enter;
try
for nIdx:=Low(FDSArray) to High(FDSArray) do
if FDSArray[nIdx].FDS = nDS then
begin
FDSArray[nIdx].FUsed := False;
Break;
end;
finally
FLock.Leave;
end;
end;
end;
//Desc: 执行写操作
function TFDM.SQLExecute(const nSQL: string; var nHint: string): Integer;
var nItem: SQLItem;
begin
nItem := SQLItem.Create;
try
nItem.SQL := nSQL;
Result := SQLExecute(nItem, nHint);
finally
//nItem.Free;
end;
end;
function TFDM.SQLExecute(const nSQL: SQLItem; var nHint: string): Integer;
var nRes: SrvResult;
nChannel: PChannelItem;
begin
Result := -1;
nRes := nil;
nChannel := gChannelManager.LockChannel(cChannel_DB);
try
if not Assigned(nChannel) then
begin
nHint := '无可用数据通道'; Exit;
end;
with nChannel^ do
begin
if not Assigned(FChannel) then
FChannel := CoSrvDB.Create(FMsg, FHttp);
//xxxxx
FHttp.TargetURL := gSysParam.FRemoteURL;
nRes := ISrvDB(FChannel).SQLExecute('', '', nSQL);
//执行远程操作
if not Assigned(nRes) then
begin
nHint := '远程操作失败'; Exit;
end;
if nRes.Re_sult then
Result := nRes.DataInt;
nHint := nRes.DataStr;
end;
finally
nRes.Free;
gChannelManager.ReleaseChannel(nChannel);
end;
end;
function TFDM.SQLUpdates(const nSQLList: SQLItems; const nAtomic: Boolean;
var nHint: string): Integer;
var nRes: SrvResult;
nChannel: PChannelItem;
begin
Result := -1;
nRes := nil;
nChannel := gChannelManager.LockChannel(cChannel_DB);
try
if not Assigned(nChannel) then
begin
nHint := '无可用数据通道'; Exit;
end;
with nChannel^ do
begin
if not Assigned(FChannel) then
FChannel := CoSrvDB.Create(FMsg, FHttp);
//xxxxx
FHttp.TargetURL := gSysParam.FRemoteURL;
nRes := ISrvDB(FChannel).SQLUpdates('', '', nSQLList, nAtomic);
//执行远程操作
if not Assigned(nRes) then
begin
nHint := '远程操作失败'; Exit;
end;
if nRes.Re_sult then
Result := nRes.DataInt;
nHint := nRes.DataStr;
end;
finally
nRes.Free;
gChannelManager.ReleaseChannel(nChannel);
end;
end;
//Desc: 用户登录
function TFDM.SignIn(const nUser, nPwd: string; var nHint: string): Boolean;
var nRes: SrvResult;
nChannel: PChannelItem;
begin
Result := False;
nRes := nil;
nChannel := gChannelManager.LockChannel(cChannel_Conn);
try
if not Assigned(nChannel) then
begin
nHint := '无可用数据通道'; Exit;
end;
with nChannel^ do
begin
if not Assigned(FChannel) then
FChannel := CoSrvConn.Create(FMsg, FHttp);
//xxxxx
FHttp.TargetURL := gSysParam.FRemoteURL;
nRes := ISrvConn(FChannel).SignIn('', '', '', nUser, nPwd, '', '');
//执行远程操作
if not Assigned(nRes) then
begin
nHint := '远程操作失败'; Exit;
end;
Result := nRes.Re_sult;
nHint := nRes.DataStr;
if not Result then Exit;
with gSysParam do
begin
FUserID := nUser;
FUserPwd := nPwd;
FIsAdmin := nRes.DataInt = cLevel_Master;
end;
FreeAndNil(nRes);
nRes := ISrvConn(FChannel).SweetHeart;
gSysParam.FTerminalID := nRes.DataStr;
end;
finally
nRes.Free;
gChannelManager.ReleaseChannel(nChannel);
end;
end;
//Desc: 定位服务地址
function TFDM.FindServer: Boolean;
var nInt: Integer;
begin
Result := False;
nInt := 0;
FServerURL := '';
ROClient.ServiceName := cService_Conn;
ROClient.RefreshServerList();
while true do
begin
Inc(nInt);
if nInt > 5 * 500 then Break;
Application.ProcessMessages;
Sleep(2);
if FServerURL <> '' then
begin
gSysParam.FRemoteURL := FServerURL;
Result := True; Break;
end;
end;
end;
//------------------------------------------------------------------------------
type
TMyDiscoveryResultOptions = class(TRODiscoveryOptions)
private
FPath: string;
published
property Path: string read FPath write FPath;
end;
//Desc: 找到服务地址
procedure TFDM.ROClientNewServiceFound(aSender: TObject; aName: String;
aDiscoveryOptions: TRODiscoveryOptions);
var nOpt: TMyDiscoveryResultOptions;
begin
if Assigned(aDiscoveryOptions) and (aDiscoveryOptions is TMyDiscoveryResultOptions) then
begin
nOpt := aDiscoveryOptions as TMyDiscoveryResultOptions;
FServerURL := Format('http://%s%s', [aName, nOpt.Path]);
end;
end;
initialization
RegisterROClass(TMyDiscoveryResultOptions);
finalization
UnregisterROClass(TMyDiscoveryResultOptions);
end.
|
unit ResFichas;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ToolWin, ComCtrls, StdActns, ActnList, ImgList, Menus, ExtCtrls, Grids,
Db, DBTables;
type
TFResFichas = class(TForm)
Panel1: TPanel;
StatusBar1: TStatusBar;
MainMenu1: TMainMenu;
Ventana1: TMenuItem;
Ayuda1: TMenuItem;
ImageList1: TImageList;
ActionList1: TActionList;
Salir: TAction;
Imprimir: TAction;
EditCopy1: TEditCopy;
EditCut1: TEditCut;
EditPaste1: TEditPaste;
Ayuda: TAction;
Fin1: TMenuItem;
Ayuda2: TMenuItem;
CoolBar1: TCoolBar;
DecisionCube1: TDecisionCube;
QRes: TDecisionQuery;
DecisionSource1: TDecisionSource;
DecisionPivot1: TDecisionPivot;
DecisionGrid1: TDecisionGrid;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure EnHint( Sender: TObject );
end;
var
FResFichas: TFResFichas;
implementation
{$R *.DFM}
procedure TFResFichas.EnHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
procedure TFResFichas.FormActivate(Sender: TObject);
begin
Application.OnHint := EnHint;
end;
procedure TFResFichas.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.OnHint := nil;
end;
procedure TFResFichas.FormCreate(Sender: TObject);
begin
QRes.Open;
end;
end.
|
unit ModPatternMatchingUnsharp;
interface
procedure BruteForcePos(s, p : string;
var lsTemp, rsTemp, lpTemp, rpTemp : integer
);
procedure WriteAndResetStats;
implementation
var numComp : longint;
function Eq(a,b : char) : boolean;
begin
inc(numComp);
Eq := (a = b);
end;
procedure WriteAndResetStats;
begin
writeLn('Number of comparisons: ', numComp);
numComp := 0;
end;
procedure BruteForcePos(s, p : string;
var lsTemp, rsTemp, lpTemp, rpTemp : integer
);
var
i : integer;
pLen, sLen : integer;
curLength, longestLength : integer;
begin
pLen := Length(p);
sLen := Length(s);
i := 0;
curLength := 0;
longestLength := 0;
for i := 1 to sLen do begin
if slen - i < longestLength then// remaining text to match is already shorter than longest length
break;
if Eq(s[i],p[1]) then begin
curLength := 1;
while Eq(s[i+curLength],p[curLength+1]) and (curLength <= pLen) do begin
inc(curLength);
end;
if curLength > longestLength then begin
lsTemp := i;
rsTemp := i + curLength - 1;
lpTemp := 1;
rpTemp := curLength;
longestLength := rsTemp - lsTemp + 1;
end;
curLength := 0;
end;
end;
end;
begin
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerSequenceGenerator;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
ClpCryptoLibTypes,
ClpAsn1Tags,
ClpDerOutputStream,
ClpDerGenerator,
ClpIProxiedInterface,
ClpIDerSequenceGenerator;
type
TDerSequenceGenerator = class(TDerGenerator, IDerSequenceGenerator)
strict private
var
F_bOut: TMemoryStream;
public
constructor Create(outStream: TStream); overload;
constructor Create(outStream: TStream; tagNo: Int32;
isExplicit: Boolean); overload;
destructor Destroy(); override;
procedure AddObject(const obj: IAsn1Encodable); override;
function GetRawOutputStream(): TStream; override;
procedure Close(); override;
end;
implementation
{ TDerSequenceGenerator }
procedure TDerSequenceGenerator.AddObject(const obj: IAsn1Encodable);
var
temp: TDerOutputStream;
begin
temp := TDerOutputStream.Create(F_bOut);
try
temp.WriteObject(obj);
finally
temp.Free;
end;
end;
procedure TDerSequenceGenerator.Close;
var
temp: TCryptoLibByteArray;
begin
F_bOut.Position := 0;
System.SetLength(temp, F_bOut.Size);
F_bOut.Read(temp[0], F_bOut.Size);
WriteDerEncoded(TAsn1Tags.Constructed or TAsn1Tags.Sequence, temp);
end;
constructor TDerSequenceGenerator.Create(outStream: TStream);
begin
Inherited Create(outStream);
F_bOut := TMemoryStream.Create();
end;
constructor TDerSequenceGenerator.Create(outStream: TStream; tagNo: Int32;
isExplicit: Boolean);
begin
Inherited Create(outStream, tagNo, isExplicit);
F_bOut := TMemoryStream.Create();
end;
destructor TDerSequenceGenerator.Destroy;
begin
F_bOut.Free;
inherited Destroy;
end;
function TDerSequenceGenerator.GetRawOutputStream: TStream;
begin
result := F_bOut;
end;
end.
|
unit AdvMenus;
{ $Id: AdvMenus.pas,v 1.7 2004/05/11 07:40:03 voba Exp $ }
// $Log: AdvMenus.pas,v $
// Revision 1.7 2004/05/11 07:40:03 voba
// no message
//
// Revision 1.6 2001/04/05 08:52:17 law
// - cleanup: использование модулей WinTypes и WinProcs заменен на Windows.
//
// Revision 1.5 2001/02/20 13:22:13 voba
// no message
//
// Revision 1.4 2001/01/17 11:58:20 voba
// no message
//
// Revision 1.3 2000/12/15 15:36:28 law
// - вставлены директивы Log.
//
interface
uses Forms, Windows, SysUtils, Menus, Classes, Messages;
type
EMenuError = class(Exception);
TSystemMenuItem = class(TComponent)
private
FAdded: Boolean;
FParentHandle: HMENU;
FPosInParent: Integer;
FBreak: TMenuBreak;
FPopUp,
FChecked,
FEnabled: Boolean;
FItems: TList;
FCaption: string;
FHandle: HMENU;
FOnClick: TNotifyEvent;
function AppendTo(Menu: HMENU; Position: Word): Boolean;
procedure RedrawItem;
procedure SetBreak(Value: TMenuBreak);
procedure SetCaption(Value: string);
procedure SetChecked(Value: Boolean);
procedure SetEnabled(Value: Boolean);
procedure SetSubMenu(Value: Boolean);
{function HandleExists(Menu: HMENU): Boolean;}
function ItemExists(AItem: TSystemMenuItem): Boolean;
protected
function GetHandle: HMENU; virtual;
function GetItem(Index: Integer): TSystemMenuItem;
function GetCount: Integer;
procedure Click(Sender: TObject); virtual;
function GetItemFromHandle(Menu: HMenu): TSystemMenuItem;
public
procedure Add(AItem: TSystemMenuItem; Position: Word);
procedure Remove(AItem: TSystemMenuItem);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Items[Index: Integer]: TSystemMenuItem read GetItem; default;
property Handle: HMenu read GetHandle;
property Count: Integer read GetCount;
published
property Break: TMenuBreak read FBreak write SetBreak default mbNone;
property Caption: string read FCaption write SetCaption;
property Checked: Boolean read FChecked write SetChecked default False;
property Enabled: Boolean read FEnabled write SetEnabled default True;
property IsSubMenu: Boolean read FPopUp write SetSubMenu;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
end;
TSystemMenu = class(TComponent)
private
FAutoHandled: Boolean;
{FHandle: HMenu;}
FItems: TSystemMenuItem;
FWindowHandle: HWND;
procedure SetWindowHandle(Value: HWND);
procedure SetAutoHandled(Value: Boolean);
protected
function GetHandle: HMenu; virtual;
procedure ClearHandles(AItem: TSystemMenuItem);
public
property Items: TSystemMenuItem read FItems write FItems;
property WindowHandle: HWND read FWindowHandle write SetWindowHandle;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure HandleEvents(Msg: TMsg; FirstItem: TSystemMenuItem); virtual;
procedure ClearAll;
procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
published
property AutoHandled: Boolean read FAutoHandled write SetAutoHandled;
end;
function SystemMenuItemToMenuItem(AItem: TSystemMenuItem): TMenuItem;
function MenuItemToSystemMenuItem(AItem: TMenuItem): TSystemMenuItem;
Type
TLinkPopUpMenu = class(TPopUpMenu)
private
FPrimaryPopUpMenu : TPopUpMenu;
FPrimaryMenuItem : TMenuItem;
FActive: Boolean;
FOnAppend: TNotifyEvent;
FOnRemove: TNotifyEvent;
Inserted: TList;
Done: Boolean;
function CopyMenu(src: TMenuItem) : TMenuItem;
Procedure SetActive(Value : Boolean);
Procedure SetPrimaryPopUpMenu(Value : TPopUpMenu);
protected
procedure DoPopup(Item: TObject); reintroduce;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure AddPopup;
procedure Popup(X, Y: Integer); override;
property PrimaryMenuItem : TMenuItem read FPrimaryMenuItem write FPrimaryMenuItem;
published
Property PrimaryPopUpMenu : TPopUpMenu Read FPrimaryPopUpMenu Write SetPrimaryPopUpMenu;
property Active: Boolean read FActive write SetActive;
property OnAppend: TNotifyEvent read FOnAppend write FOnAppend;
property OnRemove: TNotifyEvent read FOnRemove write FOnRemove;
end;
procedure Register;
implementation
{var
HSystemMenu: HMENU;}
Uses ImgList;
Type
{$HINTS OFF}
THackMenuItem = class(TComponent)
{$IfDef VER130}
private
FCaption: string;
FHandle: HMENU;
FChecked: Boolean;
FEnabled: Boolean;
FDefault: Boolean;
FAutoHotkeys: TMenuItemAutoFlag;
FAutoLineReduction: TMenuItemAutoFlag;
FRadioItem: Boolean;
FVisible: Boolean;
FGroupIndex: Byte;
FImageIndex: TImageIndex;
FActionLink: TMenuActionLink;
FBreak: TMenuBreak;
FBitmap: TBitmap;
FCommand: Word;
FHelpContext: THelpContext;
FHint: string;
FItems: TList;
FShortCut: TShortCut;
FParent: TMenuItem;
end;
{$else}
private
FBreak: TMenuBreak;
FCaption: PString;
FChecked: Boolean;
FEnabled: Boolean;
FHandle: HMENU;
FHelpContext: THelpContext;
FHint: PString;
FItems: TList;
FShortCut: TShortCut;
FVisible: Boolean;
FGroupIndex: Byte;
FOnChange: TMenuChangeEvent;
FOnClick: TNotifyEvent;
FCommand: Word;
FParent: TMenuItem;
FMerged: TMenuItem;
end;
{$endif}
{$HINTS ON}
function SystemMenuItemToMenuItem(AItem: TSystemMenuItem): TMenuItem;
begin
Result := TMenuItem.Create(Application);
Result.Caption := AItem.Caption;
Result.Enabled := AItem.Enabled;
Result.Checked := AItem.Checked;
Result.Break := AItem.Break;
Result.OnClick := AItem.OnClick;
end;
function MenuItemToSystemMenuItem(AItem: TMenuItem): TSystemMenuItem;
begin
Result := TSystemMenuItem.Create(Application);
Result.Caption := AItem.Caption;
Result.Enabled := AItem.Enabled;
Result.Checked := AItem.Checked;
Result.Break := AItem.Break;
Result.OnClick := AItem.OnClick;
end;
{TSystemMenuItem}
constructor TSystemMenuItem.Create(AOwner: TComponent);
begin
FEnabled := True;
FBreak := mbNone;
FPopUp := False;
FCaption := '';
FAdded := False;
inherited Create(AOwner);
end;
destructor TSystemMenuItem.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
procedure TSystemMenuItem.Click(Sender: TObject);
begin
if Assigned(FOnClick) then FOnClick(Self);
end;
function TSystemMenuItem.GetHandle: HMenu;
begin
if FHandle = 0 then FHandle := CreateMenu;
Result := FHandle;
end;
function TSystemMenuItem.AppendTo(Menu: HMenu; Position: Word): Boolean;
const
Breaks: array[TMenuBreak] of Longint = (0, MF_MENUBREAK, MF_MENUBARBREAK);
Checks: array[Boolean] of LongInt = (MF_UNCHECKED, MF_CHECKED);
Enables: array[Boolean] of LongInt = (MF_DISABLED or MF_GRAYED, MF_ENABLED);
PopUps: array[Boolean] of LongInt = (0, MF_POPUP);
Separators: array[Boolean] of LongInt = (MF_STRING, MF_SEPARATOR);
var
NewFlags: Word;
CCaption: array [0..255] of Char;
begin
NewFlags := Breaks[FBreak] or Checks[FChecked] or Enables[FEnabled]
or PopUps[FPopUp] or Separators[FCaption = '-'] or MF_BYPOSITION;
StrPCopy(CCaption, FCaption);
Result := InsertMenu(Menu, Position, NewFlags, GetHandle, CCaption);
FPosInParent := Position;
FParentHandle := Menu;
FAdded := True;
end;
procedure TSystemMenuItem.Add(AItem: TSystemMenuItem; Position: Word);
begin
if ItemExists(AItem) then
begin
raise EMenuError.Create('Menu inserted twice');
exit;
end;
if not AItem.AppendTo(Handle, Position) then
begin
raise EMenuError.Create('Unable insert menu item');
exit;
end;
if FItems = nil then
FItems := TList.Create;
FItems.Insert(Position, AItem);
end;
procedure TSystemMenuItem.Remove(AItem: TSystemMenuItem);
begin
DeleteMenu(AItem.FParentHandle, AItem.FPosInParent, MF_BYPOSITION);
FItems.Remove(AItem);
if FItems.Count = 0 then IsSubMenu := False;
AItem.Free;
end;
function TSystemMenuItem.GetItem(Index: Integer): TSystemMenuItem;
begin
if FItems = nil
then Result := nil
else Result := FItems[Index];
end;
function TSystemMenuItem.GetCount: Integer;
begin
if FItems = nil then Result := 0
else Result := FItems.Count;
end;
procedure TSystemMenuItem.RedrawItem;
const
Breaks: array[TMenuBreak] of Longint = (0, MF_MENUBREAK, MF_MENUBARBREAK);
Checks: array[Boolean] of LongInt = (MF_UNCHECKED, MF_CHECKED);
Enables: array[Boolean] of LongInt = (MF_DISABLED or MF_GRAYED, MF_ENABLED);
PopUps: array[Boolean] of LongInt = (0, MF_POPUP);
Separators: array[Boolean] of LongInt = (MF_STRING, MF_SEPARATOR);
var
NewFlags: Word;
{Item: TSystemMenuItem;}
CCaption: array [0..255] of Char;
begin
NewFlags := Breaks[FBreak] or Checks[FChecked] or Enables[FEnabled]
or PopUps[FPopUp] or Separators[FCaption = '-'] or MF_BYPOSITION;
StrPCopy(CCaption, FCaption);
if not ModifyMenu(FParentHandle, FPosInParent, NewFlags, FHandle, CCaption)
then raise EMenuError.Create('Error modifing menu');
end;
procedure TSystemMenuItem.SetBreak(Value: TMenuBreak);
begin
if FBreak <> Value then
begin
FBreak := Value;
if FAdded then RedrawItem;
end;
end;
procedure TSystemMenuItem.SetCaption(Value: string);
begin
if FCaption <> Value then
begin
FCaption := Value;
if FAdded then RedrawItem;
end;
end;
procedure TSystemMenuItem.SetChecked(Value: Boolean);
begin
if FChecked <> Value then
begin
FChecked := Value;
if FAdded then RedrawItem;
end;
end;
procedure TSystemMenuItem.SetEnabled(Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
if FAdded then RedrawItem;
end;
end;
procedure TSystemMenuItem.SetSubMenu(Value: Boolean);
begin
if FPopUp <> Value then
begin
FPopUp := Value;
if FAdded then RedrawItem;
end;
end;
{function TSystemMenuItem.HandleExists(Menu: HMenu): Boolean;
var
i: integer;
AItem: TSystemMenuItem;
begin
if FItems = nil then
begin
Result := False;
exit;
end else
for i := 0 to FItems.Count - 1 do
begin
AItem := FItems[i];
if (Menu = AItem.FHandle) then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
}
function TSystemMenuItem.ItemExists(AItem: TSystemMenuItem): Boolean;
var
i: integer;
begin
if FItems = nil then
begin
Result := False;
exit;
end else
for i := 0 to FItems.Count - 1 do
begin
if AItem = FItems[i] then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
function TSystemMenuItem.GetItemFromHandle(Menu: HMenu): TSystemMenuItem;
var
i: integer;
AItem: TSystemMenuItem;
begin
if FItems = nil then
begin
Result := nil;
exit;
end else
for i := 0 to FItems.Count - 1 do
begin
AItem := FItems[i];
if Menu = AItem.FHandle then
begin
Result := AItem;
exit;
end;
end;
Result := nil;
end;
{TSystemMenu}
constructor TSystemMenu.Create(AOwner: TComponent);
begin
inherited Create(aOwner);
FItems := TSystemMenuItem.Create(Self);
FAutoHandled := True;
end;
destructor TSystemMenu.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
function TSystemMenu.GetHandle: HMenu;
begin
Result := FItems.GetHandle;
end;
procedure TSystemMenu.HandleEvents(Msg: TMsg; FirstItem: TSystemMenuItem);
var
i: integer;
begin
if not Assigned(FirstItem)
then FirstItem := Items;
if not Assigned(FirstItem)
then exit;
for i := 0 to FirstItem.Count - 1 do
begin
if FirstItem.Items[i].Handle = LongWord(Msg.WParam)
then FirstItem.Items[i].OnClick(Self);
HandleEvents(Msg, FirstItem.Items[i]);
end;
end;
procedure TSystemMenu.ClearAll;
begin
GetSystemMenu(Application.MainForm.Handle, True);
ClearHandles(FItems);
FItems.Free;
FItems := TSystemMenuItem.Create(Self);
end;
procedure TSystemMenu.SetAutoHandled(Value: Boolean);
begin
if FAutoHandled <> Value then FAutoHandled := Value;
if FAutoHandled then Application.OnMessage := AppMessage
else Application.OnMessage := nil;
end;
procedure TSystemMenu.AppMessage(var Msg: TMsg; var Handled: Boolean);
begin
HandleEvents(Msg, nil);
end;
procedure TSystemMenu.ClearHandles(AItem: TSystemMenuItem);
var
i: integer;
begin
for i := 0 to AItem.Count - 1 do
begin
AItem[i].FHandle := 0;
ClearHandles(AItem[i]);
end;
end;
procedure TSystemMenu.SetWindowHandle(Value: HWND);
begin
FWindowHandle := Value;
FItems.FHandle := GetSystemMenu(FWindowHandle, False);
end;
{TLinkPopUpMenu}
function TLinkPopUpMenu.CopyMenu(src: TMenuItem) : TMenuItem;
// Var
// NSM : TMenuItem;
// i: Integer;
Begin
{NSM := NewItem(src.Caption, src.ShortCut, src.Checked,
src.Enabled, src.OnClick, src.HelpContext,
src.Name + 'Item');
If src.Count <> 0 then
For i := 0 to src.Count - 1 do
NSM.Add(CopyMenu(src.Items[i]));
Result := NSM;}
Result:=Src;
Inserted.Add(Result);
end;
Procedure TLinkPopUpMenu.SetActive(Value : Boolean);
Begin
If FActive = Value then exit;
FActive:=Value;
AddPopup;
end;
Procedure TLinkPopUpMenu.SetPrimaryPopUpMenu(Value : TPopUpMenu);
Begin
If FPrimaryPopUpMenu = Value then exit;
FPrimaryPopUpMenu := Value;
If FPrimaryMenuItem = Nil then
FPrimaryMenuItem := FPrimaryPopUpMenu.Items;
AddPopup;
end;
procedure TLinkPopUpMenu.DoPopup(Item: TObject);
var
lOnPopup: TNotifyEvent;
begin
lOnPopup := OnPopUp;
if Assigned(lOnPopup) then lOnPopup(Item);
end;
procedure TLinkPopUpMenu.Popup(X, Y: Integer);
Var
SaveActive : Boolean;
Begin
SaveActive := Active;
Active := True;
DoPopup(Self);
if FPrimaryPopUpMenu = Nil then
inherited Popup(X, Y)
else
begin
FPrimaryPopUpMenu.PopupComponent:=PopupComponent;
FPrimaryPopUpMenu.Popup(X, Y);
end;
Active := SaveActive;
end;
constructor TLinkPopUpMenu.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
Inserted := TList.Create;
Done := False;
end;
destructor TLinkPopUpMenu.Destroy;
begin
Inserted.Free;
inherited Destroy;
end;
procedure TLinkPopUpMenu.AddPopup;
var
i, k: Integer;
mi_x, mi_y: TMenuItem;
begin
{inherited Popup(X, Y);}
if Assigned(FPrimaryMenuItem) then
begin
if fActive then
begin
if Assigned(FOnAppend) then FOnAppend(Self);
if not Done then
begin
for i := 0 to Items.Count - 1 do
{FPrimaryMenuItem.Add(CopyMenu(Items[i]));}
FPrimaryMenuItem.Insert(i,CopyMenu(Items[i]));
Done := True;
end;
end
else
begin
///if Assigned(FPrimaryMenuItem)then
/// begin
if Assigned(FOnRemove) then FOnRemove(Self);
for i := FPrimaryMenuItem.Count - 1 downto 0 do
begin
mi_x := FPrimaryMenuItem.Items[i];
for k := Inserted.Count - 1 downto 0 do
begin
mi_y := Inserted.Items[k];
if mi_x = mi_y
then
Begin
FPrimaryMenuItem.Remove(mi_x {FPrimaryMenuItem.Items[i]});
THackMenuItem(mi_x).FParent := Items;
Inserted.Delete(k);
end;
end;
end;
Done := False;
///end;
end;
end;
end;
procedure Register;
begin
RegisterComponents('Custom', [TLinkPopUpMenu]);
RegisterComponents('Custom', [TSystemMenuItem]);
RegisterComponents('Custom', [TSystemMenu]);
end;
end.
|
unit fmFloatingWindow;
interface
uses
System.Classes, Vcl.Forms, Winapi.Windows, System.SysUtils, Winapi.Messages,
Vcl.Graphics, Vcl.StdCtrls, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, System.DateUtils,
Variants, Vcl.ComCtrls, Vcl.Imaging.jpeg, System.ImageList, Vcl.ImgList, ActiveDs_TLB,
Winapi.CommCtrl, Winapi.ActiveX, ADCmdUCMA_TLB, ADC.UCMAEvents, System.Win.ComObj,
System.StrUtils, ADC.ADObject, ADC.Common, ADC.ImgProcessor, ADC.UserEdit, ADC.GlobalVar,
ADC.Types, ADC.AD;
const
WM_FWND_THREAD = WM_USER + 1;
STATUS_TEXT_UNKNOWN = 'Состояние присутствия неизвестно';
STATUS_TEXT_UPDATING = 'Идет обновление...';
STATUS_IMAGE_UNKNOWN = 0;
STATUS_IMAGE_ONLINE = 1;
STATUS_IMAGE_IDLE = 2;
STATUS_IMAGE_BUSY = 3;
STATUS_IMAGE_DO_NOT_DISTURB = 4;
type
PContactActivity = ^TContactActivity;
TContactActivity = record
_Handle: THandle;
_Contact: IUCMAContact;
end;
type
PContactInfo = ^TContactInfo;
TContactInfo = record
_Handle: THandle;
_DistingushedName: string;
DisplayName: string;
Info1: string;
Info2: string;
Image: TImgByteArray;
end;
type
TForm_FloatingWindow = class(TForm)
PaintBox_Background: TPaintBox;
Image_Status: TImage;
Image_Contact: TImage;
Label_Name: TLabel;
Label_Info1: TLabel;
Label_Info2: TLabel;
ImageList_Status_Classic: TImageList;
ImageList_Status_Modern: TImageList;
ImageList_Contact: TImageList;
Timer_Display: TTimer;
Timer_StatusRefresh: TTimer;
procedure PaintBox_BackgroundPaint(Sender: TObject);
procedure Timer_DisplayTimer(Sender: TObject);
procedure Timer_StatusRefreshTimer(Sender: TObject);
strict private
const FFormPadding = 9;
const TIMER_MODE_DISPLAY_DELAY = 0;
const TIMER_MODE_DISPLAY_DURATION = 1;
protected
procedure WndProc(var Message: TMessage); override;
procedure VisibleChanging; override;
private
FOwner: TForm;
FDisplayStyle: TFloatingWindowStyle;
FListView: TListView;
FObj: TADObject;
FContact: IUCMAContact;
FEventSink: TUCMAEventSink;
FClientSignedIn: Boolean;
FDisplayActivity: Boolean;
FDisplayDelay: Integer;
FDisplayDuration: Integer;
FJPEG_Default: TJPEGImage;
FDefaultHeight: Integer;
FSA: SECURITY_ATTRIBUTES;
FThreads: array of THandle;
procedure AlignControls;
procedure SetPosition;
procedure SetDisplayDelay(const Value: Integer);
procedure CreateUCMAClient;
procedure DestroyUCMAClient;
procedure SignInUCMAClient;
procedure SetStatusImage(AImageIndex: Integer);
procedure SetContactImage(AObject: TADObject); overload;
procedure SetContactImage(AImage: PSafeArray); overload;
procedure SetContactImage(AImage: TImgByteArray); overload;
function ContactIdleTimeToString(AIdleStartTime: TDateTime): string;
function ContactActivityTextEx(AContact: IUCMAContact): string;
procedure OnClientSignIn(Sender: TObject);
procedure OnClientSignOut(Sender: TObject);
procedure OnClientDisconnected(Sender: TObject);
procedure OnSettingChanged(Sender: TObject);
procedure OnContactInformationChanged(Sender: TObject);
procedure OnUriChanged(Sender: TObject; oldURI, newURI: WideString);
procedure SetDisplayActivity(const Value: Boolean);
procedure SetDisplayStyle(const Value: TFloatingWindowStyle);
public
{ Public declarations }
constructor Create(AOwner: TComponent; ListView: TListView = nil); overload;
destructor Destroy;
procedure Show(AUser: TADObject); overload;
procedure Hide(Clear: Boolean); overload;
procedure Reset;
property DisplayStyle: TFloatingWindowStyle read FDisplayStyle write SetDisplayStyle;
property DisplayDelay: Integer read FDisplayDelay write SetDisplayDelay;
property DisplayDuration: Integer read FDisplayDuration write FDisplayDuration;
property DisplayActivity: Boolean read FDisplayActivity write SetDisplayActivity;
end;
var
Form_FloatingWindow: TForm_FloatingWindow;
FContactInfo: TContactInfo;
FContactActivity: TContactActivity;
FThreadID_GetContactActiveDirectoryInfo: DWORD;
FThreadID_GetContactActivity: DWORD;
implementation
{$R *.dfm}
{ В отдельном потоке вытягиваем информацию пользователя из Active Directory }
procedure GetContactActiveDirectoryInfo(lpParam: LPVOID); stdcall;
var
c: PContactInfo absolute lpParam;
u: TUserEdit;
begin
try
case apAPI of
ADC_API_LDAP: u.GetInfo(LDAPBinding, c^._DistingushedName);
ADC_API_ADSI: u.GetInfoDS(ADSIBinding, c^._DistingushedName);
end;
except
end;
if GetCurrentThreadID = FThreadID_GetContactActiveDirectoryInfo then
begin
c^.DisplayName := u.displayName;
c^.Info1 := u.title;
c^.Info2 := u.physicalDeliveryOfficeName;
c^.Image := u.thumbnailPhoto;
PostMessage(c^._Handle, WM_FWND_THREAD, 0, GetCurrentThreadID);
end;
end;
{ В отдельном потоке вытягиваем информацию пользователя из Active Directory }
procedure GetContactActivity(lpParam: LPVOID); stdcall;
var
c: PContactActivity absolute lpParam;
res: Integer;
begin
try
case c^._Contact.Availability of
0 : res := STATUS_IMAGE_UNKNOWN; { None }
1..4999 : res := STATUS_IMAGE_ONLINE; { Free }
5000..6499 : res := STATUS_IMAGE_IDLE; { FreeIdle }
6500..7499 : res := STATUS_IMAGE_BUSY; { Busy }
7500..9499 : res := STATUS_IMAGE_BUSY; { BusyIdle }
9500..12499 : res := STATUS_IMAGE_DO_NOT_DISTURB; { DoNotDisturb }
12500..15499 : res := STATUS_IMAGE_IDLE; { TemporarilyAway }
15500..18499 : res := STATUS_IMAGE_IDLE; { Away }
else raise Exception.Create('Availability unknown'); { >= 18500: Offline }
end;
except
res := STATUS_IMAGE_UNKNOWN;
end;
if GetCurrentThreadID = FThreadID_GetContactActivity then
begin
PostMessage(c^._Handle, WM_FWND_THREAD, res, GetCurrentThreadID);
end;
end;
{ TForm_FloatingWindow }
function TForm_FloatingWindow.ContactActivityTextEx(
AContact: IUCMAContact): string;
var
a: Integer;
s: string;
t: TDateTime;
begin
try
a := AContact.Availability;
s := AContact.Activity;
t := AContact.IdleStartTime;
if not s.IsEmpty then
begin
if (a >= 5000) and (a < 6500) or (a >= 12500)
then Result := s + ' ' + ContactIdleTimeToString(t)
else Result := s;
end else raise Exception.Create('Presence unknown');
except
Result := STATUS_TEXT_UNKNOWN;
end;
end;
function TForm_FloatingWindow.ContactIdleTimeToString(
AIdleStartTime: TDateTime): string;
var
m: Int64;
h: Int64;
d: Int64;
f: string;
begin
m := MinutesBetween(AIdleStartTime, Now);
if m = 0 then
begin
// Result := 'меньше минуты';
Exit;
end;
d := m div 60 div 24;
if d > 0
then m := m - d * 24 * 60;
h := m div 60;
if h > 0
then m := m - h * 60;
if d > 0
then f := '%0:d дн.'
else if h > 0
then f := '%1:d час. %2:d мин.'
else f := '%2:d мин.';
Result := Format(f, [d, h, m]);
end;
constructor TForm_FloatingWindow.Create(AOwner: TComponent; ListView: TListView);
begin
if not (AOwner is TForm) then
raise Exception.Create('Owner should be TForm');
inherited Create(AOwner);
FOwner := TForm(AOwner);
FListView := ListView;
FJPEG_Default := TJPEGImage.Create;
FormStyle := fsStayOnTop;
BorderStyle := bsNone;
TransparentColorValue := clPurple;
Color := TransparentColorValue;
TransparentColor := True;
Position := poDesigned;
Width := 320;
Height := 69;
SetLength(FThreads, 2);
SetDisplayStyle(fwsSkype);
SetDisplayActivity(False);
SetDisplayDelay(500);
FDisplayDuration := 3000;
FContact := nil;
FEventSink := nil;
with FSA do
begin
nLength := SizeOf(SECURITY_ATTRIBUTES);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
AlignControls;
FDefaultHeight := Image_Contact.Top * 2 + Image_Contact.Height;
Height := FDefaultHeight;
Reset;
end;
procedure TForm_FloatingWindow.CreateUCMAClient;
begin
if FEventSink <> nil then
try
FEventSink.Disconnect;
FEventSink.Free;
except
end;
FEventSink := nil;
if FContact <> nil then
try
FContact.FreeContact;
except
end;
FContact := nil;
try
FContact := CreateComObject(CLASS_UCMAContact) as IUCMAContact;
FClientSignedIn := FContact.ClientSignIn;
except
FContact := nil;
end;
FEventSink := TUCMAEventSink.Create;
try
FEventSink.Connect(FContact);
FEventSink.OnClientSignIn := OnClientSignIn;
FEventSink.OnClientSignOut := OnClientSignOut;
FEventSink.OnClientDisconnected := OnClientDisconnected;
FEventSink.OnContactInformationChanged := OnContactInformationChanged;
FEventSink.OnSettingChanged := OnSettingChanged;
FEventSink.OnUriChanged := OnUriChanged;
except
end;
end;
destructor TForm_FloatingWindow.Destroy;
var
i: Integer;
begin
FJPEG_Default.Free;
DestroyUCMAClient;
inherited Destroy;
end;
procedure TForm_FloatingWindow.DestroyUCMAClient;
begin
try
FEventSink.Disconnect;
FEventSink.Free;
except
end;
FEventSink := nil;
try
FContact.FreeContact;
except
end;
FContact := nil;
end;
procedure TForm_FloatingWindow.PaintBox_BackgroundPaint(Sender: TObject);
var
ImgRect: TRect;
i: Integer;
RoundValue: Integer;
begin
case FDisplayStyle of
fwsLync : RoundValue := 3;
fwsSkype : RoundValue := 0;
end;
with Sender as TPaintBox do
begin
Canvas.Brush.Color := TransparentColorValue;
Canvas.FillRect(BoundsRect);
Canvas.Pen.Color := clSilver;
Canvas.Brush.Color := clWindow;
Canvas.RoundRect(
ClientRect.TopLeft.X,
ClientRect.TopLeft.Y,
ClientRect.BottomRight.X,
ClientRect.BottomRight.Y,
RoundValue,
RoundValue
);
case FDisplayStyle of
fwsLync: begin
Canvas.Pen.Color := clGray;
ImgRect := Image_Contact.ClientRect;
ImgRect.Offset(Image_Contact.Left, Image_Contact.Top);
Canvas.Rectangle(
ImgRect.TopLeft.X - 1,
ImgRect.TopLeft.Y - 1,
ImgRect.BottomRight.X + 1,
ImgRect.BottomRight.Y + 1
);
end;
fwsSkype: begin
end;
end;
end;
AlignControls;
end;
procedure TForm_FloatingWindow.Hide(Clear: Boolean);
begin
if Clear then
begin
Self.FObj := nil;
end;
inherited Hide;
Reset;
end;
procedure TForm_FloatingWindow.OnClientDisconnected(Sender: TObject);
begin
FClientSignedIn := False;
end;
procedure TForm_FloatingWindow.OnClientSignIn(Sender: TObject);
begin
FClientSignedIn := True;
end;
procedure TForm_FloatingWindow.OnClientSignOut(Sender: TObject);
begin
FClientSignedIn := False;
end;
procedure TForm_FloatingWindow.OnContactInformationChanged(Sender: TObject);
var
s: string;
begin
Timer_StatusRefreshTimer(Timer_StatusRefresh);
// s := FContact.DisplayName;
// if not s.IsEmpty
// then Label_Name.Caption := s;
//
// s := FContact.Title;
// if not s.IsEmpty
// then Label_Info1.Caption := s;
//
// Label_Info2.Caption := ContactActivityTextEx(FContact);
//
// try
// case FContact.Availability of
// 1..4999 : SetStatusImage(STATUS_IMAGE_ONLINE);
// 5000..6499 : SetStatusImage(STATUS_IMAGE_IDLE);
// 6500..7499 : SetStatusImage(STATUS_IMAGE_BUSY);
// 7500..9499 : SetStatusImage(STATUS_IMAGE_BUSY);
// 9500..12499 : SetStatusImage(STATUS_IMAGE_DO_NOT_DISTURB);
// 12500..15499 : SetStatusImage(STATUS_IMAGE_IDLE);
// 15500..18499 : SetStatusImage(STATUS_IMAGE_IDLE);
// else raise Exception.Create('Availability unknown');
// end;
// except
// SetStatusImage(STATUS_IMAGE_UNKNOWN);
// end;
//
// SetContactImage(FContact.Photo);
end;
procedure TForm_FloatingWindow.OnSettingChanged(Sender: TObject);
begin
end;
procedure TForm_FloatingWindow.OnUriChanged(Sender: TObject; oldURI,
newURI: WideString);
begin
end;
procedure TForm_FloatingWindow.Reset;
var
i: Integer;
begin
for i := Low(FThreads) to High(FThreads) do
if FThreads[i] <> 0 then
begin
// TerminateThread(FThreads[i], 0);
CloseHandle(FThreads[i]);
FThreads[i] := 0;
end;
Timer_Display.Enabled := False;
Timer_Display.Tag := TIMER_MODE_DISPLAY_DELAY;
Timer_Display.Interval := FDisplayDelay;
Timer_StatusRefresh.Enabled := False;
try FContact.FreeContact; except end;
SetStatusImage(STATUS_IMAGE_UNKNOWN);
Label_Name.Caption := '';
Label_Info1.Caption := '';
if DisplayActivity
then Label_Info2.Caption := STATUS_TEXT_UPDATING
else Label_Info2.Caption := '';
end;
procedure TForm_FloatingWindow.SetPosition;
var
Rightmost, Bottommost: Integer;
R: TRect;
P: TPoint;
li : TLIstItem;
lvHitInfo: TLVHitTestInfo;
begin
if (FOwner.WindowState = wsMaximized) and (FListView <> nil) then
begin
Rightmost := FListView.ClientToScreen(Point(FListView.ClientWidth, 0)).X;
Bottommost := FListView.ClientToScreen(Point(0, FListView.ClientHeight)).Y;
end else
begin
Rightmost := Screen.DesktopWidth;
Bottommost := Screen.WorkAreaHeight;
end;
if Mouse.CursorPos.X > Rightmost - Width - 16
then Left := Rightmost - Width
else Left := Mouse.CursorPos.X + 16;
if Mouse.CursorPos.Y > Bottommost - Height - 18
then Top := Mouse.CursorPos.Y - Height - 9
else Top := Mouse.CursorPos.Y + 18;
end;
procedure TForm_FloatingWindow.SetStatusImage(AImageIndex: Integer);
var
imgList: TImageList;
begin
case FDisplayStyle of
fwsLync : imgList := ImageList_Status_Classic;
fwsSkype : imgList := ImageList_Status_Modern;
end;
if (imgList = nil) or (AImageIndex < 0) or (AImageIndex > imgList.Count - 1) then
begin
Image_Status.Picture := nil
end else
begin
imgList.GetBitmap(AImageIndex, Image_Status.Picture.Bitmap);
end;
imgList := nil;
Image_Status.Refresh;
end;
procedure TForm_FloatingWindow.SetContactImage(AImage: TImgByteArray);
var
srcB: TBitmap;
resB: TBitmap;
R: TRect;
begin
srcB := TBitmap.Create;
try
try
if Length(AImage) = 0
then raise Exception.Create('No contact image');
TImgProcessor.ByteArrayToImage(AImage, srcB);
except;
srcB.Assign(FJPEG_Default);
end;
if (srcB.Width > Image_Contact.Width) or (srcB.Height > Image_Contact.Height) then
begin
resB := TBitmap.Create;
try
{ Вписывание изображения по ширине/высоте }
if srcB.Height > srcB.Width then
begin
resB.Width := Image_Contact.ClientWidth;
resB.Height := (resB.Width * srcB.Height) div srcB.Width;
R := resB.Canvas.ClipRect;
R.Inflate(0, -Abs(resB.Height - resB.Width) div 2);
R.Offset(0, -Abs(resB.Height - resB.Width) div 4);
end else
begin
resB.Height := Image_Contact.ClientHeight;
resB.Width := (resB.Height * srcB.Width) div srcB.Height;
R := resB.Canvas.ClipRect;
R.Inflate(-Abs(resB.Width - resB.Height) div 2, 0);
end;
TImgProcessor.SmoothResize(srcB, resB);
Image_Contact.Canvas.CopyMode := cmSrcCopy;
Image_Contact.Canvas.CopyRect(
Image_Contact.Canvas.ClipRect,
resB.Canvas,
R
);
{ Изменение размера с сохранением пропорций }
// if srcB.Width > srcB.Height then
// begin
// resB.Width := Image_Contact.ClientWidth;
// resB.Height := (resB.Width * srcB.Height) div srcB.Width;
// end else
// begin
// resB.Height := Image_Contact.ClientHeight;
// resB.Width := (resB.Height * srcB.Width) div srcB.Height;
// end;
// TImgProcessor.SmoothResize(srcB, resB);
// Image_Contact.Picture.Bitmap.Assign(resB);
finally
resB.Free;
end;
end else Image_Contact.Picture.Bitmap.Assign(srcB);
finally
srcB.Free;
end;
Image_Contact.Refresh;
end;
procedure TForm_FloatingWindow.SetContactImage(AObject: TADObject);
var
ms: TMemoryStream;
imgBytes: TImgByteArray;
begin
if (AObject <> nil) and (AObject.thumbnailFileSize > 0) then
begin
ms := TMemoryStream.Create;
try
AObject.thumbnailPhoto.SaveToStream(ms);
SetLength(imgBytes, ms.Size);
ms.Position := 0;
ms.ReadBuffer(imgBytes[0], Length(imgBytes));
finally
ms.Free;
end;
end;
SetContactImage(imgBytes);
SetLength(imgBytes, 0);
end;
procedure TForm_FloatingWindow.SetContactImage(AImage: PSafeArray);
var
LBound: Integer;
HBound: Integer;
ImgBytes: TImgByteArray;
i: Integer;
ib: Byte;
begin
SafeArrayGetLBound(AImage, 1, LBound);
SafeArrayGetUBound(AImage, 1, HBound);
SetLength(ImgBytes, HBound + 1);
for i := LBound to HBound do
begin
SafeArrayGetElement(AImage, i, ib);
ImgBytes[i] := ib;
end;
SafeArrayDestroy(AImage);
SetContactImage(ImgBytes);
end;
procedure TForm_FloatingWindow.SetDisplayActivity(const Value: Boolean);
begin
Timer_StatusRefresh.Enabled := Value;
FDisplayActivity := Value;
if FDisplayActivity then
begin
CreateUCMAClient;
SignInUCMAClient;
end else DestroyUCMAClient;
end;
procedure TForm_FloatingWindow.SetDisplayDelay(const Value: Integer);
var
TimerState: Boolean;
begin
if Value < 1
then FDisplayDelay := 1
else FDisplayDelay := Value;
TimerState := Timer_Display.Enabled;
Timer_Display.Enabled := False;
Timer_Display.Interval := FDisplayDelay;
Timer_Display.Enabled := TimerState;
end;
procedure TForm_FloatingWindow.SetDisplayStyle(const Value: TFloatingWindowStyle);
var
TmpBMP: TBitmap;
begin
case Value of
fwsLync..fwsSkype: FDisplayStyle := Value;
else FDisplayStyle := fwsSkype;
end;
with FJPEG_Default do
try
CompressionQuality := 100;
Smoothing := True;
TmpBMP := TBitmap.Create;
try
case FDisplayStyle of
fwsLync: ImageList_Contact.GetBitmap(0, TmpBMP);
fwsSkype: ImageList_Contact.GetBitmap(1, TmpBMP);
else ImageList_Contact.GetBitmap(1, TmpBMP);
end;
Assign(TmpBMP);
finally
TmpBMP.Free;
end;
except
end;
AlignControls;
PaintBox_Background.Repaint;
end;
procedure TForm_FloatingWindow.Show(AUser: TADObject);
begin
SetPosition;
if AUser = nil then
begin
Self.Hide(True);
Exit;
end;
SetPosition;
if FObj <> AUser then
begin
{ Если задержка отображения небольшая, то скрывать окно нет смысла. }
{ Поэтому просто сбрасываем его состояние. }
if FDisplayDelay > 99 then Hide(False) else Reset;
FObj := AUser;
SetContactImage(FObj);
Label_Name.Caption := IfThen(
FObj.displayName.IsEmpty,
FObj.name,
FObj.displayName
);
Label_Info1.Caption := FObj.title;
if not FDisplayActivity
then Label_Info2.Caption := FObj.physicalDeliveryOfficeName;
{ Закомментированный код ниже обновляет информацию о пользователе }
{ напрямую из Active Directory, чем нагружает сеть и ОЗУ }
// ZeroMemory(@FContactInfo, SizeOf(TContactInfo));
// with FContactInfo do
// begin
// _Handle := Self.Handle;
// _DistingushedName := FObj.distinguishedName;
// end;
//
// FThreads[0] := CreateThread(
// @FSA,
// 0,
// @GetContactActiveDirectoryInfo,
// @FContactInfo,
// 0,
// FThreadID_GetContactActiveDirectoryInfo
// );
if FDisplayActivity then
try
if FContact = nil then CreateUCMAClient;
if not FClientSignedIn then SignInUCMAClient;
FContact.SetContact(FObj.msRTCSIP_PrimaryUserAddress);
// FContact.SetContact(FObj.distinguishedName);
// Self.OnContactInformationChanged(FEventSink);
Timer_StatusRefreshTimer(Timer_StatusRefresh);
Timer_StatusRefresh.Enabled := True;
except
Label_Info2.Caption := STATUS_TEXT_UNKNOWN;
end;
Timer_Display.Tag := TIMER_MODE_DISPLAY_DELAY;
Timer_Display.Enabled := True;
end;
end;
procedure TForm_FloatingWindow.SignInUCMAClient;
begin
if FContact <> nil then
try
FClientSignedIn := FContact.ClientSignIn;
except
FClientSignedIn := False;
end;
end;
procedure TForm_FloatingWindow.Timer_DisplayTimer(Sender: TObject);
var
t: TTimer absolute Sender;
i: Integer;
begin
if Sender is TTimer then
case t.Tag of
TIMER_MODE_DISPLAY_DELAY: begin
PaintBox_BackgroundPaint(PaintBox_Background);
for i := 0 to Self.ControlCount - 1 do
Self.Controls[i].Refresh;
ShowWindow(Self.Handle, SW_SHOWNOACTIVATE);
{ Выставляем Visible := True, т.к. если не выставить, то не будет работать метод Hide }
Self.Visible := True;
t.Enabled := False;
t.Tag := TIMER_MODE_DISPLAY_DURATION;
t.Interval := FDisplayDuration;
t.Enabled := FDisplayDuration > 0;
end;
TIMER_MODE_DISPLAY_DURATION: begin
Self.Hide(False);
end;
end;
end;
procedure TForm_FloatingWindow.Timer_StatusRefreshTimer(Sender: TObject);
begin
if not Self.Visible
then Exit;
ZeroMemory(@FContactActivity, SizeOf(TContactActivity));
with FContactActivity do
begin
_Handle := Self.Handle;
_Contact := Self.FContact;
end;
FThreads[1] := CreateThread(
@FSA,
0,
@GetContactActivity,
@FContactActivity,
0,
FThreadID_GetContactActivity
);
end;
procedure TForm_FloatingWindow.VisibleChanging;
begin
inherited;
case Visible of
True: begin
{ Если окно отображается и будет скрыто }
end;
False: begin
{ Если окно скрыто и будет отображено }
end;
end;
end;
procedure TForm_FloatingWindow.WndProc(var Message: TMessage);
var
s: string;
begin
inherited;
case Message.Msg of
WM_FWND_THREAD: begin
if Message.LParam = FThreadID_GetContactActiveDirectoryInfo then
begin
if FContactInfo.DisplayName.IsEmpty
then try FContactInfo.DisplayName := FObj.name; except end;
Label_Name.Caption := FContactInfo.DisplayName;
Label_Info1.Caption := FContactInfo.Info1;
if not FDisplayActivity
then Label_Info2.Caption := FContactInfo.Info2;
if Length(FContactInfo.Image) > 0
then SetContactImage(FContactInfo.Image)
else SetContactImage(FObj);
end else
if Message.LParam = FThreadID_GetContactActivity then
begin
SetStatusImage(Message.WParam);
// SetContactImage(FContact.Photo);
Label_Info2.Caption := ContactActivityTextEx(FContact);
end;
end;
end;
end;
procedure TForm_FloatingWindow.AlignControls;
var
dy: Integer;
begin
Image_Status.Top := FFormPadding;
Image_Status.Visible := FDisplayActivity{ and (FDrawStyle = fwsClassic)};
if FDisplayActivity then
begin
case FDisplayStyle of
fwsLync: begin
Image_Status.Left := FFormPadding;
Image_Status.Width := 10;
end;
fwsSkype: begin
Image_Status.Left := 1;
Image_Status.Width := 8;
end;
end;
Image_Contact.Left := Image_Status.Left + Image_Status.Width;
end else Image_Contact.Left := FFormPadding + 1;
Image_Contact.Top := Image_Status.Top + 1;
Label_Name.Left := Image_Contact.Left + Image_Contact.Width + 10;
Label_Name.Top := Image_Contact.Top - 1;
Label_Name.Width := ClientWidth - Label_Name.Left - FFormPadding;
Label_Info1.Left := Label_Name.Left;
Label_Info1.Top := Label_Name.Top + Label_Name.Height + 4;
Label_Info1.Width := Label_Name.Width;
Label_Info2.Left := Label_Name.Left;
Label_Info2.Top := Label_Info1.Top + Label_Info1.Height + 4;
Label_Info2.Width := Label_Name.Width;
end;
end.
|
unit uSkillBox;
interface
uses
Graphics,
// Own units
UCommon;
type
TSkillBox = class(THODObject)
private
public
Image: array of TBitmap;
//** Конструктор.
constructor Create;
//** Деструктор.
destructor Destroy; override;
end;
var
SkillBox: TSkillBox;
implementation
uses Classes, uUtils;
{ TSkill }
constructor TSkillBox.Create;
var
I: Integer;
begin
SetLength(Image, 6);
for I := 0 to High(Image) do
begin
Image[I] := TBitMap.Create;
with Image[I] do
begin
Transparent := True;
end;
end;
SplitBMP(Image, Path + '\Data\Images\Skills.bmp');
end;
destructor TSkillBox.Destroy;
var
i: Integer;
begin
for i := 0 to High(Image) do Image[i].Free;
inherited;
end;
initialization
SkillBox := TSkillBox.Create;
finalization
SkillBox.Free;
end.
|
{ Invokable implementation File for TTest which implements ITest }
unit SoapImpl;
interface
uses
InvokeRegistry, Types, XSBuiltIns, SoapIntf, Winapi.Windows, Controls,
SynCommons,QLog;
type
{ TTest }
TWSYXDSVR = class(TInvokableClass, IWSYXDSVR)
public
function HelloWorld: string;
end;
implementation
uses
uDataYxDserver, Winapi.Messages, Forms, Soap.EncdDecd, System.SysUtils;
const
Success_Result = '<Result><Code>1</Code><Info>³É¹¦</Info></Result>';
Success_Info = '<Result><Code>1</Code><Info>@Info@</Info></Result>';
Fail_Result = '<Result><Code>0</Code><Info>@Info@</Info></Result>';
WM_HTTPINFO = WM_USER + 203;
function TWSYXDSVR.HelloWorld: string;
var
Af: TYxDSvr;
Log: string;
begin
Result := Fail_Result;
try
try
Af := TYxDSvr.Create(nil);
try
if not Af.HelloWorld then
begin
Result := stringreplace(Fail_Result, '@Info@', Af.FERROR, []);
Exit;
end;
Result := stringreplace(Success_Info, '@Info@', Af.FRet, []);
finally
freeandnil(Af);
end;
except
on e: exception do
begin
Result := stringreplace(Fail_Result, '@Info@', e.message, []);
Exit;
end;
end;
finally
Log := Log + #13#10 + Result;
if POS('<Code>0</Code>', Log) > 0 then
begin
PostLog(llError,Log);
PostMessage(Application.MainForm.Handle, WM_HTTPINFO, 0, 2);
end
else
PostLog(llMessage,Log);
end;
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(TWSYXDSVR);
end.
|
unit nscLister;
(*-----------------------------------------------------------------------------
Название: nscLister
Автор: М. Морозов
Назначение:
Версия:
$Id: nscLister.pas,v 1.15 2014/07/02 14:45:30 lulin Exp $
История:
$Log: nscLister.pas,v $
Revision 1.15 2014/07/02 14:45:30 lulin
- собираем библиотеки.
Revision 1.14 2014/02/19 09:08:50 morozov
{RequestLink: 294584542}
Revision 1.13 2014/02/13 11:48:41 morozov
{RequestLink: 294584542}
Revision 1.12 2011/04/18 17:38:14 lulin
{RequestLink:263750840}.
Revision 1.11 2011/04/18 17:13:22 lulin
{RequestLink:263750840}.
Revision 1.10 2007/10/17 11:00:04 mmorozov
- change: отказываемся от шаблона для публикации операций, т.к. для Desing-Time использование шаблона недопустимо;
Revision 1.9 2007/10/17 09:27:08 mmorozov
- new: публикация операций "Выделить все", "Снять выделение" выделена в отдельный шаблон;
Revision 1.8 2007/02/13 11:44:30 mmorozov
- new: заголовок дерева (TvtHeader) использует таблицу стилей (CQ: OIT5-24283);
Revision 1.7 2005/04/20 08:55:58 demon
- new behavior: Свойство OnClickHeader переехало в TvtListerHeader , а у TvtCustomLister оно исчезло (изменение от Василия)
Revision 1.6 2005/03/21 08:00:33 mmorozov
new: опубликовано свойство TnscLister.StyleId;
Revision 1.5 2005/03/14 15:11:22 mmorozov
- использование property TvtCustomLister.UseStyleTable;
Revision 1.4 2005/02/21 17:36:15 lulin
- удалено ненужное свойство.
Revision 1.3 2005/02/21 16:54:10 lulin
- удалено ненужное свойство.
Revision 1.2 2004/12/25 09:11:32 mmorozov
new: published property OnGetItemTextHint;
Revision 1.1 2004/12/09 10:17:12 mmorozov
new: наследник TvtLister используемый в проекте Немезис;
-----------------------------------------------------------------------------*)
interface
uses
Classes,
Messages,
l3InternalInterfaces,
l3Types,
vtLister,
vcmExternalInterfaces
;
type
TnscCustomLister = class(TvtCustomLister,
{$IfNDef NoVCM}
IvcmOperationsProvider,
{$EndIf NoVCM}
Il3CommandPublisherInfo
)
{* - компонент TvtCutomLister используемый в Немезисе. }
private
// internal fields
f_Published : Boolean;
private
// Il3CommandPublisherInfo
function IsCommandPublished(Cmd: Tl3OperationCode): Boolean;
{-}
protected
// IvcmOperationsProvider
{$IfNDef NoVCM}
procedure ProvideOps(const aPublisher : IvcmOperationsPublisher);
virtual;
{* - предоставить список доступных операций. }
{$EndIf NoVCM}
protected
// operation handlers
{$IfNDef NoVCM}
procedure DeselectAllExecute(const aParams : IvcmExecuteParamsPrim);
procedure DeselectAllTest(const aParams : IvcmTestParamsPrim);
{-}
procedure SelectAllExecute(const aParams : IvcmExecuteParamsPrim);
procedure SelectAllTest(const aParams : IvcmTestParamsPrim);
{-}
{$EndIf NoVCM}
function DoIsCommandPublished(Cmd: Tl3OperationCode): Boolean;
virtual;
{-}
protected
// property methods
function pm_GetIsEmpty: Boolean;
{* - наличие элементов в дереве. }
protected
// properties
property IsEmpty: Boolean
read pm_GetIsEmpty;
{-}
public
//public methods
constructor Create(AOwner : TComponent);
override;
{-}
end;//TnscCustomLister
TnscLister = class(TnscCustomLister)
{* - компонент для DesignTime. }
published
// published properties
property Images;
property AutoRowHeight;
property BorderStyle;
property Columns;
property Header;
property IntegralHeight;
property MultiSelect;
property InternalSelector;
property ProtectColor;
property RowHeight;
property ScrollStyle;
property SelectColor;
property SelectNonFocusColor;
property ShowHeader;
property UseTabStops;
property PickedList;
property TriplePicked;
property MultiStrokeItem;
property ReadOnly;
property ViewOptions;
property ActionElementMode;
property StyleId;
property OnCharToItem;
property OnGetStrItem;
property OnGetPCharItem;
property OnGetItemImageIndex; //OnGetItemBitmap;
property OnGetItemColor;
property OnGetItemFont;
property OnGetItemCursor;
property OnGetItemStatus;
property OnGetItemTextHint;
property OnIsSelected;
property OnSelect;
property OnSelectChange;
property OnSelectChanged;
property OnTopIndexChanged;
property OnCurrentChanged;
property OnCountChanged;
property OnUserCommand;
property OnIsCommandProcessed;
{inherited properties}
property Align;
property Color;
property Controller;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Anchors;
property Constraints;
{inherited events}
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnActionElement;
property OnResize;
end;
implementation
uses
Windows,
StdCtrls,
ovcConst,
l3Base,
OfficeLike_Text_Controls
;
{$IfNDef NoVCM}
const
cenEdit = en_Edit;
copSelectAll = op_SelectAll;
copDeselectAll = op_Deselect;
{ TnsLister }
procedure TnscCustomLister.ProvideOps(
const aPublisher: IvcmOperationsPublisher);
begin
f_Published := true;
with aPublisher do
begin
PublishOp(cenEdit,
copSelectAll,
SelectAllExecute,
SelectAllTest);
PublishOp(cenEdit,
copDeselectAll,
DeselectAllExecute,
DeselectAllTest);
end;//with aPublisher do
end;//ProvideOps
procedure TnscCustomLister.SelectAllExecute(
const aParams : IvcmExecuteParamsPrim);
begin
{$IfNDef DesignTimeLibrary}
vlbSelectAllItems;
{$EndIf DesignTimeLibrary}
end;
procedure TnscCustomLister.DeselectAllExecute(const aParams : IvcmExecuteParamsPrim);
begin
{$IfNDef DesignTimeLibrary}
vlbDeselectAllItems;
{$EndIf DesignTimeLibrary}
end;
procedure TnscCustomLister.DeselectAllTest(const aParams : IvcmTestParamsPrim);
begin
aParams.Op.Flag[vcm_ofEnabled] := not IsEmpty and MultiSelect;
end;
procedure TnscCustomLister.SelectAllTest(const aParams : IvcmTestParamsPrim);
begin
aParams.Op.Flag[vcm_ofEnabled] := not IsEmpty and MultiSelect;
end;
{$EndIf NoVCM}
function TnscCustomLister.DoIsCommandPublished(Cmd: Tl3OperationCode): Boolean;
// virtual;
{-}
begin
Result := Cmd in [ccAllSelect, ccAllDeselect];
end;//DoIsCommandPublished
function TnscCustomLister.IsCommandPublished(Cmd: Tl3OperationCode): Boolean;
begin
Result := f_Published and DoIsCommandPublished(Cmd);
end;//IsCommandPublished
constructor TnscCustomLister.Create(AOwner : TComponent);
// override;
{-}
begin
inherited Create(AOwner);
UseStyleTable := True;
end;//Create
function TnscCustomLister.pm_GetIsEmpty: Boolean;
// override;
{* - наличие элементов в дереве. }
begin
Result := Total > 0;
end;//pm_GetIsEmpty
end.
|
unit Dt_containers;
{ $Id: Dt_containers.pas,v 1.7 2014/05/23 16:25:24 lulin Exp $ }
// $Log: Dt_containers.pas,v $
// Revision 1.7 2014/05/23 16:25:24 lulin
// {RequestLink:537249703}
//
// Revision 1.6 2014/05/23 15:58:14 lulin
// {RequestLink:537249703}
//
// Revision 1.5 2004/09/21 12:04:21 lulin
// - Release заменил на Cleanup.
//
{$I DtDefine.inc}
interface
uses
l3Base,
Contnrs,
l3ProtoObject,
dtNumRange,
dtNumRangeList
;
type
// вспомогательный тип для TNumSet
(* TNumRange = class(Tl3ProtoObject)
public
LowNum,
HiNum: LongWord;
constructor Create(aLowNum, aHiNum: LongWord);
function HasIntersectionWith(aRange: TNumRange): Boolean;
function JoinWith(aRange: TNumRange): Integer;
// возвращает число добавленных ((кол-во в aRange) - (кол-во дубликатов)) номеров
function Amount: Integer;
end;*)
TNumSet = class(Tl3ProtoObject)
// Просто пачка (i.e. set) номеров. Используется при передаче туда-сюда.
// Добавление дубликатов обрабатывает корректно.
private
f_Ranges: TdtNumRangeList;
f_Amount: Integer;
function GetRange(Index: Integer): TdtNumRange;
protected
procedure Cleanup; override;
public
constructor Create;
procedure Clear;
procedure AddNum(aNum: LongWord); // добавление одного номера
procedure AddRange(aLowNum, aHiNum: LongWord); // добавление группы номеров
procedure AddSet(aSet: TNumSet); // добавление номеров из другой пачки
function Pick: LongWord; // извлечение одного номера
function RangesAmount: Integer;
property Ranges[Index: Integer]: TdtNumRange read GetRange;
property Amount: Integer read f_Amount; // кол-во номеров "в наличии"
end;
implementation
uses
SysUtils, Math;
{ TNumSet }
procedure TNumSet.AddNum(aNum: LongWord);
begin
AddRange(aNum, aNum);
end;
procedure TNumSet.AddRange(aLowNum, aHiNum: LongWord);
var
l_NewRange,
l_CurRange: TdtNumRange;
I: Integer;
begin
l_NewRange := TdtNumRange.Create(aLowNum, aHiNum);
try
// Удаление дубликатов след. образом:
// перебирам все имеющиеся интервалы - если среди них встречаем пересекающийся
// с новым, то его содержимое переносим в новый, а его самого удаляем.
for I := f_Ranges.Count - 1 downto 0 do
begin
l_CurRange := f_Ranges[I];
if l_NewRange.HasIntersectionWith(l_CurRange) then
begin
l_NewRange.JoinWith(l_CurRange);
Dec(f_Amount, l_CurRange.Amount);
f_Ranges.Delete(I);
end;
end;
f_Ranges.Add(l_NewRange);
Inc(f_Amount, l_NewRange.Amount);
finally
FreeAndNil(l_NewRange);
end;//try..finally
end;
procedure TNumSet.AddSet(aSet: TNumSet);
var
I: Integer;
begin
for I := 0 to aSet.F_Ranges.Count - 1 do
AddRange(aSet.F_Ranges[I].LowNum,
aSet.F_Ranges[I].HiNum);
end;
procedure TNumSet.Clear;
begin
f_Ranges.Clear;
f_Amount := 0;
end;
constructor TNumSet.Create;
begin
inherited Create;
f_Ranges := TdtNumRangeList.Create;
end;
function TNumSet.GetRange(Index: Integer): TdtNumRange;
begin
Result := f_Ranges[Index];
end;
function TNumSet.Pick: LongWord;
var
l_Range: TdtNumRange;
begin
if Amount = 0 then
raise Exception.Create('Попытка получения элемента из пустого множества.');
l_Range := f_Ranges.Items[0];
Result := l_Range.LowNum;
if l_Range.Amount > 1 then
Inc(l_Range.LowNum)
else
f_Ranges.Delete(0);
Dec(f_Amount, 1);
end;
function TNumSet.RangesAmount: Integer;
begin
Result := f_Ranges.Count;
end;
procedure TNumSet.Cleanup;
begin
FreeAndNil(f_Ranges);
inherited;
end;
{ TNumRange }
(*function TNumRange.Amount: Integer;
begin
Result := HiNum - LowNum + 1;
end;
constructor TNumRange.Create(aLowNum, aHiNum: LongWord);
begin
inherited Create;
if aLowNum <= aHiNum then
begin
LowNum := aLowNum;
HiNum := aHiNum;
end
else
begin
LowNum := aHiNum;
HiNum := aLowNum;
end;
end;
function TNumRange.HasIntersectionWith(aRange: TNumRange): Boolean;
begin
Result := (Self.HiNum >= aRange.LowNum) and
(Self.LowNum <= aRange.HiNum);
end;
function TNumRange.JoinWith(aRange: TNumRange): Integer;
begin
if not HasIntersectionWith(aRange) then
raise Exception.Create('Попытка объединения непересекающихся диапазонов.');
Self.LowNum := Min(Self.LowNum, aRange.LowNum);
Self.HiNum := Max(Self.HiNum, aRange.HiNum);
end;*)
end.
|
unit udf_math;
interface
uses Windows;
function FormatFloat(var Value : Double; var K : Integer): Double; cdecl; export;
function ValueInStr(S: PChar; var Value: Integer): Integer; cdecl; export;
function Trim(S: PChar): PChar; cdecl; export;
implementation
uses SysUtils;
var
hThreadLocalVariables: Integer; (* Index to thread-local storage *)
const
cSignificantlyLarger = 1024 * 4;
type
TISC_QUAD = record
gds_quad_high : Longint;
gds_quad_low : Longint;
end;
PISC_QUAD = ^TISC_QUAD;
TThreadLocalVariables = class(TObject)
protected
FPChar: PChar;
FPCharSize: Integer;
FQuad: PISC_QUAD;
public
constructor Create;
destructor Destroy; override;
end;
function ThreadLocals: TThreadLocalVariables;
begin
result := TLSGetValue(hThreadLocalVariables);
if result = nil then begin
result := TThreadLocalVariables.Create;
TLSSetValue(hThreadLocalVariables, result);
end;
end;
function MakeResultString(Source, OptionalDest: PChar; Len: Integer): PChar;
begin
result := OptionalDest;
if (Len = 0) then
Len := StrLen(Source) + 1;
if (result = nil) then begin
{$ifdef FREE_IT}
result := ib_util_malloc(Len);
{$else}
with ThreadLocals do begin
(*
* If the current PChar is smaller than than Source, or
* it is significanly larger than Source, then reallocate it
* in cSignificantlyLarger chunks.
*)
if (FPCharSize < Len) or
(FPCharSize > Len + cSignificantlyLarger) then begin
FPCharSize := 0;
(*
* Realistically, we'll never return strings longer than about
* 2k, so I'd rather risk spending time in a loop that *adds* than
* "compute" FPCharSize by performing division and modulo arithmetic.
* Addition is very fast, and the while loop will in general, only
* be at most 1 to 2 steps.
*)
while (FPCharSize < Len) do
Inc(FPCharSize, cSignificantlyLarger);
ReallocMem(FPChar, FPCharSize);
end;
result := FPChar;
end;
{$endif}
end;
if (Source <> result) then begin
if (Source = nil) or (Len = 1) then
result[0] := #0
else
Move(Source^, result^, Len);
end;
end;
function Trim(S: PChar): PChar;
begin
//Result := MakeResultString(PChar(Trim(PAnsiChar(S))), nil, 0);
//Result := StrPCopy lstrcat(S, S);
StrPCopy(Result, SysUtils.Trim(S));
end;
function FormatFloat(var Value : Double; var K : Integer): Double;
var
ScaledPart, Temp : double;
begin
ScaledPart:=Value/Exp(K * Ln(10));
Temp:=Frac(ScaledPart);
ScaledPart:=Int(ScaledPart);
if Temp>=0.49999999 then ScaledPart:=ScaledPart+1;
if Temp<=-0.49999999 then ScaledPart:=ScaledPart-1;
Result:=StrToFloat(FloatToStr(ScaledPart*Exp(K * Ln(10))));
end;
function ValueInStr(S: PChar; var Value: Integer): Integer;
var
i: Integer;
w: string;
begin
Result := 0;
w := '';
for i := 0 to StrLen(S) - 1 do begin
if S[i] = ',' then begin
if IntToStr(Value) = w then begin
Result := 1;
Exit;
end
else w := '';
end
else w := w + s[i];
end;
if (w <> '') and (IntToStr(Value) = w) then Result := 1;
end;
{ TThreadLocalVariables }
constructor TThreadLocalVariables.Create;
begin
ReallocMem(FPChar, cSignificantlyLarger);
FPCharSize := cSignificantlyLarger;
ReallocMem(FQuad, SizeOf(TISC_QUAD));
end;
destructor TThreadLocalVariables.Destroy;
begin
inherited;
end;
end.
|
{
drawer.pas
Drawer class for components, wires and other elements
Copyright (C) 2007 Felipe Monteiro de Carvalho
This file is part of Turbo Circuit.
Turbo Circuit is free software;
you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2
as published by the Free Software Foundation.
Turbo Circuit 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.
Please note that the General Public License version 2 does not permit
incorporating Turbo Circuit into proprietary programs.
AUTHORS: Felipe Monteiro de Carvalho
}
unit drawer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics,
constants, tcutils, dbcomponents, document,
fpvectorial;
type
{ TItemsDrawer }
TItemsDrawer = class(TObject)
private
Points: array[0..2] of TPoint;
procedure DrawPosCross(ACanvas: TCanvas; APos: TPoint);
public
DeltaX, DeltaY: Integer;
Orientation: TCComponentOrientation;
IC_Width, IC_Pins, IC_Half_Pins: Cardinal;
FPointSeparator: TFormatSettings;
constructor Create;
{ Component drawing methods }
procedure DrawComponentFromString(ACanvas: TCanvas; AString: string);
procedure DrawComponentFromStringList(ACanvas: TCanvas; AStringList: TStrings);
procedure DrawComponentSelection(ACanvas: TCanvas; AComponent: PTCComponent); overload;
procedure DrawComponentSelection(ACanvas: TCanvas; ARect: TRect); overload;
procedure DrawFromDrawingCodeLine(ACanvas: TCanvas; Cmds: T10Strings);
{ Wire drawing methods }
procedure DrawWire(ACanvas: TCanvas; AElement: PTCElement);
procedure DrawWireSelection(ACanvas: TCanvas; AWire: PTCWire; AWirePart: DWord);
{ Text element drawing methods }
procedure DrawText(ACanvas: TCanvas; AElement: PTCElement);
procedure DrawTextSelection(ACanvas: TCanvas; AElement: TvText);
procedure DrawTextExtra(ACanvas: TCanvas; AElement: TvText);
{ Polyline drawing methods }
procedure DrawPolyline(ACanvas: TCanvas; AElement: PTCElement);
procedure DrawPolylineSelection(ACanvas: TCanvas; AElement: PTCElement; APointNr: Integer);
{ Raster Image drawing methods }
procedure DrawRasterImage(ACanvas: TCanvas; AElement: PTCElement);
{ Ellipse drawing methods }
//procedure DrawEllipse(ACanvas: TCanvas; AElement: PTCElement);
{ General methods }
function FixCoordinates(APoint: TPoint): TPoint;
function GridCoordsToSheet(AX, AY: Single): TPoint;
end;
var
vItemsDrawer: TItemsDrawer;
implementation
{ TItemsDrawer }
{@@
Convenience method. Receives a multiline string
and passes it to DrawComponentFromStringList
@param AString The string containing the drawing instructions.
It should be in the internal database format, i.e. with #
instead of new lines.
@see #DrawComponentFromStringList
}
procedure TItemsDrawer.DrawComponentFromString(ACanvas: TCanvas; AString: string);
var
StringList: TStringList;
begin
StringList := TStringList.Create;
try
StringList.Text := TComponentsDatabase.DBDrawingCodeToMemoString(AString);
DrawComponentFromStringList(ACanvas, StringList);
finally
StringList.Free;
end;
end;
{@@
Draws a component given a string list with the
instructions to draw it, one in each line.
}
procedure TItemsDrawer.DrawComponentFromStringList(ACanvas: TCanvas;
AStringList: TStrings);
var
i: Integer;
Cmds: T10Strings;
begin
for i := 0 to AStringList.Count - 1 do
begin
Cmds := SeparateString(AStringList.Strings[i], lpSpace);
DrawFromDrawingCodeLine(ACanvas, Cmds);
end;
end;
{@@
Draws the screen indication that a given component
is selected
}
procedure TItemsDrawer.DrawComponentSelection(ACanvas: TCanvas;
AComponent: PTCComponent);
var
TargetRect: TRect;
begin
if not Assigned(AComponent) then exit;
Orientation := AComponent^.Orientation;
vComponentsDatabase.GoToRecByID(AComponent^.TypeID);
TargetRect := Bounds(
vDocument.GetComponentTopLeft(AComponent).X,
vDocument.GetComponentTopLeft(AComponent).Y,
vComponentsDatabase.GetWidth(),
vComponentsDatabase.GetHeight());
TargetRect.Left := TargetRect.Left * INT_SHEET_GRID_SPACING;
TargetRect.Top := TargetRect.Top * INT_SHEET_GRID_SPACING;
TargetRect.Right := TargetRect.Right * INT_SHEET_GRID_SPACING;
TargetRect.Bottom := TargetRect.Bottom * INT_SHEET_GRID_SPACING;
FixCoordinates(TargetRect.BottomRight);
DrawComponentSelection(ACanvas, TargetRect);
end;
{@@
Draws the screen indication that a given component
is selected
}
procedure TItemsDrawer.DrawComponentSelection(ACanvas: TCanvas; ARect: TRect);
begin
{ Upper-left corner }
ACanvas.Line(
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Top - INT_SHEET_GRID_HALFSPACING,
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Top);
ACanvas.Line(
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Top - INT_SHEET_GRID_HALFSPACING,
ARect.Left,
ARect.Top - INT_SHEET_GRID_HALFSPACING);
{ Upper-right corner }
ACanvas.Line(
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Top - INT_SHEET_GRID_HALFSPACING,
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Top);
ACanvas.Line(
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Top - INT_SHEET_GRID_HALFSPACING,
ARect.Right,
ARect.Top - INT_SHEET_GRID_HALFSPACING);
{ Lower-left corner }
ACanvas.Line(
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING,
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Bottom);
ACanvas.Line(
ARect.Left - INT_SHEET_GRID_HALFSPACING,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING,
ARect.Left,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING);
{ Lower-right corner }
ACanvas.Line(
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING,
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Bottom);
ACanvas.Line(
ARect.Right + INT_SHEET_GRID_HALFSPACING,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING,
ARect.Right,
ARect.Bottom + INT_SHEET_GRID_HALFSPACING);
end;
{@@
Draws one line of instruction for drawing a component
The format of such instructions is:
[Command], [Param1], [Param2], etc ...
Possible commands are:
LINE - Draws a line.
(Param1, Param2) forms a (x, y) point
indicating the inital point of the line.
(Param3, Param4) forms a (x, y) point
indicating the final point of the line.
TEXT - Draws a text.
(Param1, Param2) forms a (left, top) point
indicating where the text will be placed
Param3 is the UTF-8 text to be written
Param4 is the height of the font
ARC - Draws an arc
(Param1, Param2) forms the (left, top) position of the arc
(Param3, Param4) forms the (right, bottom) position of the arc
Param5 is the UTF-8 text to be written
Param6 is the height of the font
TRIANGLE - Draws a triangle
IC - Draws an integrated circuit
IC_TEXT_LEFT_1 - Draws the texts for the pins in an IC
IC_TEXT_LEFT_2 -
IC_TEXT_RIGHT_1 -
IC_TEXT_RIGHT_2 -
}
procedure TItemsDrawer.DrawFromDrawingCodeLine(ACanvas: TCanvas; Cmds: T10Strings);
var
i: Integer;
procedure GetPoint_1;
begin
Points[0].X := Round((DeltaX + StrToFloat(Cmds[1], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[0].Y := Round((DeltaY + StrToFloat(Cmds[2], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[0] := FixCoordinates(Points[0]);
end;
procedure GetPoint_2;
begin
Points[1].X := Round((DeltaX + StrToFloat(Cmds[3], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[1].Y := Round((DeltaY + StrToFloat(Cmds[4], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[1] := FixCoordinates(Points[1]);
end;
procedure GetPoint_3;
begin
Points[2].X := Round((DeltaX + StrToFloat(Cmds[5], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[2].Y := Round((DeltaY + StrToFloat(Cmds[6], FPointSeparator)) * INT_SHEET_GRID_SPACING);
Points[2] := FixCoordinates(Points[2]);
end;
begin
try
if Cmds[0] = STR_DRAWINGCODE_LINE then
begin
GetPoint_1;
GetPoint_2;
ACanvas.Line(Points[0], Points[1]);
end
else if Cmds[0] = STR_DRAWINGCODE_TEXT then
begin
GetPoint_1;
if Cmds[4] <> '' then ACanvas.Font.Height := StrToInt(Cmds[4]);
ACanvas.Brush.Color := clWhite;
ACanvas.Pen.Color := clBlack;
ACanvas.TextOut(Points[0].X, Points[0].Y, Cmds[3]);
end
else if Cmds[0] = STR_DRAWINGCODE_ARC then
begin
GetPoint_1;
GetPoint_2;
ACanvas.Arc(
Points[0].X, Points[0].Y,
Points[1].X, Points[1].Y,
StrToInt(Cmds[5]), StrToInt(Cmds[6]));
end
else if Cmds[0] = STR_DRAWINGCODE_TRIANGLE then
begin
GetPoint_1;
GetPoint_2;
GetPoint_3;
ACanvas.Polygon(Points);
end
else if Cmds[0] = STR_DRAWINGCODE_IC then
begin
{ Get Width and number of pins }
IC_Width := StrToInt(Cmds[1]);
IC_Pins := StrToInt(Cmds[2]);
IC_Half_Pins := IC_Pins div 2;
Points[0] := GridCoordsToSheet(IC_Width + 1, IC_Half_Pins + 1);
Points[1] := GridCoordsToSheet(1, 0);
{ IC Body }
ACanvas.Rectangle(Points[1].X, Points[1].Y, Points[0].X + 1, Points[0].Y + 1);
{ Pins on the left }
for i := 0 to IC_Half_Pins - 1 do
ACanvas.Line(GridCoordsToSheet(0, 1 + i), GridCoordsToSheet(1, 1 + i));
{ Pins on the right }
for i := 0 to IC_Half_Pins - 1 do
ACanvas.Line(GridCoordsToSheet(IC_Width + 1, 1 + i), GridCoordsToSheet(IC_Width + 2, 1 + i));
{ IC Name on the top}
Points[2] := GridCoordsToSheet(1, 0);
ACanvas.TextOut(Points[2].X, Points[2].Y - ACanvas.Font.Height, Cmds[3]);
end
else if Cmds[0] = STR_DRAWINGCODE_IC_TEXT_LEFT_1 then
begin
for i := 0 to 7 do
if Cmds[i + 1] <> '' then
begin
Points[0] := GridCoordsToSheet(1, i);
ACanvas.TextOut(Points[0].X + 1, Points[0].Y, Cmds[i + 1]);
end;
end
else if Cmds[0] = STR_DRAWINGCODE_IC_TEXT_LEFT_2 then
begin
for i := 0 to 7 do
if Cmds[i + 1] <> '' then
begin
Points[0] := GridCoordsToSheet(1, i + 8);
ACanvas.TextOut(Points[0].X, Points[0].Y, Cmds[i + 1]);
end;
end
else if Cmds[0] = STR_DRAWINGCODE_IC_TEXT_RIGHT_1 then
begin
for i := 0 to 7 do
if Cmds[i + 1] <> '' then
begin
Points[0] := GridCoordsToSheet(1 + IC_Width - 2, i);
ACanvas.TextOut(Points[0].X, Points[0].Y, Cmds[i + 1]);
end;
end
else if Cmds[0] = STR_DRAWINGCODE_IC_TEXT_RIGHT_2 then
begin
for i := 0 to 7 do
if Cmds[i + 1] <> '' then
begin
Points[0] := GridCoordsToSheet(1 + IC_Width - 2, i + 8);
ACanvas.TextOut(Points[0].X, Points[0].Y, Cmds[i + 1]);
end;
end;
except
// Exit silently in floating-point conversion exceptions
end;
end;
{@@
Draws a wire
}
procedure TItemsDrawer.DrawWire(ACanvas: TCanvas; AElement: PTCElement);
var
AWire: PTCWire;
PtFrom, PtTo: TPoint;
begin
AWire := PTCWire(AElement);
PtFrom.X := AWire^.Pos.X * INT_SHEET_GRID_SPACING;
PtFrom.Y := AWire^.Pos.Y * INT_SHEET_GRID_SPACING;
PtTo.X := AWire^.PtTo.X * INT_SHEET_GRID_SPACING;
PtTo.Y := AWire^.PtTo.Y * INT_SHEET_GRID_SPACING;
ACanvas.Line(PtFrom, PtTo);
end;
{@@
Draws the screen indication that a given wire
is selected
}
procedure TItemsDrawer.DrawWireSelection(ACanvas: TCanvas; AWire: PTCWire;
AWirePart: DWord);
begin
case AWirePart of
ELEMENT_START_POINT: ACanvas.Rectangle(
AWire^.Pos.X * INT_SHEET_GRID_SPACING - INT_SHEET_GRID_HALFSPACING,
AWire^.Pos.Y * INT_SHEET_GRID_SPACING - INT_SHEET_GRID_HALFSPACING,
AWire^.Pos.X * INT_SHEET_GRID_SPACING + INT_SHEET_GRID_HALFSPACING,
AWire^.Pos.Y * INT_SHEET_GRID_SPACING + INT_SHEET_GRID_HALFSPACING);
ELEMENT_END_POINT: ACanvas.Rectangle(
AWire^.PtTo.X * INT_SHEET_GRID_SPACING - INT_SHEET_GRID_HALFSPACING,
AWire^.PtTo.Y * INT_SHEET_GRID_SPACING - INT_SHEET_GRID_HALFSPACING,
AWire^.PtTo.X * INT_SHEET_GRID_SPACING + INT_SHEET_GRID_HALFSPACING,
AWire^.PtTo.Y * INT_SHEET_GRID_SPACING + INT_SHEET_GRID_HALFSPACING);
end;
end;
procedure TItemsDrawer.DrawText(ACanvas: TCanvas; AElement: PTCElement);
var
AText: PTCText;
begin
if AElement = nil then Exit;
AText := PTCText(AElement);
DrawPosCross(ACanvas, AText^.Pos);
ACanvas.TextOut(
AText^.Pos.X * INT_SHEET_GRID_SPACING,
AText^.Pos.Y * INT_SHEET_GRID_SPACING,
AText^.Text);
end;
procedure TItemsDrawer.DrawTextSelection(ACanvas: TCanvas; AElement: TvText);
var
CanvasPos: TPoint;
lFirstLine: String;
begin
if AElement = nil then Exit;
CanvasPos := vDocument.VectorialPosToCanvasPos(AElement.X, AElement.Y);
ACanvas.Pen.Style := psDash;
ACanvas.Brush.Style := bsClear;
if AElement.Value.Count = 0 then lFirstLine := 'M'
else lFirstLine := AElement.Value.Strings[0];
ACanvas.Rectangle(
CanvasPos.X,
CanvasPos.Y,
CanvasPos.X + ACanvas.TextWidth(lFirstLine),
CanvasPos.Y + (ACanvas.TextHeight(lFirstLine) + 2) * AElement.Value.Count
);
ACanvas.Pen.Style := psSolid;
ACanvas.Brush.Style := bsSolid;
end;
procedure TItemsDrawer.DrawTextExtra(ACanvas: TCanvas; AElement: TvText);
var
CanvasPos: TPoint;
begin
if AElement = nil then Exit;
CanvasPos := vDocument.VectorialPosToCanvasPos(AElement.X, AElement.Y);
ACanvas.Pen.Style := psDash;
ACanvas.Brush.Style := bsClear;
ACanvas.Line(CanvasPos.X - 10, CanvasPos.Y, CanvasPos.X + 10, CanvasPos.Y);
ACanvas.Line(CanvasPos.X, CanvasPos.Y - 10, CanvasPos.X, CanvasPos.Y + 10);
ACanvas.Pen.Style := psSolid;
ACanvas.Brush.Style := bsSolid;
end;
procedure TItemsDrawer.DrawPolyline(ACanvas: TCanvas; AElement: PTCElement);
var
APolyline: PTCPolyline absolute AElement;
i: Integer;
begin
ACanvas.Pen.Color := clBlack;
ACanvas.Pen.Width := APolyline^.Width;
ACanvas.Brush.Color := clBlack;
if AElement = nil then Exit;
for i := 1 to APolyline^.NPoints - 1 do
ACanvas.Line(
APolyline^.Points[i - 1].X * INT_SHEET_GRID_SPACING,
APolyline^.Points[i - 1].Y * INT_SHEET_GRID_SPACING,
APolyline^.Points[i].X * INT_SHEET_GRID_SPACING,
APolyline^.Points[i].Y * INT_SHEET_GRID_SPACING
);
ACanvas.Pen.Width := 1;
end;
procedure TItemsDrawer.DrawPolylineSelection(ACanvas: TCanvas;
AElement: PTCElement; APointNr: Integer);
begin
end;
procedure TItemsDrawer.DrawRasterImage(ACanvas: TCanvas; AElement: PTCElement);
var
ARasterImage: PTCRasterImage absolute AElement;
i: Integer;
begin
if AElement = nil then Exit;
DrawPosCross(ACanvas, AElement^.Pos);
if ARasterImage^.ImageData <> nil then
begin
ACanvas.StretchDraw(
Bounds(
ARasterImage^.Pos.X * INT_SHEET_GRID_SPACING,
ARasterImage^.Pos.Y * INT_SHEET_GRID_SPACING,
Round(ARasterImage^.ImageData.Graphic.Width * ARasterImage^.Proportion * vDocument.ZoomLevel),
Round(ARasterImage^.ImageData.Graphic.Height * ARasterImage^.Proportion * vDocument.ZoomLevel)
),
ARasterImage^.ImageData.Graphic);
end;
end;
{procedure TItemsDrawer.DrawEllipse(ACanvas: TCanvas; AElement: PTCElement);
var
AEllipse: PTCEllipse absolute AElement;
begin
if AElement = nil then Exit;
ACanvas.Ellipse(AEllipse^.Pos.X * INT_SHEET_GRID_SPACING, AEllipse^.Pos.Y * INT_SHEET_GRID_SPACING,
AEllipse^.BottomRight.X * INT_SHEET_GRID_SPACING, AEllipse^.BottomRight.Y * INT_SHEET_GRID_SPACING);
end;}
procedure TItemsDrawer.DrawPosCross(ACanvas: TCanvas; APos: TPoint);
begin
ACanvas.Pen.Style := psDash;
ACanvas.Line(
APos.X * INT_SHEET_GRID_SPACING - INT_SHEET_DEFAULT_GRID_SPACING,
APos.Y * INT_SHEET_GRID_SPACING,
APos.X * INT_SHEET_GRID_SPACING + INT_SHEET_DEFAULT_GRID_SPACING,
APos.Y * INT_SHEET_GRID_SPACING
);
ACanvas.Line(
APos.X * INT_SHEET_GRID_SPACING,
APos.Y * INT_SHEET_GRID_SPACING - INT_SHEET_DEFAULT_GRID_SPACING,
APos.X * INT_SHEET_GRID_SPACING,
APos.Y * INT_SHEET_GRID_SPACING + INT_SHEET_DEFAULT_GRID_SPACING
);
ACanvas.Pen.Style := psSolid;
end;
constructor TItemsDrawer.Create;
begin
FPointSeparator := DefaultFormatSettings;
FPointSeparator.DecimalSeparator := '.';
//FPointSeparator.ThousandSeparator := '#';// disable the thousand separator
end;
{@@
Given the inputs:
APoint - A point, in pixels, which represents
an absolute position on the schematics screen,
with the suposition that the component has coEast
orientation.
(DeltaX, DeltaY) - The origin of the component in
grid units.
This method calculates a new absolute position on
the schematics screen, fixed to correctly observe
the orientation of the component.
This method was introduced to help other methods
which produce an absolute screen position and then
need to adequate it to the orientation of the
component.
}
function TItemsDrawer.FixCoordinates(APoint: TPoint): TPoint;
var
BigDeltaX, BigDeltaY: Integer;
begin
BigDeltaX := DeltaX * INT_SHEET_GRID_SPACING;
BigDeltaY := DeltaY * INT_SHEET_GRID_SPACING;
case Orientation of
coEast: Result := APoint;
coNorth:
begin
Result.X := BigDeltaX + (APoint.Y - BigDeltaY);
Result.Y := BigDeltaY - (APoint.X - BigDeltaX);
end;
coWest:
begin
Result.X := BigDeltaX - (APoint.X - BigDeltaX);
Result.Y := BigDeltaY - (APoint.Y - BigDeltaY);
end;
coSouth:
begin
Result.X := BigDeltaX - (APoint.Y - BigDeltaY);
Result.Y := BigDeltaY + (APoint.X - BigDeltaX);
end;
end;
end;
{@@
Converts simple grid coordinates to sheet coordinates already
taking the rotation into account.
}
function TItemsDrawer.GridCoordsToSheet(AX, AY: Single): TPoint;
begin
Result := FixCoordinates(Point(
Round((DeltaX + AX) * INT_SHEET_GRID_SPACING),
Round((DeltaY + AY) * INT_SHEET_GRID_SPACING)
));
end;
initialization
vItemsDrawer := TItemsDrawer.Create;
finalization
vItemsDrawer.Free;
end.
|
unit clDetalheTransporte;
interface
uses clConexao;
type
TDetalheTransporte = Class(TObject)
private
constructor Create;
destructor Destroy;
procedure MaxSeq;
function gerRelatorio: Integer;
function getChegada: TTime;
function getDetalhe: String;
function getObservacoes: String;
function getRegistro: TDateTime;
function getSaida: TTime;
function getSequencia: Integer;
function getUsuario: String;
procedure setChegada(const Value: TTime);
procedure setDetalhe(const Value: String);
procedure setObservacoes(const Value: String);
procedure setRegistro(const Value: TDateTime);
procedure setRelatorio(const Value: Integer);
procedure setSaida(const Value: TTime);
procedure setSequencia(const Value: Integer);
procedure setUsuario(const Value: String);
function getInicio: TTime;
function getTermino: TTime;
procedure setInicio(const Value: TTime);
procedure setTermino(const Value: TTime);
protected
_relatorio: Integer;
_sequencia: Integer;
_desricao: String;
_chegada: TTime;
_inicio: TTime;
_termino: TTime;
_saida: TTime;
_observacoes: String;
_usuario: String;
_registro: TDateTime;
_conexao: TConexao;
public
property Relatorio: Integer read gerRelatorio write setRelatorio;
property Sequencia: Integer read getSequencia write setSequencia;
property Detalhe: String read getDetalhe write setDetalhe;
property Chegada: TTime read getChegada write setChegada;
property Inicio: TTime read getInicio write setInicio;
property Termino: TTime read getTermino write setTermino;
property Saida: TTime read getSaida write setSaida;
property Observacoes: String read getObservacoes write setObservacoes;
property Usuario: String read getUsuario write setUsuario;
property Registro: TDateTime read getRegistro write setRegistro;
function Validar(): Boolean;
function Delete(filtro: String): Boolean;
function getObject(id, filtro: String): Boolean;
function getObjects(): Boolean;
function getField(campo, coluna: String): String;
function Insert(): Boolean;
function Update(): Boolean;
End;
const
TABLENAME = 'TBDETALHETRANSPORTE';
implementation
{ TDetalheTransporte }
uses SysUtils, Dialogs, udm, clUtil, DB, Math, DateUtils, ZAbstractRODataset,
ZAbstractDataset, ZDataset;
constructor TDetalheTransporte.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TDetalheTransporte.Destroy;
begin
_conexao.Free;
end;
function TDetalheTransporte.Validar(): Boolean;
begin
Result := False;
if TUTil.Empty(TimeToStr(Self.Chegada)) then
begin
MessageDlg('Informe a Hora da Chegada!', mtWarning, [mbOK], 0);
Exit;
end;
if TUTil.Empty(Self.Detalhe) then
begin
MessageDlg('Informe o Detalhe do Transporte!', mtWarning, [mbOK], 0);
Exit;
end;
Result := True;
end;
function TDetalheTransporte.Delete(filtro: string): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'RELATORIO' then
begin
SQL.Add('WHERE SEQ_RELATORIO = :RELATORIO');
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
end;
if filtro = 'SEQUENCIA' then
begin
SQL.Add('WHERE SEQ_RELATORIO = :RELATORIO AND SEQ_DETALHE = :SEQUENCIA');
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TDetalheTransporte.getObject(id: string; filtro: string): Boolean;
var
dsGet: TZQuery;
begin
try
Result := False;
dsGet := dm.qryGetObject;
with dsGet do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'RELATORIO' then
begin
SQL.Add('WHERE SEQ_RELATORIO = :RELATORIO');
ParamByName('RELATORIO').AsInteger := StrToInt(id);
end;
if filtro = 'SEQUENCIA' then
begin
SQL.Add('WHERE SEQ_RELATORIO = :RELATORIO AND SEQ_DETALHE = :SEQUENCIA');
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
ParamByName('SEQUENCIA').AsInteger := StrToInt(id);
end;
dm.ZConn.PingServer;
Connection := dm.ZConn;
Open;
if not(IsEmpty) then
begin
if RecordCount >= 1 then
begin
Self.Relatorio := FieldByName('SEQ_RELATORIO').AsInteger;
Self.Sequencia := FieldByName('SEQ_DETALHE').AsInteger;
Self.Detalhe := FieldByName('DES_TRANSPORTE').AsString;
Self.Chegada := FieldByName('HOR_CHEGADA').AsDateTime;
Self.Inicio := FieldByName('HOR_INICIO_CARGA').AsDateTime;
Self.Termino := FieldByName('HOR_TERMINO_CARGA').AsDateTime;
Self.Saida := FieldByName('HOR_SAIDA').AsDateTime;
Self.Observacoes := FieldByName('DES_OBSERVACOES').AsString;
Self.Usuario := FieldByName('NOM_EXECUTANTE').AsString;
Self.Registro := FieldByName('DAT_MANUTENCAO').AsDateTime;
end;
end
else
begin
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TDetalheTransporte.getObjects(): Boolean;
begin
try
Result := False;
with dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
dm.ZConn.PingServer;
Open;
if IsEmpty then
begin
MessageDlg('Nenhum registro encontrado!', mtWarning, [mbOK], 0);
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TDetalheTransporte.gerRelatorio: Integer;
begin
Result := _relatorio;
end;
function TDetalheTransporte.getChegada: TTime;
begin
Result := _chegada;
end;
function TDetalheTransporte.getDetalhe: String;
begin
Result := _desricao;
end;
function TDetalheTransporte.getObservacoes: String;
begin
Result := _observacoes;
end;
function TDetalheTransporte.getRegistro: TDateTime;
begin
Result := _registro;
end;
function TDetalheTransporte.getSaida: TTime;
begin
Result := _saida;
end;
function TDetalheTransporte.getSequencia: Integer;
begin
Result := _sequencia;
end;
function TDetalheTransporte.getTermino: TTime;
begin
Result := _termino;
end;
function TDetalheTransporte.getUsuario: String;
begin
Result := _usuario;
end;
function TDetalheTransporte.getField(campo: string; coluna: string): String;
begin
try
Result := '';
with dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT ' + campo + ' FROM ' + TABLENAME);
if coluna = 'SEQUENCIA' then
begin
SQL.Add('WHERE SEQ_RELATORIO = :RELATORIO AND SEQ_DETALHE = :SEQUENCIA');
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end;
if coluna = 'SEQUENCIA' then
begin
SQL.Add('WHERE SEQ_DETALHE= :SEQUENCIA');
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end;
dm.ZConn.PingServer;
Open;
if IsEmpty then
begin
MessageDlg('Nenhum registro encontrado!', mtWarning, [mbOK], 0);
end
else
begin
Result := FieldByName(campo).AsString;
end;
Close;
SQL.Clear;
end;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TDetalheTransporte.getInicio: TTime;
begin
Result := _inicio;
end;
procedure TDetalheTransporte.MaxSeq;
begin
try
with dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT MAX(SEQ_DETALHE) AS NUMERO FROM ' + TABLENAME +
' WHERE SEQ_RELATORIO = :RELATORIO');
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
Self.Sequencia := FieldByName('NUMERO').AsInteger + 1;
end
else
begin
Self.Sequencia := 1;
end;
Close;
SQL.Clear;
end;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
procedure TDetalheTransporte.setChegada(const Value: TTime);
begin
_chegada := Value;
end;
procedure TDetalheTransporte.setDetalhe(const Value: String);
begin
_desricao := Value;
end;
procedure TDetalheTransporte.setInicio(const Value: TTime);
begin
_inicio := Value;
end;
procedure TDetalheTransporte.setObservacoes(const Value: String);
begin
_observacoes := Value;
end;
procedure TDetalheTransporte.setRegistro(const Value: TDateTime);
begin
_registro := Value;
end;
procedure TDetalheTransporte.setRelatorio(const Value: Integer);
begin
_relatorio := Value;
end;
procedure TDetalheTransporte.setSaida(const Value: TTime);
begin
_saida := Value;
end;
procedure TDetalheTransporte.setSequencia(const Value: Integer);
begin
_sequencia := Value;
end;
procedure TDetalheTransporte.setTermino(const Value: TTime);
begin
_termino := Value;
end;
procedure TDetalheTransporte.setUsuario(const Value: String);
begin
_usuario := Value;
end;
function TDetalheTransporte.Insert(): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + '(SEQ_RELATORIO, ' +
'SEQ_DETALHE, ' + 'DES_TRANSPORTE, ' + 'HOR_CHEGADA, ' +
'HOR_INICIO_CARGA, ' + 'HOR_TERMINO_CARGA, ' + 'HOR_SAIDA, ' +
'DES_OBSERVACOES, ' + 'NOM_EXECUTANTE, ' + 'DAT_MANUTENCAO) ' +
'VALUES (' + ':RELATORIO, ' + ':SEQUENCIA, ' + ':DETALHE, ' +
':CHEGADA, ' + ':INICIO, ' + ':TERMINO, ' + ':SAIDA, ' +
':OBSERVACOES, ' + ':USUARIO, ' + ':REGISTRO)';
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('DETALHE').AsString := Self.Detalhe;
ParamByName('CHEGADA').AsTime := Self.Chegada;
ParamByName('INICIO').AsTime := Self.Inicio;
ParamByName('TERMINO').AsTime := Self.Termino;
ParamByName('SAIDA').AsTime := Self.Saida;
ParamByName('OBSERVACOES').AsString := Self.Observacoes;
ParamByName('USUARIO').AsString := Self.Usuario;
ParamByName('REGISTRO').AsDateTime := Self.Registro;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TDetalheTransporte.Update(): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'DES_TRANSPORTE = :DETALHE, ' + 'HOR_CHEGADA = :CHEGADA, ' +
'HOR_INICIO_CARGA = :INICIO, ' + 'HOR_TERMINO_CARGA = :TERMINO ' +
'HOR_SAIDA = :SAIDA, ' + 'DES_OBSERVACOES = :OBSERVACOES, '
+ 'NOM_USUARIO = :USUARIO, ' + 'DAT_MANUTENCAO = :REGISTRO '
+ 'WHERE ' + 'SEQ_RELATORIO = :RELATORIO AND SEQ_DETALHE = :SEQUENCIA';
ParamByName('RELATORIO').AsInteger := Self.Relatorio;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('DETALHE').AsString := Self.Detalhe;
ParamByName('CHEGADA').AsTime := Self.Chegada;
ParamByName('INICIO').AsTime := Self.Inicio;
ParamByName('TERMINO').AsTime := Self.Termino;
ParamByName('SAIDA').AsTime := Self.Saida;
ParamByName('OBSERVACOES').AsString := Self.Observacoes;
ParamByName('USUARIO').AsString := Self.Usuario;
ParamByName('REGISTRO').AsDateTime := Self.Registro;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
end.
|
unit ColorSpaces;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, NumUtils;
const
maxRgb = 255;
maxHls = 240;
type
THlsQuad =
packed record
hlsHue : byte;
hlsLight : byte;
hlsSat : byte;
hlsReserved : byte;
end;
function RgbToBgr( RgbQuad : dword ) : dword;
function RgbToHls( Rgb : TRgbQuad ) : THlsQuad;
function HlsToRgb( Hls : THlsQuad ) : TRgbQuad;
function HlsHue( Rgb : TRgbQuad ) : integer;
function HlsLight( Rgb : TRgbQuad ) : integer;
function HlsSaturation( Rgb : TRgbQuad ) : integer;
procedure ChangeHueOf( var Rgb : TRgbQuad; NewHue : integer );
procedure ChangeLightOf( var Rgb : TRgbQuad; NewLight : integer );
procedure ScaleLightOf( var Rgb : TRgbQuad; scale : single );
procedure ChangeSaturationOf( var Rgb : TRgbQuad; NewSat : integer );
// Tint Colors ------------------------------------------------------------------------
procedure TintRgbEntries( Indx, Count : integer; var RgbEntries; TintRgb, BaseRgb : longint );
// Gamma Correction -------------------------------------------------------------------
procedure GammaCorrectRgbEntries( Indx, Count : integer; var RgbEntries; Percent : integer );
implementation
function RgbToBgr( RgbQuad : dword ) : dword;
var
Rgb : TRgbQuad absolute RgbQuad;
Res : TRgbQuad absolute Result;
begin
Result := RgbQuad;
Res.rgbRed := Rgb.rgbBlue;
Res.rgbBlue := Rgb.rgbRed;
end;
procedure ChangeHueOf( var Rgb : TRgbQuad; NewHue : integer );
var
tmpHls : THlsQuad;
begin
tmpHls := RgbToHls( Rgb );
tmpHls.hlsHue := NewHue;
Rgb := HlsToRgb( tmpHls );
end;
procedure ChangeLightOf( var Rgb : TRgbQuad; NewLight : integer );
var
tmpHls : THlsQuad;
begin
tmpHls := RgbToHls( Rgb );
tmpHls.hlsLight := NewLight;
Rgb := HlsToRgb( tmpHls );
end;
procedure ScaleLightOf( var Rgb : TRgbQuad; scale : single );
var
tmpHls : THlsQuad;
begin
tmpHls := RgbToHls( Rgb );
tmpHls.hlsLight := min( 255, round(sqr(0.4 + scale)*integer(tmpHls.hlsLight) ));
Rgb := HlsToRgb( tmpHls );
end;
procedure ChangeSaturationOf( var Rgb : TRgbQuad; NewSat : integer );
var
tmpHls : THlsQuad;
begin
tmpHls := RgbToHls( Rgb );
tmpHls.hlsSat := NewSat;
Rgb := HlsToRgb( tmpHls );
end;
function HlsHue( Rgb : TRgbQuad ) : integer; // !!!! Could be optimized..
begin
Result := RgbToHls( Rgb ).hlsHue;
end;
function HlsSaturation( Rgb : TRgbQuad ) : integer; // !!!! Could be optimized..
begin
Result := RgbToHls( Rgb ).hlsSat;
end;
const
hueUndefined = 160;
function HlsLight( Rgb : TRgbQuad ) : integer;
var
RgbMax, RgbMin : cardinal;
begin
with Rgb do
begin
RgbMax := Max3( rgbBlue, rgbGreen, rgbRed );
RgbMin := Min3( rgbBlue, rgbGreen, rgbRed );
Result := ( (RgbMax + RgbMin) * maxHls + maxRgb ) div (maxRgb * 2 );
end;
end;
function RgbToHls( Rgb : TRgbQuad ) : THlsQuad;
var
s, r, k : cardinal;
Hue, Light, Sat : integer;
deltaR, deltaG, deltaB : cardinal;
RgbMax, RgbMin : cardinal;
begin
with {Result,} Rgb do
begin
RgbMax := Max3( rgbBlue, rgbGreen, rgbRed );
RgbMin := Min3( rgbBlue, rgbGreen, rgbRed );
s := RgbMax + RgbMin;
r := RgbMax - RgbMin;
Light := (s * maxHls + maxRgb ) div (maxRgb * 2 );
if RgbMax = RgbMin
then // Achromatic case, R = G = B
begin
Sat := 0;
Hue := hueUndefined;
end
else // Chromatic case
begin
// Saturation
if Light <= maxHls div 2
then Sat := (r * maxHls + s div 2 ) div s
else
begin
k := 2 * maxRgb - s;
Sat := (r * maxHls + k div 2 ) div k;
end;
// Hue
deltaR := ((RgbMax - rgbRed ) * (maxHls div 6 ) + r div 2 ) div r;
deltaG := ((RgbMax - rgbGreen ) * (maxHls div 6 ) + r div 2 ) div r;
deltaB := ((RgbMax - rgbBlue ) * (maxHls div 6 ) + r div 2 ) div r;
if RgbMax = rgbRed
then Hue := deltaB - deltaG
else
if RgbMax = rgbGreen
then Hue := maxHls div 3 + deltaR - deltaB
else Hue := maxHls * 2 div 3 + deltaG - deltaR;
if Hue < 0
then inc( Hue, maxHls );
if Hue > maxHls
then dec( Hue, maxHls );
end;
end;
with Result do
begin
hlsHue := Hue;
hlsLight := Light;
hlsSat := Sat;
hlsReserved := 0;
end;
end;
function HueToRgb( magic1, magic2, hue : integer ) : dword;
var
r : integer;
begin
// Range check: note values passed add/substract thirds of range
if hue < 0
then inc( hue, maxHls );
if hue > maxHls
then dec( hue, maxHls );
r := magic2 - magic1;
// Return r, g, or b value from this tridant
if hue < maxHls div 6
then Result := magic1 + (r * hue + (maxHls div 12 ) ) div (maxHls div 6 )
else
if hue < maxHls div 2
then Result := magic2
else
if hue < maxHls * 2 div 3
then Result := magic1 + (r * (maxHls * 2 div 3 - hue ) + maxHls div 12 )
div (maxHls div 6 )
else Result := magic1;
end;
function HlsToRgb( Hls : THlsQuad ) : TRgbQuad;
var
r : cardinal;
magic1, magic2 : cardinal; // Calculated magic numbers (really!!)
begin
with Result, Hls do
begin
if hlsSat = 0
then // Achromatic case
begin
r := hlsLight * maxRgb div maxHls;
rgbRed := r;
rgbGreen := r;
rgbBlue := r;
if hlsHue <> hueUndefined
then ; // Error!!
end
else // Chromatic case
begin
// Set up magic numbers
if hlsLight <= maxHls div 2
then magic2 := (hlsLight * (maxHls + hlsSat ) + maxHls div 2 ) div maxHls
else magic2 := hlsLight + hlsSat - (hlsLight * hlsSat + maxHls div 2 ) div maxHls;
magic1 := 2 * hlsLight - magic2;
// Get Rgb, change units from maxHls to maxRgb
rgbRed := (HueToRgb( magic1, magic2, hlsHue + maxHls div 3 ) * maxRgb + maxHls div 2 ) div maxHls;
rgbGreen := (HueToRgb( magic1, magic2, hlsHue ) * maxRgb + maxHls div 2 ) div maxHls;
rgbBlue := (HueToRgb( magic1, magic2, hlsHue - maxHls div 3 ) * maxRgb + maxHls div 2 ) div maxHls;
end;
end;
end;
procedure GammaCorrectRgbEntries( Indx, Count : integer; var RgbEntries; Percent : integer );
var
Entries : array[0..255] of TRgbQuad absolute RgbEntries;
i : integer;
Hls : THlsQuad;
begin
for i := Indx to Indx + Count - 1 do
begin
Hls := RgbToHls( Entries[i] );
with Hls do
begin
hlsLight := hlsLight * Percent div 100;
if hlsLight > maxHls
then hlsLight := maxHls;
end;
Entries[i] := HlsToRgb( Hls );
end;
end;
procedure TintRgbEntries( Indx, Count : integer; var RgbEntries; TintRgb, BaseRgb : longint );
var
i : integer;
Entries : array[0..255] of TRgbQuad absolute RgbEntries;
TintLight : integer;
BaseLight : integer;
CurrentHls : THlsQuad;
NewLight : integer;
begin
CurrentHls := RgbToHls( TRgbQuad( TintRgb ) );
BaseLight := HlsLight( TRgbQuad( BaseRgb ) );
TintLight := CurrentHls.hlsLight;
for i := Indx to Indx + Count - 1 do
begin
NewLight := HlsLight( Entries[i] ) + TintLight - BaseLight;
if NewLight > maxHls
then CurrentHls.hlsLight := maxHls
else
if NewLight < 0
then CurrentHls.hlsLight := 0
else CurrentHls.hlsLight := NewLight;
Entries[i] := HlsToRgb( CurrentHls );
end;
end;
end.
|
{******************************************************************************}
{ }
{ Hook and Translate }
{ }
{ The contents of this file are subject to the MIT License (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at https://opensource.org/licenses/MIT }
{ }
{ 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 GdiHook.pas. }
{ }
{ Contains various graphics related classes and subroutines required for }
{ creating a chart and its nodes, and visual chart interaction. }
{ }
{ Unit owner: Mišel Krstović }
{ Last modified: March 8, 2010 }
{ }
{******************************************************************************}
unit GdiHook;
interface
uses Windows;
implementation
const NULL = 0;
function InjectDLL(idProcess : DWORD) : integer;
var
hProcess : THandle;
szDLLPath : string; //array[0..100-1] of char;
exitCode : DWORD;
lpDLLName : Pointer;
hThread : THandle;
BytesWritten : Cardinal;
idThread : DWORD;
begin
// Get the process handle
hProcess := OpenProcess(PROCESS_ALL_ACCESS, false, idProcess);
if (hProcess = NULL) then begin
result := 0;
exit;
end;
szDLLPath := 'GdiHook.dll'; // this is the name of your DLL to inject
// Allocate memory for writing data within the process
lpDLLName := VirtualAllocEx(hProcess, nil, sizeof(szDLLPath), MEM_RESERVE OR MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (lpDLLName = nil) then begin
result := -1;
exit;
end;
// Write the library path to the allocated memory
if not(
WriteProcessMemory(
hProcess,
lpDLLName,
PChar(szDLLPath),
sizeof(szDLLPath),
BytesWritten
)
) then begin
result := -2;
exit;
end;
// use CreateRemoteThread to call LoadLibrary within the remote process with the
// pDLLName as its parameter, so the library is mapped into the remote process
hThread := CreateRemoteThread(hProcess, nil, 0, GetProcAddress(GetModuleHandle('kernel32.dll'), 'LoadLibraryA'),
lpDLLName, 0, idThread);
if (hThread = NULL) then begin
result := -3;
exit;
end;
WaitForSingleObject(hThread, INFINITE);
GetExitCodeThread(hThread, exitCode);
CloseHandle(hThread);
// Free the memory
VirtualFreeEx(hProcess, lpDLLName, sizeof(szDLLPath), MEM_RELEASE);
result := exitCode;
end;
end.
|
unit TasksUnit;
interface
uses Classes, Contnrs, SysUtils, DbUnit;
type
TTaskItem = class(TDbItem)
public
Desc: string;
Text: string;
Priority: integer;
Status: integer;
PersonID: integer;
DepartID: integer;
Author: string;
BeginDate: TDateTime;
EndDate: TDateTime;
function GetValue(const FName: string): string; override;
procedure SetValue(const FName, FValue: string); override;
end;
TTaskList = class(TDbItemList)
private
AFilterID: integer;
AFilterType: integer;
public
BeginDate: TDateTime;
EndDate: TDateTime;
constructor Create(); reintroduce;
function NewItem(): TDbItem; override;
procedure LoadList();
procedure SaveList();
procedure Sort();
// Filter type: 0-none, 1-person, 2-depart
procedure SetFilter(FilterType, FilterID: integer);
end;
type
TStringArray = array of string;
implementation
uses MainFunc;
// === TTaskItem ===
function TTaskItem.GetValue(const FName: string): string;
begin
if FName='id' then
result:=IntToStr(self.ID)
else if FName='name' then
result:=self.Name
else if FName='text' then
result:=self.Text
else if FName='priority' then
result:=IntToStr(self.Priority)
else if FName='status' then
result:=IntToStr(self.Status)
else if FName='person_id' then
result:=IntToStr(self.PersonID)
else if FName='depart_id' then
result:=IntToStr(self.DepartID)
else if FName='author' then
result:=self.Author
else if FName='begin_date' then
result:=DateTimeToStr(self.BeginDate)
else if FName='end_date' then
result:=DateTimeToStr(self.EndDate)
else
result:='';
end;
procedure TTaskItem.SetValue(const FName, FValue: string);
begin
if FName='id' then
self.ID:=StrToIntDef(FValue, 0)
else if FName='name' then
self.Name:=FValue
else if FName='text' then
self.Text:=FValue
else if FName='priority' then
self.Priority:=StrToIntDef(FValue, 0)
else if FName='status' then
self.Status:=StrToIntDef(FValue, 0)
else if FName='person_id' then
self.PersonID:=StrToIntDef(FValue, 0)
else if FName='depart_id' then
self.DepartID:=StrToIntDef(FValue, 0)
else if FName='author' then
self.Author:=FValue
else if FName='begin_date' then
self.BeginDate:=StrToDateTime(FValue)
else if FName='end_date' then
self.EndDate:=StrToDateTime(FValue);
end;
// === TTaskList ===
constructor TTaskList.Create();
var
ti: TDbTableInfo;
begin
ti:=DbDriver.GetDbTableInfo('tasks');
if not Assigned(ti) then
begin
ti:=TDbTableInfo.Create();
with ti do
begin
TableName:='tasks';
AddField('id','I');
AddField('name','S');
AddField('text','S');
AddField('priority','I');
AddField('status','I');
AddField('person_id','L:personnel');
AddField('depart_id','I');
AddField('author','S');
AddField('begin_date','D');
AddField('end_date','D');
end;
end;
inherited Create(ti);
end;
procedure StringToItem(Str: string; Task: TTaskItem);
var
sl: TStringList;
i: integer;
begin
sl:=TStringList.Create();
sl.CommaText:=StringReplace(Str, '~>', #13+#10, [rfReplaceAll]);
i:=0;
Task.ID:=StrToIntDef(sl[i], 0);
Inc(i);
Task.Desc:=sl[i];
Inc(i);
Task.Text:=sl[i];
Inc(i);
Task.Priority:=StrToIntDef(sl[i], 0);
Inc(i);
Task.Status:=StrToIntDef(sl[i], 0);
Inc(i);
Task.PersonID:=StrToIntDef(sl[i], 0);
Inc(i);
Task.DepartID:=StrToIntDef(sl[i], 0);
Inc(i);
Task.Author:=sl[i];
Inc(i);
if sl[i]<>'' then Task.BeginDate:=StrToDateTime(sl[i]);
Inc(i);
if sl[i]<>'' then Task.EndDate:=StrToDateTime(sl[i]);
sl.Free();
end;
function ItemToString(Task: TTaskItem): string;
var
sl: TStringList;
begin
sl:=TStringList.Create();
sl.Add(IntToStr(Task.ID));
sl.Add(Task.Desc);
sl.Add(Task.Text);
sl.Add(IntToStr(Task.Priority));
sl.Add(IntToStr(Task.Status));
sl.Add(IntToStr(Task.PersonID));
sl.Add(IntToStr(Task.DepartID));
sl.Add(Task.Author);
sl.Add(DateTimeToStr(Task.BeginDate));
sl.Add(DateTimeToStr(Task.EndDate));
result:=StringReplace(sl.CommaText, #13+#10, '~>', [rfReplaceAll]);
sl.Free();
end;
procedure TTaskList.LoadList();
var
sFilter: string;
begin
if self.AFilterType=1 then sFilter:='person_id='+IntToStr(self.AFilterID);
DbDriver.GetTable(self, sFilter);
end;
procedure TTaskList.SaveList();
begin
DbDriver.SetTable(self);
end;
function CompareFunc(Item1, Item2: Pointer): Integer;
begin
result := TTaskItem(Item2).Priority - TTaskItem(Item1).Priority;
end;
procedure TTaskList.Sort();
begin
inherited Sort(@CompareFunc);
end;
function TTaskList.NewItem(): TDbItem;
var
NewItem: TTaskItem;
begin
NewItem:=TTaskItem.Create();
self.AddItem(NewItem, true);
result:=NewItem;
end;
procedure TTaskList.SetFilter(FilterType, FilterID: integer);
begin
self.AFilterType:=FilterType;
self.AFilterID:=FilterID;
self.LoadList();
end;
end.
|
// **********************************************************************
//
// Copyright (c) 2001 MT Tools.
//
// All Rights Reserved
//
// MT_DORB is based in part on the product DORB,
// written by Shadrin Victor
//
// See Readme.txt for contact information
//
// **********************************************************************
unit ssl_int;
interface
uses
orbtypes,Classes,addr_int,code_int,iior_int,SysUtils,comp_int;
{$I dorb.inc}
type
(*
* The security spec says that AssociationOptions is
* unsigned short, but Visibroker defines it as unsigned long.
* I dont know whether this is a bug in VB or whether the
* spec changed the definition (perhaps it was an enum before?).
* For compatibility with VB we use unsigned long as well...
*)
{$IFDEF MTDORB_SSL_VB_COMPAT}
AssociationOptions = _ulong;
{$ELSE}
AssociationOptions = _ushort;
{$ENDIF}
ISSLPrincipal = interface(IPrincipal)
['{8CC321AD-F495-4E83-A021-B7F1B156348D}']
end;
ISSLAddress = interface(IAddress)
['{2E4F1484-B85B-493F-989B-B407BD74FB37}']
function content(): IAddress;
procedure set_content(const addr: IAddress);
end;
ISSLProfile = interface(IIORProfile)
['{88B0C476-9A0A-4409-9C81-95152D75A1EA}']
function IORProfile(): IIORProfile;
end;
ISSLComponent = interface(IORBComponent)
['{5E0175FC-24F4-452D-B01C-96E2349DAF07}']
function port(): _ushort;
end;
ISSLTransport = interface(ITransport)
['{DC73C39D-25CB-4A52-9AC9-6969830010A5}']
function accept(): boolean;
end;
implementation
end.
|
unit TestGeocodingSamplesUnit;
interface
uses
TestFramework, Classes, SysUtils,
BaseTestOnlineExamplesUnit;
type
TTestGeocodingSamples = class(TTestOnlineExamples)
private
published
procedure BatchForwardGeocodeAddress;
procedure BulkForwardGeocodeAddresses;
procedure ReverseGeocodeAddress;
procedure GetSingleAddress;
procedure GetAddresses;
procedure GetZipCodes;
procedure GetLimitedAddresses;
procedure GetLimitedZipCodes;
procedure GetZipCodeAndHouseNumber;
procedure GetLimitedZipCodeAndHouseNumber;
end;
implementation
uses NullableBasicTypesUnit, GeocodingUnit, DirectionPathPointUnit,
GeocodingAddressUnit, CommonTypesUnit, BulkGeocodingRequestUnit;
procedure TTestGeocodingSamples.BatchForwardGeocodeAddress;
var
ErrorString: String;
Address: String;
Geocoding: TGeocoding;
begin
Address := 'Los Angeles International Airport, CA';
Geocoding := FRoute4MeManager.Geocoding.ForwardGeocodeAddress(Address, ErrorString);
try
CheckNotNull(Geocoding);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocoding);
end;
Address := 'qwsdwfwfwef2';
Geocoding := FRoute4MeManager.Geocoding.ForwardGeocodeAddress(Address, ErrorString);
try
CheckNull(Geocoding);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocoding);
end;
end;
procedure TTestGeocodingSamples.BulkForwardGeocodeAddresses;
var
ErrorString: String;
Addresses: TAddressInfoArray;
Geocodings: TGeocodingList;
begin
// todo 4: задал вопрос Олегу, какой ответ должен быть правильный
// Олег ответил, что сообщил о проблеме разработчикам, у него пример CURL тоже не работает.
// Надо проверить, может быть разработчики уже решили проблему.
(* сейчас это:
{"optimization_problem_id":"96ED7C330F00C281DDD4DACEC9AAE9A1","address_count":1,"status":true}
SetLength(Addresses, 3);
Addresses[0] := TAddressInfo.Create('6817 Harrison Rd, Fredericksburg, VA 22407',
'MirandaJCohen@dayrep.com', 'Reste1982', 'arridea.com', '404-317-9869', 'Miranda', 'Cohen');
Addresses[1] := TAddressInfo.Create('7404 Drew Ln, Fredericksburg, VA 22407',
'WilliamCBennett@rhyta.com', 'Enton1954', '', '912-852-2180', 'William', 'Bennett');
Addresses[2] := TAddressInfo.Create('12316 Willow Woods Dr, Fredericksburg, VA 22407',
'GeorgeENicholson@armyspy.com', 'Smis1967', '', '912-852-2180', 'George', 'Nicholson');
Geocodings := FRoute4MeManager.Geocoding.ForwardGeocodeAddresses(Addresses, ErrorString);
try
CheckNotNull(Geocodings);
CheckEquals(3, Geocodings.Count);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocodings);
end;*)
SetLength(Addresses, 1);
Addresses[0] := TAddressInfo.Create('qweasd',
'qweasd@dayrep.com', 'qweasd', 'qweasd.com', '111-111-111', 'qweasd', 'qweasd');
Geocodings := FRoute4MeManager.Geocoding.ForwardGeocodeAddresses(Addresses, ErrorString);
try
CheckNotNull(Geocodings);
CheckEquals(0, Geocodings.Count);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocodings);
end;
end;
procedure TTestGeocodingSamples.GetAddresses;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
begin
Addresses := FRoute4MeManager.Geocoding.GetAddresses(ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.GetLimitedAddresses;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
Limit, Offset: integer;
begin
Limit := 3;
Offset := 1;
// бывают случаи, когда не проходит с первого раза
Addresses := FRoute4MeManager.Geocoding.GetAddresses(Limit, Offset, ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.GetLimitedZipCodeAndHouseNumber;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
Limit, Offset: integer;
ZipCode, HouseNumber: String;
begin
Limit := 3;
Offset := 1;
ZipCode := '00601';
HouseNumber := '17';
Addresses := FRoute4MeManager.Geocoding.GetZipCodeAndHouseNumber(
ZipCode, HouseNumber, Limit, Offset, ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.GetLimitedZipCodes;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
Limit, Offset: integer;
ZipCode: String;
begin
Limit := 3;
Offset := 1;
ZipCode := '00601';
Addresses := FRoute4MeManager.Geocoding.GetZipCodes(ZipCode, Limit, Offset, ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.GetSingleAddress;
var
Pk: integer;
ErrorString: String;
Address: TGeocodingAddress;
begin
Pk := 4;
Address := FRoute4MeManager.Geocoding.GetSingleAddress(Pk, ErrorString);
try
CheckNotNull(Address);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Address);
end;
Pk := -1;
Address := FRoute4MeManager.Geocoding.GetSingleAddress(Pk, ErrorString);
try
CheckNull(Address);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Address);
end;
end;
procedure TTestGeocodingSamples.GetZipCodeAndHouseNumber;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
ZipCode, HouseNumber: String;
begin
ZipCode := '00601';
HouseNumber := '17';
Addresses := FRoute4MeManager.Geocoding.GetZipCodeAndHouseNumber(
ZipCode, HouseNumber, ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.GetZipCodes;
var
ErrorString: String;
Addresses: TGeocodingAddressList;
ZipCode: String;
begin
ZipCode := '00601';
Addresses := FRoute4MeManager.Geocoding.GetZipCodes(ZipCode, ErrorString);
try
CheckNotNull(Addresses);
CheckTrue(Addresses.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Addresses);
end;
end;
procedure TTestGeocodingSamples.ReverseGeocodeAddress;
var
ErrorString: String;
Location: TDirectionPathPoint;
Geocoding: TGeocodingList;
begin
Location := TDirectionPathPoint.Create(42.35863, -71.05670);
Geocoding := FRoute4MeManager.Geocoding.ReverseGeocodeAddress(Location, ErrorString);
try
CheckNotNull(Geocoding);
CheckTrue(Geocoding.Count > 0);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocoding);
end;
Location := TDirectionPathPoint.Create(123456789, 1234564789);
try
Geocoding := FRoute4MeManager.Geocoding.ReverseGeocodeAddress(Location, ErrorString);
CheckNotNull(Geocoding);
CheckEquals(0, Geocoding.Count);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Geocoding);
end;
end;
initialization
RegisterTest('Examples\Online\Geocoding\', TTestGeocodingSamples.Suite);
end.
|
unit uSregConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls,iniFiles;
type
TfmsRegTConfig = class(TForm)
Bevel1: TBevel;
sb_Save: TSpeedButton;
sbCancel: TSpeedButton;
chk_DeviceSearch: TCheckBox;
chk_RealRegist: TCheckBox;
chk_MacView: TCheckBox;
chk_EventSave: TCheckBox;
procedure sbCancelClick(Sender: TObject);
procedure sb_SaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmsRegTConfig: TfmsRegTConfig;
implementation
uses
uCommon;
{$R *.dfm}
procedure TfmsRegTConfig.sbCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfmsRegTConfig.sb_SaveClick(Sender: TObject);
var
ini_fun : TiniFile;
begin
ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI');
G_bDeviceSearch := chk_DeviceSearch.Checked;
if chk_DeviceSearch.Checked then
ini_fun.WriteString('Config','DEVICESEARCH','TRUE')
else ini_fun.WriteString('Config','DEVICESEARCH','FALSE');
G_bRealRegist := chk_RealRegist.Checked;
if chk_DeviceSearch.Checked then
ini_fun.WriteString('Config','REALREGIST','TRUE')
else ini_fun.WriteString('Config','REALREGIST','FALSE');
G_bMacView := chk_MacView.Checked;
if chk_MacView.Checked then
ini_fun.WriteString('Config','MACVIEW','TRUE')
else ini_fun.WriteString('Config','MACVIEW','FALSE');
G_bEventControlerSave := chk_EventSave.Checked;
if chk_EventSave.Checked then
ini_fun.WriteString('Config','EventControlerSave','TRUE')
else ini_fun.WriteString('Config','EventControlerSave','FALSE');
ini_fun.Free;
Close;
end;
procedure TfmsRegTConfig.FormCreate(Sender: TObject);
begin
chk_DeviceSearch.Checked := G_bDeviceSearch;
chk_RealRegist.Checked := G_bRealRegist;
chk_MacView.Checked := G_bMacView ;
chk_EventSave.Checked := G_bEventControlerSave ;
end;
end.
|
unit NtUtils.Ldr;
interface
uses
NtUtils.Exceptions;
{ Delayed import }
// Check if a function presents in ntdll
function LdrxCheckNtDelayedImport(Name: AnsiString): TNtxStatus;
// Check if a function presents in a dll
function LdrxCheckModuleDelayedImport(ModuleName: String;
ProcedureName: AnsiString): TNtxStatus;
{ Other }
// Get base address of a loaded dll
function LdrxGetDllHandle(DllName: String; out DllHandle: HMODULE): TNtxStatus;
// Get a function address
function LdrxGetProcedureAddress(DllHandle: HMODULE; ProcedureName: AnsiString;
out Status: TNtxStatus): Pointer;
implementation
uses
System.SysUtils, System.Generics.Collections, Ntapi.ntdef, Ntapi.ntldr;
var
ImportCache: TDictionary<AnsiString, NTSTATUS>;
OldFailureHook: TDelayedLoadHook;
function LdrxCheckNtDelayedImport(Name: AnsiString): TNtxStatus;
var
ProcName: ANSI_STRING;
ProcAddr: Pointer;
begin
if not Assigned(ImportCache) then
ImportCache := TDictionary<AnsiString,NTSTATUS>.Create;
Result.Location := 'LdrGetProcedureAddress("' + String(Name) + '")';
if ImportCache.TryGetValue(Name, Result.Status) then
Exit;
ProcName.FromString(Name);
Result.Status := LdrGetProcedureAddress(hNtdll, ProcName, 0, ProcAddr);
ImportCache.Add(Name, Result.Status);
end;
function LdrxCheckModuleDelayedImport(ModuleName: String;
ProcedureName: AnsiString): TNtxStatus;
var
DllName: UNICODE_STRING;
ProcName: ANSI_STRING;
hDll: NativeUInt;
ProcAddr: Pointer;
begin
DllName.FromString(ModuleName);
Result.Location := 'LdrGetDllHandle';
Result.Status := LdrGetDllHandle(nil, nil, DllName, hDll);
if not NT_SUCCESS(Result.Status) then
begin
// Try to load it
Result.Location := 'LdrLoadDll';
Result.Status := LdrLoadDll(nil, nil, DllName, hDll);
if not NT_SUCCESS(Result.Status) then
Exit;
end;
ProcName.FromString(ProcedureName);
Result.Location := 'LdrGetProcedureAddress';
Result.Status := LdrGetProcedureAddress(hDll, ProcName, 0, ProcAddr);
end;
function NtxpDelayedLoadHook(dliNotify: dliNotification;
pdli: PDelayLoadInfo): Pointer; stdcall;
const
DELAY_MSG = 'Delayed load of ';
begin
// Report delayed load errors
case dliNotify of
dliFailLoadLibrary:
ENtError.Report(NTSTATUS_FROM_WIN32(pdli.dwLastError),
DELAY_MSG + pdli.szDll);
dliFailGetProcAddress:
ENtError.Report(NTSTATUS_FROM_WIN32(pdli.dwLastError),
DELAY_MSG + pdli.dlp.szProcName);
end;
if Assigned(OldFailureHook) then
OldFailureHook(dliNotify, pdli);
Result := nil;
end;
function LdrxGetDllHandle(DllName: String; out DllHandle: HMODULE): TNtxStatus;
var
DllNameStr: UNICODE_STRING;
begin
DllNameStr.FromString(DllName);
Result.Location := 'LdrGetDllHandle("' + DllName + '")';
Result.Status := LdrGetDllHandle(nil, nil, DllNameStr, DllHandle);
end;
function LdrxGetProcedureAddress(DllHandle: HMODULE; ProcedureName: AnsiString;
out Status: TNtxStatus): Pointer;
var
ProcNameStr: ANSI_STRING;
begin
ProcNameStr.FromString(ProcedureName);
Status.Location := 'LdrGetProcedureAddress("' + String(ProcedureName) + '")';
Status.Status := LdrGetProcedureAddress(DllHandle, ProcNameStr, 0, Result);
end;
initialization
OldFailureHook := SetDliFailureHook2(NtxpDelayedLoadHook);
finalization
ImportCache.Free;
end.
|
unit UDialog;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.Objects;
type
IProcessDialogResult = Interface
procedure ProcessDialogResult;
End;
TDialogFrame = class(TFrame)
CloseButton: TButton;
Panel1: TPanel;
Rectangle1: TRectangle;
procedure CloseButtonClick(Sender: TObject);
private
{ Private declarations }
ParentPanel: TPanel;
protected
FProcessDialogResult: IProcessDialogResult;
public
{ Public declarations }
DialogResult: TModalResult; // if cancel value = mrCancel else value = mrOK
ReturnString: String; // keep the selected Value or input value
ReturnStringList: TStringList;
property ProcessDialogResult: IProcessDialogResult read FProcessDialogResult
write FProcessDialogResult;
procedure show;
constructor Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult); overload;
end;
implementation
{$R *.fmx}
procedure TDialogFrame.CloseButtonClick(Sender: TObject);
begin
DialogResult := mrCancel;
ParentPanel.Enabled := True;
FProcessDialogResult.ProcessDialogResult;
end;
constructor TDialogFrame.Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult);
begin
inherited Create(nil);
FProcessDialogResult := CallBackProc;
self.Parent := ParentForm;
self.ParentPanel := ParentPanel;
self.Position.X := (ParentForm.Width - self.Width) / 2;
self.Position.Y := (ParentForm.Height - self.Height) / 2;
ParentPanel.Enabled := false;
end;
procedure TDialogFrame.Show;
begin
ParentPanel.Enabled := false;
self.Visible := true;
end;
end.
|
{ @abstract(This unit contains print preview form.)
@author(Tomas Krysl (tk@tkweb.eu))
@created(18 Sep 2009)
@lastmod(20 Jun 2010)
Copyright © 2009 Tomas Krysl (tk@@tkweb.eu)<BR><BR>
<B>License:</B><BR>
This code is distributed as a freeware. You are free to use it as part
of your application for any purpose including freeware, commercial and
shareware applications. The origin of this source code must not be
misrepresented; you must not claim your authorship. You may modify this code
solely for your own purpose. Please feel free to contact the author if you
think your changes might be useful for other users. You may distribute only
the original package. The author accepts no liability for any damage
that may result from using this code. }
unit KPrintPreview;
{$include kcontrols.inc}
interface
uses
{$IFDEF FPC}
LCLType, LCLIntf, LResources,
{$ELSE}
Windows, Messages, ToolWin, ImgList,
{$ENDIF}
SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ActnList, Buttons, StdCtrls,
ExtCtrls, KControls;
type
{ TKPrintPreviewForm }
TKPrintPreviewForm = class(TForm)
ILMain: TImageList;
ALMain: TActionList;
ACPageFirst: TAction;
ACPageLast: TAction;
ACPageNext: TAction;
ACPagePrevious: TAction;
ACClose: TAction;
ILMainDis: TImageList;
ToBMain: TToolBar;
TBPageFirst: TToolButton;
TBPagePrevious: TToolButton;
ToolButton1: TToolButton;
ToolButton3: TToolButton;
TBPageNext: TToolButton;
TBPageLast: TToolButton;
PNPage: TPanel;
EDPage: TEdit;
UDPage: TUpDown;
ToolButton6: TToolButton;
PNScale: TPanel;
CoBScale: TComboBox;
TBClose: TToolButton;
Preview: TKPrintPreview;
TBPrint: TToolButton;
ToolButton4: TToolButton;
ACPrint: TAction;
procedure CoBScaleExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ACPageFirstExecute(Sender: TObject);
procedure ACPageFirstUpdate(Sender: TObject);
procedure ACPagePreviousExecute(Sender: TObject);
procedure ACPageNextExecute(Sender: TObject);
procedure ACPageNextUpdate(Sender: TObject);
procedure ACPageLastExecute(Sender: TObject);
procedure ACCloseExecute(Sender: TObject);
procedure ACCloseUpdate(Sender: TObject);
procedure EDPageExit(Sender: TObject);
procedure UDPageClick(Sender: TObject; Button: TUDBtnType);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure PreviewChanged(Sender: TObject);
procedure ACPrintExecute(Sender: TObject);
procedure ACPrintUpdate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure ScaleChanged;
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses
KFunctions;
procedure TKPrintPreviewForm.FormCreate(Sender: TObject);
begin
CoBScale.ItemIndex := 9; // page width
Preview.DoubleBuffered := True;
end;
procedure TKPrintPreviewForm.FormShow(Sender: TObject);
begin
UDPage.Min := Preview.StartPage;
UDPage.Max := Preview.EndPage;
end;
procedure TKPrintPreviewForm.CoBScaleExit(Sender: TObject);
begin
ScaleChanged;
end;
procedure TKPrintPreviewForm.ACPageFirstExecute(Sender: TObject);
begin
Preview.FirstPage;
end;
procedure TKPrintPreviewForm.ACPageFirstUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Preview.Page > Preview.StartPage;
end;
procedure TKPrintPreviewForm.ACPagePreviousExecute(Sender: TObject);
begin
Preview.PreviousPage;
end;
procedure TKPrintPreviewForm.ACPageNextExecute(Sender: TObject);
begin
Preview.NextPage;
end;
procedure TKPrintPreviewForm.ACPageNextUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Preview.Page < Preview.EndPage;
end;
procedure TKPrintPreviewForm.ACPageLastExecute(Sender: TObject);
begin
Preview.LastPage;
end;
procedure TKPrintPreviewForm.ACPrintExecute(Sender: TObject);
begin
Preview.Control.PrintOut;
end;
procedure TKPrintPreviewForm.ACPrintUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Assigned(Preview.Control) and Preview.Control.CanPrint;
end;
procedure TKPrintPreviewForm.ACCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TKPrintPreviewForm.ACCloseUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := True;
end;
procedure TKPrintPreviewForm.EDPageExit(Sender: TObject);
begin
Preview.Page := MinMax(StrToIntDef(EDPage.Text, Preview.Page), Preview.StartPage, Preview.EndPage);
EDPage.Text := IntToStr(Preview.Page);
end;
procedure TKPrintPreviewForm.UDPageClick(Sender: TObject; Button: TUDBtnType);
begin
EDPageExit(nil);
end;
procedure TKPrintPreviewForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
begin
Close;
Key := 0;
end;
end;
procedure TKPrintPreviewForm.PreviewChanged(Sender: TObject);
begin
EDPage.Text := IntToStr(Preview.Page);
end;
procedure TKPrintPreviewForm.ScaleChanged;
var
S: string;
begin
S := CoBScale.Text;
if CoBScale.Items.IndexOf(S) < 0 then
CoBScale.ItemIndex := -1;
case CoBScale.ItemIndex of
-1:
begin
while (S <> '') and not CharInSetEx(S[Length(S)], ['0'..'9']) do Delete(S, Length(S), 1);
Preview.Scale := StrToIntDef(S, 100);
end;
0: Preview.Scale := 25;
1: Preview.Scale := 50;
2: Preview.Scale := 75;
3: Preview.Scale := 100;
4: Preview.Scale := 125;
5: Preview.Scale := 150;
6: Preview.Scale := 200;
7: Preview.Scale := 500;
end;
case CoBScale.ItemIndex of
-1:
begin
Preview.ScaleMode := smScale;
CobScale.Text := Format('%d %%', [Preview.Scale]);
end;
0..7: Preview.ScaleMode := smScale;
8: Preview.ScaleMode := smWholePage;
9: Preview.ScaleMode := smPageWidth;
end;
end;
{$IFDEF FPC}
initialization
{$i kprintpreview.lrs}
{$ELSE}
{$R *.dfm}
{$ENDIF}
end.
|
unit EmailTests;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TEmailTests = class(TObject)
public
[Test]
[TestCase('T1', 'C:\Users\jreddekopp\Documents\AviMarkTests\Brentwood Animal Hospital Purchase Order.msg,True')]
[TestCase('T1', '../../data/T1 - Not AVI Email.txt,False')]
procedure TestIfAviEmail(emailFile, isAviEmail: string);
[Test]
[TestCase('T1', '../../data/T1 - Not AVI Email.txt')]
procedure TestRelayEmail(emailFile: string);
end;
implementation
uses
IdMessage, System.SysUtils,
EmailOrdering.Models.Config, IdSMTP, IdExplicitTLSClientServerBase;
{ TEmailTests }
procedure TEmailTests.TestIfAviEmail(emailFile, isAviEmail: string);
var
LIdMessage: TIdMessage;
begin
LIdMessage := TIdMessage.Create(nil);
try
LIdMessage.LoadFromFile(emailFile);
inttostr(LIdMessage.MessageParts.Count);
finally
LIdMessage.Free;
end;
end;
procedure TEmailTests.TestRelayEmail(emailFile: string);
var
LIdMessage: TIdMessage;
LConfig: TConfig;
LOldConfig: TConfig;
begin
LIdMessage := TIdMessage.Create(nil);
LOldConfig := TConfig.GetInstance;
LConfig := TConfig.Create;
try
LConfig.smtpHost := 'smtp.gmail.com';
LConfig.smtpPort := 587;
LConfig.smtpAuthType := 'satSASL';
LConfig.smtpUsername := 'wddcTestFeb2017@gmail.com';
LConfig.smtpPassword := 'BHuKvR6GTCGp4ZwRtgCW';
LConfig.Save;
LIdMessage.LoadFromFile(emailFile);
finally
LIdMessage.Free;
LOldConfig.Save;
LConfig.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TEmailTests);
end.
|
{$I OVC.INC}
{$B-} {Complete Boolean Evaluation}
{$I+} {Input/Output-Checking}
{$P+} {Open Parameters}
{$T-} {Typed @ Operator}
{$W-} {Windows Stack Frame}
{$X+} {Extended Syntax}
{$IFNDEF Win32}
{$G+} {286 Instructions}
{$N+} {Numeric Coprocessor}
{$C MOVEABLE,DEMANDLOAD,DISCARDABLE}
{$ENDIF}
{*********************************************************}
{* OVCTCBEF.PAS 2.17 *}
{* Copyright (c) 1995-98 TurboPower Software Co *}
{* All rights reserved. *}
{*********************************************************}
unit OvcTCBEF;
{-Orpheus Table Cell - base entry field type}
interface
uses
{$IFDEF Win32}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Messages,
Graphics, Classes, Controls, Forms, StdCtrls, Menus,
OvcData, OvcConst, OvcBase, OvcCaret, OvcColor,
OvcCmd, OvcEF,
OvcTCmmn, OvcTCell, OvcTGRes, OvcTable, OvcTCStr;
type
TOvcTCBaseEntryField = class(TOvcTCBaseString)
protected {private}
{.Z+}
FEdit : TOvcBaseEntryField;
FEditDisplay : TOvcBaseEntryField;
FOnError : TValidationErrorEvent;
FOnUserCommand : TUserCommandEvent;
FOnUserValidation : TUserValidationEvent;
CopyOfData : pointer;
CopyOfDataSize : Integer; {!!.17}
{.Z-}
protected
{.Z+}
function GetAutoAdvanceChar : boolean;
function GetAutoAdvanceLeftRight : boolean;
function GetAutoSelect : boolean;
function GetBeepOnError : boolean;
function GetCaretIns : TOvcCaret;
function GetCaretOvr : TOvcCaret;
function GetCaretToEnd : boolean;
function GetControlCharColor : TColor;
function GetDataSize : integer;
function GetDecimalPlaces : byte;
function GetErrorColors : TOvcColors;
function GetForceInsert : boolean;
function GetForceOvertype : boolean;
function GetHighlightColors : TOvcColors;
function GetInsertPushes : boolean;
function GetMaxLength : word;
function GetModified : boolean;
function GetPadChar : AnsiChar;
function GetPasswordChar : AnsiChar;
function GetPasswordMode : boolean;
function GetRangeHi : string;
function GetRangeLo : string;
function GetRightAlign : boolean; {!!.10}
function GetRightJustify : boolean;
function GetSoftValidation : boolean;
function GetStripLiterals : boolean;
function GetTextMargin : integer;
function GetTrimBlanks : boolean;
procedure SetAutoAdvanceChar(AAC : boolean);
procedure SetAutoAdvanceLeftRight(AALR : boolean);
procedure SetAutoSelect(ASel : boolean);
procedure SetBeepOnError(BOE : boolean);
procedure SetCaretIns(CI : TOvcCaret);
procedure SetCaretOvr(CO : TOvcCaret);
procedure SetCaretToEnd(CTE : boolean);
procedure SetControlCharColor(CCC : TColor);
procedure SetDecimalPlaces(DP : byte);
procedure SetErrorColors(EC : TOvcColors);
procedure SetForceInsert(FI : boolean);
procedure SetForceOvertype(FO : boolean);
procedure SetHighlightColors(HC : TOvcColors);
procedure SetInsertPushes(IP : boolean);
procedure SetMaxLength(ML : word);
procedure SetPadChar(PC : AnsiChar);
procedure SetPasswordChar(PC : AnsiChar);
procedure SetPasswordMode(PM : boolean);
procedure SetRangeHi(RI : string);
procedure SetRangeLo(RL : string);
procedure SetRightAlign(RA : boolean); {!!.10}
procedure SetRightJustify(RJ : boolean);
procedure SetSoftValidation(SV : boolean);
procedure SetStripLiterals(SL : boolean);
procedure SetTextMargin(TM : integer);
procedure SetTrimBlanks(TB : boolean);
procedure DefineProperties(Filer: TFiler); override;
procedure tcPaint(TableCanvas : TCanvas;
const CellRect : TRect;
RowNum : TRowNum;
ColNum : TColNum;
const CellAttr : TOvcCellAttributes;
Data : pointer); override;
{.Z-}
{properties for entry fields, to be exposed by descendants}
property AutoAdvanceChar : boolean
read GetAutoAdvanceChar write SetAutoAdvanceChar;
property AutoAdvanceLeftRight : boolean
read GetAutoAdvanceLeftRight write SetAutoAdvanceLeftRight;
property AutoSelect : boolean
read GetAutoSelect write SetAutoSelect;
property BeepOnError : boolean
read GetBeepOnError write SetBeepOnError;
property CaretIns : TOvcCaret
read GetCaretIns write SetCaretIns;
property CaretOvr : TOvcCaret
read GetCaretOvr write SetCaretOvr;
property CaretToEnd : boolean
read GetCaretToEnd write SetCaretToEnd;
property ControlCharColor : TColor
read GetControlCharColor write SetControlCharColor;
property DecimalPlaces : byte
read GetDecimalPlaces write SetDecimalPlaces;
property ForceInsert : boolean
read GetForceInsert write SetForceInsert;
property ForceOvertype : boolean
read GetForceOvertype write SetForceOvertype;
property HighlightColors : TOvcColors
read GetHighlightColors write SetHighlightColors;
property InsertPushes : boolean
read GetInsertPushes write SetInsertPushes;
property MaxLength : word
read GetMaxLength write SetMaxLength;
property PadChar : AnsiChar
read GetPadChar write SetPadChar;
property PasswordChar : AnsiChar
read GetPasswordChar write SetPasswordChar;
property PasswordMode : boolean
read GetPasswordMode write SetPasswordMode;
property RangeHi : string
read GetRangeHi write SetRangeHi
stored false;
property RangeLo : string
read GetRangeLo write SetRangeLo
stored false;
property RightAlign : boolean {!!.10}
read GetRightAlign write SetRightAlign; {!!.10}
property RightJustify : boolean
read GetRightJustify write SetRightJustify;
property StripLiterals : boolean
read GetStripLiterals write SetStripLiterals;
property TextMargin : integer
read GetTextMargin write SetTextMargin;
property TrimBlanks : boolean
read GetTrimBlanks write SetTrimBlanks;
{events}
property OnError : TValidationErrorEvent
read FOnError write FOnError;
property OnUserCommand : TUserCommandEvent
read FOnUserCommand write FOnUserCommand;
property OnUserValidation : TUserValidationEvent
read FOnUserValidation write FOnUserValidation;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; {!!.17}
override;
function CreateEntryField(AOwner : TComponent) : TOvcBaseEntryField; virtual; abstract;
function EditHandle : THandle; override;
procedure EditHide; override;
procedure EditMove(CellRect : TRect); override;
function CanSaveEditedData(SaveValue : boolean) : boolean; override;
procedure SaveEditedData(Data : pointer); override;
procedure StartEditing(RowNum : TRowNum; ColNum : TColNum;
CellRect : TRect;
const CellAttr : TOvcCellAttributes;
CellStyle: TOvcTblEditorStyle;
Data : pointer); override;
procedure StopEditing(SaveValue : boolean;
Data : pointer); override;
property DataSize : integer
read GetDataSize;
property Modified : boolean
read GetModified;
published {!!.13}
property Version; {!!.13}
end;
implementation
type {for typecast to get around protected clause}
TOvcBEF = class(TOvcBaseEntryField)
public
property AutoAdvanceChar;
property AutoAdvanceLeftRight;
property AutoSelect;
property BeepOnError;
property CaretIns;
property CaretOvr;
property ControlCharColor;
property DecimalPlaces;
property ErrorColors;
property ForceInsert;
property ForceOvertype;
property HighlightColors;
property InsertPushes;
property MaxLength;
property PadChar;
property PasswordChar;
property PasswordMode;
property RangeHi;
property RangeLo;
property ShowHint;
property SoftValidation;
property TextMargin;
property TrimBlanks;
end;
{===TOvcTCBaseEntryField=============================================}
constructor TOvcTCBaseEntryField.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FEdit := CreateEntryField(Self);
FEdit.Visible := false;
FEditDisplay := CreateEntryField(Self);
FEditDisplay.Visible := false;
end;
{!!.17} {added}
destructor TOvcTCBaseEntryField.Destroy;
begin
if (CopyOfData <> nil) and (CopyOfDataSize > 0) then
FreeMem(CopyOfData, CopyOfDataSize);
inherited Destroy;
end;
{--------}
function TOvcTCBaseEntryField.CanSaveEditedData(SaveValue : boolean) : boolean;
begin
Result := true;
if Assigned(FEdit) then
if SaveValue then
with TOvcBEF(FEdit) do {!!.01}
if Controller.ErrorPending then {!!.01}
Result := false {!!.01}
else {!!.01}
Result := ValidateSelf
else
FEdit.Restore;
end;
{--------}
function TOvcTCBaseEntryField.EditHandle : THandle;
begin
if Assigned(FEdit) then
Result := FEdit.Handle
else
Result := 0;
end;
{--------}
procedure TOvcTCBaseEntryField.EditHide;
begin
if Assigned(FEdit) then
with FEdit do
begin
SetWindowPos(FEdit.Handle, HWND_TOP,
0, 0, 0, 0,
SWP_HIDEWINDOW or SWP_NOREDRAW or SWP_NOZORDER);
end;
end;
{--------}
procedure TOvcTCBaseEntryField.EditMove(CellRect : TRect);
var
EditHandle : HWND;
begin
if Assigned(FEdit) then
begin
EditHandle := FEdit.Handle;
with CellRect do
SetWindowPos(EditHandle, HWND_TOP,
Left, Top + ((Bottom - Top) - FEdit.Height) div 2 + 3, Right-Left,
FEdit.Height,
SWP_SHOWWINDOW or SWP_NOREDRAW or SWP_NOZORDER);
InvalidateRect(EditHandle, nil, false);
UpdateWindow(EditHandle);
end;
end;
{--------}
procedure TOvcTCBaseEntryField.tcPaint(TableCanvas : TCanvas;
const CellRect : TRect;
RowNum : TRowNum;
ColNum : TColNum;
const CellAttr : TOvcCellAttributes;
Data : pointer);
var
S : ShortString;
begin
if (Data = nil) then
inherited tcPaint(TableCanvas, CellRect, RowNum, ColNum, CellAttr, Data)
else
begin
FEditDisplay.Controller := TOvcTable(FTable).Controller;
FEditDisplay.Parent := FTable;
SetWindowPos(FEditDisplay.Handle, HWND_TOP, 0, 0, 0, 0,
SWP_HIDEWINDOW or SWP_NOREDRAW or SWP_NOZORDER);
FEditDisplay.SetValue(Data^);
S := FEditDisplay.DisplayString;
inherited tcPaint(TableCanvas, CellRect, RowNum, ColNum, CellAttr, @S);
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SaveEditedData(Data : pointer);
begin
if Assigned(Data) then
begin
FEdit.GetValue(CopyOfData^);
Move(CopyOfData^, Data^, CopyOfDataSize); {!!.17}
end;
end;
{--------}
procedure TOvcTCBaseEntryField.StartEditing(RowNum : TRowNum; ColNum : TColNum;
CellRect : TRect;
const CellAttr : TOvcCellAttributes;
CellStyle: TOvcTblEditorStyle;
Data : pointer);
begin
CopyOfDataSize := FEdit.DataSize; {!!.17}
GetMem(CopyOfData, CopyOfDataSize); {!!.17}
if (Data = nil) then
FillChar(CopyOfData^, CopyOfDataSize, 0) {!!.17}
else
Move(Data^, CopyOfData^, CopyOfDataSize); {!!.17}
with TOvcBEF(FEdit) do
begin
Parent := FTable;
Font := CellAttr.caFont;
Font.Color := CellAttr.caFontColor;
Color := CellAttr.caColor;
BorderStyle := bsNone;
Ctl3D := false;
case CellStyle of
tesBorder : BorderStyle := bsSingle;
tes3D : Ctl3D := true;
end;{case}
FEdit.Left := CellRect.Left; {V}
If Height >= CellRect.Bottom - CellRect.Top
then
Begin
FEdit.Top := CellRect.Top;
FEdit.Height := CellRect.Bottom - CellRect.Top;
end
else FEdit.Top:=CellRect.Top + ((CellRect.Bottom - CellRect.Top) - FEdit.Height) div 2 + 3;
FEdit.Width := CellRect.Right - CellRect.Left;
{Top := CellRect.Top;
Width := CellRect.Right - CellRect.Left;
Height := CellRect.Bottom - CellRect.Top;}
Hint := Self.Hint;
ShowHint := Self.ShowHint;
TabStop := false;
Controller := TOvcTable(FTable).Controller;
SetValue(CopyOfData^);
Visible := true;
OnChange := Self.OnChange;
OnClick := Self.OnClick;
OnDblClick := Self.OnDblClick;
OnDragDrop := Self.OnDragDrop;
OnDragOver := Self.OnDragOver;
OnEndDrag := Self.OnEndDrag;
OnEnter := Self.OnEnter;
OnError := Self.OnError;
OnExit := Self.OnExit;
OnKeyDown := Self.OnKeyDown;
OnKeyPress := Self.OnKeyPress;
OnKeyUp := Self.OnKeyUp;
OnMouseDown := Self.OnMouseDown;
OnMouseMove := Self.OnMouseMove;
OnMouseUp := Self.OnMouseUp;
OnUserCommand := Self.OnUserCommand;
OnUserValidation := Self.OnUserValidation;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.StopEditing(SaveValue : boolean;
Data : pointer);
begin
if SaveValue and Assigned(Data) then
begin
FEdit.GetValue(CopyOfData^);
Move(CopyOfData^, Data^, CopyOfDataSize); {!!.17}
end;
FreeMem(CopyOfData, CopyOfDataSize); {!!.17}
CopyOfData := nil;
CopyOfDataSize := 0; {!!.17}
EditHide;
end;
{====================================================================}
{===TOvcTCBaseEntryField property access=============================}
procedure TOvcTCBaseEntryField.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
with Filer do
begin
DefineBinaryProperty('RangeHigh',
TOvcBEF(FEdit).efReadRangeHi, TOvcBEF(FEdit).efWriteRangeHi, true);
DefineBinaryProperty('RangeLow',
TOvcBEF(FEdit).efReadRangeLo, TOvcBEF(FEdit).efWriteRangeLo, true);
end;
end;
{--------}
function TOvcTCBaseEntryField.GetAutoAdvanceChar : boolean;
begin
if Assigned(FEdit) then
Result := FEdit.AutoAdvanceChar
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetAutoAdvanceLeftRight : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).AutoAdvanceLeftRight
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetAutoSelect : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).AutoSelect
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetBeepOnError : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).BeepOnError
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetCaretIns : TOvcCaret;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).CaretIns
else Result := nil;
end;
{--------}
function TOvcTCBaseEntryField.GetCaretOvr : TOvcCaret;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).CaretOvr
else Result := nil;
end;
{--------}
function TOvcTCBaseEntryField.GetCaretToEnd : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).CaretToEnd
else Result := true;
end;
{--------}
function TOvcTCBaseEntryField.GetControlCharColor : TColor;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).ControlCharColor
else Result := clRed;
end;
{--------}
function TOvcTCBaseEntryField.GetDataSize : integer;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).DataSize
else Result := 0;
end ;
{--------}
function TOvcTCBaseEntryField.GetDecimalPlaces : byte;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).DecimalPlaces
else Result := 0;
end ;
{--------}
function TOvcTCBaseEntryField.GetErrorColors : TOvcColors;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).ErrorColors
else Result := nil;
end;
{--------}
function TOvcTCBaseEntryField.GetForceInsert : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).ForceInsert
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetForceOvertype : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).ForceOvertype
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetHighlightColors : TOvcColors;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).HighlightColors
else Result := nil;
end;
{--------}
function TOvcTCBaseEntryField.GetInsertPushes : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).InsertPushes
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetModified : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).Modified
else Result := false;
end ;
{--------}
function TOvcTCBaseEntryField.GetMaxLength : word;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).MaxLength
else Result := 0;
end;
{--------}
function TOvcTCBaseEntryField.GetPadChar : AnsiChar;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).PadChar
else Result := ' ';
end;
{--------}
function TOvcTCBaseEntryField.GetPasswordChar : AnsiChar;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).PasswordChar
else Result := '*';
end;
{--------}
function TOvcTCBaseEntryField.GetPasswordMode : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).PasswordMode
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetRangeHi : string;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).RangeHi
else Result := '';
end;
{--------}
function TOvcTCBaseEntryField.GetRangeLo : string;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).RangeLo
else Result := '';
end;
{--------}
function TOvcTCBaseEntryField.GetRightAlign : boolean; {!!.10}
begin {!!.10}
if Assigned(FEdit) then {!!.10}
Result := TOvcBEF(FEdit).RightAlign {!!.10}
else Result := false; {!!.10}
end; {!!.10}
{--------}
function TOvcTCBaseEntryField.GetRightJustify : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).RightJustify
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetSoftValidation : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).SoftValidation
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetStripLiterals : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).StripLiterals
else Result := false;
end;
{--------}
function TOvcTCBaseEntryField.GetTextMargin : integer;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).TextMargin
else Result := 0;
end;
{--------}
function TOvcTCBaseEntryField.GetTrimBlanks : boolean;
begin
if Assigned(FEdit) then
Result := TOvcBEF(FEdit).TrimBlanks
else Result := false;
end;
{--------}
procedure TOvcTCBaseEntryField.SetAutoAdvanceChar(AAC : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).AutoAdvanceChar := AAC;
end;
{--------}
procedure TOvcTCBaseEntryField.SetAutoAdvanceLeftRight(AALR : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).AutoAdvanceLeftRight := AALR;
end;
{--------}
procedure TOvcTCBaseEntryField.SetAutoSelect(ASel : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).AutoSelect := ASel;
end;
{--------}
procedure TOvcTCBaseEntryField.SetBeepOnError(BOE : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).BeepOnError := BOE;
end;
{--------}
procedure TOvcTCBaseEntryField.SetCaretIns(CI : TOvcCaret);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).CaretIns := CI;
end;
{--------}
procedure TOvcTCBaseEntryField.SetCaretOvr(CO : TOvcCaret);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).CaretOvr := CO;
end;
{--------}
procedure TOvcTCBaseEntryField.SetCaretToEnd(CTE : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).CaretToEnd := CTE;
end;
{--------}
procedure TOvcTCBaseEntryField.SetControlCharColor(CCC : TColor);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).ControlCharColor := CCC;
end;
{--------}
procedure TOvcTCBaseEntryField.SetDecimalPlaces(DP : byte);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).DecimalPlaces := DP;
TOvcBEF(FEditDisplay).DecimalPlaces := DP;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetErrorColors(EC : TOvcColors);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).ErrorColors := EC;
end;
{--------}
procedure TOvcTCBaseEntryField.SetForceInsert(FI : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).ForceInsert := FI;
end;
{--------}
procedure TOvcTCBaseEntryField.SetForceOvertype(FO : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).ForceOvertype := FO;
end;
{--------}
procedure TOvcTCBaseEntryField.SetHighlightColors(HC : TOvcColors);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).HighlightColors := HC;
end;
{--------}
procedure TOvcTCBaseEntryField.SetInsertPushes(IP : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).InsertPushes := IP;
end;
{--------}
procedure TOvcTCBaseEntryField.SetMaxLength(ML : word);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).MaxLength := ML;
TOvcBEF(FEditDisplay).MaxLength := ML;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetPadChar(PC : AnsiChar);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).PadChar := PC;
TOvcBEF(FEditDisplay).PadChar := PC;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetPasswordChar(PC : AnsiChar);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).PasswordChar := PC;
TOvcBEF(FEditDisplay).PasswordChar := PC;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetPasswordMode(PM : boolean);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).PasswordMode := PM;
TOvcBEF(FEditDisplay).PasswordMode := PM;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetRangeHi(RI : string);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).RangeHi := RI;
end;
{--------}
procedure TOvcTCBaseEntryField.SetRangeLo(RL : string);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).RangeLo := RL;
end;
{--------}
procedure TOvcTCBaseEntryField.SetRightAlign(RA : boolean); {!!.10}
begin {!!.10}
if Assigned(FEdit) then {!!.10}
begin {!!.10}
TOvcBEF(FEdit).RightAlign := RA; {!!.10}
TOvcBEF(FEditDisplay).RightAlign := RA; {!!.10}
end; {!!.10}
end; {!!.10}
{--------}
procedure TOvcTCBaseEntryField.SetRightJustify(RJ : boolean);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).RightJustify := RJ;
TOvcBEF(FEditDisplay).RightJustify := RJ;
end;
end;
{--------}
procedure TOvcTCBaseEntryField.SetSoftValidation(SV : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).SoftValidation := SV;
end;
{--------}
procedure TOvcTCBaseEntryField.SetStripLiterals(SL : boolean);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).StripLiterals := SL;
end;
{--------}
procedure TOvcTCBaseEntryField.SetTextMargin(TM : integer);
begin
if Assigned(FEdit) then TOvcBEF(FEdit).TextMargin := TM;
end;
{--------}
procedure TOvcTCBaseEntryField.SetTrimBlanks(TB : boolean);
begin
if Assigned(FEdit) then
begin
TOvcBEF(FEdit).TrimBlanks := TB;
TOvcBEF(FEditDisplay).TrimBlanks := TB;
end;
end;
{====================================================================}
end. |
{ ***************************************************************************
Copyright (c) 2016-2021 Kike P�rez
Unit : Quick.SMTP
Description : Send Emails
Author : Kike P�rez
Version : 1.5
Created : 12/10/2017
Modified : 08/09/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.SMTP;
interface
{$i QuickLib.inc}
uses
Classes,
Generics.Collections,
SysUtils,
IdGlobal,
IdSMTP,
IdMessage,
IdReplySMTP,
IdSSLOpenSSL,
IdText,
IdAttachment,
IdAttachmentFile,
IdAttachmentMemory,
IdExplicitTLSClientServerBase,
IdHTTP;
type
TAttachment = class
private
fFilename : string;
fContent : TStream;
public
constructor Create(const aFilename : string; const aContent : TStream);
destructor Destroy; override;
property Filename : string read fFilename;
property Content : TStream read fContent;
end;
TMailMessage = class
private
fSenderName : string;
fFrom : string;
fRecipient : string;
fSubject : string;
fBody : string;
fCC : string;
fBCC : string;
fReplyTo : string;
fBodyFromFile : Boolean;
fAttachments : TStringList;
fAttachmentFiles : TObjectList<TAttachment>;
procedure SetBody(aValue : string);
procedure SetAttachments(const Value: TStringList);
public
constructor Create;
destructor Destroy; override;
property SenderName : string read fSenderName write fSenderName;
property From : string read fFrom write fFrom;
property Recipient : string read fRecipient write fRecipient;
property Subject : string read fSubject write fSubject;
property Body : string read fBody write SetBody;
property CC : string read fCC write fCC;
property BCC : string read fBCC write fBCC;
property ReplyTo : string read fReplyTo write fReplyTo;
property Attachments : TStringList read fAttachments write SetAttachments;
property AttachmentFiles : TObjectList<TAttachment> read fAttachmentFiles;
procedure AddAttachment(const aFilename : string; aStream : TStream); overload;
procedure AddAttachment(const aFilename, aFilePath : string); overload;
procedure AddBodyFromFile(const cFileName : string);
end;
TSMTP = class(TIdSMTP)
private
fServerAuth : Boolean;
fUseSSL : Boolean;
fMail : TMailMessage;
public
constructor Create; overload;
constructor Create(const cHost : string; cPort : Integer; cUseSSL : Boolean = False); overload;
destructor Destroy; override;
property ServerAuth : Boolean read fServerAuth write fServerAuth;
property UseSSL: Boolean read fUseSSL write fUseSSL;
property Mail : TMailMessage read fMail write fMail;
function SendMail: Boolean; overload;
function SendMail(aMail : TMailMessage) : Boolean; overload;
function SendEmail(const aFromEmail,aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean; overload;
function SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean; overload;
function SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string; const aAttachments : TStringList) : Boolean; overload;
end;
implementation
{ TMailMessage }
constructor TMailMessage.Create;
begin
fCC := '';
fBCC := '';
fBody := '';
fAttachments := TStringList.Create;
fAttachmentFiles := TObjectList<TAttachment>.Create(True);
end;
destructor TMailMessage.Destroy;
begin
if Assigned(fAttachments) then fAttachments.Free;
if Assigned(fAttachmentFiles) then fAttachmentFiles.Free;
inherited;
end;
procedure TMailMessage.AddAttachment(const aFilename, aFilePath : string);
var
fs : TFileStream;
begin
if not FileExists(aFilePath) then raise Exception.CreateFmt('MailMessage: file "%s" not found!',[aFilename]);
fs := TFileStream.Create(aFilePath,fmOpenRead);
fAttachmentFiles.Add(TAttachment.Create(aFilename,fs));
end;
procedure TMailMessage.AddAttachment(const aFilename : string; aStream : TStream);
begin
fAttachmentFiles.Add(TAttachment.Create(aFilename,aStream));
end;
procedure TMailMessage.AddBodyFromFile(const cFileName: string);
begin
fBodyFromFile := True;
fBody := cFileName;
end;
procedure TMailMessage.SetAttachments(const Value: TStringList);
begin
if Assigned(fAttachments) then fAttachments.Free;
fAttachments := Value;
end;
procedure TMailMessage.SetBody(aValue: string);
begin
fBodyFromFile := False;
fBody := aValue;
end;
{ TSMTP }
constructor TSMTP.Create;
begin
inherited Create;
fMail := TMailMessage.Create;
Port := 25;
UseTLS := TIdUseTLS.utNoTLSSupport;
fUseSSL := False;
end;
constructor TSMTP.Create(const cHost : string; cPort : Integer; cUseSSL : Boolean = False);
begin
Create;
Host := cHost;
Port := cPort;
fUseSSL := cUseSSL;
end;
destructor TSMTP.Destroy;
begin
if Assigned(fMail) then fMail.Free;
inherited;
end;
function TSMTP.SendEmail(const aFromEmail, aFromName, aSubject, aTo, aCC, aBC, aReplyTo, aBody: string): Boolean;
begin
fMail.From := aFromEmail;
Result := SendEmail(aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody);
end;
function TSMTP.SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean;
begin
Result := SendEmail(aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody,nil);
end;
function TSMTP.SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string; const aAttachments : TStringList) : Boolean;
var
mail : TMailMessage;
begin
if fMail.From.IsEmpty then raise Exception.Create('Email sender not specified!');
mail := TMailMessage.Create;
try
Mail.From := fMail.From;
if aFromName.IsEmpty then Mail.SenderName := fMail.From
else Mail.SenderName := aFromName;
Mail.Subject := aSubject;
Mail.Body := aBody;
Mail.Recipient := aTo;
Mail.CC := aCC;
Mail.BCC := aBC;
Mail.ReplyTo := aReplyTo;
if aAttachments <> nil then Mail.Attachments := aAttachments;
Result := Self.SendMail(mail);
finally
mail.Free;
end;
end;
function TSMTP.SendMail: Boolean;
begin
Result := SendMail(fMail);
end;
function TSMTP.SendMail(aMail : TMailMessage) : Boolean;
var
msg : TIdMessage;
SSLHandler : TIdSSLIOHandlerSocketOpenSSL;
email : string;
filename : string;
mBody : TIdText;
idattach : TIdAttachment;
attach : TAttachment;
begin
Result := False;
SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
idattach := nil;
mBody := nil;
msg := TIdMessage.Create(nil);
try
//create mail msg
msg.From.Address := aMail.From;
if aMail.SenderName <> '' then msg.From.Name := aMail.SenderName;
msg.Subject := aMail.Subject;
for email in aMail.Recipient.Split([',',';']) do msg.Recipients.Add.Address := email;
for email in aMail.CC.Split([',',';']) do msg.CCList.Add.Address := email;
for email in aMail.BCC.Split([',',';']) do msg.BCCList.Add.Address := email;
for email in aMail.ReplyTo.Split([',',';']) do msg.ReplyTo.Add.Address := email;
if aMail.fBodyFromFile then
begin
msg.Body.LoadFromFile(aMail.Body);
end
else
begin
mBody := TIdText.Create(msg.MessageParts);
mBody.ContentType := 'text/html';
mBody.CharSet:= 'utf-8';
mBody.Body.Text := aMail.Body;
end;
//add attachements if exists
if aMail.Attachments.Count > 0 then
begin
for filename in aMail.Attachments do
begin
idattach := TIdAttachmentFile.Create(msg.MessageParts,filename);
end;
end;
//add stream attachments if exists
if aMail.AttachmentFiles.Count > 0 then
begin
//mBody.ContentType := 'multipart/mixed';
//msg.ContentType := 'multipart/mixed';
for attach in aMail.AttachmentFiles do
begin
idattach := TIdAttachmentMemory.Create(msg.MessageParts,attach.Content);
idattach.Filename := attach.Filename;
end;
end;
//configure smtp SSL
try
if fUseSSL then
begin
Self.IOHandler := SSLHandler;
SSLHandler.MaxLineAction := maException;
SSLHandler.SSLOptions.Method := sslvTLSv1_2;
SSLHandler.SSLOptions.Mode := sslmUnassigned;
SSLHandler.SSLOptions.VerifyMode := [];
SSLHandler.SSLOptions.VerifyDepth := 0;
if fPort = 465 then Self.UseTLS := utUseImplicitTLS
else Self.UseTLS := utUseExplicitTLS;
end;
//server auth
if ServerAuth then Self.AuthType := TIdSMTPAuthenticationType.satDefault;
Self.Port := fPort;
except
on E : Exception do raise Exception.Create(Format('[%s] : %s',[Self.ClassName,e.Message]));
end;
//send email
try
Self.Connect;
if Self.Connected then
begin
Self.Send(msg);
Self.Disconnect(False);
Result := True;
end;
except
on E : Exception do raise Exception.Create(Format('[%s] : %s',[Self.ClassName,e.Message]));
end;
finally
if Assigned(idattach) then idattach.Free;
if Assigned(mBody) then mBody.Free;
msg.Free;
end;
finally
SSLHandler.Free;
end;
end;
{ TAttachment }
constructor TAttachment.Create(const aFilename: string; const aContent: TStream);
begin
fFilename := aFilename;
fContent := aContent;
end;
destructor TAttachment.Destroy;
begin
if Assigned(fContent) then fContent.Free;
inherited;
end;
end.
|
unit MFichas.Model.GrupoProduto.Metodos.Editar;
interface
uses
System.SysUtils,
System.Generics.Collections,
MFichas.Model.GrupoProduto.Interfaces,
MFichas.Model.Entidade.GRUPOPRODUTO;
type
TModelGrupoProdutoMetodosEditar = class(TInterfacedObject, iModelGrupoProdutoMetodosEditar)
private
[weak]
FParent : iModelGrupoProduto;
FEntidade : TGRUPOPRODUTO;
FGUUID : String;
FDescricao : String;
FAtivoInativo: Integer;
FListaGrupo: TObjectList<TGRUPOPRODUTO>;
constructor Create(AParent: iModelGrupoProduto);
procedure RecuperarObjetoDoBancoDeDados;
procedure Gravar;
public
destructor Destroy; override;
class function New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosEditar;
function GUUID(AGUUID: String) : iModelGrupoProdutoMetodosEditar;
function Descricao(ADescricao: String): iModelGrupoProdutoMetodosEditar;
function AtivoInativo(AValue: Integer): iModelGrupoProdutoMetodosEditar;
function &End : iModelGrupoProdutoMetodos;
end;
implementation
{ TModelGrupoProdutoMetodosEditar }
function TModelGrupoProdutoMetodosEditar.&End: iModelGrupoProdutoMetodos;
begin
Result := FParent.Metodos;
RecuperarObjetoDoBancoDeDados;
Gravar;
end;
function TModelGrupoProdutoMetodosEditar.AtivoInativo(
AValue: Integer): iModelGrupoProdutoMetodosEditar;
begin
Result := Self;
FAtivoInativo := AValue;
end;
constructor TModelGrupoProdutoMetodosEditar.Create(AParent: iModelGrupoProduto);
begin
FParent := AParent;
FEntidade := TGRUPOPRODUTO.Create;
end;
function TModelGrupoProdutoMetodosEditar.Descricao(
ADescricao: String): iModelGrupoProdutoMetodosEditar;
begin
Result := Self;
if ADescricao.IsNullOrWhiteSpace(ADescricao) then
raise Exception.Create(
'Não é possível alterar um grupo sem um Nome/Descrição.'
);
FDescricao := ADescricao.ToUpper;
end;
destructor TModelGrupoProdutoMetodosEditar.Destroy;
begin
{$IFDEF MSWINDOWS}
FreeAndNil(FEntidade);
if Assigned(FListaGrupo) then
FreeAndNil(FListaGrupo);
{$ELSE}
FEntidade.Free;
FEntidade.DisposeOf;
if Assigned(FListaGrupo) then
begin
FListaGrupo.Free;
FListaGrupo.DisposeOf;
end;
{$ENDIF}
inherited;
end;
procedure TModelGrupoProdutoMetodosEditar.Gravar;
begin
FParent.DAO.Modify(FEntidade);
FEntidade.GUUID := FGUUID;
FEntidade.DESCRICAO := FDescricao;
FEntidade.STATUS := FAtivoInativo;
FParent.DAO.Update(FEntidade);
end;
function TModelGrupoProdutoMetodosEditar.GUUID(
AGUUID: String): iModelGrupoProdutoMetodosEditar;
begin
Result := Self;
FGUUID := AGUUID;
end;
class function TModelGrupoProdutoMetodosEditar.New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosEditar;
begin
Result := Self.Create(AParent);
end;
procedure TModelGrupoProdutoMetodosEditar.RecuperarObjetoDoBancoDeDados;
begin
FListaGrupo := FParent.DAO.FindWhere('GUUID = ' + QuotedStr(FGUUID));
FEntidade.GUUID := FListaGrupo[0].GUUID;
FEntidade.DESCRICAO := FListaGrupo[0].DESCRICAO;
FEntidade.STATUS := FListaGrupo[0].STATUS;
FEntidade.DATACADASTRO := FListaGrupo[0].DATACADASTRO;
FEntidade.DATAALTERACAO := FListaGrupo[0].DATAALTERACAO;
end;
end.
|
unit BasicsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\BasicsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "BasicsPack" MUID: (4F43A128007E)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwTypeInfo
, tfwScriptingInterfaces
, kwCompiledWordWorker
, l3Interfaces
;
type
TkwCompiledPushWord = class(TkwCompiledWordWorker)
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetRef(const aCtx: TtfwContext): TtfwWord; override;
function WordName: Il3CString; override;
end;//TkwCompiledPushWord
function CompareValues(const aV1: TtfwStackValue;
const aV2: TtfwStackValue;
const aCtx: TtfwContext;
aCaller: TtfwWord): Boolean;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwConstLike
, kwCompiledWordPrim
, tfwGlobalKeyWord
, TypInfo
, tfwWordWorkerEx
, tfwParserInterfaces
, tfwAxiomaticsResNameGetter
, l3Chars
, Windows
, l3String
, l3MessagesService
, tfwClassRef
, Classes
, l3Math
, l3Base
, kwInteger
, kwString
, kwValue
, kwWordPtrPushWord
, kwForwardDeclarationHolder
, tfwCS
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4F43A128007Eimpl_uses*
//#UC END# *4F43A128007Eimpl_uses*
;
type
TkwDefine = {final} class(TtfwConstLike)
protected
function AfterWordMaxCount(const aCtx: TtfwContext): Integer; override;
procedure FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWordPrim;
const aContext: TtfwContext); override;
{* Завершает определение вновь созданного слова }
function GetNewWordName(const aContext: TtfwContext): Il3CString; override;
class function GetWordNameForRegister: AnsiString; override;
public
function IsImmediate(const aCtx: TtfwContext): Boolean; override;
end;//TkwDefine
TkwTrue = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта True }
private
function True(const aCtx: TtfwContext): Boolean;
{* Реализация слова скрипта True }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwTrue
TkwFalse = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта False }
private
function False(const aCtx: TtfwContext): Boolean;
{* Реализация слова скрипта False }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwFalse
TkwMsg = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Msg }
private
procedure Msg(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта Msg }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwMsg
TkwPrint = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта . }
private
procedure Print(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта . }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPrint
TkwLOOP = {final} class(TtfwWordWorkerEx)
{* Слово скрипта LOOP }
private
procedure LOOP(const aCtx: TtfwContext;
aWord: TtfwWord;
aCount: Integer);
{* Реализация слова скрипта LOOP }
protected
class function GetWordNameForRegister: AnsiString; override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function RightParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure DoRun(const aCtx: TtfwContext); override;
end;//TkwLOOP
TkwWHILEDO = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта WHILEDO }
private
procedure WHILEDO(const aCtx: TtfwContext;
aWord: TtfwWord;
aCondition: TtfwWord);
{* Реализация слова скрипта WHILEDO }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwWHILEDO
TkwBREAK = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта BREAK }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBREAK
TkwCONTINUE = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта CONTINUE }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCONTINUE
TkwEXIT = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта EXIT }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwEXIT
TkwHALT = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта HALT }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwHALT
TkwBREAKITERATOR = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта BREAK-ITERATOR }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBREAKITERATOR
TkwNOP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта NOP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwNOP
TkwSLEEP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта SLEEP }
private
procedure SLEEP(const aCtx: TtfwContext;
aDuration: Integer);
{* Реализация слова скрипта SLEEP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSLEEP
TkwProcessMessages = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ProcessMessages }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwProcessMessages
TkwCheckAssert = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ASSERT }
private
procedure CheckAssert(const aCtx: TtfwContext;
aCondition: Boolean);
{* Реализация слова скрипта ASSERT }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCheckAssert
TkwASSERTS = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ASSERTS }
private
procedure ASSERTS(const aCtx: TtfwContext;
const aMsg: AnsiString;
aCondition: Boolean);
{* Реализация слова скрипта ASSERTS }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwASSERTS
TkwNil = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта nil }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwNil
TkwDoWord = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DO }
private
procedure DoWord(const aCtx: TtfwContext;
aWord: TtfwWord);
{* Реализация слова скрипта DO }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDoWord
TkwSmartEquals = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ?== }
private
function SmartEquals(const aCtx: TtfwContext;
const aV1: TtfwStackValue;
const aV2: TtfwStackValue): Boolean;
{* Реализация слова скрипта ?== }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSmartEquals
TkwSmartNotEquals = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ?!= }
private
function SmartNotEquals(const aCtx: TtfwContext;
const aV1: TtfwStackValue;
const aV2: TtfwStackValue): Boolean;
{* Реализация слова скрипта ?!= }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSmartNotEquals
TkwPushWord = {final} class(TtfwWordWorkerEx)
{* Слово скрипта @ }
private
function PushWord(const aCtx: TtfwContext;
aWord: TtfwWord): TtfwWord;
{* Реализация слова скрипта @ }
protected
class function GetWordNameForRegister: AnsiString; override;
function SuppressNextImmediate(const aContext: TtfwContext;
aWordNumber: Integer): TtfwSuppressNextImmediate; override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function RightParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure DoRun(const aCtx: TtfwContext); override;
end;//TkwPushWord
TkwCurrentException = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта current:exception }
private
function current_exception(const aCtx: TtfwContext): TObject;
{* Реализация слова скрипта current:exception }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCurrentException
TkwCurrentExceptionClass = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта current:exception:class }
private
function current_exception_class(const aCtx: TtfwContext): TClass;
{* Реализация слова скрипта current:exception:class }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCurrentExceptionClass
TkwCurrentExceptionClassName = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта current:exception:ClassName }
private
function current_exception_ClassName(const aCtx: TtfwContext): AnsiString;
{* Реализация слова скрипта current:exception:ClassName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCurrentExceptionClassName
TkwCurrentExceptionMessage = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта current:exception:Message }
private
function current_exception_Message(const aCtx: TtfwContext): AnsiString;
{* Реализация слова скрипта current:exception:Message }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCurrentExceptionMessage
TkwInc = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ++ }
private
function Inc(const aCtx: TtfwContext;
aValue: Integer): Integer;
{* Реализация слова скрипта ++ }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwInc
TkwDec = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта -- }
private
function Dec(const aCtx: TtfwContext;
aValue: Integer): Integer;
{* Реализация слова скрипта -- }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDec
TkwAdd = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта + }
private
function Add(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): TtfwStackValue;
{* Реализация слова скрипта + }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwAdd
TkwSub = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта - }
private
function Sub(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта - }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSub
TkwDivision = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DIV }
private
function Division(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта DIV }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDivision
TkwMul = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта * }
private
function Mul(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта * }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwMul
TkwDivide = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта / }
private
function Divide(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта / }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDivide
TkwMul2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2* }
private
function Mul2(const aCtx: TtfwContext;
aA: Integer): Integer;
{* Реализация слова скрипта 2* }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwMul2
TkwDiv2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2/ }
private
function Div2(const aCtx: TtfwContext;
aA: Integer): Integer;
{* Реализация слова скрипта 2/ }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDiv2
TkwMulDiv = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта */ }
private
function MulDiv(const aCtx: TtfwContext;
aC: Integer;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта */ }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwMulDiv
TkwBoolNot = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ! }
private
function BoolNot(const aCtx: TtfwContext;
aA: Boolean): Boolean;
{* Реализация слова скрипта ! }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBoolNot
TkwModFromDiv = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта MOD }
private
function ModFromDiv(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта MOD }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwModFromDiv
TkwBoolAnd = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта && }
private
function BoolAnd(const aCtx: TtfwContext;
aB: Boolean;
aA: Boolean): Boolean;
{* Реализация слова скрипта && }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBoolAnd
TkwBoolOr = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта || }
private
function BoolOr(const aCtx: TtfwContext;
aB: Boolean;
aA: Boolean): Boolean;
{* Реализация слова скрипта || }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBoolOr
TkwNotZero = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта !=0 }
private
function NotZero(const aCtx: TtfwContext;
aA: Integer): Boolean;
{* Реализация слова скрипта !=0 }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwNotZero
TkwEqualZero = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта =0 }
private
function EqualZero(const aCtx: TtfwContext;
aA: Integer): Boolean;
{* Реализация слова скрипта =0 }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwEqualZero
TkwSWAP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта SWAP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSWAP
TkwDROP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DROP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDROP
TkwDUP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DUP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDUP
TkwDUPIfNotZero = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ?DUP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDUPIfNotZero
TkwROT = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ROT }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwROT
TkwPICK = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта PICK }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPICK
TkwInvertROT = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта -ROT }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwInvertROT
TkwSWAP2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2SWAP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwSWAP2
TkwOVER2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2OVER }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwOVER2
TkwDUP2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2DUP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDUP2
TkwDROP2 = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта 2DROP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDROP2
TkwNIP = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта NIP }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwNIP
TkwTUCK = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта TUCK }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwTUCK
TkwOVER = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта OVER }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwOVER
TkwROLL = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ROLL }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwROLL
TkwNotEquals = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта != }
private
function NotEquals(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта != }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwNotEquals
TkwGREATER = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта GREATER }
private
function GREATER(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта GREATER }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwGREATER
TkwLESS = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта LESS }
private
function LESS(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта LESS }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwLESS
TkwEquals = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта == }
private
function Equals(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта == }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwEquals
TkwLessThanZero = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта <0 }
private
function LessThanZero(const aCtx: TtfwContext;
aB: Integer): Boolean;
{* Реализация слова скрипта <0 }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwLessThanZero
TkwGreaterThanZero = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта >0 }
private
function GreaterThanZero(const aCtx: TtfwContext;
aB: Integer): Boolean;
{* Реализация слова скрипта >0 }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwGreaterThanZero
TkwBitAnd = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта & }
private
function BitAnd(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта & }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBitAnd
TkwBitOR = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта | }
private
function BitOR(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта | }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBitOR
TkwBitNot = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ~ }
private
function BitNot(const aCtx: TtfwContext;
aB: Integer): Integer;
{* Реализация слова скрипта ~ }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwBitNot
TkwStackLevel = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта StackLevel }
private
function StackLevel(const aCtx: TtfwContext): Integer;
{* Реализация слова скрипта StackLevel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwStackLevel
TkwReduceStackLevel = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта ReduceStackLevel }
private
procedure ReduceStackLevel(const aCtx: TtfwContext;
aValue: Integer);
{* Реализация слова скрипта ReduceStackLevel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwReduceStackLevel
TkwCtxParserPushString = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:Parser:PushString }
private
procedure Ctx_Parser_PushString(const aCtx: TtfwContext;
const aValue: Il3CString);
{* Реализация слова скрипта Ctx:Parser:PushString }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxParserPushString
TkwCtxParserPushSymbol = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:Parser:PushSymbol }
private
procedure Ctx_Parser_PushSymbol(const aCtx: TtfwContext;
const aValue: Il3CString);
{* Реализация слова скрипта Ctx:Parser:PushSymbol }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxParserPushSymbol
TkwCtxParserPushInt = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:Parser:PushInt }
private
procedure Ctx_Parser_PushInt(const aCtx: TtfwContext;
aValue: Integer);
{* Реализация слова скрипта Ctx:Parser:PushInt }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxParserPushInt
TkwCtxParser = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:Parser }
private
function Ctx_Parser(const aCtx: TtfwContext): ItfwParserEx;
{* Реализация слова скрипта Ctx:Parser }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxParser
TkwAtomicIf = {final} class(TtfwWordWorkerEx)
{* Слово скрипта ? }
private
procedure AtomicIf(const aCtx: TtfwContext;
aWord: TtfwWord;
aCondition: Boolean);
{* Реализация слова скрипта ? }
protected
class function GetWordNameForRegister: AnsiString; override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function RightParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure DoRun(const aCtx: TtfwContext); override;
end;//TkwAtomicIf
TkwCompileValue = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта CompileValue }
private
procedure CompileValue(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileValue }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCompileValue
TkwIMMEDIATE = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта IMMEDIATE }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
function IsImmediate(const aCtx: TtfwContext): Boolean; override;
end;//TkwIMMEDIATE
TkwCtxScriptCaller = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:ScriptCaller }
private
function Ctx_ScriptCaller(const aCtx: TtfwContext): ItfwScriptCaller;
{* Реализация слова скрипта Ctx:ScriptCaller }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxScriptCaller
TkwCtxEngine = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:Engine }
private
function Ctx_Engine(const aCtx: TtfwContext): ItfwScriptEngine;
{* Реализация слова скрипта Ctx:Engine }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxEngine
TkwCtxStoredValuesStack = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:StoredValuesStack }
private
function Ctx_StoredValuesStack(const aCtx: TtfwContext): ItfwStoredValuesStack;
{* Реализация слова скрипта Ctx:StoredValuesStack }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxStoredValuesStack
TkwCreateAndRaise = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта CreateAndRaise }
private
procedure CreateAndRaise(const aCtx: TtfwContext;
aClass: TClass;
const aMessage: AnsiString);
{* Реализация слова скрипта CreateAndRaise }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCreateAndRaise
TkwCompileRef = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта CompileRef }
private
procedure CompileRef(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileRef }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCompileRef
TkwCompileWeakRef = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта CompileWeakRef }
private
procedure CompileWeakRef(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileWeakRef }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCompileWeakRef
TkwDUPN = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DUPN }
private
procedure DUPN(const aCtx: TtfwContext;
aN: Integer);
{* Реализация слова скрипта DUPN }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDUPN
TkwDROPN = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта DROPN }
private
procedure DROPN(const aCtx: TtfwContext;
aN: Integer);
{* Реализация слова скрипта DROPN }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwDROPN
TkwCtxEnterCS = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:EnterCS }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxEnterCS
TkwCtxLeaveCS = {final} class(TtfwGlobalKeyWord)
{* Слово скрипта Ctx:LeaveCS }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwCtxLeaveCS
TBasicsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter)
{* Регистрация скриптованой аксиоматики }
public
class function ResName: AnsiString; override;
end;//TBasicsPackResNameGetter
function CompareValues(const aV1: TtfwStackValue;
const aV2: TtfwStackValue;
const aCtx: TtfwContext;
aCaller: TtfwWord): Boolean;
//#UC START# *4F51EE02033C_4F43A128007E_var*
procedure CompareAsPrintable;
begin//CompareAsPrintable
Result := l3Same(aV1.AsPrintable, aV2.AsPrintable);
end;//CompareAsPrintable
function Ref(anObj: TObject): TObject;
begin//Ref
try
if (anObj Is TtfwWord) then
Result := TtfwWord(anObj).GetRefForCompare
else
Result := anObj;
except
//http://mdp.garant.ru/pages/viewpage.action?pageId=600103362&focusedCommentId=624088919#comment-624088919
Result := anObj;
end;//try..except
end;//Ref
var
l_C : AnsiChar;
//#UC END# *4F51EE02033C_4F43A128007E_var*
begin
//#UC START# *4F51EE02033C_4F43A128007E_impl*
Result := false;
if (aV1.rType = aV2.rType) then
begin
Case aV1.rType of
tfw_vtVoid:
Result := true;
tfw_vtInt:
Result := (aV1.rInteger = aV2.rInteger);
tfw_vtBool:
Result := (aV1.AsBoolean = aV2.AsBoolean);
tfw_vtStr:
Result := l3Same(aV1.AsString, aV2.AsString);
tfw_vtObj:
Result := (Ref(aV1.AsObject) = Ref(aV2.AsObject));
tfw_vtList:
Result := (aV1.AsIntf = aV2.AsIntf);
tfw_vtIntf:
Result := (aV1.AsIntf = aV2.AsIntf);
tfw_vtNil:
Result := true;
tfw_vtFile:
Result := (aV1.AsIntf = aV2.AsIntf);
tfw_vtChar:
Result := (aV1.AsChar = aV2.AsChar);
(* tfw_vtWStr:
Result := l3Same(aV1.AsWString, aV2.AsWString);*)
(* tfw_vtBracket:
Result := true;*)
else
aCaller.RunnerError('Неизвестный тип для сравнения', aCtx);
end;//aV1.rType
end//aV1.rType = aV2.rType
else
begin
Case aV1.rType of
(* tfw_svtVoid:
Result := true;
tfw_svtInt:
Result := (aV1.rInteger = aV2.rInteger);
tfw_svtBool:
Result := (aV1.AsBoolean = aV2.AsBoolean);*)
tfw_vtStr:
begin
Case aV2.rType of
(* tfw_vtWStr:
Result := l3Same(aV1.AsString.AsWStr, aV2.AsWString);*)
tfw_vtChar:
begin
l_C := aV2.AsChar;
Result := l3Same(aV1.AsString.AsWStr, l3PCharLen(@l_C, 1, CP_ANSI));
end;//tfw_svtChar
else
CompareAsPrintable;
end;//Case aV2.rType
end;//tfw_svtStr
tfw_vtObj:
Case aV2.rType of
tfw_vtNil:
Result := (Ref(aV1.AsObject) = nil);
else
CompareAsPrintable;
end;//Case aV2.rType
tfw_vtIntf:
Case aV2.rType of
tfw_vtNil:
Result := (aV1.AsIntf = nil);
else
CompareAsPrintable;
end;//Case aV2.rType
tfw_vtNil:
Case aV2.rType of
tfw_vtIntf:
Result := (aV2.AsIntf = nil);
tfw_vtObj:
Result := (Ref(aV2.AsObject) = nil);
else
CompareAsPrintable;
end;//Case aV2.rType
(* tfw_svtFile:
Result := (aV1.AsIntf = aV2.AsIntf);*)
tfw_vtChar:
begin
l_C := aV1.AsChar;
Case aV2.rType of
tfw_vtStr:
Result := l3Same(l3PCharLen(@l_C, 1, CP_ANSI), aV2.AsString.AsWStr);
(* tfw_vtWStr:
Result := l3Same(l3PCharLen(@l_C, 1, CP_ANSI), aV2.AsWString);*)
else
CompareAsPrintable;
end;//Case aV2.rType
end;//tfw_svtChar
(* tfw_vtWStr:
Case aV2.rType of
tfw_vtStr:
Result := l3Same(aV1.AsWString, aV2.AsString.AsWStr);
tfw_vtChar:
begin
l_C := aV2.AsChar;
Result := l3Same(aV1.AsWString, l3PCharLen(@l_C, 1, CP_ANSI));
end;//tfw_svtChar
else
CompareAsPrintable;
end;//Case aV2.rType*)
(* tfw_svtBracket:
Result := true;*)
else
CompareAsPrintable;
end;//aV1.rType
end;//aV1.rType = aV2.rType
//#UC END# *4F51EE02033C_4F43A128007E_impl*
end;//CompareValues
function TkwDefine.IsImmediate(const aCtx: TtfwContext): Boolean;
//#UC START# *4DB6D7F70155_55880B6D01A0_var*
//#UC END# *4DB6D7F70155_55880B6D01A0_var*
begin
//#UC START# *4DB6D7F70155_55880B6D01A0_impl*
Result := false;
//#UC END# *4DB6D7F70155_55880B6D01A0_impl*
end;//TkwDefine.IsImmediate
function TkwDefine.AfterWordMaxCount(const aCtx: TtfwContext): Integer;
//#UC START# *4DB9B446039A_55880B6D01A0_var*
//#UC END# *4DB9B446039A_55880B6D01A0_var*
begin
//#UC START# *4DB9B446039A_55880B6D01A0_impl*
Result := 0;
//#UC END# *4DB9B446039A_55880B6D01A0_impl*
end;//TkwDefine.AfterWordMaxCount
procedure TkwDefine.FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWordPrim;
const aContext: TtfwContext);
{* Завершает определение вновь созданного слова }
//#UC START# *4F219629036A_55880B6D01A0_var*
var
l_W : TtfwWord;
l_Key : TtfwKeyWord;
//#UC END# *4F219629036A_55880B6D01A0_var*
begin
//#UC START# *4F219629036A_55880B6D01A0_impl*
l_W := aContext.rEngine.PopObj As TtfwWord;
l_Key := TtfwKeyWord(l_W.Key);
try
aWordToFinish.SetWord(aContext, l_W);
finally
l_W.Key := l_Key;
end;//try..finally
//#UC END# *4F219629036A_55880B6D01A0_impl*
end;//TkwDefine.FinishDefinitionOfNewWord
function TkwDefine.GetNewWordName(const aContext: TtfwContext): Il3CString;
//#UC START# *4F37B3F10318_55880B6D01A0_var*
//#UC END# *4F37B3F10318_55880B6D01A0_var*
begin
//#UC START# *4F37B3F10318_55880B6D01A0_impl*
Result := aContext.rEngine.PopString;
//#UC END# *4F37B3F10318_55880B6D01A0_impl*
end;//TkwDefine.GetNewWordName
class function TkwDefine.GetWordNameForRegister: AnsiString;
begin
Result := 'Define';
end;//TkwDefine.GetWordNameForRegister
procedure TkwCompiledPushWord.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55A50F960186_var*
//#UC END# *4DAEEDE10285_55A50F960186_var*
begin
//#UC START# *4DAEEDE10285_55A50F960186_impl*
aCtx.rEngine.PushObj(WordToWork);
//#UC END# *4DAEEDE10285_55A50F960186_impl*
end;//TkwCompiledPushWord.DoDoIt
function TkwCompiledPushWord.GetRef(const aCtx: TtfwContext): TtfwWord;
//#UC START# *558D2BCA0324_55A50F960186_var*
//#UC END# *558D2BCA0324_55A50F960186_var*
begin
//#UC START# *558D2BCA0324_55A50F960186_impl*
Result := WordToWork;
Result := Result.GetRef(aCtx);
//#UC END# *558D2BCA0324_55A50F960186_impl*
end;//TkwCompiledPushWord.GetRef
function TkwCompiledPushWord.WordName: Il3CString;
//#UC START# *55AFD7DA0258_55A50F960186_var*
//#UC END# *55AFD7DA0258_55A50F960186_var*
begin
//#UC START# *55AFD7DA0258_55A50F960186_impl*
Result := WordToWork.WordName;
//#UC END# *55AFD7DA0258_55A50F960186_impl*
end;//TkwCompiledPushWord.WordName
function TkwTrue.True(const aCtx: TtfwContext): Boolean;
{* Реализация слова скрипта True }
//#UC START# *5511611100EB_5511611100EB_Word_var*
//#UC END# *5511611100EB_5511611100EB_Word_var*
begin
//#UC START# *5511611100EB_5511611100EB_Word_impl*
Result := System.true;
//#UC END# *5511611100EB_5511611100EB_Word_impl*
end;//TkwTrue.True
class function TkwTrue.GetWordNameForRegister: AnsiString;
begin
Result := 'True';
end;//TkwTrue.GetWordNameForRegister
function TkwTrue.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwTrue.GetResultTypeInfo
function TkwTrue.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwTrue.GetAllParamsCount
function TkwTrue.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwTrue.ParamsTypes
procedure TkwTrue.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushBool(True(aCtx));
end;//TkwTrue.DoDoIt
function TkwFalse.False(const aCtx: TtfwContext): Boolean;
{* Реализация слова скрипта False }
//#UC START# *55116124039C_55116124039C_Word_var*
//#UC END# *55116124039C_55116124039C_Word_var*
begin
//#UC START# *55116124039C_55116124039C_Word_impl*
Result := System.false;
//#UC END# *55116124039C_55116124039C_Word_impl*
end;//TkwFalse.False
class function TkwFalse.GetWordNameForRegister: AnsiString;
begin
Result := 'False';
end;//TkwFalse.GetWordNameForRegister
function TkwFalse.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwFalse.GetResultTypeInfo
function TkwFalse.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwFalse.GetAllParamsCount
function TkwFalse.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwFalse.ParamsTypes
procedure TkwFalse.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushBool(False(aCtx));
end;//TkwFalse.DoDoIt
procedure TkwMsg.Msg(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта Msg }
//#UC START# *55116B670356_55116B670356_Word_var*
var
l_S : AnsiString;
//#UC END# *55116B670356_55116B670356_Word_var*
begin
//#UC START# *55116B670356_55116B670356_Word_impl*
l_S := l3Str(aValue.AsPrintable);
MessageBoxA(0, PAnsiChar(l_S), 'script message', MB_OK);
//#UC END# *55116B670356_55116B670356_Word_impl*
end;//TkwMsg.Msg
class function TkwMsg.GetWordNameForRegister: AnsiString;
begin
Result := 'Msg';
end;//TkwMsg.GetWordNameForRegister
function TkwMsg.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwMsg.GetResultTypeInfo
function TkwMsg.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwMsg.GetAllParamsCount
function TkwMsg.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct]);
end;//TkwMsg.ParamsTypes
procedure TkwMsg.DoDoIt(const aCtx: TtfwContext);
var l_aValue: TtfwStackValue;
begin
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
Msg(aCtx, l_aValue);
end;//TkwMsg.DoDoIt
procedure TkwPrint.Print(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта . }
//#UC START# *55116B9100CF_55116B9100CF_Word_var*
//#UC END# *55116B9100CF_55116B9100CF_Word_var*
begin
//#UC START# *55116B9100CF_55116B9100CF_Word_impl*
aCtx.rCaller.Print(aValue.AsPrintable);
//#UC END# *55116B9100CF_55116B9100CF_Word_impl*
end;//TkwPrint.Print
class function TkwPrint.GetWordNameForRegister: AnsiString;
begin
Result := '.';
end;//TkwPrint.GetWordNameForRegister
function TkwPrint.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPrint.GetResultTypeInfo
function TkwPrint.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPrint.GetAllParamsCount
function TkwPrint.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct]);
end;//TkwPrint.ParamsTypes
procedure TkwPrint.DoDoIt(const aCtx: TtfwContext);
var l_aValue: TtfwStackValue;
begin
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
Print(aCtx, l_aValue);
end;//TkwPrint.DoDoIt
procedure TkwLOOP.LOOP(const aCtx: TtfwContext;
aWord: TtfwWord;
aCount: Integer);
{* Реализация слова скрипта LOOP }
//#UC START# *5513E11A00F5_5513E11A00F5_Word_var*
var
l_I : Integer;
//#UC END# *5513E11A00F5_5513E11A00F5_Word_var*
begin
//#UC START# *5513E11A00F5_5513E11A00F5_Word_impl*
for l_I := 0 to Pred(aCount) do
try
aWord.DoIt(aCtx);
except
on EtfwBreak do
break;
on EtfwContinue do
continue;
end;//try..except
//#UC END# *5513E11A00F5_5513E11A00F5_Word_impl*
end;//TkwLOOP.LOOP
class function TkwLOOP.GetWordNameForRegister: AnsiString;
begin
Result := 'LOOP';
end;//TkwLOOP.GetWordNameForRegister
function TkwLOOP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwLOOP.GetResultTypeInfo
function TkwLOOP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwLOOP.GetAllParamsCount
function TkwLOOP.RightParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwLOOP.RightParamsCount
function TkwLOOP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwLOOP.ParamsTypes
procedure TkwLOOP.DoRun(const aCtx: TtfwContext);
var l_aWord: TtfwWord;
var l_aCount: Integer;
begin
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aCount := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCount: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
LOOP(aCtx, l_aWord, l_aCount);
end;//TkwLOOP.DoRun
procedure TkwWHILEDO.WHILEDO(const aCtx: TtfwContext;
aWord: TtfwWord;
aCondition: TtfwWord);
{* Реализация слова скрипта WHILEDO }
//#UC START# *5513E760006C_5513E760006C_Word_var*
//#UC END# *5513E760006C_5513E760006C_Word_var*
begin
//#UC START# *5513E760006C_5513E760006C_Word_impl*
while true do
begin
aCondition.DoIt(aCtx);
if not aCtx.rEngine.PopBool then
break;
try
aWord.DoIt(aCtx);
except
on EtfwBreak do
break;
on EtfwContinue do
continue;
end;//try..except
end;//while true
//#UC END# *5513E760006C_5513E760006C_Word_impl*
end;//TkwWHILEDO.WHILEDO
class function TkwWHILEDO.GetWordNameForRegister: AnsiString;
begin
Result := 'WHILEDO';
end;//TkwWHILEDO.GetWordNameForRegister
function TkwWHILEDO.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwWHILEDO.GetResultTypeInfo
function TkwWHILEDO.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwWHILEDO.GetAllParamsCount
function TkwWHILEDO.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(TtfwWord)]);
end;//TkwWHILEDO.ParamsTypes
procedure TkwWHILEDO.DoDoIt(const aCtx: TtfwContext);
var l_aWord: TtfwWord;
var l_aCondition: TtfwWord;
begin
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aCondition := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCondition: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
WHILEDO(aCtx, l_aWord, l_aCondition);
end;//TkwWHILEDO.DoDoIt
class function TkwBREAK.GetWordNameForRegister: AnsiString;
begin
Result := 'BREAK';
end;//TkwBREAK.GetWordNameForRegister
function TkwBREAK.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwBREAK.GetResultTypeInfo
function TkwBREAK.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwBREAK.GetAllParamsCount
function TkwBREAK.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwBREAK.ParamsTypes
procedure TkwBREAK.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513EC0A01DB_Word_var*
//#UC END# *4DAEEDE10285_5513EC0A01DB_Word_var*
begin
//#UC START# *4DAEEDE10285_5513EC0A01DB_Word_impl*
raise EtfwBreak.Instance;
//#UC END# *4DAEEDE10285_5513EC0A01DB_Word_impl*
end;//TkwBREAK.DoDoIt
class function TkwCONTINUE.GetWordNameForRegister: AnsiString;
begin
Result := 'CONTINUE';
end;//TkwCONTINUE.GetWordNameForRegister
function TkwCONTINUE.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCONTINUE.GetResultTypeInfo
function TkwCONTINUE.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCONTINUE.GetAllParamsCount
function TkwCONTINUE.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCONTINUE.ParamsTypes
procedure TkwCONTINUE.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513EC3F02BC_Word_var*
//#UC END# *4DAEEDE10285_5513EC3F02BC_Word_var*
begin
//#UC START# *4DAEEDE10285_5513EC3F02BC_Word_impl*
raise EtfwContinue.Instance;
//raise EtfwContinue.Create('Выход на начало цикла');
//#UC END# *4DAEEDE10285_5513EC3F02BC_Word_impl*
end;//TkwCONTINUE.DoDoIt
class function TkwEXIT.GetWordNameForRegister: AnsiString;
begin
Result := 'EXIT';
end;//TkwEXIT.GetWordNameForRegister
function TkwEXIT.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwEXIT.GetResultTypeInfo
function TkwEXIT.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwEXIT.GetAllParamsCount
function TkwEXIT.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwEXIT.ParamsTypes
procedure TkwEXIT.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513EC59004D_Word_var*
//#UC END# *4DAEEDE10285_5513EC59004D_Word_var*
begin
//#UC START# *4DAEEDE10285_5513EC59004D_Word_impl*
raise EtfwExit.Instance;
//raise EtfwExit.Create('Выход из процедуры');
//#UC END# *4DAEEDE10285_5513EC59004D_Word_impl*
end;//TkwEXIT.DoDoIt
class function TkwHALT.GetWordNameForRegister: AnsiString;
begin
Result := 'HALT';
end;//TkwHALT.GetWordNameForRegister
function TkwHALT.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwHALT.GetResultTypeInfo
function TkwHALT.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwHALT.GetAllParamsCount
function TkwHALT.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwHALT.ParamsTypes
procedure TkwHALT.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513EC7A029E_Word_var*
//#UC END# *4DAEEDE10285_5513EC7A029E_Word_var*
begin
//#UC START# *4DAEEDE10285_5513EC7A029E_Word_impl*
raise EtfwHalt.Instance;
//raise EtfwHalt.Create('Выход из скрипта');
//#UC END# *4DAEEDE10285_5513EC7A029E_Word_impl*
end;//TkwHALT.DoDoIt
class function TkwBREAKITERATOR.GetWordNameForRegister: AnsiString;
begin
Result := 'BREAK-ITERATOR';
end;//TkwBREAKITERATOR.GetWordNameForRegister
function TkwBREAKITERATOR.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwBREAKITERATOR.GetResultTypeInfo
function TkwBREAKITERATOR.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwBREAKITERATOR.GetAllParamsCount
function TkwBREAKITERATOR.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwBREAKITERATOR.ParamsTypes
procedure TkwBREAKITERATOR.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513EC94003D_Word_var*
//#UC END# *4DAEEDE10285_5513EC94003D_Word_var*
begin
//#UC START# *4DAEEDE10285_5513EC94003D_Word_impl*
raise EtfwBreakIterator.Instance;
//raise EtfwBreakIterator.Create('Выход из итератора');
//#UC END# *4DAEEDE10285_5513EC94003D_Word_impl*
end;//TkwBREAKITERATOR.DoDoIt
class function TkwNOP.GetWordNameForRegister: AnsiString;
begin
Result := 'NOP';
end;//TkwNOP.GetWordNameForRegister
function TkwNOP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwNOP.GetResultTypeInfo
function TkwNOP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwNOP.GetAllParamsCount
function TkwNOP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwNOP.ParamsTypes
procedure TkwNOP.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513F98C032C_Word_var*
//#UC END# *4DAEEDE10285_5513F98C032C_Word_var*
begin
//#UC START# *4DAEEDE10285_5513F98C032C_Word_impl*
// - осознанно ничего не делаем
//#UC END# *4DAEEDE10285_5513F98C032C_Word_impl*
end;//TkwNOP.DoDoIt
procedure TkwSLEEP.SLEEP(const aCtx: TtfwContext;
aDuration: Integer);
{* Реализация слова скрипта SLEEP }
//#UC START# *5513F9A002BA_5513F9A002BA_Word_var*
//#UC END# *5513F9A002BA_5513F9A002BA_Word_var*
begin
//#UC START# *5513F9A002BA_5513F9A002BA_Word_impl*
SysUtils.Sleep(aDuration);
//#UC END# *5513F9A002BA_5513F9A002BA_Word_impl*
end;//TkwSLEEP.SLEEP
class function TkwSLEEP.GetWordNameForRegister: AnsiString;
begin
Result := 'SLEEP';
end;//TkwSLEEP.GetWordNameForRegister
function TkwSLEEP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwSLEEP.GetResultTypeInfo
function TkwSLEEP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwSLEEP.GetAllParamsCount
function TkwSLEEP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwSLEEP.ParamsTypes
procedure TkwSLEEP.DoDoIt(const aCtx: TtfwContext);
var l_aDuration: Integer;
begin
try
l_aDuration := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDuration: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
SLEEP(aCtx, l_aDuration);
end;//TkwSLEEP.DoDoIt
class function TkwProcessMessages.GetWordNameForRegister: AnsiString;
begin
Result := 'ProcessMessages';
end;//TkwProcessMessages.GetWordNameForRegister
function TkwProcessMessages.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwProcessMessages.GetResultTypeInfo
function TkwProcessMessages.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwProcessMessages.GetAllParamsCount
function TkwProcessMessages.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwProcessMessages.ParamsTypes
procedure TkwProcessMessages.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513F9CA0059_Word_var*
//#UC END# *4DAEEDE10285_5513F9CA0059_Word_var*
begin
//#UC START# *4DAEEDE10285_5513F9CA0059_Word_impl*
try
Tl3MessagesService.Instance.ProcessMessages;
except
on E: Exception do
begin
l3System.Exception2Log(E);
raise;
end;//on E: Exception
end;//try..finally
//#UC END# *4DAEEDE10285_5513F9CA0059_Word_impl*
end;//TkwProcessMessages.DoDoIt
procedure TkwCheckAssert.CheckAssert(const aCtx: TtfwContext;
aCondition: Boolean);
{* Реализация слова скрипта ASSERT }
//#UC START# *5513FABD01F6_5513FABD01F6_Word_var*
//#UC END# *5513FABD01F6_5513FABD01F6_Word_var*
begin
//#UC START# *5513FABD01F6_5513FABD01F6_Word_impl*
aCtx.rCaller.Check(aCondition);
//#UC END# *5513FABD01F6_5513FABD01F6_Word_impl*
end;//TkwCheckAssert.CheckAssert
class function TkwCheckAssert.GetWordNameForRegister: AnsiString;
begin
Result := 'ASSERT';
end;//TkwCheckAssert.GetWordNameForRegister
function TkwCheckAssert.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCheckAssert.GetResultTypeInfo
function TkwCheckAssert.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCheckAssert.GetAllParamsCount
function TkwCheckAssert.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Boolean)]);
end;//TkwCheckAssert.ParamsTypes
procedure TkwCheckAssert.DoDoIt(const aCtx: TtfwContext);
var l_aCondition: Boolean;
begin
try
l_aCondition := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCondition: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CheckAssert(aCtx, l_aCondition);
end;//TkwCheckAssert.DoDoIt
procedure TkwASSERTS.ASSERTS(const aCtx: TtfwContext;
const aMsg: AnsiString;
aCondition: Boolean);
{* Реализация слова скрипта ASSERTS }
//#UC START# *5513FB260063_5513FB260063_Word_var*
//#UC END# *5513FB260063_5513FB260063_Word_var*
begin
//#UC START# *5513FB260063_5513FB260063_Word_impl*
aCtx.rCaller.Check(aCondition, aMsg);
//#UC END# *5513FB260063_5513FB260063_Word_impl*
end;//TkwASSERTS.ASSERTS
class function TkwASSERTS.GetWordNameForRegister: AnsiString;
begin
Result := 'ASSERTS';
end;//TkwASSERTS.GetWordNameForRegister
function TkwASSERTS.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwASSERTS.GetResultTypeInfo
function TkwASSERTS.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwASSERTS.GetAllParamsCount
function TkwASSERTS.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiString, TypeInfo(Boolean)]);
end;//TkwASSERTS.ParamsTypes
procedure TkwASSERTS.DoDoIt(const aCtx: TtfwContext);
var l_aMsg: AnsiString;
var l_aCondition: Boolean;
begin
try
l_aMsg := aCtx.rEngine.PopDelphiString;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aMsg: AnsiString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aCondition := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCondition: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
ASSERTS(aCtx, l_aMsg, l_aCondition);
end;//TkwASSERTS.DoDoIt
class function TkwNil.GetWordNameForRegister: AnsiString;
begin
Result := 'nil';
end;//TkwNil.GetWordNameForRegister
function TkwNil.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwNil.GetResultTypeInfo
function TkwNil.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwNil.GetAllParamsCount
function TkwNil.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwNil.ParamsTypes
procedure TkwNil.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5513FB5B00B2_Word_var*
//#UC END# *4DAEEDE10285_5513FB5B00B2_Word_var*
begin
//#UC START# *4DAEEDE10285_5513FB5B00B2_Word_impl*
aCtx.rEngine.Push(TtfwStackValue_NULL);
//#UC END# *4DAEEDE10285_5513FB5B00B2_Word_impl*
end;//TkwNil.DoDoIt
procedure TkwDoWord.DoWord(const aCtx: TtfwContext;
aWord: TtfwWord);
{* Реализация слова скрипта DO }
//#UC START# *5513FC1D0085_5513FC1D0085_Word_var*
//#UC END# *5513FC1D0085_5513FC1D0085_Word_var*
begin
//#UC START# *5513FC1D0085_5513FC1D0085_Word_impl*
aWord.DoIt(aCtx);
//#UC END# *5513FC1D0085_5513FC1D0085_Word_impl*
end;//TkwDoWord.DoWord
class function TkwDoWord.GetWordNameForRegister: AnsiString;
begin
Result := 'DO';
end;//TkwDoWord.GetWordNameForRegister
function TkwDoWord.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDoWord.GetResultTypeInfo
function TkwDoWord.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwDoWord.GetAllParamsCount
function TkwDoWord.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwWord)]);
end;//TkwDoWord.ParamsTypes
procedure TkwDoWord.DoDoIt(const aCtx: TtfwContext);
var l_aWord: TtfwWord;
begin
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
DoWord(aCtx, l_aWord);
end;//TkwDoWord.DoDoIt
function TkwSmartEquals.SmartEquals(const aCtx: TtfwContext;
const aV1: TtfwStackValue;
const aV2: TtfwStackValue): Boolean;
{* Реализация слова скрипта ?== }
//#UC START# *5514019E03BD_5514019E03BD_Word_var*
//#UC END# *5514019E03BD_5514019E03BD_Word_var*
begin
//#UC START# *5514019E03BD_5514019E03BD_Word_impl*
Result := CompareValues(aV1, aV2, aCtx, Self);
//#UC END# *5514019E03BD_5514019E03BD_Word_impl*
end;//TkwSmartEquals.SmartEquals
class function TkwSmartEquals.GetWordNameForRegister: AnsiString;
begin
Result := '?==';
end;//TkwSmartEquals.GetWordNameForRegister
function TkwSmartEquals.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwSmartEquals.GetResultTypeInfo
function TkwSmartEquals.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwSmartEquals.GetAllParamsCount
function TkwSmartEquals.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwSmartEquals.ParamsTypes
procedure TkwSmartEquals.DoDoIt(const aCtx: TtfwContext);
var l_aV1: TtfwStackValue;
var l_aV2: TtfwStackValue;
begin
try
l_aV1 := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aV1: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aV2 := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aV2: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(SmartEquals(aCtx, l_aV1, l_aV2));
end;//TkwSmartEquals.DoDoIt
function TkwSmartNotEquals.SmartNotEquals(const aCtx: TtfwContext;
const aV1: TtfwStackValue;
const aV2: TtfwStackValue): Boolean;
{* Реализация слова скрипта ?!= }
//#UC START# *551401F0003E_551401F0003E_Word_var*
//#UC END# *551401F0003E_551401F0003E_Word_var*
begin
//#UC START# *551401F0003E_551401F0003E_Word_impl*
Result := not CompareValues(aV1, aV2, aCtx, Self);
//#UC END# *551401F0003E_551401F0003E_Word_impl*
end;//TkwSmartNotEquals.SmartNotEquals
class function TkwSmartNotEquals.GetWordNameForRegister: AnsiString;
begin
Result := '?!=';
end;//TkwSmartNotEquals.GetWordNameForRegister
function TkwSmartNotEquals.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwSmartNotEquals.GetResultTypeInfo
function TkwSmartNotEquals.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwSmartNotEquals.GetAllParamsCount
function TkwSmartNotEquals.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwSmartNotEquals.ParamsTypes
procedure TkwSmartNotEquals.DoDoIt(const aCtx: TtfwContext);
var l_aV1: TtfwStackValue;
var l_aV2: TtfwStackValue;
begin
try
l_aV1 := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aV1: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aV2 := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aV2: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(SmartNotEquals(aCtx, l_aV1, l_aV2));
end;//TkwSmartNotEquals.DoDoIt
function TkwPushWord.PushWord(const aCtx: TtfwContext;
aWord: TtfwWord): TtfwWord;
{* Реализация слова скрипта @ }
//#UC START# *551420EE03BE_551420EE03BE_Word_var*
//#UC END# *551420EE03BE_551420EE03BE_Word_var*
begin
//#UC START# *551420EE03BE_551420EE03BE_Word_impl*
if (aWord Is TkwForwardDeclarationHolder) then
Result := TkwForwardDeclarationHolder(aWord).Holded
else
Result := aWord;
//#UC END# *551420EE03BE_551420EE03BE_Word_impl*
end;//TkwPushWord.PushWord
class function TkwPushWord.GetWordNameForRegister: AnsiString;
begin
Result := '@';
end;//TkwPushWord.GetWordNameForRegister
function TkwPushWord.SuppressNextImmediate(const aContext: TtfwContext;
aWordNumber: Integer): TtfwSuppressNextImmediate;
begin
Result := tfw_sniYes;
end;//TkwPushWord.SuppressNextImmediate
function TkwPushWord.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwWord);
end;//TkwPushWord.GetResultTypeInfo
function TkwPushWord.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPushWord.GetAllParamsCount
function TkwPushWord.RightParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPushWord.RightParamsCount
function TkwPushWord.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwPushWord.ParamsTypes
procedure TkwPushWord.DoRun(const aCtx: TtfwContext);
var l_aWord: TtfwWord;
begin
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(PushWord(aCtx, l_aWord));
end;//TkwPushWord.DoRun
function TkwCurrentException.current_exception(const aCtx: TtfwContext): TObject;
{* Реализация слова скрипта current:exception }
//#UC START# *551577F400BC_551577F400BC_Word_var*
//#UC END# *551577F400BC_551577F400BC_Word_var*
begin
//#UC START# *551577F400BC_551577F400BC_Word_impl*
Result := aCtx.rException;
//#UC END# *551577F400BC_551577F400BC_Word_impl*
end;//TkwCurrentException.current_exception
class function TkwCurrentException.GetWordNameForRegister: AnsiString;
begin
Result := 'current:exception';
end;//TkwCurrentException.GetWordNameForRegister
function TkwCurrentException.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TObject);
end;//TkwCurrentException.GetResultTypeInfo
function TkwCurrentException.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCurrentException.GetAllParamsCount
function TkwCurrentException.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCurrentException.ParamsTypes
procedure TkwCurrentException.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushObj(current_exception(aCtx));
end;//TkwCurrentException.DoDoIt
function TkwCurrentExceptionClass.current_exception_class(const aCtx: TtfwContext): TClass;
{* Реализация слова скрипта current:exception:class }
//#UC START# *5515780800CC_5515780800CC_Word_var*
//#UC END# *5515780800CC_5515780800CC_Word_var*
begin
//#UC START# *5515780800CC_5515780800CC_Word_impl*
if (aCtx.rException = nil) then
Result := nil
else
Result := aCtx.rException.ClassType;
//#UC END# *5515780800CC_5515780800CC_Word_impl*
end;//TkwCurrentExceptionClass.current_exception_class
class function TkwCurrentExceptionClass.GetWordNameForRegister: AnsiString;
begin
Result := 'current:exception:class';
end;//TkwCurrentExceptionClass.GetWordNameForRegister
function TkwCurrentExceptionClass.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiClassRef;
end;//TkwCurrentExceptionClass.GetResultTypeInfo
function TkwCurrentExceptionClass.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCurrentExceptionClass.GetAllParamsCount
function TkwCurrentExceptionClass.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCurrentExceptionClass.ParamsTypes
procedure TkwCurrentExceptionClass.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushClass(current_exception_class(aCtx));
end;//TkwCurrentExceptionClass.DoDoIt
function TkwCurrentExceptionClassName.current_exception_ClassName(const aCtx: TtfwContext): AnsiString;
{* Реализация слова скрипта current:exception:ClassName }
//#UC START# *5515781D0251_5515781D0251_Word_var*
//#UC END# *5515781D0251_5515781D0251_Word_var*
begin
//#UC START# *5515781D0251_5515781D0251_Word_impl*
if (aCtx.rException = nil) then
Result := ''
else
Result := aCtx.rException.ClassName;
//#UC END# *5515781D0251_5515781D0251_Word_impl*
end;//TkwCurrentExceptionClassName.current_exception_ClassName
class function TkwCurrentExceptionClassName.GetWordNameForRegister: AnsiString;
begin
Result := 'current:exception:ClassName';
end;//TkwCurrentExceptionClassName.GetWordNameForRegister
function TkwCurrentExceptionClassName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwCurrentExceptionClassName.GetResultTypeInfo
function TkwCurrentExceptionClassName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCurrentExceptionClassName.GetAllParamsCount
function TkwCurrentExceptionClassName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCurrentExceptionClassName.ParamsTypes
procedure TkwCurrentExceptionClassName.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString(current_exception_ClassName(aCtx));
end;//TkwCurrentExceptionClassName.DoDoIt
function TkwCurrentExceptionMessage.current_exception_Message(const aCtx: TtfwContext): AnsiString;
{* Реализация слова скрипта current:exception:Message }
//#UC START# *551578460058_551578460058_Word_var*
//#UC END# *551578460058_551578460058_Word_var*
begin
//#UC START# *551578460058_551578460058_Word_impl*
if (aCtx.rException = nil) then
Result := ''
else
Result := aCtx.rException.Message;
//#UC END# *551578460058_551578460058_Word_impl*
end;//TkwCurrentExceptionMessage.current_exception_Message
class function TkwCurrentExceptionMessage.GetWordNameForRegister: AnsiString;
begin
Result := 'current:exception:Message';
end;//TkwCurrentExceptionMessage.GetWordNameForRegister
function TkwCurrentExceptionMessage.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwCurrentExceptionMessage.GetResultTypeInfo
function TkwCurrentExceptionMessage.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCurrentExceptionMessage.GetAllParamsCount
function TkwCurrentExceptionMessage.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCurrentExceptionMessage.ParamsTypes
procedure TkwCurrentExceptionMessage.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString(current_exception_Message(aCtx));
end;//TkwCurrentExceptionMessage.DoDoIt
function TkwInc.Inc(const aCtx: TtfwContext;
aValue: Integer): Integer;
{* Реализация слова скрипта ++ }
//#UC START# *551597600166_551597600166_Word_var*
//#UC END# *551597600166_551597600166_Word_var*
begin
//#UC START# *551597600166_551597600166_Word_impl*
Result := aValue + 1;
//#UC END# *551597600166_551597600166_Word_impl*
end;//TkwInc.Inc
class function TkwInc.GetWordNameForRegister: AnsiString;
begin
Result := '++';
end;//TkwInc.GetWordNameForRegister
function TkwInc.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwInc.GetResultTypeInfo
function TkwInc.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwInc.GetAllParamsCount
function TkwInc.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwInc.ParamsTypes
procedure TkwInc.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Integer;
begin
try
l_aValue := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Inc(aCtx, l_aValue));
end;//TkwInc.DoDoIt
function TkwDec.Dec(const aCtx: TtfwContext;
aValue: Integer): Integer;
{* Реализация слова скрипта -- }
//#UC START# *551597780135_551597780135_Word_var*
//#UC END# *551597780135_551597780135_Word_var*
begin
//#UC START# *551597780135_551597780135_Word_impl*
Result := aValue - 1;
//#UC END# *551597780135_551597780135_Word_impl*
end;//TkwDec.Dec
class function TkwDec.GetWordNameForRegister: AnsiString;
begin
Result := '--';
end;//TkwDec.GetWordNameForRegister
function TkwDec.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwDec.GetResultTypeInfo
function TkwDec.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwDec.GetAllParamsCount
function TkwDec.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwDec.ParamsTypes
procedure TkwDec.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Integer;
begin
try
l_aValue := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Dec(aCtx, l_aValue));
end;//TkwDec.DoDoIt
function TkwAdd.Add(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): TtfwStackValue;
{* Реализация слова скрипта + }
//#UC START# *551597B8004D_551597B8004D_Word_var*
//#UC END# *551597B8004D_551597B8004D_Word_var*
begin
//#UC START# *551597B8004D_551597B8004D_Word_impl*
Case aA.rType of
tfw_vtInt:
Result := TtfwStackValue_C(aA.AsInt + aB.AsInt);
tfw_vtStr:
Result := TtfwStackValue_C(TtfwCStringFactory.Cat(aA.AsString, aB.AsString));
else
begin
Result := TtfwStackValue_E;
BadValueType(aA.rType, aCtx);
end;//else
end;//Case aA.rType
//#UC END# *551597B8004D_551597B8004D_Word_impl*
end;//TkwAdd.Add
class function TkwAdd.GetWordNameForRegister: AnsiString;
begin
Result := '+';
end;//TkwAdd.GetWordNameForRegister
function TkwAdd.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiStruct;
end;//TkwAdd.GetResultTypeInfo
function TkwAdd.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwAdd.GetAllParamsCount
function TkwAdd.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwAdd.ParamsTypes
procedure TkwAdd.DoDoIt(const aCtx: TtfwContext);
var l_aB: TtfwStackValue;
var l_aA: TtfwStackValue;
begin
try
l_aB := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.Push(Add(aCtx, l_aB, l_aA));
end;//TkwAdd.DoDoIt
function TkwSub.Sub(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта - }
//#UC START# *551597E800AA_551597E800AA_Word_var*
//#UC END# *551597E800AA_551597E800AA_Word_var*
begin
//#UC START# *551597E800AA_551597E800AA_Word_impl*
Result := aA - aB;
//#UC END# *551597E800AA_551597E800AA_Word_impl*
end;//TkwSub.Sub
class function TkwSub.GetWordNameForRegister: AnsiString;
begin
Result := '-';
end;//TkwSub.GetWordNameForRegister
function TkwSub.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwSub.GetResultTypeInfo
function TkwSub.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwSub.GetAllParamsCount
function TkwSub.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwSub.ParamsTypes
procedure TkwSub.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Sub(aCtx, l_aB, l_aA));
end;//TkwSub.DoDoIt
function TkwDivision.Division(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта DIV }
//#UC START# *551598030154_551598030154_Word_var*
//#UC END# *551598030154_551598030154_Word_var*
begin
//#UC START# *551598030154_551598030154_Word_impl*
Result := aA div aB;
//#UC END# *551598030154_551598030154_Word_impl*
end;//TkwDivision.Division
class function TkwDivision.GetWordNameForRegister: AnsiString;
begin
Result := 'DIV';
end;//TkwDivision.GetWordNameForRegister
function TkwDivision.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwDivision.GetResultTypeInfo
function TkwDivision.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwDivision.GetAllParamsCount
function TkwDivision.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwDivision.ParamsTypes
procedure TkwDivision.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Division(aCtx, l_aB, l_aA));
end;//TkwDivision.DoDoIt
function TkwMul.Mul(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта * }
//#UC START# *5515981700DC_5515981700DC_Word_var*
//#UC END# *5515981700DC_5515981700DC_Word_var*
begin
//#UC START# *5515981700DC_5515981700DC_Word_impl*
Result := aA * aB;
//#UC END# *5515981700DC_5515981700DC_Word_impl*
end;//TkwMul.Mul
class function TkwMul.GetWordNameForRegister: AnsiString;
begin
Result := '*';
end;//TkwMul.GetWordNameForRegister
function TkwMul.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwMul.GetResultTypeInfo
function TkwMul.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwMul.GetAllParamsCount
function TkwMul.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwMul.ParamsTypes
procedure TkwMul.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Mul(aCtx, l_aB, l_aA));
end;//TkwMul.DoDoIt
function TkwDivide.Divide(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта / }
//#UC START# *551598250365_551598250365_Word_var*
//#UC END# *551598250365_551598250365_Word_var*
begin
//#UC START# *551598250365_551598250365_Word_impl*
Result := aA div aB;
//#UC END# *551598250365_551598250365_Word_impl*
end;//TkwDivide.Divide
class function TkwDivide.GetWordNameForRegister: AnsiString;
begin
Result := '/';
end;//TkwDivide.GetWordNameForRegister
function TkwDivide.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwDivide.GetResultTypeInfo
function TkwDivide.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwDivide.GetAllParamsCount
function TkwDivide.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwDivide.ParamsTypes
procedure TkwDivide.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Divide(aCtx, l_aB, l_aA));
end;//TkwDivide.DoDoIt
function TkwMul2.Mul2(const aCtx: TtfwContext;
aA: Integer): Integer;
{* Реализация слова скрипта 2* }
//#UC START# *5515984C0341_5515984C0341_Word_var*
//#UC END# *5515984C0341_5515984C0341_Word_var*
begin
//#UC START# *5515984C0341_5515984C0341_Word_impl*
Result := aA shl 1;
//#UC END# *5515984C0341_5515984C0341_Word_impl*
end;//TkwMul2.Mul2
class function TkwMul2.GetWordNameForRegister: AnsiString;
begin
Result := '2*';
end;//TkwMul2.GetWordNameForRegister
function TkwMul2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwMul2.GetResultTypeInfo
function TkwMul2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwMul2.GetAllParamsCount
function TkwMul2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwMul2.ParamsTypes
procedure TkwMul2.DoDoIt(const aCtx: TtfwContext);
var l_aA: Integer;
begin
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Mul2(aCtx, l_aA));
end;//TkwMul2.DoDoIt
function TkwDiv2.Div2(const aCtx: TtfwContext;
aA: Integer): Integer;
{* Реализация слова скрипта 2/ }
//#UC START# *5515987201EB_5515987201EB_Word_var*
//#UC END# *5515987201EB_5515987201EB_Word_var*
begin
//#UC START# *5515987201EB_5515987201EB_Word_impl*
Result := aA shr 1;
//#UC END# *5515987201EB_5515987201EB_Word_impl*
end;//TkwDiv2.Div2
class function TkwDiv2.GetWordNameForRegister: AnsiString;
begin
Result := '2/';
end;//TkwDiv2.GetWordNameForRegister
function TkwDiv2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwDiv2.GetResultTypeInfo
function TkwDiv2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwDiv2.GetAllParamsCount
function TkwDiv2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwDiv2.ParamsTypes
procedure TkwDiv2.DoDoIt(const aCtx: TtfwContext);
var l_aA: Integer;
begin
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Div2(aCtx, l_aA));
end;//TkwDiv2.DoDoIt
function TkwMulDiv.MulDiv(const aCtx: TtfwContext;
aC: Integer;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта */ }
//#UC START# *551598B003B0_551598B003B0_Word_var*
//#UC END# *551598B003B0_551598B003B0_Word_var*
begin
//#UC START# *551598B003B0_551598B003B0_Word_impl*
Result := l3MulDiv(aA, aB, aC);
//#UC END# *551598B003B0_551598B003B0_Word_impl*
end;//TkwMulDiv.MulDiv
class function TkwMulDiv.GetWordNameForRegister: AnsiString;
begin
Result := '*/';
end;//TkwMulDiv.GetWordNameForRegister
function TkwMulDiv.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwMulDiv.GetResultTypeInfo
function TkwMulDiv.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 3;
end;//TkwMulDiv.GetAllParamsCount
function TkwMulDiv.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwMulDiv.ParamsTypes
procedure TkwMulDiv.DoDoIt(const aCtx: TtfwContext);
var l_aC: Integer;
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aC := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aC: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(MulDiv(aCtx, l_aC, l_aB, l_aA));
end;//TkwMulDiv.DoDoIt
function TkwBoolNot.BoolNot(const aCtx: TtfwContext;
aA: Boolean): Boolean;
{* Реализация слова скрипта ! }
//#UC START# *5515993901E9_5515993901E9_Word_var*
//#UC END# *5515993901E9_5515993901E9_Word_var*
begin
//#UC START# *5515993901E9_5515993901E9_Word_impl*
Result := not aA;
//#UC END# *5515993901E9_5515993901E9_Word_impl*
end;//TkwBoolNot.BoolNot
class function TkwBoolNot.GetWordNameForRegister: AnsiString;
begin
Result := '!';
end;//TkwBoolNot.GetWordNameForRegister
function TkwBoolNot.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwBoolNot.GetResultTypeInfo
function TkwBoolNot.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwBoolNot.GetAllParamsCount
function TkwBoolNot.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Boolean)]);
end;//TkwBoolNot.ParamsTypes
procedure TkwBoolNot.DoDoIt(const aCtx: TtfwContext);
var l_aA: Boolean;
begin
try
l_aA := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(BoolNot(aCtx, l_aA));
end;//TkwBoolNot.DoDoIt
function TkwModFromDiv.ModFromDiv(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта MOD }
//#UC START# *551599950364_551599950364_Word_var*
//#UC END# *551599950364_551599950364_Word_var*
begin
//#UC START# *551599950364_551599950364_Word_impl*
Result := aA mod aB;
//#UC END# *551599950364_551599950364_Word_impl*
end;//TkwModFromDiv.ModFromDiv
class function TkwModFromDiv.GetWordNameForRegister: AnsiString;
begin
Result := 'MOD';
end;//TkwModFromDiv.GetWordNameForRegister
function TkwModFromDiv.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwModFromDiv.GetResultTypeInfo
function TkwModFromDiv.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwModFromDiv.GetAllParamsCount
function TkwModFromDiv.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwModFromDiv.ParamsTypes
procedure TkwModFromDiv.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(ModFromDiv(aCtx, l_aB, l_aA));
end;//TkwModFromDiv.DoDoIt
function TkwBoolAnd.BoolAnd(const aCtx: TtfwContext;
aB: Boolean;
aA: Boolean): Boolean;
{* Реализация слова скрипта && }
//#UC START# *551599DF020D_551599DF020D_Word_var*
//#UC END# *551599DF020D_551599DF020D_Word_var*
begin
//#UC START# *551599DF020D_551599DF020D_Word_impl*
Result := aA AND aB;
//#UC END# *551599DF020D_551599DF020D_Word_impl*
end;//TkwBoolAnd.BoolAnd
class function TkwBoolAnd.GetWordNameForRegister: AnsiString;
begin
Result := '&&';
end;//TkwBoolAnd.GetWordNameForRegister
function TkwBoolAnd.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwBoolAnd.GetResultTypeInfo
function TkwBoolAnd.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwBoolAnd.GetAllParamsCount
function TkwBoolAnd.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Boolean), TypeInfo(Boolean)]);
end;//TkwBoolAnd.ParamsTypes
procedure TkwBoolAnd.DoDoIt(const aCtx: TtfwContext);
var l_aB: Boolean;
var l_aA: Boolean;
begin
try
l_aB := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(BoolAnd(aCtx, l_aB, l_aA));
end;//TkwBoolAnd.DoDoIt
function TkwBoolOr.BoolOr(const aCtx: TtfwContext;
aB: Boolean;
aA: Boolean): Boolean;
{* Реализация слова скрипта || }
//#UC START# *55159A05030F_55159A05030F_Word_var*
//#UC END# *55159A05030F_55159A05030F_Word_var*
begin
//#UC START# *55159A05030F_55159A05030F_Word_impl*
Result := aA OR aB;
//#UC END# *55159A05030F_55159A05030F_Word_impl*
end;//TkwBoolOr.BoolOr
class function TkwBoolOr.GetWordNameForRegister: AnsiString;
begin
Result := '||';
end;//TkwBoolOr.GetWordNameForRegister
function TkwBoolOr.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwBoolOr.GetResultTypeInfo
function TkwBoolOr.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwBoolOr.GetAllParamsCount
function TkwBoolOr.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Boolean), TypeInfo(Boolean)]);
end;//TkwBoolOr.ParamsTypes
procedure TkwBoolOr.DoDoIt(const aCtx: TtfwContext);
var l_aB: Boolean;
var l_aA: Boolean;
begin
try
l_aB := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(BoolOr(aCtx, l_aB, l_aA));
end;//TkwBoolOr.DoDoIt
function TkwNotZero.NotZero(const aCtx: TtfwContext;
aA: Integer): Boolean;
{* Реализация слова скрипта !=0 }
//#UC START# *55159A2E020E_55159A2E020E_Word_var*
//#UC END# *55159A2E020E_55159A2E020E_Word_var*
begin
//#UC START# *55159A2E020E_55159A2E020E_Word_impl*
Result := (aA <> 0);
//#UC END# *55159A2E020E_55159A2E020E_Word_impl*
end;//TkwNotZero.NotZero
class function TkwNotZero.GetWordNameForRegister: AnsiString;
begin
Result := '!=0';
end;//TkwNotZero.GetWordNameForRegister
function TkwNotZero.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwNotZero.GetResultTypeInfo
function TkwNotZero.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwNotZero.GetAllParamsCount
function TkwNotZero.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwNotZero.ParamsTypes
procedure TkwNotZero.DoDoIt(const aCtx: TtfwContext);
var l_aA: Integer;
begin
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(NotZero(aCtx, l_aA));
end;//TkwNotZero.DoDoIt
function TkwEqualZero.EqualZero(const aCtx: TtfwContext;
aA: Integer): Boolean;
{* Реализация слова скрипта =0 }
//#UC START# *55159A4F0009_55159A4F0009_Word_var*
//#UC END# *55159A4F0009_55159A4F0009_Word_var*
begin
//#UC START# *55159A4F0009_55159A4F0009_Word_impl*
Result := (aA = 0);
//#UC END# *55159A4F0009_55159A4F0009_Word_impl*
end;//TkwEqualZero.EqualZero
class function TkwEqualZero.GetWordNameForRegister: AnsiString;
begin
Result := '=0';
end;//TkwEqualZero.GetWordNameForRegister
function TkwEqualZero.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwEqualZero.GetResultTypeInfo
function TkwEqualZero.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEqualZero.GetAllParamsCount
function TkwEqualZero.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwEqualZero.ParamsTypes
procedure TkwEqualZero.DoDoIt(const aCtx: TtfwContext);
var l_aA: Integer;
begin
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(EqualZero(aCtx, l_aA));
end;//TkwEqualZero.DoDoIt
class function TkwSWAP.GetWordNameForRegister: AnsiString;
begin
Result := 'SWAP';
end;//TkwSWAP.GetWordNameForRegister
function TkwSWAP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwSWAP.GetResultTypeInfo
function TkwSWAP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwSWAP.GetAllParamsCount
function TkwSWAP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwSWAP.ParamsTypes
procedure TkwSWAP.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159A960126_Word_var*
//#UC END# *4DAEEDE10285_55159A960126_Word_var*
begin
//#UC START# *4DAEEDE10285_55159A960126_Word_impl*
aCtx.rEngine.SWAP;
//#UC END# *4DAEEDE10285_55159A960126_Word_impl*
end;//TkwSWAP.DoDoIt
class function TkwDROP.GetWordNameForRegister: AnsiString;
begin
Result := 'DROP';
end;//TkwDROP.GetWordNameForRegister
function TkwDROP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDROP.GetResultTypeInfo
function TkwDROP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwDROP.GetAllParamsCount
function TkwDROP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwDROP.ParamsTypes
procedure TkwDROP.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159AAF0133_Word_var*
//#UC END# *4DAEEDE10285_55159AAF0133_Word_var*
begin
//#UC START# *4DAEEDE10285_55159AAF0133_Word_impl*
aCtx.rEngine.DROP;
//#UC END# *4DAEEDE10285_55159AAF0133_Word_impl*
end;//TkwDROP.DoDoIt
class function TkwDUP.GetWordNameForRegister: AnsiString;
begin
Result := 'DUP';
end;//TkwDUP.GetWordNameForRegister
function TkwDUP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDUP.GetResultTypeInfo
function TkwDUP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwDUP.GetAllParamsCount
function TkwDUP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwDUP.ParamsTypes
procedure TkwDUP.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159ACB036B_Word_var*
//#UC END# *4DAEEDE10285_55159ACB036B_Word_var*
begin
//#UC START# *4DAEEDE10285_55159ACB036B_Word_impl*
aCtx.rEngine.Dup;
//#UC END# *4DAEEDE10285_55159ACB036B_Word_impl*
end;//TkwDUP.DoDoIt
class function TkwDUPIfNotZero.GetWordNameForRegister: AnsiString;
begin
Result := '?DUP';
end;//TkwDUPIfNotZero.GetWordNameForRegister
function TkwDUPIfNotZero.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDUPIfNotZero.GetResultTypeInfo
function TkwDUPIfNotZero.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwDUPIfNotZero.GetAllParamsCount
function TkwDUPIfNotZero.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwDUPIfNotZero.ParamsTypes
procedure TkwDUPIfNotZero.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159AE500C8_Word_var*
//#UC END# *4DAEEDE10285_55159AE500C8_Word_var*
begin
//#UC START# *4DAEEDE10285_55159AE500C8_Word_impl*
aCtx.rEngine.DupIfNotZero;
//#UC END# *4DAEEDE10285_55159AE500C8_Word_impl*
end;//TkwDUPIfNotZero.DoDoIt
class function TkwROT.GetWordNameForRegister: AnsiString;
begin
Result := 'ROT';
end;//TkwROT.GetWordNameForRegister
function TkwROT.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwROT.GetResultTypeInfo
function TkwROT.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwROT.GetAllParamsCount
function TkwROT.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwROT.ParamsTypes
procedure TkwROT.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159B2B0192_Word_var*
//#UC END# *4DAEEDE10285_55159B2B0192_Word_var*
begin
//#UC START# *4DAEEDE10285_55159B2B0192_Word_impl*
aCtx.rEngine.ROT;
//#UC END# *4DAEEDE10285_55159B2B0192_Word_impl*
end;//TkwROT.DoDoIt
class function TkwPICK.GetWordNameForRegister: AnsiString;
begin
Result := 'PICK';
end;//TkwPICK.GetWordNameForRegister
function TkwPICK.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPICK.GetResultTypeInfo
function TkwPICK.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwPICK.GetAllParamsCount
function TkwPICK.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwPICK.ParamsTypes
procedure TkwPICK.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159B710263_Word_var*
//#UC END# *4DAEEDE10285_55159B710263_Word_var*
begin
//#UC START# *4DAEEDE10285_55159B710263_Word_impl*
aCtx.rEngine.PICK;
//#UC END# *4DAEEDE10285_55159B710263_Word_impl*
end;//TkwPICK.DoDoIt
class function TkwInvertROT.GetWordNameForRegister: AnsiString;
begin
Result := '-ROT';
end;//TkwInvertROT.GetWordNameForRegister
function TkwInvertROT.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwInvertROT.GetResultTypeInfo
function TkwInvertROT.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwInvertROT.GetAllParamsCount
function TkwInvertROT.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwInvertROT.ParamsTypes
procedure TkwInvertROT.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_55159BC002DA_Word_var*
//#UC END# *4DAEEDE10285_55159BC002DA_Word_var*
begin
//#UC START# *4DAEEDE10285_55159BC002DA_Word_impl*
aCtx.rEngine.InvertROT;
//#UC END# *4DAEEDE10285_55159BC002DA_Word_impl*
end;//TkwInvertROT.DoDoIt
class function TkwSWAP2.GetWordNameForRegister: AnsiString;
begin
Result := '2SWAP';
end;//TkwSWAP2.GetWordNameForRegister
function TkwSWAP2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwSWAP2.GetResultTypeInfo
function TkwSWAP2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwSWAP2.GetAllParamsCount
function TkwSWAP2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwSWAP2.ParamsTypes
procedure TkwSWAP2.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5519343300DE_Word_var*
//#UC END# *4DAEEDE10285_5519343300DE_Word_var*
begin
//#UC START# *4DAEEDE10285_5519343300DE_Word_impl*
aCtx.rEngine.Swap2;
//#UC END# *4DAEEDE10285_5519343300DE_Word_impl*
end;//TkwSWAP2.DoDoIt
class function TkwOVER2.GetWordNameForRegister: AnsiString;
begin
Result := '2OVER';
end;//TkwOVER2.GetWordNameForRegister
function TkwOVER2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwOVER2.GetResultTypeInfo
function TkwOVER2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwOVER2.GetAllParamsCount
function TkwOVER2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwOVER2.ParamsTypes
procedure TkwOVER2.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5519345301D5_Word_var*
//#UC END# *4DAEEDE10285_5519345301D5_Word_var*
begin
//#UC START# *4DAEEDE10285_5519345301D5_Word_impl*
aCtx.rEngine.Over2;
//#UC END# *4DAEEDE10285_5519345301D5_Word_impl*
end;//TkwOVER2.DoDoIt
class function TkwDUP2.GetWordNameForRegister: AnsiString;
begin
Result := '2DUP';
end;//TkwDUP2.GetWordNameForRegister
function TkwDUP2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDUP2.GetResultTypeInfo
function TkwDUP2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwDUP2.GetAllParamsCount
function TkwDUP2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwDUP2.ParamsTypes
procedure TkwDUP2.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_551934800380_Word_var*
//#UC END# *4DAEEDE10285_551934800380_Word_var*
begin
//#UC START# *4DAEEDE10285_551934800380_Word_impl*
aCtx.rEngine.Dup2;
//#UC END# *4DAEEDE10285_551934800380_Word_impl*
end;//TkwDUP2.DoDoIt
class function TkwDROP2.GetWordNameForRegister: AnsiString;
begin
Result := '2DROP';
end;//TkwDROP2.GetWordNameForRegister
function TkwDROP2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDROP2.GetResultTypeInfo
function TkwDROP2.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwDROP2.GetAllParamsCount
function TkwDROP2.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwDROP2.ParamsTypes
procedure TkwDROP2.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_551934A50225_Word_var*
//#UC END# *4DAEEDE10285_551934A50225_Word_var*
begin
//#UC START# *4DAEEDE10285_551934A50225_Word_impl*
aCtx.rEngine.Drop2;
//#UC END# *4DAEEDE10285_551934A50225_Word_impl*
end;//TkwDROP2.DoDoIt
class function TkwNIP.GetWordNameForRegister: AnsiString;
begin
Result := 'NIP';
end;//TkwNIP.GetWordNameForRegister
function TkwNIP.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwNIP.GetResultTypeInfo
function TkwNIP.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwNIP.GetAllParamsCount
function TkwNIP.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwNIP.ParamsTypes
procedure TkwNIP.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_551934CA02D6_Word_var*
//#UC END# *4DAEEDE10285_551934CA02D6_Word_var*
begin
//#UC START# *4DAEEDE10285_551934CA02D6_Word_impl*
aCtx.rEngine.NIP;
//#UC END# *4DAEEDE10285_551934CA02D6_Word_impl*
end;//TkwNIP.DoDoIt
class function TkwTUCK.GetWordNameForRegister: AnsiString;
begin
Result := 'TUCK';
end;//TkwTUCK.GetWordNameForRegister
function TkwTUCK.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwTUCK.GetResultTypeInfo
function TkwTUCK.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwTUCK.GetAllParamsCount
function TkwTUCK.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwTUCK.ParamsTypes
procedure TkwTUCK.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_551934E700E6_Word_var*
//#UC END# *4DAEEDE10285_551934E700E6_Word_var*
begin
//#UC START# *4DAEEDE10285_551934E700E6_Word_impl*
aCtx.rEngine.TUCK;
//#UC END# *4DAEEDE10285_551934E700E6_Word_impl*
end;//TkwTUCK.DoDoIt
class function TkwOVER.GetWordNameForRegister: AnsiString;
begin
Result := 'OVER';
end;//TkwOVER.GetWordNameForRegister
function TkwOVER.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwOVER.GetResultTypeInfo
function TkwOVER.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwOVER.GetAllParamsCount
function TkwOVER.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwOVER.ParamsTypes
procedure TkwOVER.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_551935010364_Word_var*
//#UC END# *4DAEEDE10285_551935010364_Word_var*
begin
//#UC START# *4DAEEDE10285_551935010364_Word_impl*
aCtx.rEngine.OVER;
//#UC END# *4DAEEDE10285_551935010364_Word_impl*
end;//TkwOVER.DoDoIt
class function TkwROLL.GetWordNameForRegister: AnsiString;
begin
Result := 'ROLL';
end;//TkwROLL.GetWordNameForRegister
function TkwROLL.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwROLL.GetResultTypeInfo
function TkwROLL.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwROLL.GetAllParamsCount
function TkwROLL.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwROLL.ParamsTypes
procedure TkwROLL.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5519351F01E3_Word_var*
//#UC END# *4DAEEDE10285_5519351F01E3_Word_var*
begin
//#UC START# *4DAEEDE10285_5519351F01E3_Word_impl*
aCtx.rEngine.ROLL;
//#UC END# *4DAEEDE10285_5519351F01E3_Word_impl*
end;//TkwROLL.DoDoIt
function TkwNotEquals.NotEquals(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта != }
//#UC START# *5519355003E4_5519355003E4_Word_var*
//#UC END# *5519355003E4_5519355003E4_Word_var*
begin
//#UC START# *5519355003E4_5519355003E4_Word_impl*
Case aA.rType of
tfw_vtInt:
Result := aA.AsInt <> aB.AsInt;
tfw_vtBool:
Result := aA.AsBoolean <> aB.AsBoolean;
tfw_vtStr:
Result := not l3Same(aA.AsString, aB.AsString);
tfw_vtObj:
Result := aA.AsObject <> aB.AsObject;
tfw_vtIntf:
Result := aA.AsIntf <> aB.AsIntf;
else
begin
Result := false;
BadValueType(aA.rType, aCtx);
end;//else
end;//Case aA.rType
//#UC END# *5519355003E4_5519355003E4_Word_impl*
end;//TkwNotEquals.NotEquals
class function TkwNotEquals.GetWordNameForRegister: AnsiString;
begin
Result := '!=';
end;//TkwNotEquals.GetWordNameForRegister
function TkwNotEquals.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwNotEquals.GetResultTypeInfo
function TkwNotEquals.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwNotEquals.GetAllParamsCount
function TkwNotEquals.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwNotEquals.ParamsTypes
procedure TkwNotEquals.DoDoIt(const aCtx: TtfwContext);
var l_aB: TtfwStackValue;
var l_aA: TtfwStackValue;
begin
try
l_aB := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(NotEquals(aCtx, l_aB, l_aA));
end;//TkwNotEquals.DoDoIt
function TkwGREATER.GREATER(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта GREATER }
//#UC START# *55193584030D_55193584030D_Word_var*
//#UC END# *55193584030D_55193584030D_Word_var*
begin
//#UC START# *55193584030D_55193584030D_Word_impl*
Case aA.rType of
tfw_vtInt:
Result := aA.AsInt > aB.AsInt;
tfw_vtBool:
Result := aA.AsBoolean > aB.AsBoolean;
tfw_vtStr:
Result := l3Compare(l3PCharLen(aA.AsString), l3PCharLen(aB.AsString)) > 0;
else
begin
Result := false;
BadValueType(aA.rType, aCtx);
end;//else
end;//Case aA.rType
//#UC END# *55193584030D_55193584030D_Word_impl*
end;//TkwGREATER.GREATER
class function TkwGREATER.GetWordNameForRegister: AnsiString;
begin
Result := 'GREATER';
end;//TkwGREATER.GetWordNameForRegister
function TkwGREATER.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwGREATER.GetResultTypeInfo
function TkwGREATER.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwGREATER.GetAllParamsCount
function TkwGREATER.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwGREATER.ParamsTypes
procedure TkwGREATER.DoDoIt(const aCtx: TtfwContext);
var l_aB: TtfwStackValue;
var l_aA: TtfwStackValue;
begin
try
l_aB := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(GREATER(aCtx, l_aB, l_aA));
end;//TkwGREATER.DoDoIt
function TkwLESS.LESS(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта LESS }
//#UC START# *5519359B0317_5519359B0317_Word_var*
//#UC END# *5519359B0317_5519359B0317_Word_var*
begin
//#UC START# *5519359B0317_5519359B0317_Word_impl*
Case aA.rType of
tfw_vtInt:
Result := aA.AsInt < aB.AsInt;
tfw_vtBool:
Result := aA.AsBoolean < aB.AsBoolean;
tfw_vtStr:
Result := l3Compare(l3PCharLen(aA.AsString), l3PCharLen(aB.AsString)) < 0;
else
begin
Result := false;
BadValueType(aA.rType, aCtx);
end;//else
end;//Case aA.rType
//#UC END# *5519359B0317_5519359B0317_Word_impl*
end;//TkwLESS.LESS
class function TkwLESS.GetWordNameForRegister: AnsiString;
begin
Result := 'LESS';
end;//TkwLESS.GetWordNameForRegister
function TkwLESS.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwLESS.GetResultTypeInfo
function TkwLESS.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwLESS.GetAllParamsCount
function TkwLESS.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwLESS.ParamsTypes
procedure TkwLESS.DoDoIt(const aCtx: TtfwContext);
var l_aB: TtfwStackValue;
var l_aA: TtfwStackValue;
begin
try
l_aB := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(LESS(aCtx, l_aB, l_aA));
end;//TkwLESS.DoDoIt
function TkwEquals.Equals(const aCtx: TtfwContext;
const aB: TtfwStackValue;
const aA: TtfwStackValue): Boolean;
{* Реализация слова скрипта == }
//#UC START# *551935B4011D_551935B4011D_Word_var*
//#UC END# *551935B4011D_551935B4011D_Word_var*
begin
//#UC START# *551935B4011D_551935B4011D_Word_impl*
Case aA.rType of
tfw_vtInt:
Result := aA.AsInt = aB.AsInt;
tfw_vtBool:
Result := aA.AsBoolean = aB.AsBoolean;
tfw_vtStr:
Result := l3Same(aA.AsString, aB.AsString);
tfw_vtObj:
Result := aA.AsObject = aB.AsObject;
tfw_vtIntf:
Result := aA.AsIntf = aB.AsIntf;
else
begin
Result := false;
BadValueType(aA.rType, aCtx);
end;//else
end;//Case aA.rType
//#UC END# *551935B4011D_551935B4011D_Word_impl*
end;//TkwEquals.Equals
class function TkwEquals.GetWordNameForRegister: AnsiString;
begin
Result := '==';
end;//TkwEquals.GetWordNameForRegister
function TkwEquals.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwEquals.GetResultTypeInfo
function TkwEquals.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwEquals.GetAllParamsCount
function TkwEquals.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct, @tfw_tiStruct]);
end;//TkwEquals.ParamsTypes
procedure TkwEquals.DoDoIt(const aCtx: TtfwContext);
var l_aB: TtfwStackValue;
var l_aA: TtfwStackValue;
begin
try
l_aB := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(Equals(aCtx, l_aB, l_aA));
end;//TkwEquals.DoDoIt
function TkwLessThanZero.LessThanZero(const aCtx: TtfwContext;
aB: Integer): Boolean;
{* Реализация слова скрипта <0 }
//#UC START# *551935D00032_551935D00032_Word_var*
//#UC END# *551935D00032_551935D00032_Word_var*
begin
//#UC START# *551935D00032_551935D00032_Word_impl*
Result := (aB < 0);
//#UC END# *551935D00032_551935D00032_Word_impl*
end;//TkwLessThanZero.LessThanZero
class function TkwLessThanZero.GetWordNameForRegister: AnsiString;
begin
Result := '<0';
end;//TkwLessThanZero.GetWordNameForRegister
function TkwLessThanZero.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwLessThanZero.GetResultTypeInfo
function TkwLessThanZero.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwLessThanZero.GetAllParamsCount
function TkwLessThanZero.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwLessThanZero.ParamsTypes
procedure TkwLessThanZero.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(LessThanZero(aCtx, l_aB));
end;//TkwLessThanZero.DoDoIt
function TkwGreaterThanZero.GreaterThanZero(const aCtx: TtfwContext;
aB: Integer): Boolean;
{* Реализация слова скрипта >0 }
//#UC START# *551935F7037F_551935F7037F_Word_var*
//#UC END# *551935F7037F_551935F7037F_Word_var*
begin
//#UC START# *551935F7037F_551935F7037F_Word_impl*
Result := (aB > 0);
//#UC END# *551935F7037F_551935F7037F_Word_impl*
end;//TkwGreaterThanZero.GreaterThanZero
class function TkwGreaterThanZero.GetWordNameForRegister: AnsiString;
begin
Result := '>0';
end;//TkwGreaterThanZero.GetWordNameForRegister
function TkwGreaterThanZero.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwGreaterThanZero.GetResultTypeInfo
function TkwGreaterThanZero.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwGreaterThanZero.GetAllParamsCount
function TkwGreaterThanZero.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwGreaterThanZero.ParamsTypes
procedure TkwGreaterThanZero.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(GreaterThanZero(aCtx, l_aB));
end;//TkwGreaterThanZero.DoDoIt
function TkwBitAnd.BitAnd(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта & }
//#UC START# *5519361F0234_5519361F0234_Word_var*
//#UC END# *5519361F0234_5519361F0234_Word_var*
begin
//#UC START# *5519361F0234_5519361F0234_Word_impl*
Result := aA AND aB;
//#UC END# *5519361F0234_5519361F0234_Word_impl*
end;//TkwBitAnd.BitAnd
class function TkwBitAnd.GetWordNameForRegister: AnsiString;
begin
Result := '&';
end;//TkwBitAnd.GetWordNameForRegister
function TkwBitAnd.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwBitAnd.GetResultTypeInfo
function TkwBitAnd.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwBitAnd.GetAllParamsCount
function TkwBitAnd.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwBitAnd.ParamsTypes
procedure TkwBitAnd.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(BitAnd(aCtx, l_aB, l_aA));
end;//TkwBitAnd.DoDoIt
function TkwBitOR.BitOR(const aCtx: TtfwContext;
aB: Integer;
aA: Integer): Integer;
{* Реализация слова скрипта | }
//#UC START# *55193639024F_55193639024F_Word_var*
//#UC END# *55193639024F_55193639024F_Word_var*
begin
//#UC START# *55193639024F_55193639024F_Word_impl*
Result := aA OR aB;
//#UC END# *55193639024F_55193639024F_Word_impl*
end;//TkwBitOR.BitOR
class function TkwBitOR.GetWordNameForRegister: AnsiString;
begin
Result := '|';
end;//TkwBitOR.GetWordNameForRegister
function TkwBitOR.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwBitOR.GetResultTypeInfo
function TkwBitOR.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwBitOR.GetAllParamsCount
function TkwBitOR.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer), TypeInfo(Integer)]);
end;//TkwBitOR.ParamsTypes
procedure TkwBitOR.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
var l_aA: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aA := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aA: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(BitOR(aCtx, l_aB, l_aA));
end;//TkwBitOR.DoDoIt
function TkwBitNot.BitNot(const aCtx: TtfwContext;
aB: Integer): Integer;
{* Реализация слова скрипта ~ }
//#UC START# *55193651025A_55193651025A_Word_var*
//#UC END# *55193651025A_55193651025A_Word_var*
begin
//#UC START# *55193651025A_55193651025A_Word_impl*
Result := not aB;
//#UC END# *55193651025A_55193651025A_Word_impl*
end;//TkwBitNot.BitNot
class function TkwBitNot.GetWordNameForRegister: AnsiString;
begin
Result := '~';
end;//TkwBitNot.GetWordNameForRegister
function TkwBitNot.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwBitNot.GetResultTypeInfo
function TkwBitNot.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwBitNot.GetAllParamsCount
function TkwBitNot.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwBitNot.ParamsTypes
procedure TkwBitNot.DoDoIt(const aCtx: TtfwContext);
var l_aB: Integer;
begin
try
l_aB := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aB: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(BitNot(aCtx, l_aB));
end;//TkwBitNot.DoDoIt
function TkwStackLevel.StackLevel(const aCtx: TtfwContext): Integer;
{* Реализация слова скрипта StackLevel }
//#UC START# *55682EDB02B0_55682EDB02B0_Word_var*
//#UC END# *55682EDB02B0_55682EDB02B0_Word_var*
begin
//#UC START# *55682EDB02B0_55682EDB02B0_Word_impl*
Result := aCtx.rEngine.ValuesCount;
//#UC END# *55682EDB02B0_55682EDB02B0_Word_impl*
end;//TkwStackLevel.StackLevel
class function TkwStackLevel.GetWordNameForRegister: AnsiString;
begin
Result := 'StackLevel';
end;//TkwStackLevel.GetWordNameForRegister
function TkwStackLevel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwStackLevel.GetResultTypeInfo
function TkwStackLevel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwStackLevel.GetAllParamsCount
function TkwStackLevel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwStackLevel.ParamsTypes
procedure TkwStackLevel.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushInt(StackLevel(aCtx));
end;//TkwStackLevel.DoDoIt
procedure TkwReduceStackLevel.ReduceStackLevel(const aCtx: TtfwContext;
aValue: Integer);
{* Реализация слова скрипта ReduceStackLevel }
//#UC START# *55682EFC0160_55682EFC0160_Word_var*
//#UC END# *55682EFC0160_55682EFC0160_Word_var*
begin
//#UC START# *55682EFC0160_55682EFC0160_Word_impl*
while (aCtx.rEngine.ValuesCount > aValue) do
aCtx.rEngine.Drop;
//#UC END# *55682EFC0160_55682EFC0160_Word_impl*
end;//TkwReduceStackLevel.ReduceStackLevel
class function TkwReduceStackLevel.GetWordNameForRegister: AnsiString;
begin
Result := 'ReduceStackLevel';
end;//TkwReduceStackLevel.GetWordNameForRegister
function TkwReduceStackLevel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwReduceStackLevel.GetResultTypeInfo
function TkwReduceStackLevel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwReduceStackLevel.GetAllParamsCount
function TkwReduceStackLevel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwReduceStackLevel.ParamsTypes
procedure TkwReduceStackLevel.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Integer;
begin
try
l_aValue := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
ReduceStackLevel(aCtx, l_aValue);
end;//TkwReduceStackLevel.DoDoIt
procedure TkwCtxParserPushString.Ctx_Parser_PushString(const aCtx: TtfwContext;
const aValue: Il3CString);
{* Реализация слова скрипта Ctx:Parser:PushString }
//#UC START# *5576DF540107_5576DF540107_Word_var*
//#UC END# *5576DF540107_5576DF540107_Word_var*
begin
//#UC START# *5576DF540107_5576DF540107_Word_impl*
aCtx.rParser.PushString(aValue);
//#UC END# *5576DF540107_5576DF540107_Word_impl*
end;//TkwCtxParserPushString.Ctx_Parser_PushString
class function TkwCtxParserPushString.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:Parser:PushString';
end;//TkwCtxParserPushString.GetWordNameForRegister
function TkwCtxParserPushString.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCtxParserPushString.GetResultTypeInfo
function TkwCtxParserPushString.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCtxParserPushString.GetAllParamsCount
function TkwCtxParserPushString.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiString]);
end;//TkwCtxParserPushString.ParamsTypes
procedure TkwCtxParserPushString.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Il3CString;
begin
try
l_aValue := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
Ctx_Parser_PushString(aCtx, l_aValue);
end;//TkwCtxParserPushString.DoDoIt
procedure TkwCtxParserPushSymbol.Ctx_Parser_PushSymbol(const aCtx: TtfwContext;
const aValue: Il3CString);
{* Реализация слова скрипта Ctx:Parser:PushSymbol }
//#UC START# *5576DF7D015F_5576DF7D015F_Word_var*
//#UC END# *5576DF7D015F_5576DF7D015F_Word_var*
begin
//#UC START# *5576DF7D015F_5576DF7D015F_Word_impl*
aCtx.rParser.PushSymbol(aValue);
//#UC END# *5576DF7D015F_5576DF7D015F_Word_impl*
end;//TkwCtxParserPushSymbol.Ctx_Parser_PushSymbol
class function TkwCtxParserPushSymbol.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:Parser:PushSymbol';
end;//TkwCtxParserPushSymbol.GetWordNameForRegister
function TkwCtxParserPushSymbol.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCtxParserPushSymbol.GetResultTypeInfo
function TkwCtxParserPushSymbol.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCtxParserPushSymbol.GetAllParamsCount
function TkwCtxParserPushSymbol.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiString]);
end;//TkwCtxParserPushSymbol.ParamsTypes
procedure TkwCtxParserPushSymbol.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Il3CString;
begin
try
l_aValue := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
Ctx_Parser_PushSymbol(aCtx, l_aValue);
end;//TkwCtxParserPushSymbol.DoDoIt
procedure TkwCtxParserPushInt.Ctx_Parser_PushInt(const aCtx: TtfwContext;
aValue: Integer);
{* Реализация слова скрипта Ctx:Parser:PushInt }
//#UC START# *5576DFC10276_5576DFC10276_Word_var*
//#UC END# *5576DFC10276_5576DFC10276_Word_var*
begin
//#UC START# *5576DFC10276_5576DFC10276_Word_impl*
aCtx.rParser.PushInt(aValue);
//#UC END# *5576DFC10276_5576DFC10276_Word_impl*
end;//TkwCtxParserPushInt.Ctx_Parser_PushInt
class function TkwCtxParserPushInt.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:Parser:PushInt';
end;//TkwCtxParserPushInt.GetWordNameForRegister
function TkwCtxParserPushInt.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCtxParserPushInt.GetResultTypeInfo
function TkwCtxParserPushInt.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCtxParserPushInt.GetAllParamsCount
function TkwCtxParserPushInt.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwCtxParserPushInt.ParamsTypes
procedure TkwCtxParserPushInt.DoDoIt(const aCtx: TtfwContext);
var l_aValue: Integer;
begin
try
l_aValue := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
Ctx_Parser_PushInt(aCtx, l_aValue);
end;//TkwCtxParserPushInt.DoDoIt
function TkwCtxParser.Ctx_Parser(const aCtx: TtfwContext): ItfwParserEx;
{* Реализация слова скрипта Ctx:Parser }
//#UC START# *558951EE023C_558951EE023C_Word_var*
//#UC END# *558951EE023C_558951EE023C_Word_var*
begin
//#UC START# *558951EE023C_558951EE023C_Word_impl*
Result := aCtx.rParser;
//#UC END# *558951EE023C_558951EE023C_Word_impl*
end;//TkwCtxParser.Ctx_Parser
class function TkwCtxParser.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:Parser';
end;//TkwCtxParser.GetWordNameForRegister
function TkwCtxParser.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwParserEx);
end;//TkwCtxParser.GetResultTypeInfo
function TkwCtxParser.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxParser.GetAllParamsCount
function TkwCtxParser.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxParser.ParamsTypes
procedure TkwCtxParser.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushIntf(Ctx_Parser(aCtx), TypeInfo(ItfwParserEx));
end;//TkwCtxParser.DoDoIt
procedure TkwAtomicIf.AtomicIf(const aCtx: TtfwContext;
aWord: TtfwWord;
aCondition: Boolean);
{* Реализация слова скрипта ? }
//#UC START# *55962C7502AB_55962C7502AB_Word_var*
//#UC END# *55962C7502AB_55962C7502AB_Word_var*
begin
//#UC START# *55962C7502AB_55962C7502AB_Word_impl*
if aCondition then
aWord.DoIt(aCtx);
//#UC END# *55962C7502AB_55962C7502AB_Word_impl*
end;//TkwAtomicIf.AtomicIf
class function TkwAtomicIf.GetWordNameForRegister: AnsiString;
begin
Result := '?';
end;//TkwAtomicIf.GetWordNameForRegister
function TkwAtomicIf.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwAtomicIf.GetResultTypeInfo
function TkwAtomicIf.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwAtomicIf.GetAllParamsCount
function TkwAtomicIf.RightParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwAtomicIf.RightParamsCount
function TkwAtomicIf.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Boolean)]);
end;//TkwAtomicIf.ParamsTypes
procedure TkwAtomicIf.DoRun(const aCtx: TtfwContext);
var l_aWord: TtfwWord;
var l_aCondition: Boolean;
begin
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aCondition := aCtx.rEngine.PopBool;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCondition: Boolean : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
AtomicIf(aCtx, l_aWord, l_aCondition);
end;//TkwAtomicIf.DoRun
procedure TkwCompileValue.CompileValue(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileValue }
//#UC START# *55964548035E_55964548035E_Word_var*
var
l_W : TtfwWord;
//#UC END# *55964548035E_55964548035E_Word_var*
begin
//#UC START# *55964548035E_55964548035E_Word_impl*
if (aValue.rType = tfw_vtObj) AND (aValue.AsObject Is TtfwWord) then
l_W := TtfwWord(aValue.AsObject).Use
else
l_W := TkwValue.Create(aValue);
try
RunnerAssert(l_W <> nil, 'Нет слова для компиляции', aCtx);
aCtx.rCompiler.AddCodePart(l_W, aCtx, tfw_sniNo);
finally
FreeAndNil(l_W);
end;//try..finally
//#UC END# *55964548035E_55964548035E_Word_impl*
end;//TkwCompileValue.CompileValue
class function TkwCompileValue.GetWordNameForRegister: AnsiString;
begin
Result := 'CompileValue';
end;//TkwCompileValue.GetWordNameForRegister
function TkwCompileValue.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCompileValue.GetResultTypeInfo
function TkwCompileValue.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCompileValue.GetAllParamsCount
function TkwCompileValue.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct]);
end;//TkwCompileValue.ParamsTypes
procedure TkwCompileValue.DoDoIt(const aCtx: TtfwContext);
var l_aValue: TtfwStackValue;
begin
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CompileValue(aCtx, l_aValue);
end;//TkwCompileValue.DoDoIt
class function TkwIMMEDIATE.GetWordNameForRegister: AnsiString;
begin
Result := 'IMMEDIATE';
end;//TkwIMMEDIATE.GetWordNameForRegister
function TkwIMMEDIATE.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwIMMEDIATE.GetResultTypeInfo
function TkwIMMEDIATE.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwIMMEDIATE.GetAllParamsCount
function TkwIMMEDIATE.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwIMMEDIATE.ParamsTypes
procedure TkwIMMEDIATE.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_5596615501C1_Word_var*
//#UC END# *4DAEEDE10285_5596615501C1_Word_var*
begin
//#UC START# *4DAEEDE10285_5596615501C1_Word_impl*
aCtx.SetWordInfo(aCtx.rTypeInfo.IncludeModifier(tfw_wmImmediate));
//#UC END# *4DAEEDE10285_5596615501C1_Word_impl*
end;//TkwIMMEDIATE.DoDoIt
function TkwIMMEDIATE.IsImmediate(const aCtx: TtfwContext): Boolean;
begin
Result := True;
end;//TkwIMMEDIATE.IsImmediate
function TkwCtxScriptCaller.Ctx_ScriptCaller(const aCtx: TtfwContext): ItfwScriptCaller;
{* Реализация слова скрипта Ctx:ScriptCaller }
//#UC START# *559BCE8B03A4_559BCE8B03A4_Word_var*
//#UC END# *559BCE8B03A4_559BCE8B03A4_Word_var*
begin
//#UC START# *559BCE8B03A4_559BCE8B03A4_Word_impl*
Result := aCtx.rCaller;
//#UC END# *559BCE8B03A4_559BCE8B03A4_Word_impl*
end;//TkwCtxScriptCaller.Ctx_ScriptCaller
class function TkwCtxScriptCaller.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:ScriptCaller';
end;//TkwCtxScriptCaller.GetWordNameForRegister
function TkwCtxScriptCaller.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwScriptCaller);
end;//TkwCtxScriptCaller.GetResultTypeInfo
function TkwCtxScriptCaller.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxScriptCaller.GetAllParamsCount
function TkwCtxScriptCaller.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxScriptCaller.ParamsTypes
procedure TkwCtxScriptCaller.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushIntf(Ctx_ScriptCaller(aCtx), TypeInfo(ItfwScriptCaller));
end;//TkwCtxScriptCaller.DoDoIt
function TkwCtxEngine.Ctx_Engine(const aCtx: TtfwContext): ItfwScriptEngine;
{* Реализация слова скрипта Ctx:Engine }
//#UC START# *559BCEAE039E_559BCEAE039E_Word_var*
//#UC END# *559BCEAE039E_559BCEAE039E_Word_var*
begin
//#UC START# *559BCEAE039E_559BCEAE039E_Word_impl*
Result := aCtx.rEngine;
//#UC END# *559BCEAE039E_559BCEAE039E_Word_impl*
end;//TkwCtxEngine.Ctx_Engine
class function TkwCtxEngine.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:Engine';
end;//TkwCtxEngine.GetWordNameForRegister
function TkwCtxEngine.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwScriptEngine);
end;//TkwCtxEngine.GetResultTypeInfo
function TkwCtxEngine.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxEngine.GetAllParamsCount
function TkwCtxEngine.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxEngine.ParamsTypes
procedure TkwCtxEngine.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushIntf(Ctx_Engine(aCtx), TypeInfo(ItfwScriptEngine));
end;//TkwCtxEngine.DoDoIt
function TkwCtxStoredValuesStack.Ctx_StoredValuesStack(const aCtx: TtfwContext): ItfwStoredValuesStack;
{* Реализация слова скрипта Ctx:StoredValuesStack }
//#UC START# *559BD00001BA_559BD00001BA_Word_var*
//#UC END# *559BD00001BA_559BD00001BA_Word_var*
begin
//#UC START# *559BD00001BA_559BD00001BA_Word_impl*
Result := aCtx.rStoredValuesStack;
//#UC END# *559BD00001BA_559BD00001BA_Word_impl*
end;//TkwCtxStoredValuesStack.Ctx_StoredValuesStack
class function TkwCtxStoredValuesStack.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:StoredValuesStack';
end;//TkwCtxStoredValuesStack.GetWordNameForRegister
function TkwCtxStoredValuesStack.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwStoredValuesStack);
end;//TkwCtxStoredValuesStack.GetResultTypeInfo
function TkwCtxStoredValuesStack.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxStoredValuesStack.GetAllParamsCount
function TkwCtxStoredValuesStack.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxStoredValuesStack.ParamsTypes
procedure TkwCtxStoredValuesStack.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushIntf(Ctx_StoredValuesStack(aCtx), TypeInfo(ItfwStoredValuesStack));
end;//TkwCtxStoredValuesStack.DoDoIt
procedure TkwCreateAndRaise.CreateAndRaise(const aCtx: TtfwContext;
aClass: TClass;
const aMessage: AnsiString);
{* Реализация слова скрипта CreateAndRaise }
//#UC START# *559BFEBF0299_559BFEBF0299_Word_var*
type
RException = class of Exception;
//#UC END# *559BFEBF0299_559BFEBF0299_Word_var*
begin
//#UC START# *559BFEBF0299_559BFEBF0299_Word_impl*
if aClass.InheritsFrom(Exception) then
raise RException(aClass).Create(aMessage)
else
RunnerError('Передан не класс исключения, а ' + aClass.ClassName, aCtx);
//#UC END# *559BFEBF0299_559BFEBF0299_Word_impl*
end;//TkwCreateAndRaise.CreateAndRaise
class function TkwCreateAndRaise.GetWordNameForRegister: AnsiString;
begin
Result := 'CreateAndRaise';
end;//TkwCreateAndRaise.GetWordNameForRegister
function TkwCreateAndRaise.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCreateAndRaise.GetResultTypeInfo
function TkwCreateAndRaise.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwCreateAndRaise.GetAllParamsCount
function TkwCreateAndRaise.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiClassRef, @tfw_tiString]);
end;//TkwCreateAndRaise.ParamsTypes
procedure TkwCreateAndRaise.DoDoIt(const aCtx: TtfwContext);
var l_aClass: TClass;
var l_aMessage: AnsiString;
begin
try
l_aClass := TClass(aCtx.rEngine.PopClass);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aClass: TClass : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aMessage := aCtx.rEngine.PopDelphiString;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aMessage: AnsiString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CreateAndRaise(aCtx, l_aClass, l_aMessage);
end;//TkwCreateAndRaise.DoDoIt
procedure TkwCompileRef.CompileRef(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileRef }
//#UC START# *55A50F69026F_55A50F69026F_Word_var*
var
l_W : TtfwWord;
l_PW : TkwCompiledPushWord;
//#UC END# *55A50F69026F_55A50F69026F_Word_var*
begin
//#UC START# *55A50F69026F_55A50F69026F_Word_impl*
if (aValue.rType = tfw_vtObj) AND (aValue.AsObject Is TtfwWord) then
l_W := TtfwWord(aValue.AsObject).Use
else
l_W := TkwValue.Create(aValue);
try
RunnerAssert(l_W <> nil, 'Нет слова для компиляции', aCtx);
l_PW := TkwCompiledPushWord.Create(l_W, nil, aCtx);
try
aCtx.rCompiler.AddCodePart(l_PW, aCtx, tfw_sniNo);
finally
FreeAndNil(l_PW);
end;//try..finally
finally
FreeAndNil(l_W);
end;//try..finally
//#UC END# *55A50F69026F_55A50F69026F_Word_impl*
end;//TkwCompileRef.CompileRef
class function TkwCompileRef.GetWordNameForRegister: AnsiString;
begin
Result := 'CompileRef';
end;//TkwCompileRef.GetWordNameForRegister
function TkwCompileRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCompileRef.GetResultTypeInfo
function TkwCompileRef.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCompileRef.GetAllParamsCount
function TkwCompileRef.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct]);
end;//TkwCompileRef.ParamsTypes
procedure TkwCompileRef.DoDoIt(const aCtx: TtfwContext);
var l_aValue: TtfwStackValue;
begin
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CompileRef(aCtx, l_aValue);
end;//TkwCompileRef.DoDoIt
procedure TkwCompileWeakRef.CompileWeakRef(const aCtx: TtfwContext;
const aValue: TtfwStackValue);
{* Реализация слова скрипта CompileWeakRef }
//#UC START# *55CC86DC0163_55CC86DC0163_Word_var*
var
l_W : TtfwWord;
//#UC END# *55CC86DC0163_55CC86DC0163_Word_var*
begin
//#UC START# *55CC86DC0163_55CC86DC0163_Word_impl*
if (aValue.rType = tfw_vtObj) AND (aValue.AsObject Is TtfwWord) then
l_W := TkwWordPtrPushWord.Create(aValue.AsObject As TtfwWord)
else
l_W := nil;
try
RunnerAssert(l_W <> nil, 'Нет слова для компиляции', aCtx);
aCtx.rCompiler.AddCodePart(l_W, aCtx, tfw_sniNo);
finally
FreeAndNil(l_W);
end;//try..finally
//#UC END# *55CC86DC0163_55CC86DC0163_Word_impl*
end;//TkwCompileWeakRef.CompileWeakRef
class function TkwCompileWeakRef.GetWordNameForRegister: AnsiString;
begin
Result := 'CompileWeakRef';
end;//TkwCompileWeakRef.GetWordNameForRegister
function TkwCompileWeakRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCompileWeakRef.GetResultTypeInfo
function TkwCompileWeakRef.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwCompileWeakRef.GetAllParamsCount
function TkwCompileWeakRef.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([@tfw_tiStruct]);
end;//TkwCompileWeakRef.ParamsTypes
procedure TkwCompileWeakRef.DoDoIt(const aCtx: TtfwContext);
var l_aValue: TtfwStackValue;
begin
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CompileWeakRef(aCtx, l_aValue);
end;//TkwCompileWeakRef.DoDoIt
procedure TkwDUPN.DUPN(const aCtx: TtfwContext;
aN: Integer);
{* Реализация слова скрипта DUPN }
//#UC START# *55E866650225_55E866650225_Word_var*
//#UC END# *55E866650225_55E866650225_Word_var*
begin
//#UC START# *55E866650225_55E866650225_Word_impl*
aCtx.rEngine.DupN(aN);
//#UC END# *55E866650225_55E866650225_Word_impl*
end;//TkwDUPN.DUPN
class function TkwDUPN.GetWordNameForRegister: AnsiString;
begin
Result := 'DUPN';
end;//TkwDUPN.GetWordNameForRegister
function TkwDUPN.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDUPN.GetResultTypeInfo
function TkwDUPN.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwDUPN.GetAllParamsCount
function TkwDUPN.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwDUPN.ParamsTypes
procedure TkwDUPN.DoDoIt(const aCtx: TtfwContext);
var l_aN: Integer;
begin
try
l_aN := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aN: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
DUPN(aCtx, l_aN);
end;//TkwDUPN.DoDoIt
procedure TkwDROPN.DROPN(const aCtx: TtfwContext;
aN: Integer);
{* Реализация слова скрипта DROPN }
//#UC START# *55E8667C0309_55E8667C0309_Word_var*
//#UC END# *55E8667C0309_55E8667C0309_Word_var*
begin
//#UC START# *55E8667C0309_55E8667C0309_Word_impl*
aCtx.rEngine.DropN(aN);
//#UC END# *55E8667C0309_55E8667C0309_Word_impl*
end;//TkwDROPN.DROPN
class function TkwDROPN.GetWordNameForRegister: AnsiString;
begin
Result := 'DROPN';
end;//TkwDROPN.GetWordNameForRegister
function TkwDROPN.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwDROPN.GetResultTypeInfo
function TkwDROPN.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwDROPN.GetAllParamsCount
function TkwDROPN.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Integer)]);
end;//TkwDROPN.ParamsTypes
procedure TkwDROPN.DoDoIt(const aCtx: TtfwContext);
var l_aN: Integer;
begin
try
l_aN := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aN: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
DROPN(aCtx, l_aN);
end;//TkwDROPN.DoDoIt
class function TkwCtxEnterCS.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:EnterCS';
end;//TkwCtxEnterCS.GetWordNameForRegister
function TkwCtxEnterCS.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCtxEnterCS.GetResultTypeInfo
function TkwCtxEnterCS.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxEnterCS.GetAllParamsCount
function TkwCtxEnterCS.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxEnterCS.ParamsTypes
procedure TkwCtxEnterCS.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_57C5548E014E_Word_var*
//#UC END# *4DAEEDE10285_57C5548E014E_Word_var*
begin
//#UC START# *4DAEEDE10285_57C5548E014E_Word_impl*
TtfwCS.Instance.Lock;
//#UC END# *4DAEEDE10285_57C5548E014E_Word_impl*
end;//TkwCtxEnterCS.DoDoIt
class function TkwCtxLeaveCS.GetWordNameForRegister: AnsiString;
begin
Result := 'Ctx:LeaveCS';
end;//TkwCtxLeaveCS.GetWordNameForRegister
function TkwCtxLeaveCS.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwCtxLeaveCS.GetResultTypeInfo
function TkwCtxLeaveCS.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 0;
end;//TkwCtxLeaveCS.GetAllParamsCount
function TkwCtxLeaveCS.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([]);
end;//TkwCtxLeaveCS.ParamsTypes
procedure TkwCtxLeaveCS.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_57C554AD0130_Word_var*
//#UC END# *4DAEEDE10285_57C554AD0130_Word_var*
begin
//#UC START# *4DAEEDE10285_57C554AD0130_Word_impl*
TtfwCS.Instance.Unlock;
//#UC END# *4DAEEDE10285_57C554AD0130_Word_impl*
end;//TkwCtxLeaveCS.DoDoIt
class function TBasicsPackResNameGetter.ResName: AnsiString;
begin
Result := 'BasicsPack';
end;//TBasicsPackResNameGetter.ResName
{$R BasicsPack.res}
initialization
TkwDefine.RegisterInEngine;
{* Регистрация Define }
TkwCompiledPushWord.RegisterClass;
{* Регистрация TkwCompiledPushWord }
TkwTrue.RegisterInEngine;
{* Регистрация True }
TkwFalse.RegisterInEngine;
{* Регистрация False }
TkwMsg.RegisterInEngine;
{* Регистрация Msg }
TkwPrint.RegisterInEngine;
{* Регистрация Print }
TkwLOOP.RegisterInEngine;
{* Регистрация LOOP }
TkwWHILEDO.RegisterInEngine;
{* Регистрация WHILEDO }
TkwBREAK.RegisterInEngine;
{* Регистрация BREAK }
TkwCONTINUE.RegisterInEngine;
{* Регистрация CONTINUE }
TkwEXIT.RegisterInEngine;
{* Регистрация EXIT }
TkwHALT.RegisterInEngine;
{* Регистрация HALT }
TkwBREAKITERATOR.RegisterInEngine;
{* Регистрация BREAKITERATOR }
TkwNOP.RegisterInEngine;
{* Регистрация NOP }
TkwSLEEP.RegisterInEngine;
{* Регистрация SLEEP }
TkwProcessMessages.RegisterInEngine;
{* Регистрация ProcessMessages }
TkwCheckAssert.RegisterInEngine;
{* Регистрация CheckAssert }
TkwASSERTS.RegisterInEngine;
{* Регистрация ASSERTS }
TkwNil.RegisterInEngine;
{* Регистрация Nil }
TkwDoWord.RegisterInEngine;
{* Регистрация DoWord }
TkwSmartEquals.RegisterInEngine;
{* Регистрация SmartEquals }
TkwSmartNotEquals.RegisterInEngine;
{* Регистрация SmartNotEquals }
TkwPushWord.RegisterInEngine;
{* Регистрация PushWord }
TkwCurrentException.RegisterInEngine;
{* Регистрация current_exception }
TkwCurrentExceptionClass.RegisterInEngine;
{* Регистрация current_exception_class }
TkwCurrentExceptionClassName.RegisterInEngine;
{* Регистрация current_exception_ClassName }
TkwCurrentExceptionMessage.RegisterInEngine;
{* Регистрация current_exception_Message }
TkwInc.RegisterInEngine;
{* Регистрация Inc }
TkwDec.RegisterInEngine;
{* Регистрация Dec }
TkwAdd.RegisterInEngine;
{* Регистрация Add }
TkwSub.RegisterInEngine;
{* Регистрация Sub }
TkwDivision.RegisterInEngine;
{* Регистрация Division }
TkwMul.RegisterInEngine;
{* Регистрация Mul }
TkwDivide.RegisterInEngine;
{* Регистрация Divide }
TkwMul2.RegisterInEngine;
{* Регистрация Mul2 }
TkwDiv2.RegisterInEngine;
{* Регистрация Div2 }
TkwMulDiv.RegisterInEngine;
{* Регистрация MulDiv }
TkwBoolNot.RegisterInEngine;
{* Регистрация BoolNot }
TkwModFromDiv.RegisterInEngine;
{* Регистрация ModFromDiv }
TkwBoolAnd.RegisterInEngine;
{* Регистрация BoolAnd }
TkwBoolOr.RegisterInEngine;
{* Регистрация BoolOr }
TkwNotZero.RegisterInEngine;
{* Регистрация NotZero }
TkwEqualZero.RegisterInEngine;
{* Регистрация EqualZero }
TkwSWAP.RegisterInEngine;
{* Регистрация SWAP }
TkwDROP.RegisterInEngine;
{* Регистрация DROP }
TkwDUP.RegisterInEngine;
{* Регистрация DUP }
TkwDUPIfNotZero.RegisterInEngine;
{* Регистрация DUPIfNotZero }
TkwROT.RegisterInEngine;
{* Регистрация ROT }
TkwPICK.RegisterInEngine;
{* Регистрация PICK }
TkwInvertROT.RegisterInEngine;
{* Регистрация InvertROT }
TkwSWAP2.RegisterInEngine;
{* Регистрация SWAP2 }
TkwOVER2.RegisterInEngine;
{* Регистрация OVER2 }
TkwDUP2.RegisterInEngine;
{* Регистрация DUP2 }
TkwDROP2.RegisterInEngine;
{* Регистрация DROP2 }
TkwNIP.RegisterInEngine;
{* Регистрация NIP }
TkwTUCK.RegisterInEngine;
{* Регистрация TUCK }
TkwOVER.RegisterInEngine;
{* Регистрация OVER }
TkwROLL.RegisterInEngine;
{* Регистрация ROLL }
TkwNotEquals.RegisterInEngine;
{* Регистрация NotEquals }
TkwGREATER.RegisterInEngine;
{* Регистрация GREATER }
TkwLESS.RegisterInEngine;
{* Регистрация LESS }
TkwEquals.RegisterInEngine;
{* Регистрация Equals }
TkwLessThanZero.RegisterInEngine;
{* Регистрация LessThanZero }
TkwGreaterThanZero.RegisterInEngine;
{* Регистрация GreaterThanZero }
TkwBitAnd.RegisterInEngine;
{* Регистрация BitAnd }
TkwBitOR.RegisterInEngine;
{* Регистрация BitOR }
TkwBitNot.RegisterInEngine;
{* Регистрация BitNot }
TkwStackLevel.RegisterInEngine;
{* Регистрация StackLevel }
TkwReduceStackLevel.RegisterInEngine;
{* Регистрация ReduceStackLevel }
TkwCtxParserPushString.RegisterInEngine;
{* Регистрация Ctx_Parser_PushString }
TkwCtxParserPushSymbol.RegisterInEngine;
{* Регистрация Ctx_Parser_PushSymbol }
TkwCtxParserPushInt.RegisterInEngine;
{* Регистрация Ctx_Parser_PushInt }
TkwCtxParser.RegisterInEngine;
{* Регистрация Ctx_Parser }
TkwAtomicIf.RegisterInEngine;
{* Регистрация AtomicIf }
TkwCompileValue.RegisterInEngine;
{* Регистрация CompileValue }
TkwIMMEDIATE.RegisterInEngine;
{* Регистрация IMMEDIATE }
TkwCtxScriptCaller.RegisterInEngine;
{* Регистрация Ctx_ScriptCaller }
TkwCtxEngine.RegisterInEngine;
{* Регистрация Ctx_Engine }
TkwCtxStoredValuesStack.RegisterInEngine;
{* Регистрация Ctx_StoredValuesStack }
TkwCreateAndRaise.RegisterInEngine;
{* Регистрация CreateAndRaise }
TkwCompileRef.RegisterInEngine;
{* Регистрация CompileRef }
TkwCompileWeakRef.RegisterInEngine;
{* Регистрация CompileWeakRef }
TkwDUPN.RegisterInEngine;
{* Регистрация DUPN }
TkwDROPN.RegisterInEngine;
{* Регистрация DROPN }
TkwCtxEnterCS.RegisterInEngine;
{* Регистрация Ctx_EnterCS }
TkwCtxLeaveCS.RegisterInEngine;
{* Регистрация Ctx_LeaveCS }
TBasicsPackResNameGetter.Register;
{* Регистрация скриптованой аксиоматики }
//#UC START# *551588F90151*
TtfwClassRef.Register(EStreamError);
TtfwClassRef.Register(EFileStreamError);
TtfwClassRef.Register(EFCreateError);
TtfwClassRef.Register(EFOpenError);
TtfwClassRef.Register(EFilerError);
TtfwClassRef.Register(EReadError);
TtfwClassRef.Register(EWriteError);
TtfwClassRef.Register(EClassNotFound);
TtfwClassRef.Register(EMethodNotFound);
TtfwClassRef.Register(EInvalidImage);
TtfwClassRef.Register(EResNotFound);
TtfwClassRef.Register(EListError);
TtfwClassRef.Register(EBitsError);
TtfwClassRef.Register(EStringListError);
TtfwClassRef.Register(EComponentError);
TtfwClassRef.Register(EParserError);
TtfwClassRef.Register(EOutOfResources);
TtfwClassRef.Register(EInvalidOperation);
TtfwClassRef.Register(EAssertionFailed);
TtfwClassRef.Register(EAccessViolation);
TtfwClassRef.Register(ERangeError);
TtfwClassRef.Register(EZeroDivide);
TtfwClassRef.Register(EExternalException);
TtfwClassRef.Register(EIntError);
TtfwClassRef.Register(EDivByZero);
TtfwClassRef.Register(EIntOverflow);
TtfwClassRef.Register(EInvalidOp);
TtfwClassRef.Register(EOverflow);
TtfwClassRef.Register(EUnderflow);
TtfwClassRef.Register(EInvalidPointer);
TtfwClassRef.Register(EInvalidCast);
TtfwClassRef.Register(EConvertError);
TtfwClassRef.Register(EPrivilege);
TtfwClassRef.Register(EStackOverflow);
TtfwClassRef.Register(EControlC);
TtfwClassRef.Register(EIntfCastError);
TtfwClassRef.Register(EOSError);
TtfwClassRef.Register(EtfwCompiler);
TtfwClassRef.Register(EtfwRunner);
TtfwClassRef.Register(EtfwScriptException);
TtfwClassRef.Register(EtfwContinue);
TtfwClassRef.Register(EtfwBreak);
TtfwClassRef.Register(EtfwBreakIterator);
TtfwClassRef.Register(EtfwExit);
TtfwClassRef.Register(EtfwHalt);
TtfwClassRef.Register(EtfwFail);
TtfwClassRef.Register(EtfwManualBreak);
//#UC END# *551588F90151*
TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean));
{* Регистрация типа Boolean }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwWord));
{* Регистрация типа TtfwWord }
TtfwTypeRegistrator.RegisterType(TypeInfo(TObject));
{* Регистрация типа TObject }
TtfwTypeRegistrator.RegisterType(@tfw_tiClassRef);
{* Регистрация типа TClass }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа AnsiString }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(@tfw_tiStruct);
{* Регистрация типа TtfwStackValue }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwParserEx));
{* Регистрация типа ItfwParserEx }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwScriptCaller));
{* Регистрация типа ItfwScriptCaller }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwScriptEngine));
{* Регистрация типа ItfwScriptEngine }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwStoredValuesStack));
{* Регистрация типа ItfwStoredValuesStack }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Il3CString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit uform4;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, uchecksum;
type
{ TIMEICalc }
TIMEICalc = class(TForm)
btCreateChecksum: TButton;
btCheck: TButton;
edIMEI: TEdit;
edIMEIC: TEdit;
lbFalse: TLabel;
lbIMEI: TLabel;
lbIMEIC: TLabel;
lbTrue: TLabel;
procedure btCreateChecksumClick(Sender: TObject);
procedure btCheckClick(Sender: TObject);
private
{ private declarations }
IMEI: TIMEI;
public
{ public declarations }
end;
var
IMEICalc: TIMEICalc;
implementation
{$R *.lfm}
{ TIMEICalc }
procedure TIMEICalc.btCreateChecksumClick(Sender: TObject);
begin
edIMEIC.Text := IMEI.createIMEI(edIMEI.Text);
end;
procedure TIMEICalc.btCheckClick(Sender: TObject);
begin
lbTrue.Visible := IMEI.checkIMEI(edIMEIC.Text);
lbFalse.Visible := not IMEI.checkIMEI(edIMEIC.Text);
end;
end.
|
unit ctpQuoteForm;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls, ExtCtrls,
BaseForm;
type
TfrmCtpQuote = class(TfrmBase)
pnlInit: TPanel;
btnInitMD: TButton;
btnConnectMD: TButton;
edtAddrMD: TComboBox;
btnShutDown: TButton;
pnlLogin: TPanel;
lblAccount: TLabel;
lblPassowrd: TLabel;
lblBrokeId: TLabel;
btnLoginMD: TButton;
edtAccount: TComboBox;
edtPassword: TEdit;
edtBrokeId: TComboBox;
btnLogoutMD: TButton;
pnlScribe: TPanel;
lblItem: TLabel;
btnSubscribe: TButton;
edtInstItem: TEdit;
btnUnsubscribe: TButton;
procedure btnInitMDClick(Sender: TObject);
procedure btnConnectMDClick(Sender: TObject);
procedure btnLoginMDClick(Sender: TObject);
procedure btnLogoutMDClick(Sender: TObject);
procedure btnShutDownClick(Sender: TObject);
procedure btnSubscribeClick(Sender: TObject);
procedure btnUnsubscribeClick(Sender: TObject);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(Owner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
define_app_msg,
TcpInitUtils,
TcpAgentConsole;
constructor TfrmCtpQuote.Create(Owner: TComponent);
begin
inherited;
end;
procedure TfrmCtpQuote.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WinClassName := 'WndCtpQuote';
Params.Caption := '';
Self.Caption := '';
end;
procedure TfrmCtpQuote.btnInitMDClick(Sender: TObject);
begin
GTcpAgentConsole.Quote.InitMD;
end;
procedure TfrmCtpQuote.btnConnectMDClick(Sender: TObject);
var
tmpAddrDesc: AnsiString;
tmpAddr: AnsiString;
begin
tmpAddrDesc := Trim(edtAddrMD.Text);
tmpAddr := ParseAddress(tmpAddrDesc);
SaveIniAddress(tmpAddrDesc, tmpAddr, 'MDUrl');
GTcpAgentConsole.Quote.ConnectMD(tmpAddr);
end;
procedure TfrmCtpQuote.btnShutDownClick(Sender: TObject);
begin
if GTcpAgentConsole.Quote.FindSrvWindow then
begin
SendMessage(GTcpAgentConsole.Quote.SrvWND, WM_C2S_Shutdown, 0, 0);
end;
end;
procedure TfrmCtpQuote.btnLoginMDClick(Sender: TObject);
begin
GTcpAgentConsole.Quote.LoginMD(Trim(edtBrokeId.Text), Trim(edtAccount.Text), Trim(edtPassword.Text));
SaveIniAccount(Trim(edtBrokeId.Text), Trim(edtAccount.Text));
end;
procedure TfrmCtpQuote.btnLogoutMDClick(Sender: TObject);
begin
if GTcpAgentConsole.Quote.FindSrvWindow then
begin
SendMessage(GTcpAgentConsole.Quote.SrvWND, WM_C2S_MD_RequestUserLogout, GTcpAgentConsole.CheckOutRequestId, 0);
end;
end;
procedure TfrmCtpQuote.btnSubscribeClick(Sender: TObject);
begin
GTcpAgentConsole.Quote.MDSubscribe(Trim(edtInstItem.Text));
end;
procedure TfrmCtpQuote.btnUnsubscribeClick(Sender: TObject);
var
tmpCopyData: TCopyDataCommand;
tmpAnsi: AnsiString;
begin
if GTcpAgentConsole.Quote.FindSrvWindow then
begin
//PostMessage(SrvWND, WM_C2S_UnSubscribeMarketData, 0, 0);
FillChar(tmpCopyData, SizeOf(TCopyDataCommand), 0);
tmpCopyData.Base.dwData := WM_C2S_UnSubscribeMarketData;
tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand);
tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand;
tmpAnsi := Trim(edtInstItem.Text);
CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi));
SendMessage(GTcpAgentConsole.Quote.SrvWND, WM_COPYDATA, Self.Handle, LongWord(@tmpCopyData));
end;
end;
end.
|
unit Model.Interfaces;
interface
uses
System.SysUtils,
System.Classes,
Model.DAO.Interfaces;
type
iModelEntityGenerate = interface;
iModelGeneratorParams = interface;
iModelModelGenerate = interface;
iModelRoutersGenerate = interface;
iModelGenerator = interface
['{D94A9F44-0E64-411A-940B-E1F2B29DEE08}']
function Params : iModelGeneratorParams;
function EntityGenerate: iModelEntityGenerate;
function ModelGenerate: iModelModelGenerate;
function RoutersGenerate: iModelRoutersGenerate;
end;
iModelGeneratorParams = interface
['{34161ED1-9926-4482-B296-5F3D7C9C7FB8}']
function Captalizar( aValue: Boolean) : iModelGeneratorParams; overload;
function Captalizar: Boolean; overload;
function RemoverCaracter( aValue: Boolean) : iModelGeneratorParams; overload;
function RemoverCaracter: Boolean; overload;
function SwaggerDoc( aValue: Boolean) : iModelGeneratorParams; overload;
function SwaggerDoc : Boolean; overload;
function Display( aDisplay : TProc<string>) : iModelGeneratorParams; overload;
function Display(aValue : String): iModelGeneratorParams; overload;
function Diretorio( aValue : String) : iModelGeneratorParams; overload;
function Diretorio : String; overload;
function Prefixo( aValue : String) : iModelGeneratorParams; overload;
function Prefixo: String; overload;
function Projeto( aValue : String) : iModelGeneratorParams; overload;
function Projeto: String; overload;
function &End :iModelGenerator;
end;
iModelEntityGenerate = interface
['{0416D202-BFCE-499D-9CFD-683FF7E23116}']
function Connection( aConnection : iModelDAOConnection) : iModelEntityGenerate;
function Tabela( aValue : String) : iModelEntityGenerate;
function Generate : iModelEntityGenerate;
function &End :iModelGenerator;
end;
iModelModelGenerate = interface
['{5E17278D-C4BF-4DFF-BE77-F3A0C188D81A}']
function Tabelas(aValue : TStrings) : iModelModelGenerate;
function Generate : iModelModelGenerate;
function &End :iModelGenerator;
end;
iModelRoutersGenerate = interface
['{05268B92-1409-4197-A546-5A2557B8B0A5}']
function Connection( aConnection : iModelDAOConnection) : iModelRoutersGenerate;
function Tabelas(aValue : TStrings) : iModelRoutersGenerate;
function Generate : iModelRoutersGenerate;
function &End :iModelGenerator;
end;
iModelFileControl = interface
['{1100B127-0A84-438C-ADD4-98F3A7C74D1D}']
function Add( aValue : String) : iModelFileControl;
function Clear : iModelFileControl;
function SaveToFile( aValue : String) : iModelFileControl;
function Text : String;
end;
implementation
end.
|
//Exercicio 74: Escreva um algoritmo que receba e armazene 50 números inteiros num vetor A. Calcular o quadrado dos
//respectivos números do vetor A e armazenar os resultados, respectivamente, no vetor B. Exibir os vetores A e B.
{ Solução em Portugol
Algoritmo Exercicio 74;
Tipo
vet = vetor[1..50] de inteiros;
Var
A,B: vet;
i: inteiros;
Inicio
exiba("Programa que recebe 50 números num vetor, armazena o quadrado desses números num vetor B e exibe os dois vetores.");
para i <- 1 até 50 faça
exiba("Digite o ",i,"º termo do vetor A."); // Lendo A
leia(A[i]);
B[i] <- A[i] * A[i]; // Calculando B
fimpara;
exiba("O vetor A!");
para i <- 1 até 50 faça
exiba("A[",i,"] = ",A[i]); // Exibindo A
fimpara;
exiba("O vetor B!");
para i <- 1 até 50 faça
exiba("B[",i,"] = ",B[i]); // Exibindo B
fimpara;
Fim.
}
// Solução em Pascal
Program Exercicio74;
uses crt;
Type
vet = array[1..50] of integer;
Var
A,B: vet;
i: integer;
Begin
writeln('Programa que recebe 50 números num vetor, armazena o quadrado desses números num vetor B e exibe os dois vetores.');
for i := 1 to 5 do
Begin
writeln('Digite o ',i,'º termo do vetor A.'); // Lendo A
readln(A[i]);
B[i] := A[i] * A[i]; // Calculando B
End;
writeln('O vetor A!');
for i := 1 to 5 do
writeln('A[',i,'] = ',A[i]); // Exibindo A
writeln('O vetor B!');
for i := 1 to 5 do
writeln('B[',i,'] = ',B[i]); // Exibindo B
end. |
program fptutorial13d;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
type
creature = record
Name: string;
Armor, Health, Magic, Power: integer;
end;
var
hero, JellBall: creature;
procedure LoadSettings;
begin
with Hero do
begin
Name := 'Sir Bill';
Armor := 0;
Health := 10;
Magic := 2;
Power := 5;
end;
with JellBall do
begin
Name := 'JellBall';
Armor := 0;
Health := 1;
Magic := 0;
Power := 1;
end;
end;
procedure PrintSettings;
begin
with Hero do
begin
writeln('Name: ', Name);
writeln('Armor: ', Armor);
writeln('Health: ', Health);
writeln('Magic: ', Magic);
end;
writeln; writeln;
with JellBall do
begin
writeln('Name: ', Name);
writeln('Armor: ', Armor);
writeln('Health: ', Health);
writeln('Magic: ', Magic);
end;
end;
procedure StopProgram;
begin
writeln; writeln;
writeln('Press <Enter> to Quit');
readln;
end;
begin
LoadSettings;
PrintSettings;
StopProgram;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clJson;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Contnrs;
{$ELSE}
System.Classes, System.SysUtils, System.Contnrs;
{$ENDIF}
type
EclJSONError = class(Exception)
private
FErrorCode: Integer;
public
constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False);
property ErrorCode: Integer read FErrorCode;
end;
TclJSONString = class;
TclJSONPair = class;
TclJSONObject = class;
TclJSONArray = class;
TclJSONBase = class
private
class function DecodeString(const ASource: string): WideString;
class function EncodeString(const ASource: WideString): string;
class procedure SkipWhiteSpace(var Next: PChar);
class function ParseValue(var Next: PChar): TclJSONBase;
class function ParseName(var Next: PChar): string;
class function ParsePair(var Next: PChar): TclJSONPair;
class function ParseObj(var Next: PChar): TclJSONObject;
class function ParseArray(var Next: PChar): TclJSONArray;
class function ParseRoot(var Next: PChar): TclJSONBase;
function GetValueString: string;
procedure SetValueString(const AValue: string);
protected
function GetValueWideString: WideString; virtual; abstract;
procedure SetValueWideString(const Value: WideString); virtual; abstract;
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); virtual; abstract;
{$ELSE}
function BuildJSONString: string; virtual; abstract;
{$ENDIF}
public
class function Parse(const AJSONString: string): TclJSONBase;
class function ParseObject(const AJSONString: string): TclJSONObject;
function GetJSONString: string;
property ValueString: string read GetValueString write SetValueString;
property ValueWideString: WideString read GetValueWideString write SetValueWideString;
end;
TclJSONPair = class(TclJSONBase)
private
FName: WideString;
FValue: TclJSONBase;
procedure SetValue(const AValue: TclJSONBase);
function GetName: string;
procedure SetName(const AValue: string);
protected
function GetValueWideString: WideString; override;
procedure SetValueWideString(const AValue: WideString); override;
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); override;
{$ELSE}
function BuildJSONString: string; override;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
property Name: string read GetName write SetName;
property NameWideString: WideString read FName write FName;
property Value: TclJSONBase read FValue write SetValue;
end;
TclJSONValue = class(TclJSONBase)
private
FValue: WideString;
protected
function GetValueWideString: WideString; override;
procedure SetValueWideString(const AValue: WideString); override;
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); override;
{$ELSE}
function BuildJSONString: string; override;
{$ENDIF}
public
constructor Create; overload;
constructor Create(const AValue: string); overload;
constructor Create(const AValue: WideString); overload;
end;
TclJSONString = class(TclJSONValue)
protected
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); override;
{$ELSE}
function BuildJSONString: string; override;
{$ENDIF}
end;
TclJSONBoolean = class(TclJSONValue)
private
function GetValue: Boolean;
procedure SetValue(const Value: Boolean);
protected
procedure SetValueWideString(const AValue: WideString); override;
public
constructor Create; overload;
constructor Create(AValue: Boolean); overload;
property Value: Boolean read GetValue write SetValue;
end;
TclJSONArray = class(TclJSONBase)
private
FItems: TObjectList;
function GetCount: Integer;
function GetItem(Index: Integer): TclJSONBase;
function GetObject(Index: Integer): TclJSONObject;
protected
function GetValueWideString: WideString; override;
procedure SetValueWideString(const AValue: WideString); override;
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); override;
{$ELSE}
function BuildJSONString: string; override;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
function Add(AItem: TclJSONBase): TclJSONBase;
property Count: Integer read GetCount;
property Items[Index: Integer]: TclJSONBase read GetItem;
property Objects[Index: Integer]: TclJSONObject read GetObject;
end;
TclJSONObject = class(TclJSONBase)
private
FMembers: TObjectList;
function GetCount: Integer;
function GetMember(Index: Integer): TclJSONPair;
protected
function GetValueWideString: WideString; override;
procedure SetValueWideString(const AValue: WideString); override;
{$IFDEF DELPHI2009}
procedure BuildJSONString(ABuffer: TStringBuilder); override;
{$ELSE}
function BuildJSONString: string; override;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
function MemberByName(const AName: string): TclJSONPair; overload;
function MemberByName(const AName: WideString): TclJSONPair; overload;
function ValueByName(const AName: string): string; overload;
function ValueByName(const AName: WideString): WideString; overload;
function ObjectByName(const AName: string): TclJSONObject; overload;
function ObjectByName(const AName: WideString): TclJSONObject; overload;
function ArrayByName(const AName: string): TclJSONArray; overload;
function ArrayByName(const AName: WideString): TclJSONArray; overload;
function BooleanByName(const AName: string): Boolean; overload;
function BooleanByName(const AName: WideString): Boolean; overload;
function AddMember(APair: TclJSONPair): TclJSONPair; overload;
function AddMember(const AName: WideString; AValue: TclJSONBase): TclJSONPair; overload;
function AddMember(const AName: string; AValue: TclJSONBase): TclJSONPair; overload;
function AddString(const AName, AValue: string): TclJSONString; overload;
function AddString(const AName, AValue: WideString): TclJSONString; overload;
function AddValue(const AName, AValue: string): TclJSONValue; overload;
function AddValue(const AName, AValue: WideString): TclJSONValue; overload;
function AddBoolean(const AName: string; AValue: Boolean): TclJSONBoolean; overload;
function AddBoolean(const AName: WideString; AValue: Boolean): TclJSONBoolean; overload;
property Count: Integer read GetCount;
property Members[Index: Integer]: TclJSONPair read GetMember;
end;
resourcestring
UnexpectedDataEnd = 'Unexpected end of JSON data';
UnexpectedDataSymbol = 'Unexpected symbol in JSON data';
InvalidControlSymbol = 'Invalid control symbol in JSON data';
InvalidUnicodeEscSequence = 'Invalid unicode escape sequence in JSON data';
UnrecognizedEscSequence = 'Unrecognized escape sequence in JSON data';
UnexpectedDataType = 'Unexpected data type';
const
UnexpectedDataEndCode = -100;
UnexpectedDataSymbolCode = -101;
InvalidControlSymbolCode = -102;
InvalidUnicodeEscSequenceCode = -103;
UnrecognizedEscSequenceCode = -104;
UnexpectedDataTypeCode = -106;
var
EscapeJsonStrings: Boolean = False;
implementation
uses
clWUtils;
const
JsonBoolean: array[Boolean] of string = ('false', 'true');
{ TclJSONBase }
procedure TclJSONBase.SetValueString(const AValue: string);
begin
ValueWideString := WideString(AValue);
end;
class procedure TclJSONBase.SkipWhiteSpace(var Next: PChar);
begin
while (Next^ <> #0) do
begin
case (Next^) of
#32, #9, #13, #10:
else
Break;
end;
Inc(Next);
end;
end;
class function TclJSONBase.ParseArray(var Next: PChar): TclJSONArray;
begin
Result := TclJSONArray.Create();
try
while (Next^ <> #0) do
begin
SkipWhiteSpace(Next);
if (Next^ = #0) then
begin
raise EclJSONError.Create(UnexpectedDataEnd, UnexpectedDataEndCode);
end;
case (Next^) of
']':
begin
Inc(Next);
Break;
end;
',':
begin
Inc(Next);
Result.Add(ParseRoot(Next));
Continue;
end
else
begin
Result.Add(ParseRoot(Next));
Continue;
end;
end;
Inc(Next);
end;
except
Result.Free();
raise;
end;
end;
class function TclJSONBase.ParseName(var Next: PChar): string;
var
inQuote: Boolean;
lastTwo: array[0..1] of Char;
begin
Result := '';
inQuote := False;
lastTwo[0] := #0;
lastTwo[1] := #0;
while (Next^ <> #0) do
begin
SkipWhiteSpace(Next);
case (Next^) of
#0: Break;
'"':
begin
if (lastTwo[0] <> '\') and (lastTwo[1] = '\') then
begin
Result := Result + Next^;
end else
begin
if inQuote then
begin
Inc(Next);
Break;
end;
inQuote := not inQuote;
end;
end
else
Result := Result + Next^;
end;
lastTwo[0] := lastTwo[1];
lastTwo[1] := Next^;
Inc(Next);
end;
end;
class function TclJSONBase.ParseObject(const AJSONString: string): TclJSONObject;
var
root: TclJSONBase;
begin
root := TclJSONBase.Parse(AJSONString);
try
if (root is TclJSONObject) then
begin
Result := TclJSONObject(root);
end else
begin
raise EclJSONError.Create(UnexpectedDataType, UnexpectedDataTypeCode);
end;
except
root.Free();
raise;
end;
end;
class function TclJSONBase.ParsePair(var Next: PChar): TclJSONPair;
begin
Result := TclJSONPair.Create();
try
while (Next^ <> #0) do
begin
SkipWhiteSpace(Next);
if (Next^ = #0) then
begin
raise EclJSONError.Create(UnexpectedDataEnd, UnexpectedDataEndCode);
end;
if (Next^ = ':') and (Result.NameWideString = '') then
begin
raise EclJSONError.Create(UnexpectedDataSymbol, UnexpectedDataSymbolCode);
end;
if (Result.NameWideString = '') then
begin
Result.NameWideString := DecodeString(ParseName(Next));
Continue;
end else
if (Next^ = ':') then
begin
Inc(Next);
Result.Value := ParseRoot(Next);
Break;
end else
begin
raise EclJSONError.Create(UnexpectedDataSymbol, UnexpectedDataSymbolCode);
end;
Inc(Next);
end;
except
Result.Free();
raise;
end;
end;
class function TclJSONBase.ParseObj(var Next: PChar): TclJSONObject;
begin
Result := TclJSONObject.Create();
try
while (Next^ <> #0) do
begin
SkipWhiteSpace(Next);
if (Next^ = #0) then
begin
raise EclJSONError.Create(UnexpectedDataEnd, UnexpectedDataEndCode);
end;
case (Next^) of
'}':
begin
Inc(Next);
Break;
end;
',':
begin
Inc(Next);
Result.AddMember(ParsePair(Next));
Continue;
end
else
begin
Result.AddMember(ParsePair(Next));
Continue;
end;
end;
Inc(Next);
end;
except
Result.Free();
raise;
end;
end;
class function TclJSONBase.ParseValue(var Next: PChar): TclJSONBase;
var
inQuote, isString: Boolean;
value: string;
lastTwo: array[0..1] of Char;
begin
value := '';
inQuote := False;
isString := False;
lastTwo[0] := #0;
lastTwo[1] := #0;
while (Next^ <> #0) do
begin
if (not inQuote) then
begin
SkipWhiteSpace(Next);
end;
case (Next^) of
#0: Break;
'}', ']', ',':
begin
if inQuote then
begin
value := value + Next^;
end else
begin
Break;
end;
end;
'"':
begin
if inQuote and (lastTwo[0] <> '\') and (lastTwo[1] = '\') then
begin
value := value + Next^;
end else
begin
if inQuote then
begin
Inc(Next);
Break;
end;
inQuote := not inQuote;
isString := True;
end;
end
else
value := value + Next^;
end;
lastTwo[0] := lastTwo[1];
lastTwo[1] := Next^;
Inc(Next);
end;
Result := nil;
try
if isString then
begin
Result := TclJSONString.Create();
Result.ValueWideString := DecodeString(value);
end else
begin
if (JsonBoolean[True] = value) then
begin
Result := TclJSONBoolean.Create(True);
end else
if (JsonBoolean[False] = value) then
begin
Result := TclJSONBoolean.Create(False);
end else
begin
Result := TclJSONValue.Create();
Result.ValueWideString := value;
end;
end;
except
Result.Free();
raise;
end;
end;
class function TclJSONBase.ParseRoot(var Next: PChar): TclJSONBase;
begin
Result := nil;
while (Next^ <> #0) do
begin
SkipWhiteSpace(Next);
if (Next^ = #0) then Break;
case (Next^) of
'{':
begin
Inc(Next);
Result := ParseObj(Next);
Break;
end;
'[':
begin
Inc(Next);
Result := ParseArray(Next);
Break;
end
else
begin
Result := ParseValue(Next);
Break;
end;
end;
Inc(Next);
end;
end;
class function TclJSONBase.EncodeString(const ASource: WideString): string;
var
i: Integer;
begin
Result := '"';
for i := 1 to Length(ASource) do
begin
case ASource[i] of
'/', '\', '"':
begin
Result := Result + '\' + Char(ASource[i]);
end;
#8:
begin
Result := Result + '\b';
end;
#9:
begin
Result := Result + '\t';
end;
#10:
begin
Result := Result + '\n';
end;
#12:
begin
Result := Result + '\f';
end;
#13:
begin
Result := Result + '\r';
end
else
begin
if (not EscapeJsonStrings) or (ASource[i] >= WideChar(' ')) and (ASource[i] <= WideChar('~')) then
begin
Result := Result + Char(ASource[i]);
end else
begin
Result := Result + '\u' + IntToHex(Ord(ASource[i]), 4);
end;
end;
end;
end;
Result := Result + '"';
end;
class function TclJSONBase.DecodeString(const ASource: string): WideString;
var
i, j, k, len: Integer;
code: string;
begin
code := '$ ';
len := Length(ASource);
SetLength(Result, len);
i := 1;
j := 0;
while (i <= len) do
begin
if (ASource[i] < ' ') then
begin
raise EclJSONError.Create(InvalidControlSymbol, InvalidControlSymbolCode);
end;
if (ASource[i] = '\') then
Begin
Inc(i);
case ASource[i] of
'"', '\', '/':
begin
Inc(j);
Result[j] := WideChar(ASource[i]);
Inc(i);
end;
'b':
begin
Inc(j);
Result[j] := #8;
Inc(i);
end;
't':
begin
Inc(j);
Result[j] := #9;
Inc(i);
end;
'n':
begin
Inc(j);
Result[j] := #10;
Inc(i);
end;
'f':
begin
Inc(j);
Result[j] := #12;
Inc(i);
end;
'r':
begin
Inc(j);
Result[j] := #13;
Inc(i);
end;
'u':
begin
if (i + 4 > len) then
begin
raise EclJSONError.Create(InvalidUnicodeEscSequence, InvalidUnicodeEscSequenceCode);
end;
for k := 1 to 4 do
begin
if not CharInSet(ASource[i + k], ['0'..'9', 'a'..'f', 'A'..'F']) then
begin
raise EclJSONError.Create(InvalidUnicodeEscSequence, InvalidUnicodeEscSequenceCode);
end else
begin
code[k + 1] := ASource[i + k];
end;
end;
Inc(j);
Inc(i, 5);
Result[j] := WideChar(StrToInt(code));
end
else
raise EclJSONError.Create(UnrecognizedEscSequence, UnrecognizedEscSequenceCode);
end;
end else
begin
Inc(j);
Result[j] := WideChar(ASource[i]);
Inc(i);
end;
end;
SetLength(Result, j);
end;
{$IFDEF DELPHI2009}
function TclJSONBase.GetJSONString: string;
var
buffer: TStringBuilder;
begin
buffer := TStringBuilder.Create();
try
BuildJSONString(buffer);
Result := buffer.ToString();
finally
buffer.Free();
end;
end;
{$ELSE}
function TclJSONBase.GetJSONString: string;
begin
Result := BuildJSONString();
end;
{$ENDIF}
function TclJSONBase.GetValueString: string;
begin
Result := string(ValueWideString);
end;
class function TclJSONBase.Parse(const AJSONString: string): TclJSONBase;
var
Next: PChar;
begin
Result := nil;
Next := @AJSONString[1];
if (Next^ = #0) then Exit;
Result := ParseRoot(Next);
try
SkipWhiteSpace(Next);
if (Next^ <> #0) then
begin
raise EclJSONError.Create(UnexpectedDataSymbol, UnexpectedDataSymbolCode);
end;
except
Result.Free();
raise;
end;
end;
{ TclJSONObject }
function TclJSONObject.AddMember(APair: TclJSONPair): TclJSONPair;
begin
FMembers.Add(APair);
Result := APair;
end;
function TclJSONObject.AddMember(const AName: WideString; AValue: TclJSONBase): TclJSONPair;
begin
if (AValue <> nil) then
begin
Result := AddMember(TclJSONPair.Create());
Result.NameWideString := AName;
Result.Value := AValue;
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddBoolean(const AName: string; AValue: Boolean): TclJSONBoolean;
begin
if (AValue) then
begin
Result := TclJSONBoolean(AddMember(AName, TclJSONBoolean.Create(AValue)));
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddBoolean(const AName: WideString; AValue: Boolean): TclJSONBoolean;
begin
if (AValue) then
begin
Result := TclJSONBoolean(AddMember(AName, TclJSONBoolean.Create(AValue)));
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddMember(const AName: string; AValue: TclJSONBase): TclJSONPair;
begin
if (AValue <> nil) then
begin
Result := AddMember(TclJSONPair.Create());
Result.Name := AName;
Result.Value := AValue;
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddString(const AName, AValue: WideString): TclJSONString;
begin
if (AValue <> '') then
begin
Result := TclJSONString(AddMember(AName, TclJSONString.Create(AValue)).Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddValue(const AName, AValue: WideString): TclJSONValue;
begin
if (AValue <> '') then
begin
Result := TclJSONValue(AddMember(AName, TclJSONValue.Create(AValue)).Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddString(const AName, AValue: string): TclJSONString;
begin
if (AValue <> '') then
begin
Result := TclJSONString(AddMember(AName, TclJSONString.Create(AValue)).Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.AddValue(const AName, AValue: string): TclJSONValue;
begin
if (AValue <> '') then
begin
Result := TclJSONValue(AddMember(AName, TclJSONValue.Create(AValue)).Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.ArrayByName(const AName: WideString): TclJSONArray;
var
pair: TclJSONPair;
begin
pair := MemberByName(AName);
if (pair <> nil) then
begin
if not (pair.Value is TclJSONArray) then
begin
raise EclJSONError.Create(UnexpectedDataType, UnexpectedDataTypeCode);
end;
Result := TclJSONArray(pair.Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.ArrayByName(const AName: string): TclJSONArray;
begin
Result := ArrayByName(WideString(AName));
end;
constructor TclJSONObject.Create;
begin
inherited Create();
FMembers := TObjectList.Create(True);
end;
destructor TclJSONObject.Destroy;
begin
FMembers.Free();
inherited Destroy();
end;
function TclJSONObject.GetCount: Integer;
begin
Result := FMembers.Count;
end;
function TclJSONObject.BooleanByName(const AName: string): Boolean;
begin
Result := BooleanByName(WideString(AName));
end;
function TclJSONObject.BooleanByName(const AName: WideString): Boolean;
var
pair: TclJSONPair;
begin
pair := MemberByName(AName);
if (pair <> nil) then
begin
if not (pair.Value is TclJSONValue) then
begin
raise EclJSONError.Create(UnexpectedDataType, UnexpectedDataTypeCode);
end;
Result := (pair.ValueString = 'true');
end else
begin
Result := False;
end;
end;
{$IFDEF DELPHI2009}
procedure TclJSONObject.BuildJSONString(ABuffer: TStringBuilder);
const
delimiter: array[Boolean] of string = ('', ', ');
var
i: Integer;
begin
ABuffer.Append('{');
for i := 0 to Count - 1 do
begin
ABuffer.Append(delimiter[i > 0]);
ABuffer.Append(Members[i].GetJSONString());
end;
ABuffer.Append('}');
end;
{$ELSE}
function TclJSONObject.BuildJSONString: string;
const
delimiter: array[Boolean] of string = ('', ', ');
var
i: Integer;
begin
Result := '{';
for i := 0 to Count - 1 do
begin
Result := Result + delimiter[i > 0] + Members[i].GetJSONString();
end;
Result := Result + '}';
end;
{$ENDIF}
function TclJSONObject.GetMember(Index: Integer): TclJSONPair;
begin
Result := TclJSONPair(FMembers[Index]);
end;
function TclJSONObject.GetValueWideString: WideString;
begin
Result := '';
end;
function TclJSONObject.MemberByName(const AName: WideString): TclJSONPair;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Members[i];
if (Result.NameWideString = AName) then Exit;
end;
Result := nil;
end;
function TclJSONObject.ObjectByName(const AName: WideString): TclJSONObject;
var
pair: TclJSONPair;
begin
pair := MemberByName(AName);
if (pair <> nil) then
begin
if not (pair.Value is TclJSONObject) then
begin
raise EclJSONError.Create(UnexpectedDataType, UnexpectedDataTypeCode);
end;
Result := TclJSONObject(pair.Value);
end else
begin
Result := nil;
end;
end;
function TclJSONObject.ObjectByName(const AName: string): TclJSONObject;
begin
Result := ObjectByName(WideString(AName));
end;
function TclJSONObject.MemberByName(const AName: string): TclJSONPair;
begin
Result := MemberByName(WideString(AName));
end;
procedure TclJSONObject.SetValueWideString(const AValue: WideString);
begin
end;
function TclJSONObject.ValueByName(const AName: string): string;
begin
Result := string(ValueByName(WideString(AName)));
end;
function TclJSONObject.ValueByName(const AName: WideString): WideString;
var
pair: TclJSONPair;
begin
pair := MemberByName(AName);
if (pair <> nil) then
begin
Result := pair.ValueWideString;
end else
begin
Result := '';
end;
end;
{ TclJSONPair }
constructor TclJSONPair.Create;
begin
inherited Create();
FValue := nil;
end;
destructor TclJSONPair.Destroy;
begin
SetValue(nil);
inherited Destroy();
end;
{$IFDEF DELPHI2009}
procedure TclJSONPair.BuildJSONString(ABuffer: TStringBuilder);
begin
ABuffer.Append(EncodeString(NameWideString));
ABuffer.Append(': ');
ABuffer.Append(Value.GetJSONString());
end;
{$ELSE}
function TclJSONPair.BuildJSONString: string;
begin
Result := EncodeString(NameWideString) + ': ' + Value.GetJSONString();
end;
{$ENDIF}
function TclJSONPair.GetName: string;
begin
Result := string(FName);
end;
function TclJSONPair.GetValueWideString: WideString;
begin
if (Value <> nil) then
begin
Result := Value.ValueWideString;
end else
begin
Result := '';
end;
end;
procedure TclJSONPair.SetName(const AValue: string);
begin
FName := WideString(AValue);
end;
procedure TclJSONPair.SetValue(const AValue: TclJSONBase);
begin
FValue.Free();
FValue := AValue;
end;
procedure TclJSONPair.SetValueWideString(const AValue: WideString);
begin
if (Value <> nil) then
begin
Value.ValueWideString := AValue;
end;
end;
{ TclJSONArray }
function TclJSONArray.Add(AItem: TclJSONBase): TclJSONBase;
begin
if (AItem <> nil) then
begin
FItems.Add(AItem);
end;
Result := AItem;
end;
constructor TclJSONArray.Create;
begin
inherited Create();
FItems := TObjectList.Create(True);
end;
destructor TclJSONArray.Destroy;
begin
FItems.Free();
inherited Destroy();
end;
function TclJSONArray.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TclJSONArray.GetItem(Index: Integer): TclJSONBase;
begin
Result := TclJSONBase(FItems[Index]);
end;
function TclJSONArray.GetObject(Index: Integer): TclJSONObject;
var
item: TclJSONBase;
begin
item := Items[Index];
if not (item is TclJSONObject) then
begin
raise EclJSONError.Create(UnexpectedDataType, UnexpectedDataTypeCode);
end;
Result := TclJSONObject(item);
end;
{$IFDEF DELPHI2009}
procedure TclJSONArray.BuildJSONString(ABuffer: TStringBuilder);
const
delimiter: array[Boolean] of string = ('', ', ');
var
i: Integer;
begin
ABuffer.Append('[');
for i := 0 to Count - 1 do
begin
ABuffer.Append(delimiter[i > 0]);
ABuffer.Append(Items[i].GetJSONString());
end;
ABuffer.Append(']');
end;
{$ELSE}
function TclJSONArray.BuildJSONString: string;
const
delimiter: array[Boolean] of string = ('', ', ');
var
i: Integer;
begin
Result := '[';
for i := 0 to Count - 1 do
begin
Result := Result + delimiter[i > 0] + Items[i].GetJSONString();
end;
Result := Result + ']';
end;
{$ENDIF}
function TclJSONArray.GetValueWideString: WideString;
begin
Result := '';
end;
procedure TclJSONArray.SetValueWideString(const AValue: WideString);
begin
end;
{ TclJSONValue }
constructor TclJSONValue.Create(const AValue: string);
begin
inherited Create();
ValueString := AValue;
end;
constructor TclJSONValue.Create(const AValue: WideString);
begin
inherited Create();
ValueWideString := AValue;
end;
constructor TclJSONValue.Create;
begin
inherited Create();
FValue := '';
end;
{$IFDEF DELPHI2009}
procedure TclJSONValue.BuildJSONString(ABuffer: TStringBuilder);
begin
ABuffer.Append(ValueString);
end;
{$ELSE}
function TclJSONValue.BuildJSONString: string;
begin
Result := ValueString;
end;
{$ENDIF}
function TclJSONValue.GetValueWideString: WideString;
begin
Result := FValue;
end;
procedure TclJSONValue.SetValueWideString(const AValue: WideString);
begin
FValue := AValue;
end;
{ TclJSONString }
{$IFDEF DELPHI2009}
procedure TclJSONString.BuildJSONString(ABuffer: TStringBuilder);
begin
ABuffer.Append(EncodeString(ValueWideString));
end;
{$ELSE}
function TclJSONString.BuildJSONString: string;
begin
Result := EncodeString(ValueWideString);
end;
{$ENDIF}
{ EclJSONError }
constructor EclJSONError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean);
begin
inherited Create(AErrorMsg);
FErrorCode := AErrorCode;
end;
{ TclJSONBoolean }
constructor TclJSONBoolean.Create;
begin
inherited Create();
Value := False;
end;
constructor TclJSONBoolean.Create(AValue: Boolean);
begin
inherited Create();
Value := AValue;
end;
function TclJSONBoolean.GetValue: Boolean;
begin
Result := (JsonBoolean[True] = ValueWideString);
end;
procedure TclJSONBoolean.SetValue(const Value: Boolean);
begin
ValueWideString := JsonBoolean[Value];
end;
procedure TclJSONBoolean.SetValueWideString(const AValue: WideString);
begin
if (JsonBoolean[True] = AValue) then
begin
inherited SetValueWideString(JsonBoolean[True]);
end else
begin
inherited SetValueWideString(JsonBoolean[False]);
end;
end;
end.
|
unit nsSettingsConst;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Модуль: "w:/common/components/gui/Garant/VCM/View/ParentAndChild/nsSettingsConst.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi F1 Like Application::F1Like::View::ParentAndChild::nsSettingsConst
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\common\components\gui\f1LikeAppDefine.inc}
interface
uses
vtNavigator
;
const
{ Settings Const }
gi_Internal = 'Внутренняя';
pi_Navigator_RightSize = gi_Internal + '/Навигатор/Правый размер';
pi_Navigator_LeftSize = gi_Internal + '/Навигатор/Левый размер';
dv_Navigator_LeftSize = 200;
dv_Navigator_RightSize = 200;
gi_IfaceSettings = 'Настройки интерфейса';
piHistoryItems = gi_IfaceSettings + '/HistoryItems';
cv6xHistoryItems = 25;
dvHistoryItems = cv6xHistoryItems;
pi_LeftNavigator = gi_IfaceSettings + '/Левый навигатор';
dv_LeftNavigator = vtNavigator.nsNormal;
pi_RightNavigator = gi_IfaceSettings + '/Правый навигатор';
dv_RightNavigator = vtNavigator.nsNormal;
pi_lnAutoHideFloat = pi_LeftNavigator + '/AutoFloat';
dv_lnAutoHideFloat = False;
pi_rnAutoHideFloat = pi_RightNavigator + '/AutoFloat';
dv_rnAutoHideFloat = False;
implementation
end. |
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.6 10/26/2004 9:36:28 PM JPMugaas
Updated ref.
Rev 1.5 4/19/2004 5:05:50 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.4 2004.02.03 5:45:30 PM czhower
Name changes
Rev 1.3 1/22/2004 4:39:48 PM SPerry
fixed set problems
Rev 1.2 10/19/2003 2:27:04 PM DSiders
Added localization comments.
Rev 1.1 4/7/2003 04:03:28 PM JPMugaas
User can now descover what output a parser may give.
Rev 1.0 2/19/2003 10:13:16 PM JPMugaas
Moved parsers to their own classes.
}
unit IdFTPListParseBullGCOS7;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase;
type
TIdFTPLPGOS7 = class(TIdFTPLineOwnedList)
protected
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseBullGCOS7"'*)
implementation
uses
IdException,
IdGlobal, IdFTPCommon, IdFTPListTypes, IdGlobalProtocols, IdStrings, SysUtils;
{ TIdFTPLPGOS7 }
class function TIdFTPLPGOS7.CheckListing(AListing: TStrings;
const ASysDescript: String = ''; const ADetails: Boolean = True): Boolean;
var
LData : String;
{
- - -----0 SEPT SYSADMIN AUG 26, 1997 SEQ1
- - -----0 SEPT SYSADMIN AUG 26, 1997 SEQ2
123456789012345678901234567890123456789012345678901234567890
1 2 3 4 5 6
}
function NumericOrSpace(const ALine : String): Boolean;
var
i : Integer;
begin
Result := True;
for i := 1 to Length(ALine) do
begin
if (not IsNumeric(ALine[i])) and (not CharEquals(ALine, i, ' ')) then
begin
Result := False;
Break;
end;
end;
end;
begin
Result := False;
if AListing.Count > 0 then
begin
LData := AListing[0];
Result := (Length(LData) > 54) and
(CharIsInSet(LData, 1, '-d')) and
(LData[2] = ' ') and
(CharIsInSet(LData, 3, '-dsm')) and
(LData[4] = ' ') and
(LData[24] = ' ') and
(LData[25] <> ' ') and
(NumericOrSpace(Copy(LData, 46, 2))) and
(CharIsInSet(LData, 48, ', ')) and
(LData[49] = ' ') and
(NumericOrSpace(Copy(LData, 50, 4))) and
(LData[54] = ' ') and
(LData[55] <> ' ');
end;
end;
class function TIdFTPLPGOS7.GetIdent: String;
begin
Result := 'Bull GCOS7'; {do not localize}
end;
class function TIdFTPLPGOS7.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
{
# From: FTP 7 - File Transfer Protocol
# This was a presentation that was made available in PDF form
# http://www.bull.com/servers/gcos7/ce7/ftp7-en.pdf
# reconstructed from screen-shots displayed in the presentation
}
var
LBuf : String;
LI : TIdOwnerFTPListItem;
begin
LI := AItem as TIdOwnerFTPListItem;
if LI.Data[1] = 'd' then begin
LI.ItemType := ditDirectory;
end else begin
LI.ItemType := ditFile;
end;
LI.FileName := Copy(AItem.Data, 55, MaxInt);
LBuf := StringReplace(Copy(AItem.Data, 42, 12), ',', '', [rfReplaceAll]);
if not IsWhiteString(LBuf) then begin
LI.ModifiedDate := DateStrMonthDDYY(LBuf, ' ');
end;
LI.OwnerName := Trim(Copy(AItem.Data, 25, 17));
//I don't think size is provided
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPGOS7);
finalization
UnRegisterFTPListParser(TIdFTPLPGOS7);
end.
|
unit nsWindowsListPrim;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "UserInteraction"
// Автор: Морозов М.А.
// Модуль: "w:/common/components/gui/Garant/VCM/UserInteraction/nsWindowsListPrim.pas"
// Начат: 2005/06/07 11:31:00
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Operations::OfficeLike::UserInteraction::WindowsListSupport::TnsWindowsListPrim
//
// класс управляющий списком окон
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
uses
l3Interfaces
{$If not defined(NoVCM)}
,
vcmExternalInterfaces
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
,
vcmInterfaces
{$IfEnd} //not NoVCM
,
l3Core,
l3Tree_TLB
{$If not defined(NoVCM)}
,
vcmMainForm
{$IfEnd} //not NoVCM
,
l3ProtoObject,
OfficeLikeAppInterfaces
;
type
TnsUniqueName = class(Tl3ProtoObject)
{* класс позволяющий получать уникальные имена в списке благодаря добавлению в конце повторяющихся слов значение счетчика повторения. Например Слово, Слово (1), Слово (2) и т.д }
private
// private fields
f_Unique : IvcmStrings;
private
// private methods
function MakeName(const aName: Il3CString): Il3CString;
{* возвращает уникальное имя }
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
// public methods
constructor Create; reintroduce;
end;//TnsUniqueName
TnsWindowsListPrim = class(Tl3ProtoObject)
{* класс управляющий списком окон }
private
// private fields
f_Root : Il3Node;
{* Поле для свойства Root}
private
// private methods
function CheckLength(const aName: Il3CString): Il3CString;
{* проверяет не выходит ли размер имени за допустимые пределы и корректирует при необходимости }
function NsGetWindowCaption(aForm: TvcmMainForm): Il3CString;
{* отрезает префикс оставляю только информацию о текущем контенте, а именно _caption формы находящейся в Parent зоне главной формы }
protected
// property methods
function pm_GetRoot: Il3Node;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
// public methods
function FindNode(const aForm: IvcmEntityForm): Il3Node;
{* возвращает Il3Node для формы aForm }
procedure Remove(const aForm: IvcmEntityForm);
{* удаляет форму из списка }
procedure Reload;
{* перезагружает список }
public
// public properties
property Root: Il3Node
read pm_GetRoot;
{* Root дерева окон. Загружается при первом обращении }
end;//TnsWindowsListPrim
implementation
uses
l3String
{$If not defined(NoVCM)}
,
vcmStringList
{$IfEnd} //not NoVCM
,
l3Nodes,
SysUtils
{$If not defined(NoVCM)}
,
vcmBase
{$IfEnd} //not NoVCM
,
nsWindowNode,
l3Chars
;
// start class TnsWindowsListPrim
function TnsWindowsListPrim.CheckLength(const aName: Il3CString): Il3CString;
//#UC START# *4ADC538702FA_4ADC5146016D_var*
const
cMaxWordLength = 70;
{* - максимальная длинна слова в списке. }
//#UC END# *4ADC538702FA_4ADC5146016D_var*
begin
//#UC START# *4ADC538702FA_4ADC5146016D_impl*
if (l3Len(aName) > cMaxWordLength) then
Result := l3Cat(l3Copy(aName, 0, cMaxWordLength - 3), '...')
else
Result := aName;
//#UC END# *4ADC538702FA_4ADC5146016D_impl*
end;//TnsWindowsListPrim.CheckLength
function TnsWindowsListPrim.NsGetWindowCaption(aForm: TvcmMainForm): Il3CString;
//#UC START# *4ADC564B01E9_4ADC5146016D_var*
//#UC END# *4ADC564B01E9_4ADC5146016D_var*
begin
//#UC START# *4ADC564B01E9_4ADC5146016D_impl*
Result := l3StringReplace(aForm.CCaption, l3PCharLen(aForm.CaptionPrefix), l3PCharLen(''), [rfReplaceAll]);
Result := l3LTrim(Result, cc_AllChars - cc_ANSILetter);
//#UC END# *4ADC564B01E9_4ADC5146016D_impl*
end;//TnsWindowsListPrim.NsGetWindowCaption
function TnsWindowsListPrim.FindNode(const aForm: IvcmEntityForm): Il3Node;
//#UC START# *4ADC54290390_4ADC5146016D_var*
//#UC END# *4ADC54290390_4ADC5146016D_var*
var
l_Child : Il3Node;
l_Window : InsWindow;
begin
//#UC START# *4ADC54290390_4ADC5146016D_impl*
Result := nil;
if Assigned(f_Root) then
begin
l_Child := f_Root.ChildNode;
while Assigned(l_Child) do
begin
if Supports(l_Child, InsWindow, l_Window) then
try
if l_Window.Form = aForm then
begin
Result := l_Child;
Break;
end;
finally
l_Window := nil;
end;
if l_Child.IsLast then
l_Child := nil
else
l_Child := l_Child.NextNode;
end;
end;
//#UC END# *4ADC54290390_4ADC5146016D_impl*
end;//TnsWindowsListPrim.FindNode
procedure TnsWindowsListPrim.Remove(const aForm: IvcmEntityForm);
//#UC START# *4ADC5467036A_4ADC5146016D_var*
//#UC END# *4ADC5467036A_4ADC5146016D_var*
var
l_Node : Il3Node;
begin
//#UC START# *4ADC5467036A_4ADC5146016D_impl*
l_Node := FindNode(aForm);
if Assigned(l_Node) then
l_Node.Remove;
//#UC END# *4ADC5467036A_4ADC5146016D_impl*
end;//TnsWindowsListPrim.Remove
procedure TnsWindowsListPrim.Reload;
//#UC START# *4ADC54070106_4ADC5146016D_var*
//#UC END# *4ADC54070106_4ADC5146016D_var*
var
l_Unique : TnsUniqueName;
l_Index : Integer;
begin
//#UC START# *4ADC54070106_4ADC5146016D_impl*
f_Root := nil;
l_Unique := TnsUniqueName.Create;
try
f_Root := Tl3PlaceNode.Make;
for l_Index := 0 to Pred(vcmDispatcher.FormDispatcher.MainFormsCount) do
with vcmDispatcher.FormDispatcher do
f_Root.InsertChild(TnsWindowNode.Make(
MainForm[l_Index],
l3PCharLen(l_Unique.MakeName(CheckLength(
nsGetWindowCaption((MainForm[l_Index].VCLWinControl As TvcmMainForm)))))));
finally
FreeAndNil(l_Unique);
end;//try..finally
//#UC END# *4ADC54070106_4ADC5146016D_impl*
end;//TnsWindowsListPrim.Reload
// start class TnsUniqueName
function TnsUniqueName.MakeName(const aName: Il3CString): Il3CString;
//#UC START# *4ADC560A0041_4ADC55470317_var*
//#UC END# *4ADC560A0041_4ADC55470317_var*
var
l_PInt : PInteger;
l_Indx : Integer;
begin
//#UC START# *4ADC560A0041_4ADC55470317_impl*
Result := aName;
l_Indx := f_Unique.IndexOf(Result);
if (l_Indx = -1) then
begin
New(l_PInt);
l_PInt^ := 0;
f_Unique.AddObject(aName, TObject(l_PInt));
end//l_Indx = -1
else
begin
l_PInt := PInteger(f_Unique.Objects[l_Indx]);
Inc(l_PInt^);
Result := l3Fmt('%s (%d)', [aName, l_PInt^]);
end;//l_Indx = -1
//#UC END# *4ADC560A0041_4ADC55470317_impl*
end;//TnsUniqueName.MakeName
constructor TnsUniqueName.Create;
//#UC START# *4ADC55A200AD_4ADC55470317_var*
//#UC END# *4ADC55A200AD_4ADC55470317_var*
begin
//#UC START# *4ADC55A200AD_4ADC55470317_impl*
inherited Create;
f_Unique := TvcmStringList.Make;
//#UC END# *4ADC55A200AD_4ADC55470317_impl*
end;//TnsUniqueName.Create
procedure TnsUniqueName.Cleanup;
//#UC START# *479731C50290_4ADC55470317_var*
var
lIndex : Integer;
lPInt : PInteger;
//#UC END# *479731C50290_4ADC55470317_var*
begin
//#UC START# *479731C50290_4ADC55470317_impl*
for lIndex := 0 to Pred(f_Unique.Count) do
begin
lPInt := PInteger(f_Unique.Objects[lIndex]);
Dispose(lPInt);
end;
f_Unique := nil;
inherited;
//#UC END# *479731C50290_4ADC55470317_impl*
end;//TnsUniqueName.Cleanup
procedure TnsUniqueName.ClearFields;
{-}
begin
f_Unique := nil;
inherited;
end;//TnsUniqueName.ClearFields
function TnsWindowsListPrim.pm_GetRoot: Il3Node;
//#UC START# *4ADC531F03B4_4ADC5146016Dget_var*
//#UC END# *4ADC531F03B4_4ADC5146016Dget_var*
begin
//#UC START# *4ADC531F03B4_4ADC5146016Dget_impl*
if not Assigned(f_Root) then
Reload;
Result := f_Root;
//#UC END# *4ADC531F03B4_4ADC5146016Dget_impl*
end;//TnsWindowsListPrim.pm_GetRoot
procedure TnsWindowsListPrim.Cleanup;
//#UC START# *479731C50290_4ADC5146016D_var*
//#UC END# *479731C50290_4ADC5146016D_var*
begin
//#UC START# *479731C50290_4ADC5146016D_impl*
f_Root := nil;
inherited;
//#UC END# *479731C50290_4ADC5146016D_impl*
end;//TnsWindowsListPrim.Cleanup
procedure TnsWindowsListPrim.ClearFields;
{-}
begin
f_Root := nil;
inherited;
end;//TnsWindowsListPrim.ClearFields
end. |
unit RealState.House.Controller;
interface
uses
MVCFramework,
MVCFramework.Commons,
JsonDataObjects;
type
[MVCPath('/api/houses')]
THouseController = class(TMVCController)
public
[MVCPath('/')]
[MVCHTTPMethod([httpGET])]
procedure GetHouses;
[MVCPath('/($id)')]
[MVCHTTPMethod([httpPOST])]
procedure SetFavorite(id: Int64);
end;
implementation
uses
System.StrUtils,
System.SysUtils,
RealState.House.Repository;
procedure THouseController.GetHouses;
var
repository: THouseRepository;
begin
Writeln(Context.Request.PathInfo);
repository := THouseRepository.Create(nil);
try
Render(repository.GetHouses);
finally
repository.Free;
end;
end;
procedure THouseController.SetFavorite(id: Int64);
var
body: TJsonObject;
repository: THouseRepository;
begin
Writeln(Context.Request.PathInfo + ', ' + Context.Request.Body);
body := TJsonObject.Parse(Context.Request.Body) as TJsonObject;
repository := THouseRepository.Create(nil);
try
repository.SetFavorite(id, body['favorite'].BoolValue);
finally
repository.Free;
end;
end;
end.
|
{ Fichier d'implémentation invocable pour Tdemos implémentant Idemos }
unit udemosImpl;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, udemosIntf;
type
{ Tdemos }
Tdemos = class(TInvokableClass, Idemos)
public
function echoEnum(const Value: TEnumTest): TEnumTest; stdcall;
function echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall;
function echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall;
function echoDouble(const Value: Double): Double; stdcall;
end;
implementation
function Tdemos.echoEnum(const Value: TEnumTest): TEnumTest; stdcall;
begin
{TODO : Implémenter la méthode echoEnum }
Result := Value;
end;
function Tdemos.echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall;
begin
{TODO : Implémenter la méthode echoDoubleArray }
Result := Value;
end;
function Tdemos.echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall;
begin
{TODO : Implémenter la méthode echoMyEmployee }
Result := Value;
end;
function Tdemos.echoDouble(const Value: Double): Double; stdcall;
begin
{TODO : Implémenter la méthode echoDouble }
Result := Value;
end;
initialization
{ Les classes invocables doivent être enregistrées }
InvRegistry.RegisterInvokableClass(Tdemos);
end.
|
unit ZMUTF819;
(*
ZMUTF19.pas - Some UTF8/16 utility functions
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
modified 2009-06-25
---------------------------------------------------------------------------*)
{$INCLUDE '.\ZipVers19.inc'}
{$IFDEF VERD6up}
{$WARN UNIT_PLATFORM OFF}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
interface
uses
SysUtils, Windows, Classes, ZipMstr19;
// convert to/from UTF8 characters
function UTF8ToStr(const astr: UTF8String): String;
function StrToUTF8(const ustr: string): UTF8String;
function StrToUTFEx(const astr: AnsiString; cp: cardinal = 0; len: integer =
-1): TZMString;
function UTF8ToWide(const astr: UTF8String; len: integer = -1): TZMWideString;
function PWideToUTF8(const pwstr: PWideChar; len: integer = -1): UTF8String;
function WideToUTF8(const astr: TZMWideString; len: integer = -1): UTF8String;
// test for valid UTF8 character(s) > 0 _ some, 0 _ none, < 0 _ invalid
function ValidUTF8(pstr: PAnsiChar; len: integer): integer; overload;
function ValidUTF8(const str: AnsiString; len: integer = -1): integer; overload;
{$IFDEF UNICODE}
//overload;
function ValidUTF8(const str: UTF8String; len: integer = -1): integer; overload;
{$ENDIF}
// convert to UTF8 (if needed)
function AsUTF8Str(const zstr: TZMString): UTF8String;
function UTF8SeqLen(c: AnsiChar): integer;
function IsUTF8Trail(c: AnsiChar): boolean;
function PUTF8ToStr(const raw: PAnsiChar; len: integer): string;
function PUTF8ToWideStr(const raw: PAnsiChar; len: integer): TZMWideString;
function StrToWideEx(const astr: AnsiString; cp: cardinal; len: integer):
TZMWideString;
// convert to Ansi/OEM escaping unsupported characters
function WideToSafe(const wstr: TZMWideString; ToOEM: boolean): AnsiString;
// test all characters are supported
function WideIsSafe(const wstr: TZMWideString; ToOEM: boolean): Boolean;
{$IFNDEF UNICODE}
function UTF8ToSafe(const ustr: AnsiString; ToOEM: boolean): AnsiString;
function PUTF8ToSafe(const raw: PAnsiChar; len: integer): AnsiString;
function UTF8IsSafe(const ustr: AnsiString; ToOEM: boolean): Boolean;
// only applicable when converting to OEM
function AnsiIsSafe(const ustr: AnsiString; ToOEM: boolean): Boolean;
{$ENDIF}
// -------------------------- ------------ -------------------------
implementation
uses ZMCompat19, ZMUtils19;
function PUTF8ToWideStr(const raw: PAnsiChar; len: integer): TZMWideString;
const
MB_ERR_INVALID_CHARS = $00000008; // error for invalid chars
var
wcnt: integer;
flg: cardinal;
p: pAnsiChar;
rlen: Integer;
begin
Result := '';
if (raw = nil) or (len = 0) then
exit;
rlen := Len;
if len < 0 then
begin
len := -1;
p := raw;
rlen := 0;
while p^ <> #0 do
begin
inc(p);
Inc(rlen);
end;
end;
rlen := rlen * 2;
{$IFDEF UNICODE}
flg := MB_ERR_INVALID_CHARS;
{$ELSE}
if Win32MajorVersion > 4 then
flg := MB_ERR_INVALID_CHARS
else
flg := 0;
{$ENDIF}
SetLength(Result, rlen); // plenty of room
wcnt := MultiByteToWideChar(CP_UTF8, flg, raw, len,
PWideChar(Result), rlen);
if wcnt = 0 then // try again assuming Ansi
wcnt := MultiByteToWideChar(0, flg, raw, len,
PWideChar(Result), rlen);
if (wcnt > 0) and (len = -1) then
dec(wcnt); // don't want end null
SetLength(Result, wcnt);
end;
function PUTF8ToStr(const raw: PAnsiChar; len: integer): string;
begin
Result := PUTF8ToWideStr(raw, len);
end;
function PWideToUTF8(const pwstr: PWideChar; len: integer = -1): UTF8String;
var
cnt: integer;
begin
Result := '';
if len < 0 then
len := -1;
if len = 0 then
exit;
cnt := WideCharToMultiByte(CP_UTF8, 0, pwstr, len, nil, 0, nil, nil);
if cnt > 0 then
begin
SetLength(Result, cnt);
cnt := WideCharToMultiByte(CP_UTF8, 0, pwstr, len,
PAnsiChar(Result), cnt, nil, nil);
if cnt < 1 then
Result := ''; // oops - something went wrong
if (len = -1) and (Result[cnt] = #0) then
SetLength(Result, cnt - 1); // remove trailing nul
end//;
else
RaiseLastOSError;
end;
function WideToUTF8(const astr: TZMWideString; len: integer = -1): UTF8String;
begin
if len < 0 then
len := Length(astr);
Result := PWideToUTF8(@astr[1], len);
end;
function UTF8ToWide(const astr: UTF8String; len: integer = -1): TZMWideString;
begin
Result := '';
if len < 0 then
len := Length(astr);
Result := PUTF8ToWideStr(PAnsiChar(astr), len);
end;
function UTF8ToStr(const astr: UTF8String): String;
begin
Result := PUTF8ToStr(PAnsiChar(astr), Length(astr));
end;
function StrToUTF8(const ustr: string): UTF8String;
var
wtemp: TZMWideString;
begin
wtemp := ustr;
Result := WideToUTF8(wtemp, -1);
end;
function StrToUTFEx(const astr: AnsiString; cp: cardinal = 0; len: integer =
-1): TZMString;
var
ws: TZMWideString;
begin
ws := StrToWideEx(astr, cp, len);
{$IFDEF UNICODE}
Result := ws;
{$ELSE}
Result := StrToUTF8(ws);
{$ENDIF}
end;
function IsUTF8Trail(c: AnsiChar): boolean;
begin
Result := (Ord(c) and $C0) = $80;
end;
function UTF8SeqLen(c: AnsiChar): integer;
var
u8: cardinal;
begin
Result := 1;
u8 := ord(c);
if u8 >= $80 then
begin
if (u8 and $FE) = $FC then
Result := 6
else
if (u8 and $FC) = $F8 then
Result := 5
else
if (u8 and $F8) = $F0 then
Result := 4
else
if (u8 and $F0) = $E0 then
Result := 3
else
if (u8 and $E0) = $C0 then
Result := 2
else
Result := -1; // trailing byte - invalid
end;
end;
// test for valid UTF8 character(s) > 0 _ some, 0 _ none, < 0 _ invalid
function ValidUTF8(const str: AnsiString; len: integer): integer;
var
i, j, ul: integer;
begin
if len < 0 then
len := Length(str);
Result := 0;
i := 1;
while (i <= len) do
begin
ul := UTF8SeqLen(str[i]);
inc(i);
if ul <> 1 then
begin
if (ul < 1) or ((i + ul -2) > len) then
begin
Result := -1; // invalid
break;
end;
// first in seq
for j := 0 to ul -2 do
begin
if (ord(str[i]) and $C0) <> $80 then
begin
result := -1;
break;
end;
inc(i);
end;
if Result >= 0 then
inc(Result) // was valid so count it
else
break;
end;
end;
end;
// test for valid UTF8 character(s) > 0 _ some, 0 _ none, < 0 _ invalid
function ValidUTF8(pstr: PAnsiChar; len: integer): integer;
var
// i,
j, ul: integer;
begin
// if len < 0 then
// len := Length(str);
Result := 0;
// i := 1;
while (len > 0) do
begin
ul := UTF8SeqLen(pstr^);
inc(pstr);
Dec(len);
if ul <> 1 then
begin
// if (ul < 1) or ((i + ul -2) > len) then
if (ul < 1) or (( ul -1) > len) then
begin
Result := -1; // invalid
break;
end;
// first in seq
for j := 0 to ul -2 do
begin
if (ord(pstr^) and $C0) <> $80 then
begin
result := -1;
break;
end;
inc(pstr);
Dec(len);
end;
if Result >= 0 then
inc(Result) // was valid so count it
else
break;
end;
end;
end;
{$IFDEF UNICODE}
function ValidUTF8(const str: UTF8String; len: integer = -1): integer;
var
i, j, ul: integer;
begin
if len < 0 then
len := Length(str);
Result := 0;
i := 1;
while (i <= len) do
begin
ul := UTF8SeqLen(str[i]);
inc(i);
if ul <> 1 then
begin
if (ul < 1) or ((i + ul -2) > len) then
begin
Result := -1; // invalid
break;
end;
// first in seq
for j := 0 to ul -2 do
begin
if (ord(str[i]) and $C0) <> $80 then
begin
result := -1;
break;
end;
inc(i);
end;
if Result >= 0 then
inc(Result) // was valid so count it
else
break;
end;
end;
end;
{$ENDIF}
function AsUTF8Str(const zstr: TZMString): UTF8String;
begin
{$IFDEF UNICODE}
Result := UTF8String(zstr);
{$ELSE}
if ValidUTF8(zstr, -1) < 0 then
Result := StrToUTF8(zstr)
else
Result := zstr;
{$ENDIF}
end;
function StrToWideEx(const astr: AnsiString; cp: cardinal; len: integer):
TZMWideString;
var
cnt: integer;
s: AnsiString;
wcnt: integer;
begin
Result := '';
if len < 0 then
len := Length(astr);
if len = 0 then
exit;
wcnt := MultiByteToWideChar(cp, 0, PAnsiChar(astr), len, nil, 0);
if wcnt > 0 then
begin
SetLength(Result, wcnt);
cnt := MultiByteToWideChar(cp, 0, PAnsiChar(astr), len,
pWideChar(Result), wcnt);
if cnt < 1 then
Result := ''; // oops - something went wrong
end
else
// RaiseLastOSError;
begin
s := astr; // assume it is Ansi
if (len > 0) and (len < length(astr)) then
SetLength(s, len);
Result := String(s);
end;
end;
// convert to MultiByte escaping unsupported characters
function WideToSafe(const wstr: TZMWideString; ToOEM: boolean): AnsiString;
{$IFNDEF UNICODE}
const WC_NO_BEST_FIT_CHARS = $00000400;
{$endif}
var
Bad: Bool;
c: AnsiChar;
cnt: Integer;
i: Integer;
pa: PAnsiChar;
tmp: AnsiString;
subst: array [0..1] of AnsiChar;
toCP: cardinal;
wc: WideChar;
wlen: Integer;
begin
Result := '';
if wstr <> '' then
begin
if ToOEM then
toCP := CP_OEMCP
else
toCP := CP_ACP;
subst[0] := #$1B; // substitute char - escape
subst[1] := #0;
cnt := WideCharToMultiByte(ToCP, WC_NO_BEST_FIT_CHARS, PWideChar(wstr),
Length(wstr), nil, 0, PAnsiChar(@subst), @Bad);
if cnt > 0 then
begin
SetLength(Result, cnt);
cnt := WideCharToMultiByte(ToCP, WC_NO_BEST_FIT_CHARS, PWideChar(wstr),
Length(wstr), PAnsiChar(Result), cnt, PAnsiChar(@subst), @Bad);
if cnt < 1 then
Result := ''; // oops - something went wrong
end;
if Bad then
begin
tmp := Result;
Result := '';
pa := PAnsiChar(tmp);
i := 1;
wc := #0;
wlen := Length(wstr);
while (pa^ <> #0) do
begin
c := pa^;
if i < wlen then
begin
wc := wstr[i];
inc(i);
end;
if c = #$1B then
Result := Result + '#$' + AnsiString(IntToHex(Ord(wc), 4))
else
Result := Result + c;
pa := CharNextExA(toCP, pa, 0);
end;
end;
end;
end;
{$IFNDEF UNICODE}
function UTF8ToSafe(const ustr: AnsiString; ToOEM: boolean): AnsiString;
begin
Result := WideToSafe(UTF8ToWide(ustr), ToOEM);
end;
{$ENDIF}
{$IFNDEF UNICODE}
function PUTF8ToSafe(const raw: PAnsiChar; len: integer): AnsiString;
begin
Result := WideToSafe(PUTF8ToWideStr(raw, len), false);
end;
{$ENDIF}
// test all characters are supported
function WideIsSafe(const wstr: TZMWideString; ToOEM: boolean): Boolean;
var
Bad: Bool;
cnt: Integer;
toCP: cardinal;
begin
Result := true;
if ToOEM then
toCP := CP_OEMCP
else
toCP := CP_ACP;
if wstr <> '' then
begin
cnt := WideCharToMultiByte(toCP, 0, PWideChar(wstr), Length(wstr),
nil, 0, nil, @Bad);
Result := (not Bad) and (cnt > 0);
end;
end;
{$IFNDEF UNICODE}
function UTF8IsSafe(const ustr: AnsiString; ToOEM: boolean): Boolean;
begin
Result := WideIsSafe(UTF8ToWide(ustr), ToOEM);
end;
{$ENDIF}
{$IFNDEF UNICODE}
// only applicable when converting to OEM
function AnsiIsSafe(const ustr: AnsiString; ToOEM: boolean): Boolean;
begin
Result := True;
if ToOEM then
Result := WideIsSafe(WideString(ustr), ToOEM);
end;
{$ENDIF}
end.
|
unit atUserListHelper;
// Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atUserListHelper.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatUserListHelper" MUID: (4B6C27F50058)
interface
uses
l3IntfUses
, DynamicTreeUnit
, BaseTypesUnit
, SecurityUnit
;
type
TatArrayOfUID = array of TUid;
TatBaseNB2AoUHlpr = {abstract} class
public
ArrOfUID: TatArrayOfUID;
protected
function IsAdd(const aProfileNode: IProfileNode): Boolean; virtual; abstract;
public
procedure Proc(const aNode: INodeBase); virtual;
end;//TatBaseNB2AoUHlpr
TatUserListHelper = class
public
class function UserTree2TatArrayOfUID(const aRoot: INodeBase): TatArrayOfUID; virtual;
class function GetFilteredUserTree(const aRoot: INodeBase;
aFlags: Longword): INodeBase; virtual;
class function GetAdapterTestUIDs(isActiveOnly: Boolean = False): TatArrayOfUID; virtual;
class function GetOnlyAdapterTestUIDs(const aRoot: INodeBase): TatArrayOfUID; virtual;
class function GetMyUID: TUid; virtual;
end;//TatUserListHelper
implementation
uses
l3ImplUses
, atNodeHelper
, SysUtils
, atGblAdapterWorker
, atStringHelper
, IOUnit
//#UC START# *4B6C27F50058impl_uses*
//#UC END# *4B6C27F50058impl_uses*
;
type
TatNB2AoUHlpr = class(TatBaseNB2AoUHlpr)
protected
function IsAdd(const aProfileNode: IProfileNode): Boolean; override;
end;//TatNB2AoUHlpr
TatNB2AoUByNameHlpr = class(TatNB2AoUHlpr)
public
UserName: AnsiString;
protected
function IsAdd(const aProfileNode: IProfileNode): Boolean; override;
end;//TatNB2AoUByNameHlpr
procedure TatBaseNB2AoUHlpr.Proc(const aNode: INodeBase);
//#UC START# *4B6C3A240321_4B6C39F4013F_var*
var
l_ProfileNode : IProfileNode;
l_Length : Integer;
//#UC END# *4B6C3A240321_4B6C39F4013F_var*
begin
//#UC START# *4B6C3A240321_4B6C39F4013F_impl*
if Supports(aNode, IProfileNode, l_ProfileNode) AND IsAdd(l_ProfileNode) then
begin
l_Length := Length(ArrOfUID);
SetLength(ArrOfUID, l_Length+1);
ArrOfUID[l_Length] := l_ProfileNode.GetUid;
end;
//#UC END# *4B6C3A240321_4B6C39F4013F_impl*
end;//TatBaseNB2AoUHlpr.Proc
function TatNB2AoUHlpr.IsAdd(const aProfileNode: IProfileNode): Boolean;
//#UC START# *4B71720A0019_4B716F4402A1_var*
//#UC END# *4B71720A0019_4B716F4402A1_var*
begin
//#UC START# *4B71720A0019_4B716F4402A1_impl*
Result := true;
//#UC END# *4B71720A0019_4B716F4402A1_impl*
end;//TatNB2AoUHlpr.IsAdd
function TatNB2AoUByNameHlpr.IsAdd(const aProfileNode: IProfileNode): Boolean;
//#UC START# *4B71720A0019_4B716F69018B_var*
var
l_Entity : IEntityBase;
l_UserProfile : IUserProfile;
l_Name : IString;
//#UC END# *4B71720A0019_4B716F69018B_var*
begin
//#UC START# *4B71720A0019_4B716F69018B_impl*
Result := false;
if NOT inherited IsAdd(aProfileNode) then Exit;
//
aProfileNode.GetEntity(l_Entity);
if (l_Entity <> nil) AND Supports(l_Entity, IUserProfile, l_UserProfile) then
begin
l_UserProfile.GetName(l_Name);
Result := (l_Name <> nil) AND (TatStringHelper.AStr2DStr(l_Name) = UserName);
end;
//#UC END# *4B71720A0019_4B716F69018B_impl*
end;//TatNB2AoUByNameHlpr.IsAdd
class function TatUserListHelper.UserTree2TatArrayOfUID(const aRoot: INodeBase): TatArrayOfUID;
//#UC START# *4B6C321A01F5_4B6C27F50058_var*
//#UC END# *4B6C321A01F5_4B6C27F50058_var*
begin
//#UC START# *4B6C321A01F5_4B6C27F50058_impl*
Assert(aRoot <> nil, 'aRoot <> nil');
with TatNB2AoUHlpr.Create do
try
TatNodeHelper.LoadNodesThrough(aRoot, FM_SHARED_NONE, -1, Proc);
Result := ArrOfUID;
finally
Free;
end;
//#UC END# *4B6C321A01F5_4B6C27F50058_impl*
end;//TatUserListHelper.UserTree2TatArrayOfUID
class function TatUserListHelper.GetFilteredUserTree(const aRoot: INodeBase;
aFlags: Longword): INodeBase;
//#UC START# *4B70115C0096_4B6C27F50058_var*
var
l_UserFilter : IUserFilter;
l_FilterList : IFilterList;
l_SyncIndex : Integer;
//#UC END# *4B70115C0096_4B6C27F50058_var*
begin
//#UC START# *4B70115C0096_4B6C27F50058_impl*
Assert(aRoot <> nil, 'aRoot <> nil');
l_UserFilter := TatGblAdapterWorker.Instance.GblAdapterDll.MakeUserFilter;
Assert(l_UserFilter <> nil, 'l_UserFilter <> nil');
l_UserFilter.SetFlags(aFlags);
l_FilterList := TatGblAdapterWorker.Instance.GblAdapterDll.MakeFilterList;
Assert(l_FilterList <> nil, 'l_FilterList <> nil');
l_FilterList.Add(l_UserFilter);
//
aRoot.CreateViewEx(
l_FilterList,
FM_USER_FLAG_MASK,
nil, l_SyncIndex, 0, False, False, False,
Result);
//#UC END# *4B70115C0096_4B6C27F50058_impl*
end;//TatUserListHelper.GetFilteredUserTree
class function TatUserListHelper.GetAdapterTestUIDs(isActiveOnly: Boolean = False): TatArrayOfUID;
//#UC START# *4B716C2601D4_4B6C27F50058_var*
var
l_UserManager : IUserManager;
l_Root : INodeBase;
l_Flags : Longword;
//#UC END# *4B716C2601D4_4B6C27F50058_var*
begin
//#UC START# *4B716C2601D4_4B6C27F50058_impl*
l_UserManager := TatGblAdapterWorker.Instance.GblAdapterDll.MakeUserManager;
Assert(l_UserManager <> nil, 'l_UserManager <> nil');
l_UserManager.GetUsersTree(l_Root);
Assert(l_Root <> nil, 'l_Root <> nil');
//
l_Flags := UFF_USER_NOT_SYSTEM or UFF_USER_NOT_CURRENT;
if isActiveOnly then
l_Flags := l_Flags OR UFF_USER_ACTIVE;
//
l_Root := GetFilteredUserTree(l_Root, l_Flags);
Assert(l_Root <> nil, 'l_Root <> nil 2');
//
Result := GetOnlyAdapterTestUIDs(l_Root);
//#UC END# *4B716C2601D4_4B6C27F50058_impl*
end;//TatUserListHelper.GetAdapterTestUIDs
class function TatUserListHelper.GetOnlyAdapterTestUIDs(const aRoot: INodeBase): TatArrayOfUID;
//#UC START# *4B72B96C019B_4B6C27F50058_var*
//#UC END# *4B72B96C019B_4B6C27F50058_var*
begin
//#UC START# *4B72B96C019B_4B6C27F50058_impl*
Assert(aRoot <> nil, 'aRoot <> nil');
with TatNB2AoUByNameHlpr.Create do
try
UserName := TAT_USER_NAME;
TatNodeHelper.LoadNodesThrough(aRoot, FM_SHARED_NONE, -1, Proc);
Result := ArrOfUID;
finally
Free;
end;
//#UC END# *4B72B96C019B_4B6C27F50058_impl*
end;//TatUserListHelper.GetOnlyAdapterTestUIDs
class function TatUserListHelper.GetMyUID: TUid;
//#UC START# *4B758B3100BF_4B6C27F50058_var*
var
l_UserManager : IUserManager;
l_MyProfile : IUserProfile;
//#UC END# *4B758B3100BF_4B6C27F50058_var*
begin
//#UC START# *4B758B3100BF_4B6C27F50058_impl*
l_UserManager := TatGblAdapterWorker.Instance.GblAdapterDll.MakeUserManager;
Assert(l_UserManager <> nil, 'l_UserManager <> nil');
l_UserManager.GetSelfProfile(l_MyProfile);
Assert(l_MyProfile <> nil, 'l_MyProfile <> nil');
Result := l_MyProfile.GetUid;
//#UC END# *4B758B3100BF_4B6C27F50058_impl*
end;//TatUserListHelper.GetMyUID
end.
|
unit uJSONPessoa;
interface
uses Data.DBXJSONReflect, System.Generics.Collections, Data.DBXJSONCommon,
Data.DBXJSON, uPessoa;
type
TJSONPessoa = class
public
function JsonToObject(value: string): TPessoa;
function JsonToObjectList(value: string): TPessoaList;
function ObjectToJson(value: TPessoa): string; overload;
function ObjectToJson(value: TPessoaList): string; overload;
end;
var
PessoaListConverter: TObjectsConverter;
PessoaListReverter: TObjectsReverter;
implementation
function TJSONPessoa.JsonToObject(value: string): TPessoa;
var Json: TJSONObject;
UnMar: TJSONUnMarshal;
begin
Json := TJSONObject.ParseJSONValue(value) as TJSONObject;
UnMar := TJSONUnMarshal.Create;
try
Result := UnMar.UnMarshal(Json) as TPessoa;
finally
UnMar.Free;
end;
end;
function TJSONPessoa.ObjectToJson(value: TPessoa): string;
var Mar: TJSONMarshal;
begin
Mar := TJSONMarshal.Create(TJSONConverter.Create);
try
Result := (Mar.Marshal(value) as TJSONObject).ToString();
finally
Mar.Free;
end;
end;
function TJSONPessoa.JsonToObjectList(value: string): TPessoaList;
var Json: TJSONObject;
UnMar: TJSONUnMarshal;
begin
Json := TJSONObject.ParseJSONValue(value) as TJSONObject;
UnMar := TJSONUnMarshal.Create;
UnMar.RegisterReverter(TPessoaList, 'Pessoas', PessoaListReverter);
try
Result := UnMar.UnMarshal(Json) as TPessoaList;
finally
UnMar.Free;
end;
end;
function TJSONPessoa.ObjectToJson(value: TPessoaList): string;
var Mar: TJSONMarshal;
begin
Mar := TJSONMarshal.Create(TJSONConverter.Create);
Mar.RegisterConverter(TPessoaList, 'Pessoas', PessoaListConverter);
try
Result := (Mar.Marshal(value) as TJSONObject).ToString();
finally
Mar.Free;
end;
end;
initialization
PessoaListConverter := function(Data: TObject; Field: String): TListOfObjects
var
Pessoas: TPessoas;
i: integer;
begin
Pessoas := TPessoaList(Data).Pessoas;
SetLength(Result, Pessoas.Count);
if Pessoas.Count > 0 then
for I := 0 to Pessoas.Count - 1 do
Result[I] := Pessoas[i];
end;
PessoaListReverter := procedure(Data: TObject; Field: String; Args: TListOfObjects)
var
obj: TObject;
Pessoas: TPessoas;
Pessoa: TPessoa;
begin
Pessoas := TPessoaList(Data).Pessoas;
Pessoas.Clear;
for obj in Args do
begin
Pessoa := obj as TPessoa;
Pessoas.Add(Pessoa);
end;
end;
end.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
PaintBox1: TPaintBox;
ColorDialog1: TColorDialog;
Panel1: TPanel;
Button1: TButton;
procedure PaintBox1Paint(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
procedure PaintFarbverlauf(Canvas:TCanvas; x,y:Integer);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Farbe zwischen 2 vorgegebenen Farbwerten berechnen
function ColorBetween(C1, C2 : TColor; blend:Real):TColor;
var
r, g, b : Byte;
y1, y2 : Byte;
begin
C1 := ColorToRGB(C1);
C2 := ColorToRGB(C2);
y1 := GetRValue(C1);
y2 := GetRValue(C2);
r := Round(y1 + (y2-y1)*blend);
y1 := GetGValue(C1);
y2 := GetGValue(C2);
g := Round(y1 + (y2-y1)*blend);
y1 := GetBValue(C1);
y2 := GetBValue(C2);
b := Round(y1 + (y2-y1)*blend);
Result := RGB(r, g, b);
end;
// Farbe zwischen beliebig vielen vorgegebenen Farbwerten berechnen
function ColorsBetween(const colors:array of TColor; blend:Real):TColor;
var
a : Integer;
faktor : Real;
begin
if Length(colors) < 2 then
raise Exception.Create('ColorsBetween() at least 2 Colors required');
if blend <= 0.0 then
Result := colors[0]
else if blend >= 1.0 then
Result := colors[High(colors)]
else
begin
a := Trunc(High(colors) * blend);
faktor := 1.0 / High(colors);
Result := ColorBetween(colors[a], colors[a+1], (blend-(a * faktor)) / faktor);
end;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
PaintFarbverlauf(PaintBox1.Canvas, PaintBox1.Width, PaintBox1.Height);
end;
procedure TForm1.PaintFarbverlauf(Canvas:TCanvas; x,y:Integer);
var
i : Integer;
c : TColor;
begin
c := ColorDialog1.Color;
for i := 0 to x do
begin
Canvas.Pen.Color := ColorsBetween([clWhite, c, clBlack], i * 1.0/x);
Canvas.MoveTo(i, 0);
Canvas.LineTo(i, y);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ColorDialog1.Execute;
PaintBox1.Refresh;
end;
end.
|
unit DAO.ControleTransporte;
interface
uses DAO.base, Model.ControleTransporte, Generics.Collections, System.Classes;
type
TControleTransporteDAO = class(TDAO)
public
function Insert(aControle: Model.ControleTransporte.TControleTransporte) : Boolean;
function Update(aControle: Model.ControleTransporte.TControleTransporte) : Boolean;
function Delete(sFiltro: String): Boolean;
function FindControle(sFiltro: String): TObjectList<TControleTransporte>;
end;
CONST
TABLENAME = 'tbcontroletransporte';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TControleTransporteDAO.Insert(aControle : Model.ControleTransporte.TControleTransporte): Boolean;
var
sSQL : String;
begin
Result := False;
aControle.ID := GetKeyValue(TABLENAME,'ID_CONTROLE');
sSQL := 'INSERT INTO ' + TABLENAME + ' ' +
'(ID_CONTROLE, DAT_TRANSPORTE, COD_CLIENTE, DES_OPERACAO, DES_PLACA, COD_MOTORISTA, QTD_KM_SAIDA, HOR_SAIDA, ' +
'QTD_KM_RETORNO, HOR_RETORNO, QTD_KM_RODADO, DES_SERVICO, DES_OBS, VAL_SERVICO, COD_STATUS, DES_LOG) ' +
'VALUES (' +
':ID, :DATA, :CLIENTE, :OPERACAO, :PLACA, :MOTORISTA, :KMSAIDA, :HORSAIDA, :KMRETORNO, :HORRETORNO, :KMRODADO, ' +
':SERVICO, :OBS, :VALSERVICO, :STATUS, :LOG);';
Connection.ExecSQL(sSQL,[aControle.ID, aControle.DataTransporte, aControle.Cliente, aControle.Operacao, aControle.Placa,
aControle.Motorista, aControle.KmSaida, aControle.HoraSaida, aControle.KmRetorno, aControle.HoraRetorno,
aControle.KmRodado, aControle.Servico, aControle.Obs, aControle.ValServico, aControle.Status,
aControle.Log], [ftInteger, ftDate, ftInteger, ftString, ftString, ftInteger, ftFloat, ftTime,
ftFloat, ftTime, ftFloat, ftString, ftString, ftFloat, ftInteger, ftString]);
Result := True;
end;
function TControleTransporteDAO.Update(aControle : Model.ControleTransporte.TControleTransporte): Boolean;
var
sSQl : String;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'DAT_TRANSPORTE = :DATA, COD_CLIENTE = :CLIENTE, DES_OPERACAO = :OPERACAO, DES_PLACA = :PLACA, ' +
'COD_MOTORISTA = :MOTORISTA, QTD_KM_SAIDA = :KMSAIDA, HOR_SAIDA = :HORSAIDA, QTD_KM_RETORNO = :KMRETORNO, ' +
'HOR_RETORNO = :HORRETORNO, QTD_KM_RODADO = :KMRODADO, DES_SERVICO = :SERVICO, DES_OBS = :OBS, ' +
'VAL_SERVICO = :VALSERVICO, COD_STATUS = :STATUS, DES_LOG = :LOG ' +
'WHERE ID_CONTROLE = :ID;';
Connection.ExecSQL(sSQL,[aControle.DataTransporte, aControle.Cliente, aControle.Operacao, aControle.Placa,
aControle.Motorista, aControle.KmSaida, aControle.HoraSaida, aControle.KmRetorno, aControle.HoraRetorno,
aControle.KmRodado, aControle.Servico, aControle.Obs, aControle.ValServico, aControle.Status,
aControle.Log, aControle.ID], [ftDate, ftInteger, ftString, ftString, ftInteger, ftFloat, ftTime,
ftFloat, ftTime, ftFloat, ftString, ftString, ftFloat, ftInteger, ftString, ftInteger]);
Result := True;
end;
function TControleTransporteDAO.Delete(sFiltro: String): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Result := True;
end;
function TControleTransporteDAO.FindControle(sFiltro: String): TObjectList<TControleTransporte>;
var
FDQuery: TFDQuery;
Extratos: TObjectList<TControleTransporte>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
Extratos := TObjectList<TControleTransporte>.Create();
while not FDQuery.Eof do
begin
Extratos.Add(TControleTransporte.Create(FDQuery.FieldByName('ID_CONTROLE').AsInteger, FDQuery.FieldByName('DAT_TRANSPORTE').AsDateTime,
FDQuery.FieldByName('COD_CLIENTE').AsInteger, FDQuery.FieldByName('DES_OPERACAO').AsString,
FDQuery.FieldByName('DES_PLACA').AsString, FDQuery.FieldByName('COD_MOTORISTA').AsInteger,
FDQuery.FieldByName('QTD_KM_SAIDA').AsFloat, FDQuery.FieldByName('HOR_SAIDA').AsDateTime,
FDQuery.FieldByName('QTD_KM_RETORNO').AsFloat, FDQuery.FieldByName('HOR_RETORNO').AsDateTime,
FDQuery.FieldByName('QTD_KM_RODADO').AsFloat, FDQuery.FieldByName('DES_SERVICO').AsString,
FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('VAL_SERVICO').AsFloat,
FDQuery.FieldByName('COD_STATUS').AsInteger, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := Extratos;
end;
end.
|
program LineareListe (input, output);
type
tRefListe = ^tListe;
tNatZahl = 0..maxint;
tListe = record
info : integer;
next : tRefListe
end;
var
RefAnfang : tRefListe;
SuchZahl : integer;
ElementGefunden : tRefListe;
procedure Anhaengen(var ioListe : tRefListe;
inZahl : tNatZahl);
{ Haengt inZahl an ioListe an }
var Zeiger : tRefListe;
begin
Zeiger := ioListe;
if Zeiger = nil then
begin
new(ioListe);
ioListe^.info := inZahl;
ioListe^.next := nil;
end
else
begin
while Zeiger^.next <> nil do
Zeiger := Zeiger^.next;
{ Jetzt zeigt Zeiger auf das letzte Element }
new(Zeiger^.next);
Zeiger := Zeiger^.next;
Zeiger^.info := inZahl;
Zeiger^.next := nil;
end;
end;
procedure ListeEinlesen(var outListe:tRefListe);
{ liest eine durch Leerzeile abgeschlossene Folge von Integer-
Zahlen ein und speichert diese in der linearen Liste RefListe. }
var
Liste : tRefListe;
Zeile : string;
Zahl, Code : integer;
begin
writeln('Bitte geben Sie die zu sortierenden Zahlen ein.');
writeln('Beenden Sie Ihre Eingabe mit einer Leerzeile.');
Liste := nil;
readln(Zeile);
val(Zeile, Zahl, Code); { val konvertiert String nach Integer }
while Code=0 do
begin
Anhaengen(Liste, Zahl);
readln(Zeile);
val(Zeile, Zahl, Code);
end; { while }
outListe := Liste;
end; { ListeEinlesen }
procedure ListeDurchlaufen (inRefAnfang : tRefListe);
{ gibt die Werte der Listenelemente aus }
var
Zeiger : tRefListe;
begin
Zeiger := inRefAnfang;
while Zeiger <> nil do
begin
writeln (Zeiger^.info);
Zeiger := Zeiger^.next
end
end; { ListeDurchlaufen }
function ListenElemSuchen1 (
inRefAnfang : tRefListe;
inZahl : integer): tRefListe;
{ bestimmt das erste Element in einer Liste, bei dem
die info-Komponente gleich inZahl ist }
var
Zeiger : tRefListe;
begin
Zeiger := inRefAnfang;
if Zeiger <> nil then
{ Liste nicht leer }
begin
while (Zeiger <> nil) and
(Zeiger^.info <> inZahl) do
Zeiger := Zeiger^.next;
if Zeiger^.info <> inZahl then
{ dann muss Zeiger^.next = nil gewesen sein,
d.h. Zeiger zeigt auf das letzte Element.
Da dessen info-Komponente <> inZahl ist,
kommt inZahl nicht in der Liste vor. }
Zeiger := nil
end;
{ Liste nicht leer }
ListenElemSuchen1 := Zeiger
end; { ListenElemSuchen1 }
procedure SortiertEinfuegen (
inZahl : integer;
var ioRefAnfang : tRefListe);
{ fuegt ein neues Element fuer inZahl in eine
sortierte Liste ein }
var
Zeiger,
RefNeu : tRefListe;
gefunden : boolean;
begin
{ neues Element erzeugen }
new (RefNeu);
RefNeu^.info := inZahl;
if ioRefAnfang = nil then
{ Sonderfall: Liste ist leer }
begin
RefNeu^.next := ioRefAnfang; {die Liste hat ein Element (die eingegebene Zahl), deshalb next = nil}
ioRefAnfang := RefNeu {Anfang wird auf die neu erzeugte Liste gesetzt}
end
else
if ioRefAnfang^.info > inZahl then {wenn die erste Zahl in der vorhandenen Lise > der eingegeben Zahl ist}
{ Sonderfall: Einfuegen am Listenanfang }
begin
RefNeu^.next := ioRefAnfang; {next zeigt deshalb auf das bis jetzt erste Element in der Liste}
ioRefAnfang := RefNeu {der neue Anfang ist der neu eingeschobene Element in der Liste}
end
else
{ Einfuegeposition suchen }
begin
gefunden := false;
Zeiger := ioRefAnfang; {der Zeiger steht am Anfang der Liste}
while (Zeiger^.next <> nil) and {so lange die Liste nicht leer ist}
(not gefunden) do { und gefunden = true ist }
if Zeiger^.next^.info > inZahl then {da, die erste Zahl in der Liste bereits oben behandelt wurde, wird die nächste Zahl verglichen}
gefunden := true { wenn die nächste Zahl größer ist, dann ist gefunden = true }
else
Zeiger := Zeiger^.next; {sonst wird der Zeiger auf die nächste Stelle geschoben}
if gefunden then {wenn die Einfügestelle gefunden wurde}
{ Normalfall: Einfuegen in die Liste }
begin
RefNeu^.next := Zeiger^.next;
Zeiger^.next := RefNeu
end
else
{ Sonderfall: Anhaengen an das Listenende }
begin
Zeiger^.next := RefNeu;
RefNeu^.next := nil
end
end
end; { SortiertEinfuegen }
procedure Eingabesortieren(var ioRefAnfang : tRefListe);
var
Unsortiert: tRefListe;
Sortiert: tRefListe;
begin
Unsortiert := ioRefAnfang;
Sortiert := nil;
while Unsortiert <> nil do
begin
SortiertEinfuegen(Unsortiert^.info, Sortiert);
Unsortiert := Unsortiert^.next;
end;
ioRefAnfang := Sortiert;
end;
begin
ListeEinlesen (RefAnfang);
Eingabesortieren(RefAnfang);
writeln('Ergebnis: ');
ListeDurchlaufen (RefAnfang);
end.
|
unit Unit1;
{
Program: VhdCopy
Function: Copy vhd and set GUUID
Language: Pascal - Lazarus
Author: jasc2v8
Created: 2/17/2018
Updated: .
Version History
1.0.0 Initial release
fixed memory leak with AProcess.Free
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Menus, ComCtrls, ExtCtrls, EditBtn, LazUTF8, Process, DateUtils,
threadunit, ShellApi;
type
{ TForm1 }
TForm1 = class(TForm)
BtnExploreTo: TButton;
ButtonRefresh: TButton;
ButtonClone: TButton;
BtnExploreFrom: TButton;
ButtonUUID: TButton;
DirEditFrom: TDirectoryEdit;
DirEditTo: TDirectoryEdit;
Label1: TLabel;
Label2: TLabel;
ListBox1: TListBox;
ProgressBar1: TProgressBar;
Timer1: TTimer;
procedure BtnExploreToClick(Sender: TObject);
procedure ButtonCloneClick(Sender: TObject);
procedure BtnExploreFromClick(Sender: TObject);
procedure ButtonRefreshClick(Sender: TObject);
procedure ButtonUUIDClick(Sender: TObject);
procedure DirEditFromAcceptDirectory(Sender: TObject; var Value: String);
procedure DirEditFromEditingDone(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Timer1StartTimer(Sender: TObject);
private
procedure DoChangeUUID;
procedure DoClone;
procedure DoRefresh;
public
OpenFileName, SaveFileName: string;
Running, Aborting: boolean;
Thread1: TThreadUnit;
end;
const
DS=DirectorySeparator;
LE=LineEnding;
VBManageUnix = '/usr/lib/virtualbox/VBoxManage.exe';
VBManageWin32 = '"C:\Program Files (x86)\Oracle\VirtualBox\VboxManage.exe"';
VBManageWin64 = '"C:\Program Files\Oracle\VirtualBox\VboxManage.exe"';
var
Form1: TForm1;
AProcess: TProcess;
threadvar
ThreadsRunningCount: integer;
implementation
//Uses Windows, InterfaceBase;
{$R *.lfm}
function PadString(aString: string; aPadchar: string; aLength: integer): string;
begin
while Length(aString)<aLength do begin
aString:=aString+aPadchar;
end;
Result:=aString;
end;
{ TForm1 }
procedure TForm1.Timer1StartTimer(Sender: TObject);
begin
If Not Application.Active then
FlashWindow(WidgetSet.AppHandle, True);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Form1.Caption:=Application.Title;
end;
procedure TForm1.ButtonCloneClick(Sender: TObject);
begin
DoClone;
end;
procedure TForm1.BtnExploreFromClick(Sender: TObject);
begin
ShellExecute(0,'open',PChar(DirEditFrom.Text),nil,nil,1);
end;
procedure TForm1.BtnExploreToClick(Sender: TObject);
begin
ShellExecute(0,'open',PChar(DirEditTo.Text),nil,nil,1);
end;
procedure TForm1.ButtonRefreshClick(Sender: TObject);
begin
DoRefresh;
end;
procedure TForm1.ButtonUUIDClick(Sender: TObject);
begin
DoChangeUUID;
end;
procedure TForm1.DirEditFromAcceptDirectory(Sender: TObject; var Value: String);
begin
DirEditFrom.Text:=Value;
DirEditTo.Text:=Value;
DoRefresh;
end;
procedure TForm1.DirEditFromEditingDone(Sender: TObject);
begin
DirEditTo.Text:=DirEditFrom.Text;
DoRefresh;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
DirEditFrom.Text:=GetCurrentDir;
DirEditTo.Text:=GetCurrentDir;
DoRefresh;
end;
procedure TForm1.DoChangeUUID;
var
i: integer;
params: array[0..3] of string;
begin
ThreadsRunningCount:=0;
For i:=0 to ListBox1.Count-1 do begin
if ListBox1.Selected[i] then begin
params[0]:=VBManageWin64;
params[1]:='internalcommands';
params[2]:='setuuid';
params[3]:=ListBox1.Items[i];
if FileExists(params[3]) then begin
//DO NOTHING
end;
ListBox1.Items[i]:=PadString(ListBox1.Items[i],'*',90)+'CHANGING UUID...';
Thread1:=TThreadUnit.Create(i, params, False);
Inc(ThreadsRunningCount);
ProgressBar1.Style:=pbstMarquee;
ProgressBar1.Visible:=True;
end;
end;
end;
procedure TForm1.DoClone;
var
i: integer;
params: array[0..3] of string;
begin
ThreadsRunningCount:=0;
For i:=0 to ListBox1.Count-1 do begin
if ListBox1.Selected[i] then begin
params[0]:=VBManageWin64;
params[1]:='clonehd';
params[2]:=ListBox1.Items[i];
params[3]:=DirEditTo.Text+DS+ExtractFileName(ListBox1.Items[i])+'_CLONED.vhd';
if FileExists(params[3]) then begin
RenameFile(params[3], params[3]+'.BAK');
DeleteFile(params[3]);
end;
ListBox1.Items[i]:=PadString(ListBox1.Items[i],'*',90)+'CLONING...';
Thread1:=TThreadUnit.Create(i, params, False);
Inc(ThreadsRunningCount);
ProgressBar1.Style:=pbstMarquee;
ProgressBar1.Visible:=True;
end;
end;
end;
procedure TForm1.DoRefresh;
var
VhdFiles: TStringList;
begin
ListBox1.Clear;
Application.ProcessMessages;
Sleep(250);
try
VhdFiles:=TStringList.Create;
FindAllFiles(VhdFiles, DirEditFrom.Text, '*.hdd;*.vdi;*.vhd;*.vmdk', false);
ListBox1.Items:=VhdFiles;
finally
VhdFiles.Free;
end;
end;
end.
|
// DateFolder
// Purpose: Organize photos and videos by recording date
// Author: etworker
// Version:
// - 0.1 Publish on github
// - 0.1.1 Update About
// - 0.1.2 Update config
unit frmDateFolder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzPanel, RzDlgBtn, StdCtrls, ComCtrls, ActnList, StrUtils,
DateUtils, IniFiles, CCR.Exif;
const
VERSION: string = 'V0.1.1';
type
TDateFolderForm = class(TForm)
lbledtPhotoDir: TLabeledEdit;
btnButtons: TRzDialogButtons;
lbledtCamera: TLabeledEdit;
lbledtDateFormat: TLabeledEdit;
lbledtDestDir: TLabeledEdit;
chkMove: TCheckBox;
pbProgress: TProgressBar;
actlstMain: TActionList;
actProcess: TAction;
actAbout: TAction;
actClose: TAction;
lbledtImageExt: TLabeledEdit;
lbledtSubDir: TLabeledEdit;
lblStatus: TLabel;
lbledtVideoDir: TLabeledEdit;
lbledtVideoExt: TLabeledEdit;
procedure FormCreate(Sender: TObject);
procedure actProcessExecute(Sender: TObject);
procedure actAboutExecute(Sender: TObject);
procedure actCloseExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
m_AboutString: string; // 关于
m_PhotoDir: string; // 照片目录
m_VideoDir: string; // 视频目录
m_DestDir: string; // 临时目录
m_Camera: string; // 照片类型
m_SubDir: string; // 新建子目录
m_ImageExt: string; // 图片扩展名
m_ImageExtList: TStringList; // 图片扩展名列表
m_VideoExt: string; // 视频扩展名
m_VideoExtList: TStringList; // 视频扩展名列表
m_FileList: TStringList; // 文件列表
m_SubDirList: TStringList; // 子目录列表
m_DateFormat: string; // 日期格式
m_IsMove: Boolean; // 是否移动
// 设置状态信息
procedure SetStatus(str: string; IsWarning: Boolean = False);
// 分离参数
procedure SplitParams(str: string; var List: TStringList);
// 获取JPG图片拍摄时间
function GetJpgImageDate(FileName: string): TDateTime;
// 文件时间转日期时间
function FileTimeToDateTime(FT: TFileTime): TDateTime;
// 获取文件时间
function GetFileDate(FileName: string): TDateTime;
// 装载配置
function LoadSettings: Boolean;
// 保存配置
function SaveSettings: Boolean;
public
{ Public declarations }
end;
var
DateFolderForm: TDateFolderForm;
implementation
{$R *.dfm}
procedure SplitString(str: string; Delimiter: string; var strList: TStringList);
var
DelimiterPos: Integer;
begin
//Count := ExtractStrings([Delimiter], [' '], PChar(str), strList);
strList.Clear;
if str = '' then Exit;
DelimiterPos := pos(Delimiter, str);
while DelimiterPos > 0 do begin
strList.Add(Copy(str, 1, DelimiterPos - 1));
Delete(str, 1, DelimiterPos + Length(Delimiter) - 1);
DelimiterPos := Pos(Delimiter, str);
end;
strList.Add(str);
end;
function GetFileListInDir(var List: TStringList; const Dir: string; IsPlusDir: Boolean = True): Boolean;
var
fd: TSearchRec;
begin
Result := False;
List.Clear;
if not DirectoryExists(Dir) then exit;
if FindFirst(Dir + '\*.*', faAnyFile, fd) = 0 then begin
while FindNext(fd) = 0 do
if (fd.Name <> '.') and (fd.Name <> '..') then
if IsPlusDir then
List.Add(Dir + '\' + fd.Name)
else
List.Add(fd.Name);
SysUtils.FindClose(fd);
Result := True;
end;
end;
procedure TDateFolderForm.actAboutExecute(Sender: TObject);
begin
SetStatus(m_AboutString);
end;
procedure TDateFolderForm.actCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TDateFolderForm.actProcessExecute(Sender: TObject);
var
TotalFileNum: Integer; // 文件总数
TodoFileNum: Integer; // 需要处理的文件数
ProcessFileNum: Integer; // 处理了的文件数
i, j: Cardinal;
strExt: string;
FileDate: TDateTime;
DateDir: string;
OutputDir, ImageDir, VideoDir: string; // 输出目录
SubDir: string; // 新建子目录
FileName, FileExt: string;
DstFileName: string;
begin
// 获取参数
m_PhotoDir := Trim(lbledtPhotoDir.Text);
m_Camera := Trim(lbledtCamera.Text);
m_SubDir := Trim(lbledtSubDir.Text);
m_VideoDir := Trim(lbledtVideoDir.Text);
m_ImageExt := Trim(lbledtImageExt.Text);
m_VideoExt := Trim(lbledtVideoExt.Text);
m_DestDir := Trim(lbledtDestDir.Text);
m_DateFormat := Trim(lbledtDateFormat.Text);
m_IsMove := chkMove.Checked;
// 获取照片目录的文件列表
if not GetFileListInDir(m_FileList, m_PhotoDir, true) then begin
SetStatus('照片目录不存在,请检查', True);
lbledtPhotoDir.SetFocus;
Exit;
end;
// 处理照片类型
if m_Camera = '' then begin
SetStatus('照片类型不能为空,请检查', True);
lbledtCamera.SetFocus;
Exit;
end;
// 处理日期格式,如果为空,默认为 yyyy_mm_dd
if m_DateFormat = '' then m_DateFormat := 'yyyy_mm_dd';
// 提取图片扩展名列表,若空默认为jpg
m_ImageExtList.Clear;
if m_ImageExt = '' then begin
lbledtImageExt.Text := 'jpg';
m_ImageExtList.Add('jpg');
end
else begin
SplitParams(m_ImageExt, m_ImageExtList);
// 为了适应 ExtractFileExt() 得到的结果都带 .,所以提前都加上 .
for i := 0 to m_ImageExtList.Count - 1 do
m_ImageExtList.Strings[i] := '.' + Trim(m_ImageExtList.Strings[i]);
end;
// 提取视频扩展名列表,若空默认为mp4,mov
m_VideoExtList.Clear;
if m_VideoExt = '' then begin
lbledtVideoExt.Text := 'mp4,mov';
m_VideoExtList.Add('.mp4');
m_VideoExtList.Add('.mov');
end
else begin
SplitParams(m_VideoExt, m_VideoExtList);
// 为了适应 ExtractFileExt() 得到的结果都带 .,所以提前都加上 .
for i := 0 to m_VideoExtList.Count - 1 do
m_VideoExtList.Strings[i] := '.' + Trim(m_VideoExtList.Strings[i]);
end;
// 检查照片目录下的文件个数
if m_FileList.Count = 0 then begin
SetStatus('照片目录下没有文件,请检查', True);
Exit;
end;
// 过滤扩展名
TotalFileNum := m_FileList.Count;
for i := m_FileList.Count - 1 downto 0 do begin
// 取得小写扩展名
strExt := LowerCase(ExtractFileExt(m_FileList.Strings[i]));
// 如果不在扩展名列表中,则从中删除
if (m_ImageExtList.IndexOf(strExt) < 0) and (m_VideoExtList.IndexOf(strExt) < 0) then m_FileList.Delete(i);
end;
// 如果没有剩下的文件,则退出
TodoFileNum := m_FileList.Count;
if m_FileList.Count = 0 then begin
SetStatus('照片目录下没有适合的文件,请检查', True);
lbledtImageExt.SetFocus;
Exit;
end;
// 提取子目录列表
m_SubDirList.Clear;
if m_SubDir <> '' then begin
SplitParams(m_SubDir, m_SubDirList);
for i := 0 to m_SubDirList.Count - 1 do
m_SubDirList.Strings[i] := Trim(m_SubDirList.Strings[i]);
end;
// 处理临时目录,如果没有就建立,如果后面没有“\”就加上
if not DirectoryExists(m_DestDir) then ForceDirectories(m_DestDir);
if RightStr(m_DestDir, 1) <> '\' then m_DestDir := m_DestDir + '\';
// 根据文件个数,设置进度条的最大值
pbProgress.Position := 0;
pbProgress.Min := 0;
pbProgress.Max := TodoFileNum;
pbProgress.Show;
// 逐个对每个文件进行处理
ProcessFileNum := 0;
for i := 0 to m_FileList.Count - 1 do begin
Application.HandleMessage;
pbProgress.Position := i;
FileName := m_FileList.Strings[i];
FileExt := LowerCase(ExtractFileExt(FileName));
if FileExt = '.jpg' then
FileDate := GetJpgImageDate(FileName)
else
FileDate := GetFileDate(FileName);
if FileDate = 0 then begin
Application.MessageBox(PChar(Format('文件"%s"提取日期失败', [FileName])),
'注意', MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
Continue;
end;
// 获得日期
DateDir := FormatDateTime(m_DateFormat, FileDate);
// 创建子目录
if m_SubDirList.Count > 0 then
for j := 0 to m_SubDirList.Count - 1 do
ForceDirectories(m_DestDir + DateDir + '\' + m_SubDirList.Strings[j]);
// 将文件拷贝过去
if m_VideoExtList.IndexOf(FileExt) >= 0 then
OutputDir := Format('%s%s\%s\', [m_DestDir, DateDir, m_VideoDir])
else
OutputDir := Format('%s%s\%s\', [m_DestDir, DateDir, m_Camera]);
if not DirectoryExists(OutputDir) then ForceDirectories(OutputDir);
if CopyFile(PChar(FileName), PChar(OutputDir + ExtractFileName(FileName)), False) then begin
Inc(ProcessFileNum);
// 如果成功且需要移动,则删除本地的文件
if m_IsMove then DeleteFile(FileName);
end;
end;
// 隐藏进度条
pbProgress.Hide;
// 提示状态
SetStatus(Format('照片目录下共有文件 %d 个,符合扩展名的共有 %d 个,%s成功处理了 %d 个',
[TotalFileNum, TodoFileNum, #13#10, ProcessFileNum]));
end;
function TDateFolderForm.FileTimeToDateTime(FT: TFileTime): TDateTime;
var
SysTime: TSystemTime;
LocalFT: TFileTime;
begin
try
// Convert UTC time to local time
Win32Check(FileTimeToLocalFileTime(FT, LocalFT));
// Convert file time to system time, raising exception on error
Win32Check(FileTimeToSystemTime(LocalFT, SysTime));
// Convert system time to Delphi date time, raising excpetion on error
Result := SystemTimeToDateTime(SysTime);
except
Result := 0;
end;
end;
procedure TDateFolderForm.FormCreate(Sender: TObject);
begin
lbledtPhotoDir.EditLabel.Caption := '照片目录';
lbledtCamera.EditLabel.Caption := '相机名称';
lbledtSubDir.EditLabel.Caption := '新建子目录';
lbledtVideoDir.EditLabel.Caption := '视频子目录';
lbledtImageExt.EditLabel.Caption := '图片扩展名过滤';
lbledtVideoExt.EditLabel.Caption := '视频扩展名过滤';
lbledtDestDir.EditLabel.Caption := '临时目录';
lbledtDateFormat.EditLabel.Caption := '日期格式';
lblStatus.Caption := '';
pbProgress.Hide;
m_ImageExtList := TStringList.Create;
m_VideoExtList := TStringList.Create;
m_FileList := TStringList.Create;
m_SubDirList := TStringList.Create;
LoadSettings;
end;
procedure TDateFolderForm.FormDestroy(Sender: TObject);
begin
SaveSettings;
m_ImageExtList.Free;
m_VideoExtList.Free;
m_FileList.Free;
m_SubDirList.Free;
end;
function TDateFolderForm.GetFileDate(FileName: string): TDateTime;
var
fad: TWin32FileAttributeData;
LastWriteTime: TDateTime;
begin
Result := 0;
if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @fad) then Exit;
Result := FileTimeToDateTime(fad.ftLastWriteTime);
end;
function TDateFolderForm.GetJpgImageDate(FileName: string): TDateTime;
var
ExifData: TExifDataPatcher;
FileDate: TDateTime;
begin
Result := 0;
try
try
ExifData := TExifDataPatcher.Create(FileName);
except
on E: EInvalidJPEGHeader do begin
SetStatus(Format('%s is not jpg file', [FileName]), True);
// ExifData is already destroyed
ExifData := nil;
Exit;
end
else
SetStatus(Format('%s read failed', [FileName]), True);
// ExifData is already destroyed
ExifData := nil;
Exit;
end;
// 如果没有Exif时间,则用文件时间替代
FileDate := ExifData.DateTimeOriginal;
if FileDate = 0 then FileDate := ExifData.FileDateTime;
Result := FileDate;
finally
if Assigned(ExifData) then ExifData.Free;
end;
end;
function TDateFolderForm.LoadSettings: Boolean;
var
IniFile: TIniFile;
FileName: string;
begin
FileName := StringReplace(ParamStr(0), '.exe', '.ini', [rfIgnoreCase]);
IniFile := TIniFile.Create(FileName);
try
Self.Caption := IniFile.ReadString('UI', 'Title', '按拍摄日期整理照片及视频');
Self.Caption := Format('%s [%s]', [Self.Caption, VERSION]);
lbledtPhotoDir.EditLabel.Caption := IniFile.ReadString('UI', 'PhotoDir', '照片目录');
lbledtCamera.EditLabel.Caption := IniFile.ReadString('UI', 'Camera', '相机名称');
lbledtSubDir.EditLabel.Caption := IniFile.ReadString('UI', 'SubDir', '新建子目录');
lbledtVideoDir.EditLabel.Caption := IniFile.ReadString('UI', 'VideoDir', '视频子目录');
lbledtImageExt.EditLabel.Caption := IniFile.ReadString('UI', 'ImageExt', '图片扩展名过滤');
lbledtVideoExt.EditLabel.Caption := IniFile.ReadString('UI', 'VideoExt', '视频扩展名过滤');
lbledtDestDir.EditLabel.Caption := IniFile.ReadString('UI', 'DestDir', '临时目录');
lbledtDateFormat.EditLabel.Caption := IniFile.ReadString('UI', 'DateFormat', '日期格式');
chkMove.Caption := IniFile.ReadString('UI', 'IsMove', '移动照片和视频');
btnButtons.CaptionOk := IniFile.ReadString('UI', 'OK', '处理(&P)');
btnButtons.CaptionHelp := IniFile.ReadString('UI', 'Quit', '退出(&X)');
btnButtons.CaptionCancel := IniFile.ReadString('UI', 'About', '关于(&A)');
m_AboutString := IniFile.ReadString('Other', 'About',
'本软件用来将目录内的照片按拍照日期放入相应的目录。作者:ET民工,项目主页:https://github.com/etworker/DateFolder');
lbledtPhotoDir.Text := IniFile.ReadString('Config', 'PhotoDir', '');
lbledtCamera.Text := IniFile.ReadString('Config', 'Camera', 'iPhone 6s');
lbledtSubDir.Text := IniFile.ReadString('Config', 'SubDir', '');
lbledtVideoDir.Text := IniFile.ReadString('Config', 'VideoDir', 'Video');
lbledtImageExt.Text := IniFile.ReadString('Config', 'ImageExt', 'jpg');
lbledtVideoExt.Text := IniFile.ReadString('Config', 'VideoExt', 'mp4,mov');
lbledtDestDir.Text := IniFile.ReadString('Config', 'DestDir', '');
lbledtDateFormat.Text := IniFile.ReadString('Config', 'DateFormat', 'yyyy_mm_dd');
chkMove.Checked := IniFile.ReadBool('Config', 'IsMove', True);
finally
IniFile.Free;
end;
end;
function TDateFolderForm.SaveSettings: Boolean;
var
IniFile: TIniFile;
FileName: string;
begin
FileName := StringReplace(ParamStr(0), '.exe', '.ini', [rfIgnoreCase]);
IniFile := TIniFile.Create(FileName);
try
IniFile.WriteString('Config', 'PhotoDir', lbledtPhotoDir.Text);
IniFile.WriteString('Config', 'Camera', lbledtCamera.Text);
IniFile.WriteString('Config', 'SubDir', lbledtSubDir.Text);
IniFile.WriteString('Config', 'ImageExt', lbledtImageExt.Text);
IniFile.WriteString('Config', 'VideoExt', lbledtVideoExt.Text);
IniFile.WriteString('Config', 'DestDir', lbledtDestDir.Text);
IniFile.WriteString('Config', 'DateFormat', lbledtDateFormat.Text);
IniFile.WriteBool('Config', 'IsMove', chkMove.Checked);
finally
IniFile.Free;
end;
end;
procedure TDateFolderForm.SetStatus(str: string; IsWarning: Boolean);
begin
with lblStatus do begin
Layout := tlCenter;
if IsWarning then
Font.Color := clRed
else
Font.Color := clBlack;
Caption := str;
end;
end;
procedure TDateFolderForm.SplitParams(str: string; var List: TStringList);
const
SPLIT_CHARS: string = ',;|/';
var
i: Cardinal;
begin
for i := 0 to Length(SPLIT_CHARS) - 1 do begin
if Pos(SPLIT_CHARS[i], str) > 0 then begin
SplitString(str, SPLIT_CHARS[i], List);
Exit;
end;
end;
List.Add(str);
end;
end.
|
unit DAO;
interface
uses RTTIUtils;
type
iDAO = interface
['{11B1B4F8-B162-4926-97D7-91DBF36E26AE}']
procedure Salvar;
end;
TDAO<T : class> = class(TInterfacedObject, iDAO)
private
FParent : T;
public
constructor Create(Parent : T);
destructor Destroy; override;
class function New(Parent : T) : iDAO;
procedure Salvar;
end;
implementation
{ TDAO<T> }
constructor TDAO<T>.Create(Parent: T);
begin
FParent := Parent;
end;
destructor TDAO<T>.Destroy;
begin
inherited;
end;
class function TDAO<T>.New(Parent: T): iDAO;
begin
Result := Self.Create(Parent);
end;
procedure TDAO<T>.Salvar;
begin
TRTTIUtils.ValidarCampos(FParent);
end;
end.
|
unit uAgendamentoController;
interface
uses
System.SysUtils, uDMAgendamento, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms,
uFuncoesSIDomper, Data.DBXJSON , Data.DBXJSONReflect, uFiltroAgendamento,
uObsevacaoController, uTipoController, uTipoVO, Vcl.Dialogs, System.Generics.Collections,
uAgendamentoVO, uConverter;
type
TAgendamentoController = class
private
FModel: TdmAgendamento;
FOperacao: TOperacao;
procedure ObservacaoPadrao;
procedure TipoUmRegistro;
procedure VerificarAgendamentoAberto();
public
procedure Filtrar(AFiltro: TFiltroAgendamento; ACampo, ATexto: string; AContem: Boolean = False);
procedure FiltrarId(AId: Integer);
procedure LocalizarId(AId: Integer);
procedure Novo(AIdUsuario: Integer);
procedure Editar(AId: Integer; AFormulario: TForm);
function Salvar(AIdUsuario: Integer): Integer;
procedure Excluir(AIdUsuario, AId: Integer);
procedure Cancelar();
procedure Imprimir(AIdUsuario: Integer);
procedure Quadro(ADataInicial, ADataFinal: TDate; AIdUsuario, AIdRevenda: integer);
function QuadroJSON(ADataInicial, ADataFinal: TDate; AIdUsuario, AIdRevenda: integer): TObjectList<TAgendamentoVO>;
function PermissaoQuadro(AIdUsuario: Integer): Boolean;
procedure Reagendamento(AIdAgendamento: Integer;
AData, AHora: TDateTime; ATexto: string);
procedure Cancelamento(AIdAgendamento: Integer; AData, AHora:
TDateTime; ATexto: string);
procedure Encerrar(AIdAgendamento, AIdPrograma: Integer);
procedure EncerrarWEB(AIdAgendamento: Integer);
function RetornarEmails(AIdAgenda, AIdUsuario, AIdStatus: Integer): string;
function RetornarEmailsCliente(AIdAgenda: Integer): string;
procedure EnvioEmail(AIdAgenda, AIdStatus: Integer);
function RetornaTipoPrograma(AIdAgenda: Integer): Integer;
constructor Create();
destructor Destroy; override;
property Model: TdmAgendamento read FModel write FModel;
end;
implementation
{ TAgendamentoController }
uses uStatusController, uEmailBase, uEmailAgendamento,
uContaEmail, uContaEmailController, uUsuarioController, uFormProcesso,
uEmailModelo2, uEnviarEmail;
procedure TAgendamentoController.Cancelamento(
AIdAgendamento: Integer; AData, AHora: TDateTime; ATexto: string);
var
Negocio: TServerModule2Client;
begin
if AIdAgendamento = 0 then
raise Exception.Create('Informe o Id do Agendamento!');
if AData = 0 then
raise Exception.Create('Informe a Data!');
if AHora = 0 then
raise Exception.Create('Informe a Hora!');
if Trim(ATexto) = '' then
raise Exception.Create('Informe o Texto!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Negocio.AgendamentoCancelamento(dm.IdUsuario, AIdAgendamento, DateToStr(AData), TimeToStr(AHora), ATexto);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Cancelar;
begin
if FModel.CDSCadastro.State in [dsEdit, dsInsert] then
FModel.CDSCadastro.Cancel;
end;
constructor TAgendamentoController.Create;
begin
FModel := TdmAgendamento.Create(nil);
end;
destructor TAgendamentoController.Destroy;
begin
FreeAndNil(FModel);
inherited;
end;
procedure TAgendamentoController.Editar(AId: Integer; AFormulario: TForm);
var
Negocio: TServerModule2Client;
Resultado: Boolean;
begin
if AId = 0 then
raise Exception.Create('Não há Registro para Editar!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
FModel.CDSCadastro.Close;
Resultado := Negocio.AgendamentoEditar(CAgendamentoPrograma, dm.IdUsuario, AId);
FModel.CDSCadastro.Open;
TFuncoes.HabilitarCampo(AFormulario, Resultado);
FOperacao := opEditar;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Encerrar(AIdAgendamento, AIdPrograma: Integer);
var
Negocio: TServerModule2Client;
begin
if AIdAgendamento = 0 then
raise Exception.Create('Informe o Id do Agendamento!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Negocio.AgendamentoEncerramento(dm.IdUsuario, AIdAgendamento, AIdPrograma);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.EncerrarWEB(AIdAgendamento: Integer);
var
Negocio: TServerModule2Client;
begin
if AIdAgendamento = 0 then
raise Exception.Create('Informe o Id do Agendamento!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Negocio.AgendamentoEncerramentoWEB(dm.IdUsuario, AIdAgendamento);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.EnvioEmail(AIdAgenda, AIdStatus: Integer);
var
objEmailAgenda: TEmailAgendamento;
sEmail: string;
sEmailCliente: string;
objContaEmail: TContaEmailController;
begin
sEmail := '';
objContaEmail := TContaEmailController.Create;
objEmailAgenda := TEmailAgendamento.Create;
try
sEmail := objEmailAgenda.RetornarListaEmail(AIdAgenda,
dm.IdUsuario,
AIdStatus);
sEmailCliente := objEmailAgenda.RetornarListaEmailCliente(AIdAgenda);
if sEmailCliente = '' then
sEmailCliente := sEmail;
if (sEmailCliente <> '') then
begin
objContaEmail.EnviarEmail(dm.IdUsuario,
sEmailCliente,
sEmail,
objEmailAgenda.RetornarAssunto(AIdAgenda),
objEmailAgenda.TextoEmail(AIdAgenda),
'');
end;
finally
FreeAndNil(objContaEmail);
FreeAndNil(objEmailAgenda);
end;
end;
procedure TAgendamentoController.Excluir(AIdUsuario, AId: Integer);
var
Negocio: TServerModule2Client;
begin
if AId = 0 then
raise Exception.Create('Não há Registro para Excluir!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Negocio.AgendamentoExcluir(CAgendamentoPrograma, AIdUsuario, AId);
FModel.CDSConsulta.Delete;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Filtrar(AFiltro: TFiltroAgendamento; ACampo,
ATexto: string; AContem: Boolean);
var
Negocio: TServerModule2Client;
Marshal : TJSONMarshal;
oObjetoJSON : TJSONValue;
begin
TFuncoes.ValidaIntervaloDatas(AFiltro.DataInicial, AFiltro.DataFinal);
// serializa o objeto
Marshal := TJSONMarshal.Create;
try
oObjetoJSON := Marshal.Marshal(AFiltro);
finally
FreeAndNil(Marshal);
end;
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
FModel.CDSConsulta.Close;
Negocio.AgendamentoFiltrar(oObjetoJSON, ACampo, ATexto, dm.IdUsuario, AContem);
FModel.CDSConsulta.Open;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.FiltrarId(AId: Integer);
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
FModel.CDSConsulta.Close;
Negocio.AgendamentoFiltarId(AId);
FModel.CDSConsulta.Open;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Quadro(ADataInicial, ADataFinal: TDate;
AIdUsuario, AIdRevenda: integer);
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
FModel.CDSQuadro.Close;
Negocio.AgendamentoQuadro(DateToStr(ADataInicial), DateToStr(ADataFinal), AIdUsuario, AIdRevenda);
FModel.CDSQuadro.Open;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
function TAgendamentoController.QuadroJSON(ADataInicial, ADataFinal: TDate;
AIdUsuario, AIdRevenda: integer): TObjectList<TAgendamentoVO>;
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
try
Result := TConverte.JSONToObject<TListaAgendamentoVO>(Negocio.AgendamentoQuadroJSON(DateToStr(ADataInicial), DateToStr(ADataFinal), AIdUsuario, AIdRevenda));
dm.Desconectar;
except
On E: Exception do
begin
dm.ErroConexao(E.Message);
end;
end;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Reagendamento(AIdAgendamento: Integer; AData,
AHora: TDateTime; ATexto: string);
var
Negocio: TServerModule2Client;
begin
if AIdAgendamento = 0 then
raise Exception.Create('Informe o Id do Agendamento!');
if AData = 0 then
raise Exception.Create('Informe a Data!');
if AHora = 0 then
raise Exception.Create('Informe a Hora!');
if Trim(ATexto) = '' then
raise Exception.Create('Informe o Texto!');
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Negocio.AgendamentoReagendamento(DM.IdUsuario, AIdAgendamento, DateToStr(AData), TimeToStr(AHora), ATexto);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
function TAgendamentoController.RetornarEmails(AIdAgenda, AIdUsuario,
AIdStatus: Integer): string;
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Result := Negocio.AgendamentoRetornarEmails(AIdAgenda, AIdUsuario, AIdStatus);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
function TAgendamentoController.RetornarEmailsCliente(
AIdAgenda: Integer): string;
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Result := Negocio.AgendamentoRetornarCliente(AIdAgenda, dm.IdUsuario);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
function TAgendamentoController.RetornaTipoPrograma(
AIdAgenda: Integer): Integer;
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
Result := Negocio.AgendamentoTipoPrograma(AIdAgenda);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Imprimir(AIdUsuario: Integer);
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
Negocio.AgendamentoRelatorio(CAgendamentoPrograma, AIdUsuario);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.LocalizarId(AId: Integer);
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
FModel.CDSCadastro.Close;
Negocio.AgendamentoLocalizarId(CAgendamentoPrograma, AId);
FModel.CDSCadastro.Open;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
end;
procedure TAgendamentoController.Novo(AIdUsuario: Integer);
var
Negocio: TServerModule2Client;
StatusController: TStatusController;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
FModel.CDSCadastro.Close;
Negocio.AgendamentoNovo(CAgendamentoPrograma, AIdUsuario);
FModel.CDSCadastro.Open;
FModel.CDSCadastro.Append;
//==============================================================================
// status agendamento abertura
FModel.CDSCadastroSta_Codigo.AsInteger := Negocio.AgendamentoLocalizarStatusAbertura();
StatusController := TStatusController.Create;
try
StatusController.LocalizarCodigo(FModel.CDSCadastroSta_Codigo.AsInteger);
FModel.CDSCadastroAge_Status.AsInteger := StatusController.Model.CDSCadastroSta_Id.AsInteger;
FModel.CDSCadastroSta_Codigo.AsInteger := StatusController.Model.CDSCadastroSta_Codigo.AsInteger;
FModel.CDSCadastroSta_Nome.AsString := StatusController.Model.CDSCadastroSta_Nome.AsString;
finally
FreeAndNil(StatusController);
end;
ObservacaoPadrao();
TipoUmRegistro();
FOperacao := opIncluir;
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
VerificarAgendamentoAberto();
end;
procedure TAgendamentoController.ObservacaoPadrao;
var
Obs: TObservacaoController;
begin
Obs := TObservacaoController.Create;
try
Obs.LocalizarPadrao(prAgendamento);
FModel.CDSCadastroAge_Descricao.AsString := Obs.Model.CDSCadastroObs_Descricao.AsString;
finally
FreeAndNil(Obs);
end;
end;
function TAgendamentoController.PermissaoQuadro(AIdUsuario: Integer): Boolean;
var
Negocio: TServerModule2Client;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
Result := Negocio.AgendamentoPermissaoQuadro(AIdUsuario);
dm.Desconectar;
finally
FreeAndNil(Negocio);
// dm.Desconectar;
end;
end;
function TAgendamentoController.Salvar(AIdUsuario: Integer): Integer;
var
Negocio: TServerModule2Client;
Marshal : TJSONMarshal;
oObjetoJSON : TJSONValue;
Obj: TAgendamentoVO;
begin
if FModel.CDSCadastroAge_Tipo.AsInteger = 0 then
raise Exception.Create('Informe o Tipo!');
if FModel.CDSCadastro.State in [dsEdit, dsInsert] then
FModel.CDSCadastro.Post;
Obj := TAgendamentoVO.Create;
Obj.Id := FModel.CDSCadastroAge_Id.AsInteger;
Obj.Data := FModel.CDSCadastroAge_Data.AsDateTime;
Obj.Hora := FModel.CDSCadastroAge_Hora.AsDateTime;
Obj.IdUsuario := FModel.CDSCadastroAge_Usuario.AsInteger;
Obj.IdCliente := FModel.CDSCadastroAge_Cliente.AsInteger;
Obj.Contato := FModel.CDSCadastroAge_Contato.AsString;
Obj.Programa := FModel.CDSCadastroAge_Programa.AsInteger;
Obj.IdTipo := FModel.CDSCadastroAge_Tipo.AsInteger;
Obj.IdStatus := FModel.CDSCadastroAge_Status.AsInteger;
Obj.Descricao := FModel.CDSCadastroAge_Descricao.AsString;
Obj.Motivo := FModel.CDSCadastroAge_Motivo.AsString;
Obj.IdVisita := FModel.CDSCadastroAge_Visita.AsInteger;
Obj.IdAtividade := FModel.CDSCadastroAge_Atividade.AsInteger;
Obj.NomeCliente := FModel.CDSCadastroAge_NomeCliente.AsString;
// serializa o objeto
Marshal := TJSONMarshal.Create;
try
oObjetoJSON := Marshal.Marshal(obj);
finally
FreeAndNil(Marshal);
end;
dm.Conectar;
Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection);
try
Result := Negocio.AgendamentoSalvar(CAgendamentoPrograma, AIdUsuario, oObjetoJSON);
dm.Desconectar;
finally
FreeAndNil(Negocio);
FreeAndNil(Obj);
end;
end;
procedure TAgendamentoController.TipoUmRegistro;
var
obj: TTipoController;
Model: TTipoVO;
begin
obj := TTipoController.Create;
try
Model := obj.RetornoUmRegistro(prAgendamento);
if Model.Id > 0 then
begin
FModel.CDSCadastroAge_Tipo.AsInteger := Model.Id;
FModel.CDSCadastroTip_Codigo.AsInteger := Model.Codigo;
FModel.CDSCadastroTip_Nome.AsString := Model.Nome;
end;
finally
FreeAndNil(obj);
FreeAndNil(Model);
end;
end;
procedure TAgendamentoController.VerificarAgendamentoAberto;
var
Negocio: TServerModule2Client;
bResult: Boolean;
begin
dm.Conectar;
Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection);
try
bResult := Negocio.AgendamentoAberto(dm.IdUsuario);
dm.Desconectar;
finally
FreeAndNil(Negocio);
end;
if bResult then
ShowMessage('Há Agendamentos em Aberto!');
end;
end.
|
unit Model.CadastroRH;
interface
uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao;
type
TCadastroRH = class
private
FAcao: TAcao;
FDemissao: TDate;
FAdmissao: TDate;
FFuncao: Integer;
FSerieCTPS: String;
FNumeroCTPS: String;
FUFTituloEleitor: String;
FIDFolha: Integer;
FNumeroReservista: String;
FNumeroTituloEleitor: String;
FID: Integer;
FMunicipioTituloEleitor: String;
FPIS: String;
FSecaoTituloEleitor: String;
FZonaTituloEleitor: String;
FUFCTPS: String;
FStatus: Integer;
FOBS: String;
FConexao : TConexao;
FIDEmpresa: integer;
FConjuge: String;
FQuery: TFDQuery;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
property ID: Integer read FID write FID;
property PIS: String read FPIS write FPIS;
property NumeroCTPS: String read FNumeroCTPS write FNumeroCTPS;
property SerieCTPS: String read FSerieCTPS write FSerieCTPS;
property UFCTPS: String read FUFCTPS write FUFCTPS;
property NumeroTituloEleitor: String read FNumeroTituloEleitor write FNumeroTituloEleitor;
property ZonaTituloEleitor: String read FZonaTituloEleitor write FZonaTituloEleitor;
property SecaoTituloEleitor: String read FSecaoTituloEleitor write FSecaoTituloEleitor;
property MunicipioTituloEleitor: String read FMunicipioTituloEleitor write FMunicipioTituloEleitor;
property UFTituloEleitor: String read FUFTituloEleitor write FUFTituloEleitor;
property NumeroReservista: String read FNumeroReservista write FNumeroReservista;
property Conjuge: String read FConjuge write FConjuge;
property Funcao: Integer read FFuncao write FFuncao;
property Adminissao: TDate read FAdmissao write FAdmissao;
property Demissao: TDate read FDemissao write FDemissao;
property IDEmpresa: integer read FIDEmpresa write FIDEmpresa;
property IDFolha: Integer read FIDFolha write FIDFolha;
property Status: Integer read FStatus write FStatus;
property OBS: String read FOBS write FOBS;
property Query: TFDQuery read FQuery write FQuery;
property Acao: TAcao read FAcao write FAcao;
constructor Create;
function Localizar(aParam: array of variant): boolean;
function Gravar(): Boolean;
function SetupClass(FDQuery: TFDquery): boolean;
function ClearClass(): boolean;
end;
const
TABLENAME = 'cadastro_rh';
implementation
{ TCadastroRH }
function TCadastroRH.Alterar: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('update ' + TABLENAME + ' set ' +
'num_pis = :pnum_pis, num_ctps = :pnum_ctpsS, num_serie_ctps = :pnum_serie_ctps, ' +
'uf_ctps = :puf_ctps, num_titulo_eleitor = :pnum_titulo_eleitor, des_zona_eleitoral = :pdes_zona_eleitoral, ' +
'des_secao_eleitoral = :pdes_secao_eleitoral, nom_municipio_eleitoral = :pnom_municipio_eleitoral, ' +
'uf_eleitoral = :puf_eleitoral, num_reservista = :pnum_reservista, nom_conjuge = :nom_conjuge, ' +
'id_funcao = :pid_funcao, dat_admissao = :pdat_admissao, dat_demissao = :pdat_demissao, ' +
'id_empresa = :pid_empresa, id_folha = :pid_folha, id_status = :pid_status, des_obs = :pdes_obs ' +
'where id_cadastro = :pid_cadastro',
[Self.PIS, Self.NumeroCTPS, Self.SerieCTPS, Self.UFCTPS, Self.NumeroTituloEleitor,
Self.ZonaTituloEleitor, Self.SecaoTituloEleitor, Self.MunicipioTituloEleitor,
Self.UFTituloEleitor, Self.NumeroReservista, Self.Conjuge, Self.Funcao, Self.Adminissao,
Self.Demissao, Self.IDEmpresa, Self.IDFolha, Self.Status, Self.OBS, Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroRH.ClearClass: boolean;
begin
Result := False;
FDemissao := StrToDate('31-12-1899');
FAdmissao:= StrToDate('31-12-1899');
FFuncao := 0;
FSerieCTPS := '';
FNumeroCTPS := '';
FUFTituloEleitor := '';
FIDFolha := 0;
FNumeroReservista := '';
FNumeroTituloEleitor := '';
FID := 0;
FMunicipioTituloEleitor := '';
FPIS := '';
FSecaoTituloEleitor := '';
FZonaTituloEleitor := '';
FUFCTPS := '';
FStatus := 0;
FOBS := '';
FIDEmpresa := 0;
FConjuge := '';
Result := True;
end;
constructor TCadastroRH.Create;
begin
FConexao := TConexao.Create;
end;
function TCadastroRH.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_cadastro = :pid_cadastro', [Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TCadastroRH.Gravar: Boolean;
begin
Result := False;
case FAcao of
tacIncluir : Result := Self.Inserir();
tacAlterar : Result := Self.Alterar();
tacExcluir : Result := Self.Excluir();
end;
end;
function TCadastroRH.Inserir: Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('insert into ' + TABLENAME +
'(id_cadastro, num_pis, num_ctps, num_serie_ctps, uf_ctps, num_titulo_eleitor, des_zona_eleitoral, ' +
'des_sessao_eleitoral, nom_municipio_eleitoral, uf_eleitoral, num_reservista, nom_conjuge, cod_funcao, ' +
'dat_admissao, id_empresa, id_folha, id_status, des_obs) ' +
'values ' +
'(:pid_cadastro, :pnum_pis, :pnum_ctps, :pnum_serie_ctps, :puf_ctps, :pnum_titulo_eleitor, ' +
':pdes_zona_eleitoral, :pdes_sessao_eleitoral, :pnom_municipio_eleitoral, :puf_eleitoral, :pnum_reservista, ' +
':nom_conjuge, :pcod_funcao, :pdat_admissao, :pid_empresa, :pid_folha, :pid_status, :pdes_obs);',
[Self.ID, Self.PIS, Self.NumeroCTPS, Self.SerieCTPS, Self.UFCTPS, Self.NumeroTituloEleitor,
Self.ZonaTituloEleitor, Self.SecaoTituloEleitor, Self.MunicipioTituloEleitor, Self.UFTituloEleitor,
Self.NumeroReservista, Self.Conjuge, Self.Funcao,
Self.Adminissao, Self.Demissao, Self.IDEmpresa, Self.IDFolha, Self.Status, Self.OBS]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroRH.Localizar(aParam: array of variant): boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_cadastro = :id_cadastro');
FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1];
end;
if aParam[0] = 'PIS' then
begin
FDQuery.SQL.Add('where num_pis = :num_pis');
FDQuery.ParamByName('num_pis').AsString := aParam[1];
end;
if aParam[0] = 'CTPS' then
begin
FDQuery.SQL.Add('where num_ctps like :num_ctps');
FDQuery.ParamByName('num_ctps').AsString := aParam[1];
end;
if aParam[0] = 'TITULO' then
begin
FDQuery.SQL.Add('wheere num_titulo_eleitor = :num_titulo_eleitor');
FDQuery.ParamByName('num_titulo_eleitor').AsString := aParam[1];
end;
if aParam[0] = 'RESERVISTA' then
begin
FDQuery.SQL.Add('where num_reservista = :num_reservista');
FDQuery.ParamByName('num_reservista').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
FDQuery.Open();
if not FDQuery.IsEmpty then
begin
FQuery := FDQuery;
end;
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroRH.SetupClass(FDQuery: TFDquery): boolean;
begin
Result := False;
FDemissao := FDQuery.FieldByName('dat_demissao').AsDateTime;
FAdmissao:= FDQuery.FieldByName('dat_admissao').AsDateTime;
FFuncao := FDQuery.FieldByName('id_funcao').AsInteger;
FSerieCTPS := FDQuery.FieldByName('num_serie_ctps').AsString;
FNumeroCTPS := FDQuery.FieldByName('num_ctps').AsString;
FUFTituloEleitor := FDQuery.FieldByName('uf_eleitoral').AsString;
FIDFolha := FDQuery.FieldByName('id_folha').AsInteger;
FNumeroReservista := FDQuery.FieldByName('num_reservista').AsString;
FNumeroTituloEleitor := FDQuery.FieldByName('num_titulo_eleitor').AsString;
FID := FDQuery.FieldByName('id_cadastro').AsInteger;
FMunicipioTituloEleitor := FDQuery.FieldByName('nom_municipio_eleitoral').AsString;
FPIS := FDQuery.FieldByName('num_pis').AsString;
FSecaoTituloEleitor := FDQuery.FieldByName('des_secao_eleitoral').AsString;
FZonaTituloEleitor := FDQuery.FieldByName('des_zona_eleitoral').AsString;
FUFCTPS := FDQuery.FieldByName('uf_ctps').AsString;
FStatus := FDQuery.FieldByName('id_status').AsInteger;
FOBS := FDQuery.FieldByName('des_obs').AsString;
FIDEmpresa := FDQuery.FieldByName('id_empresa').AsInteger;
FConjuge := FDQuery.FieldByName('nom_conjuge').AsString;
Result := True;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Files
Description : Files functions
Author : Kike Pérez
Version : 1.5
Created : 09/03/2018
Modified : 16/11/2020
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Files;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$IFDEF FPC}
strutils,
{$IFDEF LINUX}
baseunix,
{$ENDIF}
{$ENDIF}
{$IFDEF POSIX}
Posix.Base,
Posix.SysStat,
Posix.Utime,
{$ENDIF}
DateUtils;
{$IFDEF FPC}
resourcestring
SPathTooLong = 'The specified path is too long';
SPathNotFound = 'The specified path was not found';
SPathFormatNotSupported = 'The path format is not supported';
SDirectoryNotEmpty = 'The specified directory is not empty';
SDirectoryAlreadyExists = 'The specified directory already exists';
SDirectoryInvalid = 'The specified directory name is invalid';
SSourceDirIsDestDir = 'The source directory is the same as the destination directory';
SSourceFileIsDestFile = 'The source file is the same as the destination file';
SPathToFileNeeded = 'The path must specify a file';
SSameRootDrive = 'The source and destination paths must contain the same root drive';
SDriveNotFound = 'The drive cannot be found';
SFileNotFound = 'The specified file was not found';
SFileAlreadyExists = 'The specified file already exists';
SInvalidCharsInPath = 'Invalid characters in path';
SInvalidCharsInFileName = 'Invalid characters in file name';
{$ENDIF}
type
{$IFNDEF FPC}
TTextFileOperation = (tfOpenRead,tfOpenOverwrite,tfOpenAppend);
TTextStreamFile = class
private
fReadStream : TStreamReader;
fWriteStream : TStreamWriter;
function GetEOF : Boolean;
public
constructor Create(const aFileName : string; aOpenMode : TTextFileOperation);
destructor Destroy; override;
function ReadLn: string; overload;
function ReadLn(out Data: string): Boolean; overload;
procedure WriteLn (const Data : string);
procedure Close;
property EOF: Boolean read GetEOF;
end;
{$IF Defined(MACOS) OR Defined(NEXTGEN) OR Defined(DELPHILINUX)}
TFileTime = LongInt;
{$ENDIF}
{$ELSE}
{$IFDEF LINUX}
TFILETIME = LongInt;
{$ENDIF}
{$ENDIF}
{$IFDEF FPC}
EStreamError = class(Exception);
EFileStreamError = class(EStreamError)
constructor Create(ResStringRec: PResStringRec; const FileName: string);
end;
TPathPrefixType = (pptNoPrefix, pptExtended, pptExtendedUNC);
{ TPath }
TPath = class
private
const
FCCurrentDir: string = '.';
FCParentDir: string = '..';
FCExtendedPrefix: string = '\\?\';
FCExtendedUNCPrefix: string = '\\?\UNC\';
class procedure CheckPathLength(const Path: string; const MaxLength: Integer);
public
class function GetFileNameWithoutExtension(const FileName : string) : string;
class function GetDirectoryName(const FileName : string) : string;
class function GetExtension(const Path : string) : string;
class function ChangeExtension(const Path, NewExtension : string) : string;
class function GetFileName(const aPath : string) : string;
class function EndsWithDelimiter(const aPath : string) : Boolean;
class function Combine(const aPath1, aPath2 : string) : string;
end;
TDirectory = class
public
class function Exists(const Path: string; FollowLink: Boolean = True): Boolean;
class function GetDirectories(const Path : string) : TArray<string>;
end;
TFile = class
public
class function Exists(const Path : string) : Boolean;
class function IsInUse(const Path : string) : Boolean;
class function GetSize(const Path : string) : Int64;
class function Create(const Path: string; const BufferSize: Integer): TFileStream; overload;
class function Create(const Path: string): TFileStream; overload;
class function GetExtension(const Path : string) : string;
class function GetCreationTime(const Path : string): TDateTime;
class function GetLastAccessTime(const Path : string): TDateTime;
class function GetLastWriteTime(const Path : string): TDateTime;
class procedure SetCreationTime(const Path: string; const CreationTime: TDateTime);
class procedure SetLastAccessTime(const Path: string; const LastAccessTime: TDateTime);
class procedure SetLastWriteTime(const Path: string; const LastWriteTime: TDateTime);
class function IsReadOnly(const Path : string) : Boolean;
class function Delete(const Path : string) : Boolean;
class function Move(const SourceFileName, DestFileName: string) : Boolean;
end;
TTextWriter = class
public
procedure Close; virtual; abstract;
procedure Flush; virtual; abstract;
procedure Write(Value: Boolean); overload; virtual; abstract;
procedure Write(Value: Char); overload; virtual; abstract;
procedure Write(Value: Double); overload; virtual; abstract;
procedure Write(Value: Integer); overload; virtual; abstract;
procedure Write(Value: Int64); overload; virtual; abstract;
procedure Write(Value: TObject); overload; virtual; abstract;
procedure Write(Value: Single); overload; virtual; abstract;
procedure Write(const Value: string); overload; virtual; abstract;
procedure Write(const aFormat: string; Args: array of const); overload; virtual; abstract;
procedure WriteLine; overload; virtual; abstract;
procedure WriteLine(Value: Boolean); overload; virtual; abstract;
procedure WriteLine(Value: Char); overload; virtual; abstract;
procedure WriteLine(Value: Double); overload; virtual; abstract;
procedure WriteLine(Value: Integer); overload; virtual; abstract;
procedure WriteLine(Value: Int64); overload; virtual; abstract;
procedure WriteLine(Value: TObject); overload; virtual; abstract;
procedure WriteLine(Value: Single); overload; virtual; abstract;
procedure WriteLine(const Value: string); overload; virtual; abstract;
procedure WriteLine(const aFormat: string; Args: array of const); overload; virtual; abstract;
end;
TStreamWriter = class(TTextWriter)
private
FStream: TStream;
FEncoding: TEncoding;
FNewLine: string;
FAutoFlush: Boolean;
FOwnsStream: Boolean;
FBufferIndex: Integer;
FBuffer: TBytes;
procedure WriteBytes(Bytes: TBytes);
public
constructor Create(Stream: TStream); overload;
constructor Create(Stream: TStream; Encoding: TEncoding; BufferSize: Integer = 4096); overload;
constructor Create(const Filename: string; Append: Boolean = False); overload;
constructor Create(const Filename: string; Append: Boolean; Encoding: TEncoding; BufferSize: Integer = 4096); overload;
destructor Destroy; override;
procedure Close; override;
procedure Flush; override;
procedure OwnStream; inline;
procedure Write(Value: Boolean); override;
procedure Write(Value: Char); override;
procedure Write(Value: Double); override;
procedure Write(Value: Integer); override;
procedure Write(Value: Int64); override;
procedure Write(Value: TObject); override;
procedure Write(Value: Single); override;
procedure Write(const Value: string); override;
procedure Write(const aFormat: string; Args: array of const); override;
procedure WriteLine; override;
procedure WriteLine(Value: Boolean); override;
procedure WriteLine(Value: Char); override;
procedure WriteLine(Value: Double); override;
procedure WriteLine(Value: Integer); override;
procedure WriteLine(Value: Int64); override;
procedure WriteLine(Value: TObject); override;
procedure WriteLine(Value: Single); override;
procedure WriteLine(const Value: string); override;
procedure WriteLine(const aFormat: string; Args: array of const); override;
property AutoFlush: Boolean read FAutoFlush write FAutoFlush;
property NewLine: string read FNewLine write FNewLine;
property Encoding: TEncoding read FEncoding;
property BaseStream: TStream read FStream;
end;
{$ENDIF FPC}
TDirItem = record
private
fName : string;
fIsDirectory : Boolean;
fSize : Int64;
fCreationDate : TDateTime;
fLastModified : TDateTime;
public
property Name : string read fName write fName;
property IsDirectory : Boolean read fIsDirectory write fIsDirectory;
property Size : Int64 read fSize write fSize;
property CreationDate : TDateTime read fCreationDate write fCreationDate;
property LastModified : TDateTime read fLastModified write fLastModified;
end;
{$IFNDEF FPC}
TDirItemAddProc = reference to procedure(const diritem : TDirItem);
{$ELSE}
TDirItemAddProc = procedure(const diritem : TDirItem);
{$ENDIF}
function CreateDummyFile(const aFilename : string; const aSize : Int64) : Boolean;
procedure SplitFile(const aFileName : string; aSplitByteSize : Int64);
procedure MergeFiles(const aFirstSplitFileName, aOutFileName : string); overload;
procedure MergeFiles(aFilenames : array of string; const aOutFileName : string); overload;
{$IFNDEF NEXTGEN}
function IsFileInUse(const aFileName : string) : Boolean;
{$ENDIF}
procedure FileReplaceText(const aFileName, aSearchText, AReplaceText : string);
{$IFNDEF NEXTGEN}
function FileSearchText(const aFileName, SearchText: string; caseSensitive : Boolean): Longint;
{$ENDIF}
function GetCreationTime(const aFilename : string): TDateTime;
function GetLastAccessTime(const aFileName: string): TDateTime;
function GetLastWriteTime(const aFileName : string): TDateTime;
{$IFDEF FPC}
function FindDelimiter(const Delimiters, S: string; StartIdx: Integer = 1): Integer;
{$ENDIF}
function ConvertDateTimeToFileTime(const DateTime: TDateTime; const UseLocalTimeZone: Boolean): TFileTime;
{$IFDEF MSWINDOWS}
function ConvertFileTimeToDateTime(const FileTime : TFileTime; const UseLocalTimeZone : Boolean) : TDateTime;
{$ENDIF}
procedure SetDateTimeInfo(const Path: string; const CreationTime, LastAccessTime, LastWriteTime: PDateTime; const UseLocalTimeZone: Boolean);
function GetFiles(const Path : string; Recursive : Boolean) : TArray<TDirItem>; overload;
procedure GetFiles(const Path : string; aAddToList : TDirItemAddProc; Recursive : Boolean); overload;
function GetDirectories(const Path : string; Recursive : Boolean) : TArray<TDirItem>;
function GetFilesAndDirectories(const Path : string; Recursive : Boolean) : TArray<TDirItem>; overload;
procedure GetFilesAndDirectories(const Path : string; aAddToList : TDirItemAddProc; Recursive : Boolean); overload;
implementation
{ TTextStreamFile }
{$IFNDEF FPC}
constructor TTextStreamFile.Create(const aFileName : string; aOpenMode : TTextFileOperation);
var
Append : Boolean;
begin
if aOpenMode = tfOpenRead then fReadStream := TStreamReader.Create(aFileName,True)
else
begin
if aOpenMode = tfOpenAppend then Append := True
else Append := False;
fWriteStream := TStreamWriter.Create(aFileName,Append);
end;
end;
destructor TTextStreamFile.Destroy;
begin
if Assigned(fReadStream) then fReadStream.Free;
if Assigned(fWriteStream) then fWriteStream.Free;
inherited Destroy;
end;
function TTextStreamFile.ReadLn(out Data: string): Boolean;
begin
Data := fReadStream.ReadLine;
Result := Data <> '';
end;
function TTextStreamFile.ReadLn: string;
begin
Result := fReadStream.ReadLine;
end;
procedure TTextStreamFile.WriteLn (const Data : string);
begin
fWriteStream.WriteLine(Data);
end;
function TTextStreamFile.GetEOF : Boolean;
begin
Result := fReadStream.EndOfStream;
end;
procedure TTextStreamFile.Close;
begin
if Assigned(fReadStream) then fReadStream.Close;
if Assigned(fWriteStream) then fWriteStream.Close;
end;
{$ENDIF NFPC}
{$IFDEF FPC}
{ EFileStreamError }
constructor EFileStreamError.Create(ResStringRec: PResStringRec;
const FileName: string);
begin
{$IFNDEF LINUX}
inherited CreateResFmt(ResStringRec, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]);
{$ELSE}
inherited CreateResFmt(ResStringRec, [ExpandFileName(FileName), SysErrorMessage(errno)]);
{$ENDIF}
end;
{ TPath }
class function TPath.GetFileNameWithoutExtension(const FileName: string
): string;
var
fname : string;
begin
fname := ExtractFileName(FileName);
Result := Copy(fname, 1, Length(fname) - Length(ExtractFileExt(fname)));
end;
class function TPath.ChangeExtension(const Path, NewExtension : string) : string;
var
dot : string;
begin
if NewExtension.Contains('.') then dot := ''
else dot := '.';
Result := TPath.GetFileNameWithoutExtension(Path) + dot + NewExtension;
end;
class function TPath.GetFileName(const aPath: string): string;
begin
Result := ExtractFileName(aPath);
end;
class function TPath.GetDirectoryName(const FileName : string) : string;
begin
Result := ExtractFileDir(Filename);
end;
class procedure TPath.CheckPathLength(const Path: string; const MaxLength: Integer);
begin
{$IFDEF MSWINDOWS}
if (Length(Path) >= MaxLength) then
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
if (Length(UTF8Encode(Path)) >= MaxLength) then
{$ENDIF POSIX}
raise EPathTooLongException.CreateRes(@SPathTooLong);
end;
class function TPath.GetExtension(const Path : string) : string;
begin
Result := ExtractFileExt(Path);
end;
class function TPath.EndsWithDelimiter(const aPath : string) : Boolean;
var
c : Char;
begin
if aPath = '' then Exit(False);
c := aPath[High(aPath)];
Result := (c = '\') or (c = '/');
end;
class function TPath.Combine(const aPath1, aPath2 : string) : string;
var
delim : string;
begin
delim := '';
if aPath1.Contains('/') then delim := '/'
else if aPath1.Contains('\') then delim := '\';
if delim = '' then
begin
{$IFDEF LINUX}
delim := '/';
{$ELSE}
delim := '\';
{$ENDIF}
end;
if EndsWithDelimiter(aPath1) then
begin
if EndsWithDelimiter(aPath2) then Result := aPath1 + Copy(aPath2,2,aPath2.Length)
else Result := aPath1 + aPath2;
end
else
begin
if EndsWithDelimiter(aPath2) then Result := aPath1 + aPath2
else Result := aPath1 + delim + aPath2;
end;
end;
{ TDirectory }
class function TDirectory.Exists(const Path: string; FollowLink: Boolean = True): Boolean;
begin
Result := DirectoryExists(Path);
end;
class function TDirectory.GetDirectories(const Path : string) : TArray<string>;
var
rec : TSearchRec;
begin
if FindFirst(TPath.Combine(Path,'*'),faAnyFile and faDirectory,rec) = 0 then
repeat
if ((rec.Attr and faDirectory) = faDirectory) and (rec.Name <> '.') and (rec.Name <> '..') then
begin
Result := Result + [rec.Name];
end;
until FindNext(rec) <> 0;
SysUtils.FindClose(rec);
end;
{ TFile }
class function TFile.Exists(const Path : string) : Boolean;
begin
Result := FileExists(Path);
end;
class procedure TFile.SetCreationTime(const Path: string; const CreationTime: TDateTime);
begin
SetDateTimeInfo(Path,@CreationTime,nil,nil,True);
end;
class procedure TFile.SetLastAccessTime(const Path: string; const LastAccessTime: TDateTime);
begin
SetDateTimeInfo(Path,nil,@LastAccessTime,nil,True);
end;
class procedure TFile.SetLastWriteTime(const Path: string; const LastWriteTime: TDateTime);
begin
SetDateTimeInfo(Path,nil,nil,@LastWriteTime,True);
end;
class function TFile.IsReadOnly(const Path : string) : Boolean;
begin
Result := FileIsReadOnly(Path);
end;
class function TFile.Delete(const Path : string) : Boolean;
begin
Result := DeleteFile(PChar(Path));
end;
class function TFile.Move(const SourceFileName, DestFileName: string) : Boolean;
begin
{$IFNDEF LINUX}
Result := MoveFile(PChar(SourceFileName),PChar(DestFileName));
{$ELSE}
Result := RenameFile(PChar(SourceFileName),PChar(DestFileName));
{$ENDIF}
end;
{$IFNDEF NEXTGEN}
class function TFile.IsInUse(const Path : string) : Boolean;
begin
Result := IsFileInUse(Path);
end;
{$ENDIF}
class function TFile.GetSize(const Path : string) : Int64;
var
f : File of Byte;
begin
Assign(f,Path);
try
Reset (f);
Result := FileSize(f);
finally
CloseFile(f);
end;
end;
class function TFile.GetExtension(const Path : string) : string;
begin
Result := ExtractFileExt(Path);
end;
class function TFile.GetCreationTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetCreationTime(Path);
end;
class function TFile.GetLastAccessTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetLastAccessTime(Path);
end;
class function TFile.GetLastWriteTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetLastWriteTime(Path);
end;
class function TFile.Create(const Path: string; const BufferSize: Integer): TFileStream;
begin
try
Result := TFileStream.Create(Path,fmCreate);
except
on E: EFileStreamError do
raise EInOutError.Create(E.Message);
end;
end;
class function TFile.Create(const Path: string): TFileStream;
begin
Result := Create(Path, 0);
end;
{ TStreamWriter }
procedure TStreamWriter.Close;
begin
Flush;
if FOwnsStream then
FreeAndNil(FStream);
end;
constructor TStreamWriter.Create(Stream: TStream);
begin
inherited Create;
FOwnsStream := False;
FStream := Stream;
FEncoding := TEncoding.UTF8;
SetLength(FBuffer, 1024);
FBufferIndex := 0;
FNewLine := sLineBreak;
FAutoFlush := True;
end;
constructor TStreamWriter.Create(Stream: TStream; Encoding: TEncoding; BufferSize: Integer);
begin
inherited Create;
FOwnsStream := False;
FStream := Stream;
FEncoding := Encoding;
if BufferSize >= 128 then
SetLength(FBuffer, BufferSize)
else
SetLength(FBuffer, 128);
FBufferIndex := 0;
FNewLine := sLineBreak;
FAutoFlush := True;
if Stream.Position = 0 then
WriteBytes(FEncoding.GetPreamble);
end;
constructor TStreamWriter.Create(const Filename: string; Append: Boolean);
begin
if (not FileExists(Filename)) or (not Append) then
FStream := TFileStream.Create(Filename, fmCreate)
else
begin
FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);
end;
Create(FStream);
FOwnsStream := True;
end;
constructor TStreamWriter.Create(const Filename: string; Append: Boolean;
Encoding: TEncoding; BufferSize: Integer);
begin
if (not FileExists(Filename)) or (not Append) then
FStream := TFileStream.Create(Filename, fmCreate)
else
begin
FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);
end;
Create(FStream, Encoding, BufferSize);
FOwnsStream := True;
end;
destructor TStreamWriter.Destroy;
begin
Close;
SetLength(FBuffer, 0);
inherited;
end;
procedure TStreamWriter.Flush;
begin
if FBufferIndex = 0 then
Exit;
if FStream = nil then
Exit;
FStream.Write(FBuffer[0], FBufferIndex);
FBufferIndex := 0;
end;
procedure TStreamWriter.OwnStream;
begin
FOwnsStream := True;
end;
procedure TStreamWriter.Write(const Value: string);
begin
WriteBytes(FEncoding.GetBytes(Value));
end;
procedure TStreamWriter.WriteBytes(Bytes: TBytes);
var
ByteIndex: Integer;
WriteLen: Integer;
begin
ByteIndex := 0;
while ByteIndex < Length(Bytes) do
begin
WriteLen := Length(Bytes) - ByteIndex;
if WriteLen > Length(FBuffer) - FBufferIndex then
WriteLen := Length(FBuffer) - FBufferIndex;
Move(Bytes[ByteIndex], FBuffer[FBufferIndex], WriteLen);
Inc(FBufferIndex, WriteLen);
Inc(ByteIndex, WriteLen);
if FBufferIndex >= Length(FBuffer) then
Flush;
end;
if FAutoFlush then
Flush;
end;
procedure TStreamWriter.Write(const aFormat: string; Args: array of const);
begin
WriteBytes(FEncoding.GetBytes(Format(aFormat, Args)));
end;
procedure TStreamWriter.Write(Value: Single);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Double);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Integer);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Char);
begin
WriteBytes(FEncoding.GetBytes(Value));
end;
procedure TStreamWriter.Write(Value: TObject);
begin
WriteBytes(FEncoding.GetBytes(Value.ToString));
end;
procedure TStreamWriter.Write(Value: Int64);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Boolean);
begin
WriteBytes(FEncoding.GetBytes(BoolToStr(Value, True)));
end;
procedure TStreamWriter.WriteLine(Value: Double);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Integer);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine;
begin
WriteBytes(FEncoding.GetBytes(FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Boolean);
begin
WriteBytes(FEncoding.GetBytes(BoolToStr(Value, True) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Char);
begin
WriteBytes(FEncoding.GetBytes(Value));
WriteBytes(FEncoding.GetBytes(FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Int64);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(const aFormat: string; Args: array of const);
begin
WriteBytes(FEncoding.GetBytes(Format(aFormat, Args) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: TObject);
begin
WriteBytes(FEncoding.GetBytes(Value.ToString + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Single);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(const Value: string);
begin
WriteBytes(FEncoding.GetBytes(Value + FNewLine));
end;
{$ENDIF FPC}
{other functions}
function CreateDummyFile(const aFilename : string; const aSize : Int64 ) : Boolean;
var
fs : TFileStream;
i : Integer;
buf : string;
Begin
fs := TFileStream.Create(aFilename,fmCreate);
buf := 'A';
try
fs.Seek(0, soBeginning);
for i := 0 to aSize do fs.Write(buf[1], Length(buf));
finally
fs.Free;
end;
Result := FileExists(aFilename);
End;
procedure SplitFile(const aFileName : string; aSplitByteSize : Int64);
var
fs, ss: TFileStream;
cnt : integer;
splitname: string;
begin
fs := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite) ;
try
for cnt := 1 to Trunc(fs.Size / aSplitByteSize) + 1 do
begin
splitname := ChangeFileExt(aFileName, Format('%s%.3d', ['.',cnt])) ;
ss := TFileStream.Create(splitname, fmCreate or fmShareExclusive) ;
try
if fs.Size - fs.Position < aSplitByteSize then
aSplitByteSize := fs.Size - fs.Position;
ss.CopyFrom(fs, aSplitByteSize) ;
finally
ss.Free;
end;
end;
finally
fs.Free;
end;
end;
procedure MergeFiles(const aFirstSplitFileName, aOutFileName : string);
var
fs, ss: TFileStream;
cnt: integer;
splitfilename : string;
begin
cnt := 1;
splitfilename := aFirstSplitFileName;
fs := TFileStream.Create(aOutFileName, fmCreate or fmShareExclusive) ;
try
while FileExists(splitfilename) do
begin
ss := TFileStream.Create(splitfilename, fmOpenRead or fmShareDenyWrite) ;
try
fs.CopyFrom(ss, 0) ;
finally
ss.Free;
end;
Inc(cnt) ;
splitfilename := ChangeFileExt(aFirstSplitFileName, Format('%s%.3d', ['.',cnt])) ;
end;
finally
fs.Free;
end;
end;
procedure MergeFiles(aFilenames : array of string; const aOutFileName : string);
var
filename : string;
fs,
ss : TFileStream;
begin
fs := TFileStream.Create(aOutFileName,fmCreate or fmShareExclusive) ;
try
for filename in aFilenames do
begin
if not FileExists(filename) then raise Exception.CreateFmt('Merge file %s not found!',[filename]);
ss := TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite) ;
try
fs.CopyFrom(ss,0);
finally
ss.Free;
end;
end;
finally
fs.Free;
end;
end;
function IsFileInUse(const aFileName : string) : Boolean;
{$IF NOT Defined(LINUX) AND NOT Defined(MACOS) AND NOT Defined(ANDROID)}
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(aFileName) then Exit;
try
HFileRes := CreateFile(PChar(aFileName),
GENERIC_READ or GENERIC_WRITE
,0
,nil
,OPEN_EXISTING
,FILE_ATTRIBUTE_NORMAL
,0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not(Result) then begin
CloseHandle(HFileRes);
end;
except
Result := True;
end;
end;
{$ELSE}
var
fs : TFileStream;
begin
try
fs := TFileStream.Create(aFileName, fmOpenReadWrite, fmShareExclusive);
Result := True;
fs.Free;
except
Result := False;
end;
end;
{$ENDIF}
procedure FileReplaceText(const aFileName, aSearchText, AReplaceText : string);
var
fs: TFileStream;
S: string;
begin
fs := TFileStream.Create(aFileName, fmOpenread or fmShareDenyNone);
try
SetLength(S, fs.Size);
fs.ReadBuffer(S[1], fs.Size);
finally
fs.Free;
end;
S := StringReplace(S, aSearchText, AReplaceText, [rfReplaceAll, rfIgnoreCase]);
fs := TFileStream.Create(aFileName, fmCreate);
try
fs.WriteBuffer(S[1], Length(S));
finally
fs.Free;
end;
end;
{$IFNDEF NEXTGEN}
function FileSearchText(const aFileName, SearchText: string; caseSensitive : Boolean): Longint;
const
BufferSize = $8001;
var
pBuf, pEnd, pScan, pPos: PAnsiChar;
filesize: LongInt;
bytesRemaining: LongInt;
bytesToRead: Integer;
F: file;
SearchFor: PAnsiChar;
oldMode: Word;
begin
Result := -1;
if (Length(SearchText) = 0) or (Length(aFileName) = 0) then Exit;
SearchFor := nil;
pBuf := nil;
AssignFile(F, aFileName);
oldMode := FileMode;
FileMode := 0;
Reset(F, 1);
FileMode := oldMode;
try
{$IFDEF FPC}
SearchFor := PChar(StrAlloc(Length(SearchText) + 1));
{$ELSE}
{$IFDEF DELPHI2010_UP}
SearchFor := PAnsiChar(StrAlloc(Length(SearchText) + 1));
{$ELSE}
SearchFor := StrAlloc(Length(SearchText) + 1);
{$ENDIF}
{$ENDIF FPC}
StrPCopy(SearchFor, SearchText);
{$IFDEF FPC}
if not caseSensitive then UpperCase(SearchFor);
{$ELSE}
if not caseSensitive then AnsiUpperCase(SearchFor);
{$ENDIF}
GetMem(pBuf, BufferSize);
filesize := System.Filesize(F);
bytesRemaining := filesize;
pPos := nil;
while bytesRemaining > 0 do
begin
if bytesRemaining >= BufferSize then bytesToRead := Pred(BufferSize)
else bytesToRead := bytesRemaining;
BlockRead(F, pBuf^, bytesToRead, bytesToRead);
pEnd := @pBuf[bytesToRead];
pEnd^ := #0;
pScan := pBuf;
while pScan < pEnd do
begin
{$IFDEF FPC}
if not caseSensitive then UpperCase(pScan);
{$ELSE}
if not caseSensitive then AnsiUpperCase(pScan);
{$ENDIF}
pPos := StrPos(pScan, SearchFor);
if pPos <> nil then
begin
Result := FileSize - bytesRemaining +
Longint(pPos) - Longint(pBuf);
Break;
end;
pScan := StrEnd(pScan);
Inc(pScan);
end;
if pPos <> nil then Break;
bytesRemaining := bytesRemaining - bytesToRead;
if bytesRemaining > 0 then
begin
Seek(F, FilePos(F) - Length(SearchText));
bytesRemaining := bytesRemaining + Length(SearchText);
end;
end;
finally
CloseFile(F);
if SearchFor <> nil then StrDispose(SearchFor);
if pBuf <> nil then FreeMem(pBuf, BufferSize);
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function GetLastAccessTime(const aFileName: string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
Result := 0;
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftLastAccessTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
function GetCreationTime(const aFilename : string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
Result := 0;
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftCreationTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
function GetLastWriteTime(const aFileName : string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
Result := 0;
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftLastWriteTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
{$ELSE}
{$IFDEF FPC} //FPC Linux
function GetLastAccessTime(const aFileName: string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_atime;
end;
end;
function GetCreationTime(const aFilename : string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_ctime;
end;
end;
function GetLastWriteTime(const aFileName : string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_mtime;
end;
end;
{$ELSE} //Delphi Nextgen & Linux
function GetLastAccessTime(const aFileName: string): TDateTime;
var
info : TDateTimeInfoRec;
begin
if FileGetDateTimeInfo(aFileName,info,True) then Result := info.LastAccessTime
else Result := 0.0;
end;
function GetCreationTime(const aFilename : string): TDateTime;
var
info : TDateTimeInfoRec;
begin
if FileGetDateTimeInfo(aFileName,info,True) then Result := info.CreationTime
else Result := 0.0;
end;
function GetLastWriteTime(const aFileName : string): TDateTime;
var
info : TDateTimeInfoRec;
begin
if FileGetDateTimeInfo(aFileName,info,True) then Result := info.TimeStamp
else Result := 0.0;
end;
{$ENDIF}
{$ENDIF}
{$IFDEF FPC}
function FindDelimiter(const Delimiters, S: string; StartIdx: Integer = 1): Integer;
var
Stop: Boolean;
Len: Integer;
begin
Result := 0;
Len := S.Length;
Stop := False;
while (not Stop) and (StartIdx <= Len) do
if IsDelimiter(Delimiters, S, StartIdx) then
begin
Result := StartIdx;
Stop := True;
end
else
Inc(StartIdx);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function ConvertDateTimeToFileTime(const DateTime: TDateTime; const UseLocalTimeZone: Boolean): TFileTime;
var
LFileTime: TFileTime;
SysTime: TSystemTime;
begin
Result.dwLowDateTime := 0;
Result.dwLowDateTime := 0;
DecodeDateTime(DateTime, SysTime.wYear, SysTime.wMonth, SysTime.wDay,
SysTime.wHour, SysTime.wMinute, SysTime.wSecond, SysTime.wMilliseconds);
if SystemTimeToFileTime(SysTime, LFileTime) then
if UseLocalTimeZone then
LocalFileTimeToFileTime(LFileTime, Result)
else
Result := LFileTime;
end;
function ConvertFileTimeToDateTime(const FileTime : TFileTime; const UseLocalTimeZone : Boolean) : TDateTime;
var
dft: DWORD;
lft: TFileTime;
begin
FileTimeToLocalFileTime(FileTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
{$ENDIF}
{$If Defined(FPC) AND Defined(LINUX)}
function ConvertDateTimeToFileTime(const DateTime: TDateTime; const UseLocalTimeZone: Boolean): TFileTime;
begin
{ Use the time zone if necessary }
if not UseLocalTimeZone then
Result := DateTimeToFileDate(DateTime)
else
Result := DateTimeToFileDate(DateTime);
end;
{$ENDIF}
{$IFDEF POSIX}
function ConvertDateTimeToFileTime(const DateTime: TDateTime; const UseLocalTimeZone: Boolean): TFileTime;
begin
{ Use the time zone if necessary }
if not UseLocalTimeZone then
Result := DateTimeToFileDate(TTimeZone.Local.ToLocalTime(DateTime))
else
Result := DateTimeToFileDate(DateTime);
end;
{$ENDIF}
procedure SetDateTimeInfo(const Path: string; const CreationTime, LastAccessTime, LastWriteTime: PDateTime; const UseLocalTimeZone: Boolean);
{$IFDEF MSWINDOWS}
var
LFileHnd: THandle;
LFileAttr: Cardinal;
LFileCreationTime: PFileTime;
LFileLastAccessTime: PFileTime;
LFileLastWriteTime: PFileTime;
begin
// establish what date-times must be set to the directory
LFileHnd := 0;
LFileCreationTime := nil;
LFileLastAccessTime := nil;
LFileLastWriteTime := nil;
try
try
if Assigned(CreationTime) then
begin
New(LFileCreationTime);
LFileCreationTime^ := ConvertDateTimeToFileTime(CreationTime^, UseLocalTimeZone);
end;
if Assigned(LastAccessTime) then
begin
New(LFileLastAccessTime);
LFileLastAccessTime^ := ConvertDateTimeToFileTime(LastAccessTime^, UseLocalTimeZone);
end;
if Assigned(LastWriteTime) then
begin
New(LFileLastWriteTime);
LFileLastWriteTime^ := ConvertDateTimeToFileTime(LastWriteTime^, UseLocalTimeZone);
end;
// determine if Path points to a directory or a file
SetLastError(ERROR_SUCCESS);
LFileAttr := FileGetAttr(Path);
if LFileAttr and faDirectory <> 0 then
LFileAttr := FILE_FLAG_BACKUP_SEMANTICS
else
LFileAttr := FILE_ATTRIBUTE_NORMAL;
// set the new date-times to the directory or file
LFileHnd := CreateFile(PChar(Path), GENERIC_WRITE, FILE_SHARE_WRITE, nil,
OPEN_EXISTING, LFileAttr, 0);
if LFileHnd <> INVALID_HANDLE_VALUE then
SetFileTime(LFileHnd, LFileCreationTime, LFileLastAccessTime, LFileLastWriteTime);
except
on E: EConvertError do
raise EArgumentOutOfRangeException.Create(E.Message);
end;
finally
CloseHandle(LFileHnd);
SetLastError(ERROR_SUCCESS);
Dispose(LFileCreationTime);
Dispose(LFileLastAccessTime);
Dispose(LFileLastWriteTime);
end;
end;
{$ENDIF}
{$IFDEF POSIX}
var
LFileName: Pointer;
LStatBuf: _stat;
LBuf: utimbuf;
ErrCode: Integer;
M: TMarshaller;
begin
{ Do nothing if no date/time passed. Ignore CreationTime. Unixes do not support creation times for files. }
if (LastAccessTime = nil) and (LastWriteTime = nil) then
Exit;
LFileName := M.AsAnsi(Path, CP_UTF8).ToPointer;
{ Obtain the file times. lstat may fail }
if ((LastAccessTime = nil) or (LastWriteTime = nil)) then
begin
ErrCode := stat(LFileName, LStatBuf);
{ Fail if we can't access the file properly }
if ErrCode <> 0 then
Exit; // Fail here prematurely. Do not chnage file times if we failed to fetch the old ones.
end;
try
{ Preserve of set the new value }
if LastAccessTime <> nil then
LBuf.actime := ConvertDateTimeToFileTime(LastAccessTime^, UseLocalTimeZone)
else
LBuf.actime := LStatBuf.st_atime;
{ Preserve of set the new value }
if LastWriteTime <> nil then
LBuf.modtime := ConvertDateTimeToFileTime(LastWriteTime^, UseLocalTimeZone)
else
LBuf.modtime := LStatBuf.st_mtime;
{ Call utime to set the file times }
utime(LFileName, LBuf);
except
on E: EConvertError do // May rise in ConvertDateTimeToFileTime
raise EArgumentOutOfRangeException.Create(E.Message);
end;
end;
{$ENDIF}
{$if Defined(FPC) AND Defined(LINUX)}
begin
end;
{$ENDIF}
function GetFiles(const Path : string; Recursive : Boolean) : TArray<TDirItem>;
var
rec : TSearchRec;
diritem : TDirItem;
begin
if FindFirst(IncludeTrailingPathDelimiter(Path) + '*', faAnyFile, rec) = 0 then
try
repeat
if (rec.Attr and faDirectory) <> faDirectory then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := False;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
Result := Result + [diritem];
end
else
begin
if Recursive then Result := Result + GetFiles(IncludeTrailingPathDelimiter(Path) + diritem.Name,Recursive);
end;
until FindNext(rec) <> 0;
finally
SysUtils.FindClose(rec);
end;
end;
procedure GetFiles(const Path : string; aAddToList : TDirItemAddProc; Recursive : Boolean);
var
rec : TSearchRec;
diritem : TDirItem;
begin
if FindFirst(IncludeTrailingPathDelimiter(Path) + '*', faAnyFile, rec) = 0 then
try
repeat
if (rec.Attr and faDirectory) <> faDirectory then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := False;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
aAddToList(diritem);
end
else
begin
if Recursive then GetFiles(IncludeTrailingPathDelimiter(Path) + diritem.Name,aAddToList,Recursive);
end;
until FindNext(rec) <> 0;
finally
SysUtils.FindClose(rec);
end;
end;
function GetDirectories(const Path : string; Recursive : Boolean) : TArray<TDirItem>;
var
rec : TSearchRec;
diritem : TDirItem;
begin
if FindFirst(IncludeTrailingPathDelimiter(Path) + '*', faAnyFile, rec) = 0 then
try
repeat
if ((rec.Attr and faDirectory) = faDirectory) and (rec.Name <> '.') and (rec.Name <> '..') then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := True;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
Result := Result + [diritem];
if Recursive then Result := Result + GetFiles(IncludeTrailingPathDelimiter(Path) + diritem.Name,Recursive);
end;
until FindNext(rec) <> 0;
finally
SysUtils.FindClose(rec);
end;
end;
function GetFilesAndDirectories(const Path : string; Recursive : Boolean) : TArray<TDirItem>;
var
rec : TSearchRec;
diritem : TDirItem;
dirpath : string;
wildcard : string;
begin
if Path.Contains('*') then
begin
dirpath := ExtractFilePath(Path);
wildcard := ExtractFileName(Path);
end
else
begin
dirpath := Path;
wildcard := '*';
end;
dirpath := IncludeTrailingPathDelimiter(dirpath);
if FindFirst(dirpath + wildcard, faAnyFile, rec) = 0 then
try
repeat
if (rec.Attr and faDirectory) <> faDirectory then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := False;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
Result := Result + [diritem];
end
else if (rec.Name <> '.') and (rec.Name <> '..') then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := True;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
Result := Result + [diritem];
if Recursive then Result := Result + GetFilesAndDirectories(dirpath + diritem.Name,Recursive);
end;
until FindNext(rec) <> 0;
finally
SysUtils.FindClose(rec);
end;
end;
procedure GetFilesAndDirectories(const Path : string; aAddToList : TDirItemAddProc; Recursive : Boolean);
var
rec : TSearchRec;
diritem : TDirItem;
dirpath : string;
wildcard : string;
begin
if not Assigned(aAddToList) then raise Exception.Create('GetFilesAndDirecties: AddToList cannot be nil!');
if Path.Contains('*') then
begin
dirpath := ExtractFilePath(Path);
wildcard := ExtractFileName(Path);
end
else
begin
dirpath := Path;
wildcard := '*';
end;
dirpath := IncludeTrailingPathDelimiter(dirpath);
if FindFirst(dirpath + wildcard, faAnyFile, rec) = 0 then
try
repeat
if (rec.Attr and faDirectory) <> faDirectory then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := False;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
aAddToList(diritem);
end
else if (rec.Name <> '.') and (rec.Name <> '..') then
begin
diritem.Name := rec.Name;
diritem.IsDirectory := True;
diritem.Size := rec.Size;
{$IFNDEF LINUX}
diritem.CreationDate := ConvertFileTimeToDateTime(rec.FindData.ftCreationTime,True);
diritem.LastModified := ConvertFileTimeToDateTime(rec.FindData.ftLastWriteTime,True);
{$ELSE}
diritem.CreationDate := FileDateToDateTime(rec.Time);
{$ENDIF}
aAddToList(diritem);
if Recursive then GetFilesAndDirectories(dirpath + diritem.Name,aAddToList,Recursive);
end;
until FindNext(rec) <> 0;
finally
SysUtils.FindClose(rec);
end;
end;
end.
|
//-----------------------
procedure MsgCopyMoveError(const OldName, NewName: WideString; h: THandle);
begin
MsgError(
SFormatW(MsgViewerCopyMoveError, [SExtractFileName(OldName), NewName])
+ #13#13 + MsgString(313), h);
end;
procedure MsgDeleteError(const OldName: WideString; h: THandle);
begin
MsgError(
SFormatW(MsgViewerDeleteError, [SExtractFileName(OldName)])
+ #13#13 + MsgString(313), h);
end;
//-----------------------
function TFormViewUV.GetImageBorderWidth: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
Result := Width - ClientWidth;
end;
function TFormViewUV.GetImageBorderHeight: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
Result := Height - ClientHeight;
end;
function TFormViewUV.GetImageWidthActual: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
begin
if ImageFitToWindow then
Result := ImageWidth
else
Result := Image.Width;
end;
end;
function TFormViewUV.GetImageHeightActual: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
begin
if ImageFitToWindow then
Result := ImageHeight
else
Result := Image.Height;
end;
end;
function TFormViewUV.GetImageWidthActual2: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
Result := Image.Width;
end;
function TFormViewUV.GetImageHeightActual2: Integer;
begin
Result := 0;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
Result := Image.Height;
end;
function TFormViewUV.GetImageScrollVisible: Boolean;
begin
Result := False;
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
Result := HorzScrollBar.Visible or VertScrollBar.Visible;
end;
procedure TFormViewUV.SetImageScrollVisible(AValue: Boolean);
begin
if Assigned(Viewer.ImageBox) then
with Viewer.ImageBox do
begin
HorzScrollBar.Visible := AValue;
VertScrollBar.Visible := AValue;
end;
end;
//---------------------------------------------------------------
procedure TFormViewUV.UpdateFitWindow(AUseOriginalImageSizes: boolean);
function WidthIncrement: integer;
begin
Result:= 0;
end;
function HeightIncrement: integer;
begin
Result:= 0;
if StatusBar1.Visible then
Inc(Result, StatusBar1.Height);
if Toolbar.Visible then
Inc(Result, Toolbar.Height);
end;
var
ALeft, ATop, AWidth, AHeight: integer;
begin
if (Viewer.Mode=vmodeMedia) and Viewer.IsImage then
if MediaFitWindow then
begin
//Set window sizes
ImageScrollVisible:= false;
if AUseOriginalImageSizes then
begin
AWidth:= ImageWidthActual + ImageBorderWidth;
AHeight:= ImageHeightActual + ImageBorderHeight;
end
else
begin
AWidth:= ImageWidthActual2 + ImageBorderWidth;
AHeight:= ImageHeightActual2 + ImageBorderHeight;
end;
//Return back from Maximized and Full Screen states:
ShowFullScreen:= false;
WindowState:= wsNormal;
ClientWidth:= AWidth + WidthIncrement;
ClientHeight:= AHeight + HeightIncrement;
ImageScrollVisible:= true;
//Move window
ALeft:= IMax(IMin(Left, Screen.WorkAreaWidth - Width), Screen.WorkAreaLeft);
ATop:= IMax(IMin(Top, Screen.WorkAreaHeight- Height), Screen.WorkAreaTop);
AWidth:= IMin(Width, Screen.WorkAreaWidth);
AHeight:= IMin(Height, Screen.WorkAreaHeight);
SetBounds(ALeft, ATop, AWidth, AHeight);
end;
end;
|
unit INFODIARYTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TINFODIARYRecord = record
PClNum: String[6];
PEvDate: String[10];
PEvTime: String[6];
PEventID: String[6];
PModCount: Integer;
PUserId: String[6];
PInitRv: String[10];
PRvDate: String[10];
PDoneDate: String[10];
End;
TINFODIARYBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TINFODIARYRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIINFODIARY = (INFODIARYPrimaryKey);
TINFODIARYTable = class( TDBISAMTableAU )
private
FDFClNum: TStringField;
FDFEvDate: TStringField;
FDFEvTime: TStringField;
FDFEventID: TStringField;
FDFModCount: TIntegerField;
FDFUserId: TStringField;
FDFInitRv: TStringField;
FDFRvDate: TStringField;
FDFDoneDate: TStringField;
FDFNotes: TBlobField;
procedure SetPClNum(const Value: String);
function GetPClNum:String;
procedure SetPEvDate(const Value: String);
function GetPEvDate:String;
procedure SetPEvTime(const Value: String);
function GetPEvTime:String;
procedure SetPEventID(const Value: String);
function GetPEventID:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPUserId(const Value: String);
function GetPUserId:String;
procedure SetPInitRv(const Value: String);
function GetPInitRv:String;
procedure SetPRvDate(const Value: String);
function GetPRvDate:String;
procedure SetPDoneDate(const Value: String);
function GetPDoneDate:String;
procedure SetEnumIndex(Value: TEIINFODIARY);
function GetEnumIndex: TEIINFODIARY;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TINFODIARYRecord;
procedure StoreDataBuffer(ABuffer:TINFODIARYRecord);
property DFClNum: TStringField read FDFClNum;
property DFEvDate: TStringField read FDFEvDate;
property DFEvTime: TStringField read FDFEvTime;
property DFEventID: TStringField read FDFEventID;
property DFModCount: TIntegerField read FDFModCount;
property DFUserId: TStringField read FDFUserId;
property DFInitRv: TStringField read FDFInitRv;
property DFRvDate: TStringField read FDFRvDate;
property DFDoneDate: TStringField read FDFDoneDate;
property DFNotes: TBlobField read FDFNotes;
property PClNum: String read GetPClNum write SetPClNum;
property PEvDate: String read GetPEvDate write SetPEvDate;
property PEvTime: String read GetPEvTime write SetPEvTime;
property PEventID: String read GetPEventID write SetPEventID;
property PModCount: Integer read GetPModCount write SetPModCount;
property PUserId: String read GetPUserId write SetPUserId;
property PInitRv: String read GetPInitRv write SetPInitRv;
property PRvDate: String read GetPRvDate write SetPRvDate;
property PDoneDate: String read GetPDoneDate write SetPDoneDate;
published
property Active write SetActive;
property EnumIndex: TEIINFODIARY read GetEnumIndex write SetEnumIndex;
end; { TINFODIARYTable }
procedure Register;
implementation
procedure TINFODIARYTable.CreateFields;
begin
FDFClNum := CreateField( 'ClNum' ) as TStringField;
FDFEvDate := CreateField( 'EvDate' ) as TStringField;
FDFEvTime := CreateField( 'EvTime' ) as TStringField;
FDFEventID := CreateField( 'EventID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFUserId := CreateField( 'UserId' ) as TStringField;
FDFInitRv := CreateField( 'InitRv' ) as TStringField;
FDFRvDate := CreateField( 'RvDate' ) as TStringField;
FDFDoneDate := CreateField( 'DoneDate' ) as TStringField;
FDFNotes := CreateField( 'Notes' ) as TBlobField;
end; { TINFODIARYTable.CreateFields }
procedure TINFODIARYTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TINFODIARYTable.SetActive }
procedure TINFODIARYTable.SetPClNum(const Value: String);
begin
DFClNum.Value := Value;
end;
function TINFODIARYTable.GetPClNum:String;
begin
result := DFClNum.Value;
end;
procedure TINFODIARYTable.SetPEvDate(const Value: String);
begin
DFEvDate.Value := Value;
end;
function TINFODIARYTable.GetPEvDate:String;
begin
result := DFEvDate.Value;
end;
procedure TINFODIARYTable.SetPEvTime(const Value: String);
begin
DFEvTime.Value := Value;
end;
function TINFODIARYTable.GetPEvTime:String;
begin
result := DFEvTime.Value;
end;
procedure TINFODIARYTable.SetPEventID(const Value: String);
begin
DFEventID.Value := Value;
end;
function TINFODIARYTable.GetPEventID:String;
begin
result := DFEventID.Value;
end;
procedure TINFODIARYTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TINFODIARYTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TINFODIARYTable.SetPUserId(const Value: String);
begin
DFUserId.Value := Value;
end;
function TINFODIARYTable.GetPUserId:String;
begin
result := DFUserId.Value;
end;
procedure TINFODIARYTable.SetPInitRv(const Value: String);
begin
DFInitRv.Value := Value;
end;
function TINFODIARYTable.GetPInitRv:String;
begin
result := DFInitRv.Value;
end;
procedure TINFODIARYTable.SetPRvDate(const Value: String);
begin
DFRvDate.Value := Value;
end;
function TINFODIARYTable.GetPRvDate:String;
begin
result := DFRvDate.Value;
end;
procedure TINFODIARYTable.SetPDoneDate(const Value: String);
begin
DFDoneDate.Value := Value;
end;
function TINFODIARYTable.GetPDoneDate:String;
begin
result := DFDoneDate.Value;
end;
procedure TINFODIARYTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ClNum, String, 6, Y');
Add('EvDate, String, 10, N');
Add('EvTime, String, 6, N');
Add('EventID, String, 6, N');
Add('ModCount, Integer, 0, N');
Add('UserId, String, 6, N');
Add('InitRv, String, 10, N');
Add('RvDate, String, 10, N');
Add('DoneDate, String, 10, N');
Add('Notes, Memo, 0, N');
end;
end;
procedure TINFODIARYTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ClNum;EvDate;EvTime;EventID, Y, Y, N, N');
end;
end;
procedure TINFODIARYTable.SetEnumIndex(Value: TEIINFODIARY);
begin
case Value of
INFODIARYPrimaryKey : IndexName := '';
end;
end;
function TINFODIARYTable.GetDataBuffer:TINFODIARYRecord;
var buf: TINFODIARYRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PClNum := DFClNum.Value;
buf.PEvDate := DFEvDate.Value;
buf.PEvTime := DFEvTime.Value;
buf.PEventID := DFEventID.Value;
buf.PModCount := DFModCount.Value;
buf.PUserId := DFUserId.Value;
buf.PInitRv := DFInitRv.Value;
buf.PRvDate := DFRvDate.Value;
buf.PDoneDate := DFDoneDate.Value;
result := buf;
end;
procedure TINFODIARYTable.StoreDataBuffer(ABuffer:TINFODIARYRecord);
begin
DFClNum.Value := ABuffer.PClNum;
DFEvDate.Value := ABuffer.PEvDate;
DFEvTime.Value := ABuffer.PEvTime;
DFEventID.Value := ABuffer.PEventID;
DFModCount.Value := ABuffer.PModCount;
DFUserId.Value := ABuffer.PUserId;
DFInitRv.Value := ABuffer.PInitRv;
DFRvDate.Value := ABuffer.PRvDate;
DFDoneDate.Value := ABuffer.PDoneDate;
end;
function TINFODIARYTable.GetEnumIndex: TEIINFODIARY;
var iname : string;
begin
result := INFODIARYPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := INFODIARYPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TINFODIARYTable, TINFODIARYBuffer ] );
end; { Register }
function TINFODIARYBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..9] of string = ('CLNUM','EVDATE','EVTIME','EVENTID','MODCOUNT','USERID'
,'INITRV','RVDATE','DONEDATE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 9) and (flist[x] <> s) do inc(x);
if x <= 9 then result := x else result := 0;
end;
function TINFODIARYBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftInteger;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
end;
end;
function TINFODIARYBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PClNum;
2 : result := @Data.PEvDate;
3 : result := @Data.PEvTime;
4 : result := @Data.PEventID;
5 : result := @Data.PModCount;
6 : result := @Data.PUserId;
7 : result := @Data.PInitRv;
8 : result := @Data.PRvDate;
9 : result := @Data.PDoneDate;
end;
end;
end.
|
unit K588577774;
{* [Requestlink:588577774] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K588577774.pas"
// Стереотип: "TestCase"
// Элемент модели: "K588577774" MUID: (55E594D800FE)
// Имя типа: "TK588577774"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK588577774 = class(TRTFtoEVDWriterTest)
{* [Requestlink:588577774] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK588577774
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *55E594D800FEimpl_uses*
//#UC END# *55E594D800FEimpl_uses*
;
function TK588577774.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK588577774.GetFolder
function TK588577774.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55E594D800FE';
end;//TK588577774.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK588577774.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2023 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.Storage;
interface
uses
System.Classes, System.JSON, System.SysUtils, System.SyncObjs,
System.Net.HttpClient, System.Net.URLClient, System.Generics.Collections,
REST.Types,
FB4D.Interfaces, FB4D.Response, FB4D.Request;
type
TFirebaseStorage = class(TInterfacedObject, IFirebaseStorage)
private type
TCacheFile = class
FileName: string;
MD5Hash: string;
LastUpdate: TDateTime;
FileSize: Int64;
constructor AddToCache(const aFileName: string; FSize: Int64 = 0);
end;
private
fBucket: string;
fAuth: IFirebaseAuthentication;
fStorageObjs: TDictionary<TObjectName, IStorageObject>;
fCSForStorageObjs: TCriticalSection;
fCacheFolder: string;
fMaxCacheSpaceInBytes: Int64;
fCacheSpaceInBytes: Int64;
fCacheContent: TList<TCacheFile>;
fScanSync: TCriticalSection;
fScanFinished: TDateTime;
fLastUpdateRemovedFromCache: TDateTime;
function BaseURL: string;
procedure OnGetResponse(const ObjectName: TObjectName;
Response: IFirebaseResponse);
procedure OnGetAndDownloadResponse(const ObjectName: TObjectName;
Response: IFirebaseResponse);
procedure OnDelResponse(const ObjectName: TObjectName;
Response: IFirebaseResponse);
procedure OnUploadFromStream(const ObjectName: TObjectName;
Response: IFirebaseResponse);
procedure ScanCacheFolder;
procedure ReduceCacheSize;
procedure AddToCache(StorageObj: IStorageObject; Stream: TStream);
function CheckInCache(StorageObj: IStorageObject; Stream: TStream): boolean;
function DeleteFileFromCache(const FileName: string): boolean;
procedure DeleteObjectFromCache(const ObjectName: TObjectName);
public
constructor Create(const BucketName: string; Auth: IFirebaseAuthentication);
destructor Destroy; override;
procedure Get(const ObjectName: TObjectName; OnGetStorage: TOnStorage;
OnGetError: TOnStorageError); overload;
procedure Get(const ObjectName, RequestID: string;
OnGetStorage: TOnStorageDeprecated; OnGetError: TOnRequestError);
overload; { deprecated }
function GetSynchronous(const ObjectName: TObjectName): IStorageObject;
procedure GetAndDownload(const ObjectName: TObjectName; Stream: TStream;
OnGetStorage: TOnStorage; OnGetError: TOnRequestError);
function GetAndDownloadSynchronous(const ObjectName: TObjectName;
Stream: TStream): IStorageObject;
procedure UploadFromStream(Stream: TStream; const ObjectName: TObjectName;
ContentType: TRESTContentType; OnUpload: TOnStorage;
OnUploadError: TOnStorageError);
function UploadSynchronousFromStream(Stream: TStream;
const ObjectName: TObjectName;
ContentType: TRESTContentType): IStorageObject;
procedure Delete(const ObjectName: TObjectName;
OnDelete: TOnDeleteStorage; OnDelError: TOnStorageError);
procedure DeleteSynchronous(const ObjectName: TObjectName);
// Long-term storage (beyond the runtime of the app) of loaded storage files
procedure SetupCacheFolder(const FolderName: string;
MaxCacheSpaceInBytes: Int64 = cDefaultCacheSpaceInBytes);
function IsCacheInUse: boolean;
function IsCacheScanFinished: boolean;
function GetObjectFromCache(const ObjectName: TObjectName): IStorageObject;
function GetFileFromCache(const ObjectName: TObjectName): TStream;
procedure ClearCache;
function CacheUsageInPercent: extended;
function IsCacheOverflowed: boolean;
end;
TStorageObject = class(TInterfacedObject, IStorageObject)
private
fFirebaseStorage: TFirebaseStorage;
fJSONObj: TJSONObject;
procedure InternalDownloadToStream(Stream: TStream;
OnSuccess: TOnDownload; OnError: TOnDownloadError;
OnAlternativeError: TOnStorageError; const ObjectName: string = '';
OnDeprecatedSuccess: TOnDownloadDeprecated = nil);
public
constructor Create(FirebaseStorage: TFirebaseStorage;
Response: IFirebaseResponse);
destructor Destroy; override;
procedure DownloadToStream(Stream: TStream; OnSuccess: TOnDownload;
OnError: TOnDownloadError); overload;
procedure DownloadToStream(Stream: TStream; OnSuccess: TOnDownload;
OnError: TOnStorageError); overload;
procedure DownloadToStream(const ObjectName: TObjectName; Stream: TStream;
OnSuccess: TOnDownloadDeprecated; OnError: TOnDownloadError);
overload; { deprecated }
procedure DownloadToStreamSynchronous(Stream: TStream);
function ObjectName(IncludePath: boolean = true): string;
class function GetObjectNameWithoutPath(const NameWithPath: string): string;
function Path: string;
function LastPathElement: string;
function ContentType: string;
function Size: Int64;
function Bucket: string;
function createTime(TimeZone: TTimeZone = tzLocalTime): TDateTime;
function updateTime(TimeZone: TTimeZone = tzLocalTime): TDatetime;
function DownloadToken: string;
function DownloadUrl: string;
function MD5HashCode: string;
function storageClass: string;
function etag: string;
function generation: Int64;
function metaGeneration: Int64;
function CacheFileName: string;
class function CalcCacheFileName(const NameWithPath: string): string;
end;
implementation
uses
System.NetConsts, System.NetEncoding, System.StrUtils, System.IOUtils,
System.Generics.Defaults, System.Hash,
{$IFDEF POSIX}
Posix.Unistd,
{$ENDIF}
IdGlobalProtocols,
FB4D.Helpers;
const
GOOGLE_STORAGE = 'https://firebasestorage.googleapis.com/v0/b/%s/o';
{ TFirestoreStorage }
constructor TFirebaseStorage.Create(const BucketName: string;
Auth: IFirebaseAuthentication);
function ExcludeTrailingSlash(const S: string): string;
function IsSlash(const S: string; Index: Integer): Boolean;
begin
result := (Index >= Low(string)) and (Index <= High(S)) and
(S[Index] = '/') and (ByteType(S, Index) = mbSingleByte);
end;
begin
result := S;
if IsSlash(result, High(result)) then
SetLength(result, Length(result) - 1);
end;
begin
fBucket := ExcludeTrailingSlash(BucketName);
fAuth := Auth;
fStorageObjs := TDictionary<TObjectName, IStorageObject>.Create;
fCSForStorageObjs := TCriticalSection.Create;
fCacheFolder := '';
fMaxCacheSpaceInBytes := 0;
fCacheContent := TList<TCacheFile>.Create;
fScanSync := TCriticalSection.Create;
end;
destructor TFirebaseStorage.Destroy;
var
CacheF: TCacheFile;
begin
fScanSync.Free;
fCSForStorageObjs.Free;
for CacheF in fCacheContent do
CacheF.Free;
fCacheContent.Free;
fStorageObjs.Free;
inherited;
end;
function TFirebaseStorage.BaseURL: string;
begin
result := Format(GOOGLE_STORAGE, [fBucket]);
end;
procedure TFirebaseStorage.Get(const ObjectName: TObjectName;
OnGetStorage: TOnStorage; OnGetError: TOnStorageError);
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(BaseURL, ObjectName, fAuth);
Request.SendRequest([ObjectName], rmGet, nil, nil, tmBearer, OnGetResponse,
OnGetError, TOnSuccess.CreateStorage(OnGetStorage));
end;
procedure TFirebaseStorage.Get(const ObjectName, RequestID: string;
OnGetStorage: TOnStorageDeprecated; OnGetError: TOnRequestError);
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(BaseURL, RequestID, fAuth);
Request.SendRequest([ObjectName], rmGet, nil, nil, tmBearer, OnGetResponse,
OnGetError, TOnSuccess.CreateStorageDeprecated(OnGetStorage));
end;
procedure TFirebaseStorage.OnGetResponse(const ObjectName: TObjectName;
Response: IFirebaseResponse);
var
StorageObj: TStorageObject;
begin
try
Response.CheckForJSONObj;
StorageObj := TStorageObject.Create(self, Response);
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, StorageObJ);
finally
fCSForStorageObjs.Release;
end;
case Response.OnSuccess.OnSuccessCase of
oscStorage:
if assigned(Response.OnSuccess.OnStorage) then
Response.OnSuccess.OnStorage(StorageObj);
oscStorageDeprecated:
if assigned(Response.OnSuccess.OnStorageDeprecated) then
Response.OnSuccess.OnStorageDeprecated(ObjectName, StorageObj);
else
TFirebaseHelpers.Log('FirebaseStorage.OnGetResponse ' +
Response.ContentAsString);
end;
except
on e: Exception do
begin
if assigned(Response.OnError) then
Response.OnError(ObjectName, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['FirebaseStorage.OnGetResponse', ObjectName, e.Message]);
end;
end;
end;
function TFirebaseStorage.GetSynchronous(
const ObjectName: TObjectName): IStorageObject;
var
Request: IFirebaseRequest;
Response: IFirebaseResponse;
begin
Request := TFirebaseRequest.Create(BaseURL, '', fAuth);
Response := Request.SendRequestSynchronous([ObjectName], rmGet);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.GetSynchronous ' +
Response.ContentAsString);
{$ENDIF}
Response.CheckForJSONObj;
result := TStorageObject.Create(self, Response);
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, result);
finally
fCSForStorageObjs.Release;
end;
end;
procedure TFirebaseStorage.GetAndDownload(const ObjectName: TObjectName;
Stream: TStream; OnGetStorage: TOnStorage; OnGetError: TOnRequestError);
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(BaseURL, ObjectName, fAuth);
Request.SendRequest([ObjectName], rmGet, nil, nil, tmBearer,
OnGetAndDownloadResponse, OnGetError,
TOnSuccess.CreateStorageGetAndDownload(OnGetStorage, OnGetError, Stream));
end;
procedure TFirebaseStorage.OnGetAndDownloadResponse(
const ObjectName: TObjectName; Response: IFirebaseResponse);
var
StorageObj: IStorageObject;
begin
try
Response.CheckForJSONObj;
StorageObj := TStorageObject.Create(self, Response);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.OnGetAndDownloadResponse ' +
Response.ContentAsString);
{$ENDIF}
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, StorageObJ);
finally
fCSForStorageObjs.Release;
end;
if assigned(Response.OnSuccess.OnStorageGetAndDown) then
StorageObj.DownloadToStream(Response.OnSuccess.DownStream,
Response.OnSuccess.OnStorageGetAndDown,
Response.OnSuccess.OnStorageError);
except
on e: Exception do
begin
if assigned(Response.OnError) then
Response.OnError(ObjectName, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['FirebaseStorage.OnGetAndDownloadResponse', ObjectName, e.Message]);
end;
end;
end;
function TFirebaseStorage.GetAndDownloadSynchronous(
const ObjectName: TObjectName; Stream: TStream): IStorageObject;
var
Request: IFirebaseRequest;
Response: IFirebaseResponse;
begin
Request := TFirebaseRequest.Create(BaseURL, '', fAuth);
Response := Request.SendRequestSynchronous([ObjectName], rmGet);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.GetAndDownloadSynchronous ' +
Response.ContentAsString);
{$ENDIF}
Response.CheckForJSONObj;
result := TStorageObject.Create(self, Response);
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, result);
finally
fCSForStorageObjs.Release;
end;
result.DownloadToStreamSynchronous(Stream);
end;
function TFirebaseStorage.UploadSynchronousFromStream(Stream: TStream;
const ObjectName: TObjectName; ContentType: TRESTContentType): IStorageObject;
var
Request: IFirebaseRequest;
Response: IFirebaseResponse;
QueryParams: TQueryParams;
begin
result := nil;
Request := TFirebaseRequest.Create(BaseURL, '', fAuth);
QueryParams := TQueryParams.Create;
try
QueryParams.Add('uploadType', ['media']);
QueryParams.Add('name', [ObjectName]);
Response := Request.SendRequestSynchronous([], rmPost, Stream, ContentType,
QueryParams);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.UploadSynchronousFromStream ' +
Response.ContentAsString);
{$ENDIF}
Response.CheckForJSONObj;
result := TStorageObject.Create(self, Response);
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, result);
finally
fCSForStorageObjs.Release;
end;
AddToCache(result, Stream);
finally
QueryParams.Free;
end;
end;
procedure TFirebaseStorage.UploadFromStream(Stream: TStream;
const ObjectName: TObjectName; ContentType: TRESTContentType;
OnUpload: TOnStorage; OnUploadError: TOnStorageError);
var
Request: IFirebaseRequest;
QueryParams: TQueryParams;
begin
// RSP-23318 is solved yet. Delphi 10.3.1 and earlier is no longer recommended
Request := TFirebaseRequest.Create(BaseURL, ObjectName, fAuth);
QueryParams := TQueryParams.Create;
try
QueryParams.Add('uploadType', ['media']);
QueryParams.Add('name', [ObjectName]);
Request.SendRequest([], rmPost, Stream, ContentType,
QueryParams, tmBearer, OnUploadFromStream, OnUploadError,
TOnSuccess.CreateStorageUpload(OnUpload, Stream));
finally
QueryParams.Free;
end;
end;
procedure TFirebaseStorage.OnUploadFromStream(const ObjectName: TObjectName;
Response: IFirebaseResponse);
var
StorageObj: IStorageObject;
begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.OnUploadFromStream ' +
Response.ContentAsString);
{$ENDIF}
try
Response.CheckForJSONObj;
StorageObj := TStorageObject.Create(self, Response);
fCSForStorageObjs.Acquire;
try
fStorageObjs.TryAdd(ObjectName, StorageObJ);
finally
fCSForStorageObjs.Release;
end;
if assigned(Response.OnSuccess.UpStream) then
AddToCache(StorageObj, Response.OnSuccess.UpStream);
if assigned(Response.OnSuccess.OnStorageUpload) then
Response.OnSuccess.OnStorageUpload(StorageObj)
else
TFirebaseHelpers.Log('FirebaseStorage.OnUploadFromStream ' +
Response.ContentAsString);
except
on e: Exception do
begin
if assigned(Response.OnError) then
Response.OnError(ObjectName, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['FirebaseStorage.OnUploadFromStream', ObjectName, e.Message]);
end;
end;
end;
procedure TFirebaseStorage.DeleteSynchronous(const ObjectName: TObjectName);
var
Request: IFirebaseRequest;
Response: IFirebaseResponse;
begin
Request := TFirebaseRequest.Create(BaseURL, '', fAuth);
Response := Request.SendRequestSynchronous([ObjectName], rmDelete, nil, nil);
if not Response.StatusOk then
begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.DeleteSynchronous: ' +
Response.ContentAsString);
{$ENDIF}
raise EStorageObject.CreateFmt('Delete failed: %s', [Response.StatusText]);
end else begin
fCSForStorageObjs.Acquire;
try
fStorageObjs.Remove(ObjectName);
finally
fCSForStorageObjs.Release;
end;
DeleteObjectFromCache(ObjectName);
end;
end;
procedure TFirebaseStorage.Delete(const ObjectName: TObjectName;
OnDelete: TOnDeleteStorage; OnDelError: TOnStorageError);
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(BaseURL, ObjectName, fAuth);
Request.SendRequest([ObjectName], rmDelete, nil, nil, tmBearer, OnDelResponse,
OnDelError, TOnSuccess.CreateDelStorage(OnDelete));
end;
procedure TFirebaseStorage.OnDelResponse(const ObjectName: TObjectName;
Response: IFirebaseResponse);
begin
try
if Response.StatusOk then
begin
if assigned(Response.OnSuccess.OnDelStorage) then
Response.OnSuccess.OnDelStorage(ObjectName);
fCSForStorageObjs.Acquire;
try
fStorageObjs.Remove(ObjectName);
finally
fCSForStorageObjs.Release;
end;
DeleteObjectFromCache(ObjectName);
end
else if assigned(Response.OnError) then
Response.OnError(ObjectName, Response.ErrorMsgOrStatusText)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn, ['FirebaseStorage.OnDelResponse',
ObjectName, Response.ErrorMsgOrStatusText]);
except
on e: Exception do
begin
if assigned(Response.OnError) then
Response.OnError(ObjectName, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['FirebaseStorage.OnDelResponse', ObjectName, e.Message]);
end;
end;
end;
{$REGION 'Cache Handling'}
procedure TFirebaseStorage.SetupCacheFolder(const FolderName: string;
MaxCacheSpaceInBytes: Int64);
begin
Assert(MaxCacheSpaceInBytes > 0, 'Invalid max cache space');
Assert(not FolderName.IsEmpty, 'Empty cache folder not allowed');
fCacheFolder := IncludeTrailingPathDelimiter(FolderName);
fMaxCacheSpaceInBytes := MaxCacheSpaceInBytes;
if not TDirectory.Exists(fCacheFolder) then
TDirectory.CreateDirectory(fCacheFolder);
ScanCacheFolder;
end;
procedure TFirebaseStorage.ClearCache;
var
CacheF: TCacheFile;
begin
fScanSync.Acquire;
try
for CacheF in fCacheContent do
CacheF.Free;
fCacheContent.Clear;
fCacheSpaceInBytes := 0;
finally
fScanSync.Release;
end;
if TDirectory.Exists(fCacheFolder) then
TDirectory.Delete(fCacheFolder, true);
end;
procedure TFirebaseStorage.ScanCacheFolder;
begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log('FirebaseStorage.ScanCacheFolder start ' + fCacheFolder);
{$ENDIF}
TThread.CreateAnonymousThread(
procedure
var
FileName: string;
CacheFile: TCacheFile;
begin
{$IFNDEF LINUX64}
TThread.NameThreadForDebugging('StorageObject.ScanCacheFolder');
{$ENDIF}
fScanSync.Acquire;
try
fScanFinished := 0;
fCacheSpaceInBytes := 0;
for FileName in TDirectory.GetFiles(fCacheFolder) do
begin
CacheFile := TCacheFile.AddToCache(FileName);
if TFirebaseHelpers.AppIsTerminated then
exit
else begin
fCacheSpaceInBytes := fCacheSpaceInBytes + CacheFile.FileSize;
fCacheContent.Add(CacheFile);
end;
end;
if fCacheSpaceInBytes > fMaxCacheSpaceInBytes then
ReduceCacheSize;
{$IFDEF DEBUG}
TFirebaseHelpers.LogFmt(
'FirebaseStorage.ScanCacheFolder finished, cache size %dB (%4.2f%%)',
[fCacheSpaceInBytes, CacheUsageInPercent]);
{$ENDIF}
fScanFinished := now;
fScanSync.Release;
except
on e: exception do
TFirebaseHelpers.Log('StorageObject.ScanCacheFolder Exception: ' +
e.Message);
end;
end).Start;
end;
function TFirebaseStorage.IsCacheScanFinished: boolean;
begin
result := fScanFinished > 0;
end;
function TFirebaseStorage.IsCacheInUse: boolean;
begin
result := not fCacheFolder.IsEmpty and (fMaxCacheSpaceInBytes > 0);
end;
function TFirebaseStorage.IsCacheOverflowed: boolean;
begin
result := fLastUpdateRemovedFromCache > fScanFinished;
end;
procedure TFirebaseStorage.AddToCache(StorageObj: IStorageObject;
Stream: TStream);
var
FileName: string;
CacheFile: TCacheFile;
FileStream: TFileStream;
FSize: Int64;
begin
if IsCacheInUse then
begin
FileName := fCacheFolder + StorageObj.CacheFileName;
FileStream := TFileStream.Create(FileName, fmCreate);
try
Stream.Position := 0;
FileStream.CopyFrom(Stream, Stream.Size);
FSize := Stream.Size;
finally
FileStream.Free;
end;
if FSize < fMaxCacheSpaceInBytes then
begin
CacheFile := TCacheFile.AddToCache(FileName, FSize);
fScanSync.Acquire;
try
fCacheSpaceInBytes := fCacheSpaceInBytes + CacheFile.FileSize;
fCacheContent.Add(CacheFile);
finally
fScanSync.Release;
end;
if fCacheSpaceInBytes > fMaxCacheSpaceInBytes then
ReduceCacheSize;
end;
end;
end;
function TFirebaseStorage.CacheUsageInPercent: extended;
begin
result := fCacheSpaceInBytes * 100 / fMaxCacheSpaceInBytes;
end;
function TFirebaseStorage.CheckInCache(StorageObj: IStorageObject;
Stream: TStream): boolean;
var
FileName: string;
CacheFile: TCacheFile;
FileStream: TFileStream;
begin
if IsCacheInUse then
begin
FileName := fCacheFolder + StorageObj.CacheFileName;
fScanSync.Acquire;
try
for CacheFile in fCacheContent do
if CacheFile.FileName = FileName then
begin
if CacheFile.MD5Hash = StorageObj.MD5HashCode then
begin
FileStream := TFileStream.Create(FileName,
fmShareDenyNone or fmOpenRead);
try
Stream.CopyFrom(FileStream, Stream.Size);
finally
FileStream.Free;
end;
exit(true);
end else
exit(false); // Newer version in storage > file must be updated
end;
finally
fScanSync.Release;
end;
result := false; // not in Cache
end else
result := false;
end;
procedure TFirebaseStorage.DeleteObjectFromCache(const ObjectName: TObjectName);
begin
if IsCacheInUse then
begin
fScanSync.Acquire;
try
DeleteFileFromCache(
fCacheFolder + TStorageObject.CalcCacheFileName(ObjectName));
finally
fScanSync.Release;
end;
end;
end;
function TFirebaseStorage.DeleteFileFromCache(const FileName: string): boolean;
var
CacheFile: TCacheFile;
begin
result := false;
for CacheFile in fCacheContent do
if CacheFile.FileName = FileName then
begin
fCacheContent.Remove(CacheFile);
fCacheSpaceInBytes := fCacheSpaceInBytes - CacheFile.FileSize;
CacheFile.Free;
DeleteFile(FileName);
result := true;
break;
end;
end;
procedure TFirebaseStorage.ReduceCacheSize;
const
cMaxUsageAfterClean = 90; // in % of fMaxCacheSpaceInBytes
var
CacheFile: TCacheFile;
Usage: extended;
{$IFDEF DEBUG}
Count: integer;
{$ENDIF}
begin
fScanSync.Acquire;
try
fCacheContent.Sort(TComparer<TCacheFile>.Construct(
function(const Left, Right: TCacheFile): Integer
begin
if Left.LastUpdate < Right.LastUpdate then
result := -1
else if Left.LastUpdate = Right.LastUpdate then
result := 0
else
result := 1;
end));
{$IFDEF DEBUG}
Count := 0;
{$ENDIF}
repeat
CacheFile := fCacheContent.Items[0];
fLastUpdateRemovedFromCache := CacheFile.LastUpdate;
if TFirebaseHelpers.AppIsTerminated or
not DeleteFileFromCache(CacheFile.FileName) then
exit
else begin
{$IFDEF DEBUG}
inc(Count);
{$ENDIF}
end;
Usage := CacheUsageInPercent;
until (Usage < cMaxUsageAfterClean) or (fCacheContent.Count = 0);
finally
fScanSync.Release;
end;
{$IFDEF DEBUG}
TFirebaseHelpers.LogFmt('FirebaseStorage.StartReduceCacheSize finished, ' +
'%d cache file deleted (Remain usage: %4.2f%%)', [Count, Usage]);
{$ENDIF}
end;
function TFirebaseStorage.GetObjectFromCache(
const ObjectName: TObjectName): IStorageObject;
begin
fCSForStorageObjs.Acquire;
try
if not fStorageObjs.TryGetValue(ObjectName, result) then
exit(nil);
finally
fCSForStorageObjs.Release;
end;
end;
function TFirebaseStorage.GetFileFromCache(
const ObjectName: TObjectName): TStream;
var
Obj: IStorageObject;
begin
result := nil;
Obj := GetObjectFromCache(ObjectName);
if assigned(Obj) then
begin
result := TMemoryStream.Create;
if not CheckInCache(Obj, result) then
begin
result.Free;
exit(nil);
end;
result.Position := 0;
end;
end;
{$ENDREGION}
{ TFirestoreObject }
constructor TStorageObject.Create(FirebaseStorage: TFirebaseStorage;
Response: IFirebaseResponse);
begin
fFirebaseStorage := FirebaseStorage;
fJSONObj := Response.GetContentAsJSONObj;
end;
destructor TStorageObject.Destroy;
begin
fJSONObj.Free;
inherited;
end;
function TStorageObject.createTime(TimeZone: TTimeZone): TDateTime;
begin
if not fJSONObj.TryGetValue('timeCreated', result) then
raise EStorageObject.Create('JSON field timeCreated missing')
else if TimeZone = tzLocalTime then
result := TFirebaseHelpers.ConvertToLocalDateTime(result);
end;
function TStorageObject.updateTime(TimeZone: TTimeZone): TDatetime;
begin
if not fJSONObj.TryGetValue('updated', result) then
raise EStorageObject.Create('JSON field updated missing')
else if TimeZone = tzLocalTime then
result := TFirebaseHelpers.ConvertToLocalDateTime(result);
end;
function TStorageObject.DownloadToken: string;
begin
if not fJSONObj.TryGetValue('downloadTokens', result) then
raise EStorageObject.Create('JSON field downloadTokens missing');
end;
function TStorageObject.DownloadUrl: string;
var
QueryParams: TQueryParams;
begin
QueryParams := TQueryParams.Create;
try
QueryParams.Add('alt', ['media']);
QueryParams.Add('token', [DownloadToken]);
result := Format(GOOGLE_STORAGE, [Bucket]) + '/' +
TNetEncoding.URL.Encode(ObjectName) +
TFirebaseHelpers.EncodeQueryParams(QueryParams);
finally
QueryParams.Free;
end;
end;
procedure TStorageObject.DownloadToStreamSynchronous(Stream: TStream);
var
Client: THTTPClient;
Response: IHTTPResponse;
begin
if not fFirebaseStorage.CheckInCache(self, Stream) then
begin
Client := THTTPClient.Create;
try
Response := Client.Get(DownloadUrl, Stream);
if Response.StatusCode = 200 then
fFirebaseStorage.AddToCache(self, Stream)
else begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log('StorageObject.DownloadToStreamSynchronous ' +
Response.ContentAsString);
{$ENDIF}
raise EStorageObject.CreateFmt('Download failed: %s',
[Response.StatusText]);
end;
finally
Client.Free;
end;
end;
end;
procedure TStorageObject.InternalDownloadToStream(Stream: TStream;
OnSuccess: TOnDownload; OnError: TOnDownloadError;
OnAlternativeError: TOnStorageError; const ObjectName: string = '';
OnDeprecatedSuccess: TOnDownloadDeprecated = nil);
begin
Assert(assigned(fFirebaseStorage), 'Storage reference missing');
if fFirebaseStorage.CheckInCache(self, Stream) then
begin
if assigned(OnSuccess) then
OnSuccess(self);
end else
TThread.CreateAnonymousThread(
procedure
var
Client: THTTPClient;
Response: IHTTPResponse;
ErrMsg: string;
begin
{$IFNDEF LINUX64}
TThread.NameThreadForDebugging('StorageObject.DownloadToStream');
{$ENDIF}
try
Client := THTTPClient.Create;
try
Response := Client.Get(DownloadURL, Stream);
if TFirebaseHelpers.AppIsTerminated then
exit;
if Response.StatusCode = 200 then
begin
if assigned(OnSuccess) then
TThread.Synchronize(nil,
procedure
begin
fFirebaseStorage.AddToCache(self, Stream);
OnSuccess(self);
end)
else if assigned(OnDeprecatedSuccess) then
TThread.Synchronize(nil,
procedure
begin
fFirebaseStorage.AddToCache(self, Stream);
OnDeprecatedSuccess(ObjectName, self);
end);
end else begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log('StorageObject.DownloadToStream failure: ' +
Response.ContentAsString);
{$ENDIF}
ErrMsg := Response.StatusText;
if assigned(OnError) then
TThread.Queue(nil,
procedure
begin
OnError(self, ErrMsg);
end)
else if assigned(OnAlternativeError) then
TThread.Queue(nil,
procedure
begin
OnAlternativeError(ObjectName, ErrMsg);
end);
end;
finally
Client.Free;
end;
except
on e: exception do
begin
ErrMsg := e.Message;
if assigned(OnError) and not TFirebaseHelpers.AppIsTerminated then
TThread.Queue(nil,
procedure
begin
OnError(self, ErrMsg);
end)
else if assigned(OnAlternativeError) and
not TFirebaseHelpers.AppIsTerminated then
TThread.Queue(nil,
procedure
begin
OnAlternativeError(ObjectName, ErrMsg);
end)
else
TFirebaseHelpers.Log(
'StorageObject.DownloadToStream Exception: ' + ErrMsg);
end;
end;
end).Start;
end;
procedure TStorageObject.DownloadToStream(Stream: TStream;
OnSuccess: TOnDownload; OnError: TOnDownloadError);
begin
InternalDownloadToStream(Stream, OnSuccess, OnError, nil);
end;
procedure TStorageObject.DownloadToStream(Stream: TStream;
OnSuccess: TOnDownload; OnError: TOnStorageError);
begin
InternalDownloadToStream(Stream, OnSuccess, nil, OnError);
end;
procedure TStorageObject.DownloadToStream(const ObjectName: TObjectName;
Stream: TStream; OnSuccess: TOnDownloadDeprecated; OnError: TOnDownloadError);
begin
InternalDownloadToStream(Stream, nil, OnError, nil, ObjectName, OnSuccess);
end;
function TStorageObject.ObjectName(IncludePath: boolean): string;
begin
if not fJSONObj.TryGetValue('name', result) then
raise EStorageObject.Create('JSON field name missing');
if not IncludePath then
result := result.SubString(result.LastDelimiter('/') + 1);
end;
class function TStorageObject.GetObjectNameWithoutPath(
const NameWithPath: string): string;
begin
result := NameWithPath.SubString(NameWithPath.LastDelimiter('/') + 1);
end;
function TStorageObject.Path: string;
var
p: integer;
begin
if not fJSONObj.TryGetValue('name', result) then
raise EStorageObject.Create('JSON field name missing');
p := result.LastDelimiter('/');
if p > 0 then
result := result.Substring(0, p)
else
result := '';
end;
function TStorageObject.LastPathElement: string;
var
p: integer;
begin
result := Path;
p := result.LastDelimiter('/');
if p > 0 then
result := result.Substring(p + 1)
end;
function TStorageObject.Size: Int64;
begin
if not fJSONObj.TryGetValue('size', result) then
raise EStorageObject.Create('JSON field size missing');
end;
function TStorageObject.Bucket: string;
begin
if not fJSONObj.TryGetValue('bucket', result) then
raise EStorageObject.Create('JSON field bucket missing');
end;
function TStorageObject.ContentType: string;
begin
if not fJSONObj.TryGetValue('contentType', result) then
raise EStorageObject.Create('JSON field contentType missing');
end;
function TStorageObject.MD5HashCode: string;
begin
if not fJSONObj.TryGetValue('md5Hash', result) then
raise EStorageObject.Create('JSON field md5Hash missing');
end;
function TStorageObject.storageClass: string;
begin
if not fJSONObj.TryGetValue('storageClass', result) then
raise EStorageObject.Create('JSON field storageClass missing');
end;
function TStorageObject.etag: string;
begin
if not fJSONObj.TryGetValue('etag', result) then
raise EStorageObject.Create('JSON field etag missing');
end;
function TStorageObject.generation: Int64;
begin
if not fJSONObj.TryGetValue('generation', result) then
raise EStorageObject.Create('JSON field generation missing');
end;
function TStorageObject.metaGeneration: Int64;
begin
if not fJSONObj.TryGetValue('metageneration', result) then
raise EStorageObject.Create('JSON field metageneration missing');
end;
function TStorageObject.CacheFileName: string;
begin
result := CalcCacheFileName(ObjectName);
end;
class function TStorageObject.CalcCacheFileName(
const NameWithPath: string): string;
begin
result := THashMD5.GetHashString(NameWithPath);
end;
{ TFirebaseStorage.TCacheFile }
constructor TFirebaseStorage.TCacheFile.AddToCache(const aFileName: string;
FSize: Int64);
begin
FileName := aFileName;
MD5Hash := TNetEncoding.Base64.EncodeBytesToString(
THashMD5.GetHashBytesFromFile(FileName));
LastUpdate := TFile.GetLastWriteTime(FileName);
if FSize > 0 then
FileSize := FSize
else
FileSize := FileSizeByName(FileName);
{$IFDEF DEBUG}
TFirebaseHelpers.LogFmt(
'CacheFile.AddToCache %s (Size: %dB,DateTimeUTC: %s,MD5: %s)',
[FileName, FileSize, DateTimeToStr(LastUpdate), MD5Hash]);
{$ENDIF}
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uReportService.pas }
{ Описание: Базовая реализация службы отчетов }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uReportService;
interface
uses
uServices, Classes;
type
TReportService = class(TInterfacedObject, IReportService)
private
FTemplatesDir: string;
procedure ScanDirForReports(ADirName: String; AReportList: IReportList);
protected
function IsValidTemplate(AFileName: string): Boolean; virtual; abstract;
public
constructor Create;
function GetReportNames(AReportList: IReportList; AContext: IInterface =
nil): Boolean; virtual; stdcall;
function PrintReport(AReportName, ATemplateFileName: String; AContext:
IInterface = nil; APrintParameters: IPrintReportParameters = nil):
Boolean; virtual; stdcall; abstract;
procedure SetTemplatesDir(const Value: string); stdcall;
function GetTemplatesDir: string; stdcall;
function ShowReport(AReportName, ATemplateFileName: String; AContext:
IInterface = nil): Boolean; virtual; stdcall; abstract;
property TemplatesDir: string read GetTemplatesDir write SetTemplatesDir;
end;
implementation
uses SysUtils, JclFileUtils, Windows, JclAnsiStrings, StrUtils, JclSysInfo,
uReportListImpl;
resourcestring
SReportlink = '.reportlink';
{
******************************** TReportService ********************************
}
constructor TReportService.Create;
begin
inherited Create;
FTemplatesDir := '%EXEDIR%\ReportTemplates';
end;
function TReportService.GetReportNames(AReportList: IReportList; AContext:
IInterface = nil): Boolean;
begin
ScanDirForReports(AReportList.Name, AReportList);
Result := AReportList.Count > 0;
end;
function TReportService.GetTemplatesDir: string;
begin
Result := FTemplatesDir;
ExpandEnvironmentVar(Result);
Result := StringReplace(Result, '%EXEDIR%',
ExtractFilePath(ParamStr(0)), [rfReplaceAll, rfIgnoreCase]);
end;
procedure TReportService.ScanDirForReports(ADirName: String; AReportList:
IReportList);
var
AFileNames: TStringList;
FileName: string;
I: Integer;
ReportName: string;
procedure AddTemplate(AFileName: String);
var
R: IReportTemplate;
begin
if Self.IsValidTemplate(AFileName) then
begin
ReportName := PathExtractFileNameNoExt(AFileName);
R := CreateReportTemplate;
R.Name := ReportName;
R.TemplateFileName := AFileName;
AReportList.Add(R);
end;
end;
procedure AddDir(ADirName: String);
var
NestedList: IReportList;
begin
NestedList := CreateReportList();
NestedList.Name := PathExtractFileNameNoExt(ADirName);
AReportList.Add(NestedList);
ScanDirForReports(ADirName, NestedList);
end;
function SortCompare(AItem1, AItem2: IReportListItem): Integer;
var
L: IReportList;
begin
if Supports(AItem1, IReportList, L) and not Supports(AItem2, IReportList, L) then
Result := 1
else
if Supports(AItem2, IReportList, L) and not Supports(AItem1, IReportList, L) then
Result := -1
else
begin
Result := CompareStr(AItem1.Name, AItem2.Name);
end;
end;
procedure SortReportList();
var
I: Integer;
J: Integer;
RI: IReportListItem;
begin
I := 0;
while I < (AReportList.Count-1) do
begin
for J := I+1 to AReportList.Count-1 do
begin
if SortCompare(AReportList.Items[I], AReportList.Items[J]) = -1 then
begin
RI := AReportList.Items[I];
AReportList.Items[I] := AReportList.Items[J];
AReportList.Items[J] := RI;
end;
end;
Inc(I);
end;
end;
begin
AFileNames := TStringList.Create();
if DirectoryExists(ADirName) then
begin
BuildFileList(ADirName, faDirectory, AFileNames, True);
for I := 0 to AFileNames.Count-1 do
begin
FileName := AFileNames[I];
if not AnsiEndsText('.', AFileNames[I]) then
AddDir(FileName);
end;
AFileNames.Clear;
BuildFileList(ADirName, faNormalFile, AFileNames, True);
for I := 0 to AFileNames.Count-1 do
begin
FileName := AFileNames[I];
AddTemplate(FileName);
if AnsiSameText(ExtractFileExt(FileName), SReportlink) then
begin
FileName := ExpandFileName(PathAddSeparator(ADirName)
+ FileToString(FileName));
if DirectoryExists(FileName) then
AddDir(FileName);
if FileExists(FileName) then
AddTemplate(FileName);
end;
end;
end;
AFileNames.Free;
SortReportList();
end;
procedure TReportService.SetTemplatesDir(const Value: string);
begin
if FTemplatesDir <> Value then
begin
FTemplatesDir := Value;
end;
end;
end.
|
unit cCadDepartPessoa;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TDepartPessoa = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_dept_pessoa: Integer;
F_cod_departamento: Integer;
F_nome_departamento: string;
F_cod_pessoa: Integer;
F_nome_pessoa: string;
F_dta_inclusao:TDateTime;
F_usuario_inclusao: string;
F_usuario_alteracao: string;
F_status: string;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_dept_pessoa: Integer read F_cod_dept_pessoa
write F_cod_dept_pessoa;
property cod_departamento: Integer read F_cod_departamento
write F_cod_departamento;
property nome_departamento: string read F_nome_departamento
write F_nome_departamento;
property cod_pessoa: Integer read F_cod_pessoa
write F_cod_pessoa;
property nome_pessoa: string read F_nome_pessoa
write F_nome_pessoa;
property dta_inclusao: TDateTime read F_dta_inclusao
write F_dta_inclusao;
property usuario_inclusao: string read F_usuario_inclusao
write F_usuario_inclusao;
property usuario_alteracao: string read F_usuario_alteracao
write F_usuario_alteracao;
property status: string read F_status
write F_status;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TDepartPessoa.Create;
begin
ConexaoDB := aConexao;
end;
destructor TDepartPessoa.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TDepartPessoa.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_dept_pessoa) + #13 + 'Descrição: ' + F_nome_pessoa,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_dept_pessoa WHERE cod_dept_pessoa=:cod_dept_pessoa ');
Qry.ParamByName('cod_dept_pessoa').AsInteger := F_cod_dept_pessoa;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TDepartPessoa.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_dept_pessoa '+
' SET cod_departamento=:cod_departamento, '+
' nome_departamento=:nome_departamento, cod_pessoa=:cod_pessoa, '+
' nome_pessoa=:nome_pessoa, dta_alteracao=CURRENT_TIMESTAMP, '+
' status=:status, usuario_alteracao=:usuario_alteracao '+
' WHERE cod_dept_pessoa=:cod_dept_pessoa ');
Qry.ParamByName('cod_dept_pessoa').AsInteger := F_cod_dept_pessoa;
Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento;
Qry.ParamByName('nome_departamento').AsString := F_nome_departamento;
Qry.ParamByName('cod_pessoa').AsInteger := F_cod_pessoa;
Qry.ParamByName('nome_pessoa').AsString := F_nome_pessoa;
Qry.ParamByName('status').AsString := F_status;
Qry.ParamByName('usuario_alteracao').AsString := F_usuario_alteracao;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TDepartPessoa.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_dept_pessoa '+
' (cod_departamento, nome_departamento, cod_pessoa, nome_pessoa, '+
' status, usuario_inclusao) '+
' VALUES(:cod_departamento,:nome_departamento,:cod_pessoa,:nome_pessoa, '+
' :status,:usuario_inclusao)');
Qry.ParamByName('cod_departamento').AsInteger := Self.F_cod_departamento;
Qry.ParamByName('nome_departamento').AsString := Self.F_nome_departamento;
Qry.ParamByName('cod_pessoa').AsInteger := Self.F_cod_pessoa;
Qry.ParamByName('nome_pessoa').AsString := Self.F_nome_pessoa;
Qry.ParamByName('usuario_inclusao').AsString := Self.F_usuario_inclusao;
Qry.ParamByName('status').AsString := Self.F_status;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TDepartPessoa.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_dept_pessoa, cod_departamento, nome_departamento, '+
' cod_pessoa, nome_pessoa, dta_inclusao, dta_alteracao, status, usuario_inclusao, '+
'usuario_alteracao FROM igreja.tb_dept_pessoa WHERE cod_dept_pessoa=:cod_dept_pessoa ');
Qry.ParamByName('cod_dept_pessoa').AsInteger := id;
try
Qry.Open;
Self.F_cod_dept_pessoa := Qry.FieldByName('cod_dept_pessoa').AsInteger;
Self.F_cod_departamento := Qry.FieldByName('cod_departamento').AsInteger;
Self.F_nome_pessoa := Qry.FieldByName('nome_pessoa').AsString;
Self.F_cod_pessoa := Qry.FieldByName('cod_pessoa').AsInteger;
Self.F_dta_inclusao := Qry.FieldByName('dta_inclusao').AsDateTime;
Self.F_usuario_inclusao := Qry.FieldByName('usuario_inclusao').AsString;
Self.F_usuario_alteracao := Qry.FieldByName('usuario_alteracao').AsString;
Self.F_status := Qry.FieldByName('status').AsString;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
unit TagPrs;
interface
uses Classes, Windows, SysUtils;
{
%u = logged user name
%d = date
%t = time
%r = random
}
const
T_USER_NAME = '%u';
T_DATE = '%d';
T_TIME = '%t';
T_RANDOM = '%r';
function TagParse(S: String): String;
function GetCurrentUserName : string;
implementation
function GetCurrentUserName : string;
const
cnMaxUserNameLen = 254;
var
sUserName: String;
dwUserNameLen: DWord;
begin
dwUserNameLen:=cnMaxUserNameLen-1;
SetLength(sUserName, cnMaxUserNameLen );
GetUserName(PChar(sUserName),dwUserNameLen );
SetLength(sUserName, dwUserNameLen-1);
Result:=sUserName;
end;
function TagParse(S: String): String;
begin
Randomize;
Result:=StringReplace(S, T_USER_NAME, GetCurrentUserName, [rfReplaceAll]);
Result:=StringReplace(Result, T_DATE, FormatDateTime('dd-mm-yy', Date), [rfReplaceAll]);
Result:=StringReplace(Result, T_TIME, FormatDateTime('hh-nn', Time), [rfReplaceAll]);
Result:=StringReplace(Result, T_RANDOM, IntToStr(Random(99999)), [rfReplaceAll]);
end;
end.
|
unit l3NodesKeyWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\l3NodesKeyWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "l3NodesKeyWordsPack" MUID: (54EF449A0213)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, l3Interfaces
, l3TreeInterfaces
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwPropertyLike
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwAxiomaticsResNameGetter
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *54EF449A0213impl_uses*
//#UC END# *54EF449A0213impl_uses*
;
type
TkwNodeIsFirst = {final} class(TtfwPropertyLike)
{* Слово скрипта Node:IsFirst }
private
function IsFirst(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Boolean;
{* Реализация слова скрипта Node:IsFirst }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwNodeIsFirst
TkwNodeIsLast = {final} class(TtfwPropertyLike)
{* Слово скрипта Node:IsLast }
private
function IsLast(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Boolean;
{* Реализация слова скрипта Node:IsLast }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwNodeIsLast
TkwNodeFlags = {final} class(TtfwPropertyLike)
{* Слово скрипта Node:Flags }
private
function Flags(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Integer;
{* Реализация слова скрипта Node:Flags }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwNodeFlags
TkwNodeText = {final} class(TtfwPropertyLike)
{* Слово скрипта Node:Text }
private
function Text(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Tl3WString;
{* Реализация слова скрипта Node:Text }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwNodeText
Tl3NodesKeyWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter)
{* Регистрация скриптованой аксиоматики }
public
class function ResName: AnsiString; override;
end;//Tl3NodesKeyWordsPackResNameGetter
function TkwNodeIsFirst.IsFirst(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Boolean;
{* Реализация слова скрипта Node:IsFirst }
begin
Result := aNode.IsFirst;
end;//TkwNodeIsFirst.IsFirst
class function TkwNodeIsFirst.GetWordNameForRegister: AnsiString;
begin
Result := 'Node:IsFirst';
end;//TkwNodeIsFirst.GetWordNameForRegister
function TkwNodeIsFirst.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwNodeIsFirst.GetResultTypeInfo
function TkwNodeIsFirst.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwNodeIsFirst.GetAllParamsCount
function TkwNodeIsFirst.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Il3SimpleNode)]);
end;//TkwNodeIsFirst.ParamsTypes
procedure TkwNodeIsFirst.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству IsFirst', aCtx);
end;//TkwNodeIsFirst.SetValuePrim
procedure TkwNodeIsFirst.DoDoIt(const aCtx: TtfwContext);
var l_aNode: Il3SimpleNode;
begin
try
l_aNode := Il3SimpleNode(aCtx.rEngine.PopIntf(Il3SimpleNode));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aNode: Il3SimpleNode : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(IsFirst(aCtx, l_aNode));
end;//TkwNodeIsFirst.DoDoIt
function TkwNodeIsLast.IsLast(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Boolean;
{* Реализация слова скрипта Node:IsLast }
begin
Result := aNode.IsLast;
end;//TkwNodeIsLast.IsLast
class function TkwNodeIsLast.GetWordNameForRegister: AnsiString;
begin
Result := 'Node:IsLast';
end;//TkwNodeIsLast.GetWordNameForRegister
function TkwNodeIsLast.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwNodeIsLast.GetResultTypeInfo
function TkwNodeIsLast.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwNodeIsLast.GetAllParamsCount
function TkwNodeIsLast.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Il3SimpleNode)]);
end;//TkwNodeIsLast.ParamsTypes
procedure TkwNodeIsLast.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству IsLast', aCtx);
end;//TkwNodeIsLast.SetValuePrim
procedure TkwNodeIsLast.DoDoIt(const aCtx: TtfwContext);
var l_aNode: Il3SimpleNode;
begin
try
l_aNode := Il3SimpleNode(aCtx.rEngine.PopIntf(Il3SimpleNode));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aNode: Il3SimpleNode : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(IsLast(aCtx, l_aNode));
end;//TkwNodeIsLast.DoDoIt
function TkwNodeFlags.Flags(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Integer;
{* Реализация слова скрипта Node:Flags }
begin
Result := aNode.Flags;
end;//TkwNodeFlags.Flags
class function TkwNodeFlags.GetWordNameForRegister: AnsiString;
begin
Result := 'Node:Flags';
end;//TkwNodeFlags.GetWordNameForRegister
function TkwNodeFlags.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwNodeFlags.GetResultTypeInfo
function TkwNodeFlags.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwNodeFlags.GetAllParamsCount
function TkwNodeFlags.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Il3SimpleNode)]);
end;//TkwNodeFlags.ParamsTypes
procedure TkwNodeFlags.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Flags', aCtx);
end;//TkwNodeFlags.SetValuePrim
procedure TkwNodeFlags.DoDoIt(const aCtx: TtfwContext);
var l_aNode: Il3SimpleNode;
begin
try
l_aNode := Il3SimpleNode(aCtx.rEngine.PopIntf(Il3SimpleNode));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aNode: Il3SimpleNode : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Flags(aCtx, l_aNode));
end;//TkwNodeFlags.DoDoIt
function TkwNodeText.Text(const aCtx: TtfwContext;
const aNode: Il3SimpleNode): Tl3WString;
{* Реализация слова скрипта Node:Text }
begin
Result := aNode.Text;
end;//TkwNodeText.Text
class function TkwNodeText.GetWordNameForRegister: AnsiString;
begin
Result := 'Node:Text';
end;//TkwNodeText.GetWordNameForRegister
function TkwNodeText.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwNodeText.GetResultTypeInfo
function TkwNodeText.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwNodeText.GetAllParamsCount
function TkwNodeText.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Il3SimpleNode)]);
end;//TkwNodeText.ParamsTypes
procedure TkwNodeText.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Text', aCtx);
end;//TkwNodeText.SetValuePrim
procedure TkwNodeText.DoDoIt(const aCtx: TtfwContext);
var l_aNode: Il3SimpleNode;
begin
try
l_aNode := Il3SimpleNode(aCtx.rEngine.PopIntf(Il3SimpleNode));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aNode: Il3SimpleNode : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushString(Text(aCtx, l_aNode));
end;//TkwNodeText.DoDoIt
class function Tl3NodesKeyWordsPackResNameGetter.ResName: AnsiString;
begin
Result := 'l3NodesKeyWordsPack';
end;//Tl3NodesKeyWordsPackResNameGetter.ResName
{$R l3NodesKeyWordsPack.res}
initialization
TkwNodeIsFirst.RegisterInEngine;
{* Регистрация Node_IsFirst }
TkwNodeIsLast.RegisterInEngine;
{* Регистрация Node_IsLast }
TkwNodeFlags.RegisterInEngine;
{* Регистрация Node_Flags }
TkwNodeText.RegisterInEngine;
{* Регистрация Node_Text }
Tl3NodesKeyWordsPackResNameGetter.Register;
{* Регистрация скриптованой аксиоматики }
TtfwTypeRegistrator.RegisterType(TypeInfo(Il3SimpleNode));
{* Регистрация типа Il3SimpleNode }
TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean));
{* Регистрация типа Boolean }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Tl3WString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit DownLoadThreadIndy;
interface
uses
Windows, Classes, SysUtils, SyncObjs, idComponent, idhttp, idSocks, IdIOHandlerSocket, _DGL_Point, Dialogs;
//{$define _USE_INDY_10_}
type
TSpeedClc = class(TObject)
private
FCountTimeSpace: integer;
FTotalSize: integer;
FAllSize: integer;
FDataDeque: TPointDeque;
procedure SetCountTimeSpace(const Value: integer);
procedure SetTotalSize(const Value: integer);
public
constructor Create();
destructor Destroy; override;
procedure Inti();
property CountTimeSpace: integer read FCountTimeSpace write SetCountTimeSpace;
procedure AddData(incSize: integer);
function CurSpeed_KB_S(): double;
property AllSize: integer read FAllSize;
property TotalSize: integer read FTotalSize write SetTotalSize;
end;
type
TOnProgressEvent = procedure(Sender: TObject; TotalSize, Readed: Integer) of object;
TOnOnDownLoadedEvent = procedure(Sender: TObject; IsDownLoadOk: boolean) of object;
//我的测试
TWSocksInfo = record
useProxy: boolean; //我的测试
SocksServer: string; //我的测试
SocksLevel: integer; //我的测试
SocksAuthentication: boolean; //我的测试
SocksUsercode: string; //我的测试
SocksPassword: string; //我的测试
SocksPort: string; //我的测试
end;
//我的测试
TDownLoadThread = class(TThread)
private
FReadTimeout: Integer;
procedure PrivateClearHTTP;
procedure PrivateCreateHTTP;
protected
FDestFileName: string;
FTempDestFileName: string;
FUrl: string;
FHttpCli: TIdHttp; //wsocket http 我的测试
FStream: TStream; //我的测试
FOnProgress: TOnProgressEvent; //我的测试
FBytesReaded: integer; //我的测试
FFileSize: integer; //我的测试
HandlerSocket: TIdIOHandlerSocket;
SocksInfo: TIdSocksInfo;
FDownLoadOk: boolean;
FSocksInfo: TWSocksInfo;
FOnDownLoaded: TOnOnDownLoadedEvent;
FOnError: TNotifyEvent;
procedure HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
{$IFNDEF _USE_INDY_10_}const{$ENDIF}AWorkCountMax: Integer);
procedure HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
{$IFNDEF _USE_INDY_10_}const{$ENDIF}AWorkCount: Integer);
procedure HTTPStatus(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
procedure SetOnProgress(const Value: TOnProgressEvent);
procedure SetOnDownLoaded(const Value: TOnOnDownLoadedEvent);
procedure SetOnError(const Value: TNotifyEvent);
procedure DoError();
protected
procedure PrivateCreate(url, FileName: string; aSocksInfo: TWSocksInfo;
is_String: boolean); virtual;
function GetDownLoadTmpFileName(const SrcURL: string): string;
function CreateDownLoadTmpFileStream(const SrcURL: string): TStream; virtual;
function DoDoDownLoadedStreamTest(): boolean; virtual;
protected
procedure UpdateProgress; //我的测试
procedure DoDownLoaded; //
function getResultString: string;
procedure FreeStream();
public
constructor Create(const SrcURL, DestFileName: string; aSocksInfo: TWSocksInfo); overload;
constructor Create(const SrcURL: string; aSocksInfo: TWSocksInfo); overload;
destructor Destroy; override;
procedure DoDownLoad(); virtual;
procedure Execute; override;
property ResultString: string read GetResultString;
property OnProgress: TOnProgressEvent read FOnProgress write SetOnProgress;
property OnDownLoaded: TOnOnDownLoadedEvent read FOnDownLoaded write SetOnDownLoaded;
property OnError: TNotifyEvent read FOnError write SetOnError;
property ReadTimeout: Integer read FReadTimeout write FReadTimeout;
end;
type
//我的测试
TDownLoadThreadEx = class(TDownLoadThread)
protected
FSocksInfo: TWSocksInfo;
FMD5Stream: TStream;
protected
procedure PrivateCreate(url, FileName: string; aSocksInfo: TWSocksInfo;
is_String: boolean); override;
function GetSafePos(const SrcURL: string): integer;
protected
function CreateDownLoadTmpFileStream(const SrcURL: string): TStream; override;
function DoDoDownLoadedStreamTest(): boolean; override;
public
destructor Destroy; override;
end;
implementation
uses
md5, UnitMD5Check, FORMS, IdException;
procedure TDownLoadThread.PrivateClearHTTP();
begin
if FHttpCli <> nil then
self.FHttpCli.IOHandler := nil;
//我的测试
FreeAndNil(self.FHttpCli);
//我的测试
FreeAndNil(self.HandlerSocket);
FreeAndNil(self.SocksInfo);
end;
procedure TDownLoadThread.PrivateCreateHTTP();
const
AuthMed: array[boolean] of TSocksAuthentication
= (saNoAuthentication, saUsernamePassword);
SOCKSVERS: array[4..5] of TSocksVersion
= (svSocks4, svSocks5);
begin
PrivateClearHTTP();
//我的测试
self.FHttpCli := TIdHttp.Create(nil);
assert(FReadTimeout>0);
FHttpCli.ReadTimeout := FReadTimeout; //
FHttpCli.Request.Accept := '*/*';
FHttpCli.Request.UserAgent := 'Mozilla/3.0 (compatible; IndyLibrary)';
//FHttpCli.Request.ContentType := 'application/x-www-form-urlencoded';
FHttpCli.Request.ContentType := 'application/octet-stream';
FHttpCli.Request.Connection := 'Keep-Alive';
{$IFDEF _USE_INDY_10_}
//indy 10
if FSocksInfo.useProxy then
begin
FHttpCli.ProxyParams.ProxyServer := FSocksInfo.SocksServer;
FHttpCli.ProxyParams.ProxyPort := strtoint(FSocksInfo.SocksPort);
FHttpCli.ProxyParams.ProxyUsername := FSocksInfo.SocksUsercode;
FHttpCli.ProxyParams.ProxyPassword := FSocksInfo.SocksPassword;
end;
{$ELSE}
//indy 9
self.HandlerSocket := TIdIOHandlerSocket.Create(nil);
self.FHttpCli.IOHandler := self.HandlerSocket;
//FHttpCli.ProtocolVersion:=pv1_0;
self.socksInfo := TIdSocksInfo.create(nil);
self.HandlerSocket.SocksInfo := self.SocksInfo;
if FSocksInfo.useProxy then
begin
self.HandlerSocket.SocksInfo.Version := SOCKSVERS[FSocksInfo.SocksLevel];
self.HandlerSocket.SocksInfo.Host := FSocksInfo.SocksServer;
self.HandlerSocket.SocksInfo.Port := strtoint(FSocksInfo.SocksPort);
self.HandlerSocket.SocksInfo.Authentication := AuthMed[FSocksInfo.SocksAuthentication];
self.HandlerSocket.SocksInfo.Username := FSocksInfo.SocksUsercode;
self.HandlerSocket.SocksInfo.password := FSocksInfo.SocksPassword;
end;
{$ENDIF}
//我的测试
self.FHttpCli.OnWorkBegin := self.HTTPWorkBegin;
self.FHttpCli.OnWork := self.HTTPWork;
self.FHttpCli.OnStatus := self.HTTPStatus;
end;
procedure TDownLoadThread.PrivateCreate(url: string; FileName: string;
aSocksInfo: TWSocksInfo; is_String: boolean);
const
AuthMed: array[boolean] of TSocksAuthentication
= (saNoAuthentication, saUsernamePassword);
SOCKSVERS: array[4..5] of TSocksVersion
= (svSocks4, svSocks5);
begin
FReadTimeout := 20000;
self.FSocksInfo := aSocksInfo;
self.FUrl := url;
FDestFileName := FileName;
FTempDestFileName := self.GetDownLoadTmpFileName(url);
if not is_string then
begin
//我的测试
self.FStream := self.CreateDownLoadTmpFileStream(url);
end
else
begin
self.FStream := TStringStream.Create('');
end;
FreeOnTerminate := True;
self.PrivateCreateHTTP();
self.FFileSize := 0;
self.FBytesReaded := 0;
end;
//我的测试
procedure TDownLoadThread.HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
{$IFNDEF _USE_INDY_10_}const{$ENDIF}AWorkCountMax: Integer);
var
tFileSize: integer;
begin
if aWorkCountMax > 0 then
begin
//tFileSize:=AWorkCountMax;//self.FHttpCli.Response.ContentLength;
//tFileSize:=self.FStream.Size;
//Assert(aWorkCountMax=strtoint(self.FHttpCli.Response.RawHeaders.Values['Content-Length']));
//self.FFileSize := tFileSize;
end;
end;
//我的测试
procedure TDownLoadThread.HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
{$IFNDEF _USE_INDY_10_}const{$ENDIF}AWorkCount: Integer);
begin
self.FBytesReaded := AWorkCount;
//我的测试
self.Synchronize(self.UpdateProgress);
end;
destructor TDownLoadThread.destroy;
begin
//我的测试
if FStream <> nil then
FreeStream();
PrivateClearHTTP();
inherited;
end;
procedure TDownLoadThread.UpdateProgress;
begin
if self.Terminated then
begin
self.FHttpCli.Disconnect();
end;
//Assert(FStream.Size=FFileSize);
if assigned(FOnProgress) then
FOnProgress(Self, FFileSize, FStream.Position);
end;
procedure TDownLoadThread.Execute;
begin
try
DoDownLoad();
self.Synchronize(self.DoDownLoaded);
except
self.Synchronize(self.DoError);
end;
end;
function TDownLoadThread.DoDoDownLoadedStreamTest(): boolean;
begin
result := true;
end;
procedure TDownLoadThread.DoDownLoad;
procedure SetDownloadPos();
begin
FHttpCli.Response.ContentLength := self.FFileSize;
if FStream.Position > 0 then
begin
FHttpCli.Request.ContentRangeStart := FStream.Position; //我的测试
FHttpCli.Request.ContentRangeEnd := self.FFileSize;
end;
end;
procedure ReSetDownloadHTTP();
begin
self.PrivateCreateHTTP();
FHttpCli.Head(self.FUrl);
end;
procedure tryDownLoad(MaxErrorCount, MaxTimeOutCount: integer; out isTimeOutExit: boolean);
var
tryTimeOutCount: integer;
tryErrorCount: integer;
begin
tryTimeOutCount := 0;
tryErrorCount := 0;
isTimeOutExit := false;
while (tryTimeOutCount < MaxTimeOutCount) and (tryErrorCount < MaxErrorCount) and (FStream.Position < FFileSize) do
begin
try
SetDownloadPos();
self.FHttpCli.Get(self.FUrl, self.FStream);
except
on E: EIdReadTimeout do
begin
inc(tryTimeOutCount);
ReSetDownloadHTTP();
end
else
begin
inc(tryErrorCount);
if tryErrorCount > MaxErrorCount then
raise;
ReSetDownloadHTTP();
end;
end;
end;
isTimeOutExit := tryTimeOutCount >= MaxTimeOutCount;
end;
var
isOldDownOK: boolean;
isTimeOutExit: boolean;
curLinkHaveDataLength: integer;
const csMaxErrorCount = 6;
const csMaxTimeOutCount = 3;
begin
FDownLoadOk := false;
isOldDownOK := false;
FHttpCli.Head(self.FUrl);
FFileSize := FHttpCli.Response.ContentLength;
// ShowMessage('Line:355--' + Self.FUrl + '--' + IntToStr(FFileSize));
if (FStream.Position > 0) then
begin
if FStream.Position > FFileSize then
begin
FStream.Size := FFileSize;
FStream.Position := FFileSize;
end;
isOldDownOK := (FStream.Position = FFileSize);
end;
curLinkHaveDataLength := FStream.Position;
if isOldDownOK then
FDownLoadOk := true
else
begin
tryDownLoad(csMaxErrorCount, csMaxTimeOutCount, isTimeOutExit);
FDownLoadOk := (self.FStream.Position = FFileSize);
// FDownLoadOk :=(Self.FStream.Position = FHttpCli.Response.ContentLength);
if (not FDownLoadOk) and (self.FBytesReaded <= curLinkHaveDataLength) and (isTimeOutExit) then
begin
FStream.Size := FFileSize;
// ShowMessage('Line:377--' + Self.FUrl + '--' + IntToStr(FFileSize));
FStream.Position := 0;
tryDownLoad(csMaxErrorCount, csMaxTimeOutCount, isTimeOutExit);
FDownLoadOk := (self.FStream.Position = FFileSize);
end;
end;
if FDownLoadOk then
FDownLoadOk := DoDoDownLoadedStreamTest();
if (self.FDestFileName <> '') and (FDownLoadOk) then
begin
FreeStream();
//Assert(FTempDestFileName<>FDestFileName);
DeleteFile(FDestFileName);
RenameFile(self.FTempDestFileName, FDestFileName);
end;
end;
function TDownLoadThread.getResultString: string;
begin
if Self.FStream is TStringStream then
result := (self.FStream as TStringStream).dataString
else
Assert(false);
end;
procedure TDownLoadThread.SetOnProgress(const Value: TOnProgressEvent);
begin
FOnProgress := Value;
end;
constructor TDownLoadThread.Create(const SrcURL, DestFileName: string;
aSocksInfo: TWSocksInfo);
begin
inherited Create(true);
self.PrivateCreate(SrcURL, DestFileName, aSocksInfo, false);
end;
constructor TDownLoadThread.Create(const SrcURL: string;
aSocksInfo: TWSocksInfo);
begin
inherited Create(true);
self.PrivateCreate(SrcURL, '', aSocksInfo, true);
end;
procedure TDownLoadThread.SetOnDownLoaded(
const Value: TOnOnDownLoadedEvent);
begin
FOnDownLoaded := Value;
end;
procedure TDownLoadThread.DoDownLoaded;
begin
if FStream is TFileStream then
FreeStream();
if Assigned(self.FOnDownLoaded) then self.FOnDownLoaded(self, self.FDownLoadOk);
end;
procedure TDownLoadThread.SetOnError(const Value: TNotifyEvent);
begin
FOnError := Value;
end;
procedure TDownLoadThread.DoError;
begin
if FStream is TFileStream then
FreeStream();
if Assigned(FOnError) then self.FOnError(self);
end;
procedure TDownLoadThread.FreeStream;
begin
if (self.FHttpCli <> nil) and (self.FHttpCli.Response <> nil) then
self.FHttpCli.Response.ContentStream := nil;
FreeAndNil(FStream);
end;
function TDownLoadThread.GetDownLoadTmpFileName(
const SrcURL: string): string;
function GetFileName(aURL: string): string;
begin
Result := Copy(aURL, pos('download/', aURL) + 9, Length(aURL));
end;
begin
result := extractFilePath(ParamStr(0)) + 'downLoad_' + StrMD5Std(GetFileName(SrcURL)) + '.tmp';
end;
function TDownLoadThread.CreateDownLoadTmpFileStream(
const SrcURL: string): TStream;
begin
result := TFileStream.Create(self.FTempDestFileName, fmCreate);
end;
{ TDownLoadThreadEx }
function TDownLoadThreadEx.CreateDownLoadTmpFileStream(
const SrcURL: string): TStream;
var
safePos: integer;
begin
safePos := GetSafePos(SrcURL);
if (safePos <= 0) then
begin
result := inherited CreateDownLoadTmpFileStream(SrcURL);
end
else
begin
result := TFileStream.Create(self.FTempDestFileName, fmOpenReadWrite);
result.Position := safePos;
result.Size := safePos;
end;
end;
destructor TDownLoadThreadEx.Destroy;
begin
FreeAndNil(FMD5Stream);
inherited;
end;
function TDownLoadThreadEx.DoDoDownLoadedStreamTest(): boolean;
const
csIgnore = '我的测试 ';
var
ErrorSections: TErrorSectionArray;
tmpMD5FileRecord: TMD5FileRecord;
ck: boolean;
begin
result := inherited DoDoDownLoadedStreamTest();
if not result then exit;
Assert(result);
if self.FMD5Stream.Size = 0 then exit;
if not UnitMD5Check.MD5FileToMD5FileRecord(FMD5Stream, tmpMD5FileRecord) then exit;
//data md5 check
try
ck := UnitMD5Check.CheckDataFile(self.FStream, FMD5Stream, ErrorSections);
//todo
if (ck) and (length(ErrorSections) = 0) then exit;
except
result := false;
exit;
end;
//is ignore我的测试
result := (ID_OK = windows.MessageBox(0, csIgnore, 'DownLoad ok', MB_OKCANCEL + MB_ICONWARNING));
end;
function TDownLoadThreadEx.GetSafePos(const SrcURL: string): integer;
var
MD5FileThead: TDownLoadThread;
ErrorSections: TErrorSectionArray;
DataFile: TFileStream;
DataFileSize: integer;
i: integer;
tmpMD5FileRecord: TMD5FileRecord;
begin
result := 0;
DataFileSize := 0;
FMD5Stream.Size := 0;
try
MD5FileThead := nil;
DataFile := nil;
ErrorSections := nil;
try
//DEBUG_IsTestMD5
{if true then
begin
//check
DataFile :=TFileStream.Create('Test_BEDE94B62E0169C5701E302E8067DD1F.downLoad.tmp',fmOpenRead or fmShareDenyWrite);
DataFileSize:=DataFile.Size;
if (not UnitMD5Check.CheckDataFile(
'Test_BEDE94B62E0169C5701E302E8067DD1F.downLoad.tmp',
'Test_BEDE94B62E0169C5701E302E8067DD1F.downLoad.tmp.md5',ErrorSections)) then
exit;
end
else }
begin
//DownLoad md5 File
if (LowerCase(ExtractFileExt(SrcURL)) <> '.md5') and (LowerCase(ExtractFileExt(SrcURL)) <> '.vol') then
begin
MD5FileThead := TDownLoadThread.Create(SrcURL + '.md5', self.FSocksInfo);
MD5FileThead.FreeOnTerminate := false;
MD5FileThead.DoDownLoad();
if UnitMD5Check.MD5FileToMD5FileRecord(MD5FileThead.FStream, tmpMD5FileRecord) then
begin
MD5FileThead.FStream.Position := 0;
FMD5Stream.CopyFrom(MD5FileThead.FStream, MD5FileThead.FStream.Size);
end;
//
if (not FileExists(FTempDestFileName)) then
exit;
//check
DataFile := TFileStream.Create(FTempDestFileName, fmOpenRead or fmShareDenyWrite);
DataFileSize := DataFile.Size;
if (not UnitMD5Check.CheckDataFile(DataFile, MD5FileThead.FStream, ErrorSections)) then
exit;
end;
end;
finally
if (DataFile <> nil) then FreeAndNil(DataFile);
if (MD5FileThead <> nil) then FreeAndNil(MD5FileThead);
end;
except
exit;
end;
//
//get safe pos
result := DataFileSize;
for i := 0 to length(ErrorSections) - 1 do
begin
if integer(ErrorSections[i].PosIndex) < result then
result := ErrorSections[i].PosIndex;
end;
Assert(result <= DataFileSize);
Assert(result >= 0);
end;
procedure TDownLoadThreadEx.PrivateCreate(url, FileName: string;
aSocksInfo: TWSocksInfo; is_String: boolean);
begin
Assert(FMD5Stream = nil);
FMD5Stream := TStringStream.Create('');
FSocksInfo := aSocksInfo;
inherited;
end;
{ TSpeedClc }
procedure TSpeedClc.AddData(incSize: integer);
var
NewData: TPoint;
begin
NewData.x := windows.GetTickCount;
if (FAllSize = 0) then
NewData.x := 0;
NewData.y := incSize;
self.FDataDeque.PushFront(NewData);
inc(self.FAllSize, incSize);
end;
function TSpeedClc.CurSpeed_KB_S: double;
var
newTime: integer;
oldTime: integer;
SumSize: integer;
i: integer;
begin
newTime := windows.GetTickCount;
oldTime := newTime - self.FCountTimeSpace;
SumSize := 0;
i := 0;
while (i < self.FDataDeque.Size) do
begin
if FDataDeque.Items[i].x >= oldTime then
inc(SumSize, FDataDeque.Items[i].y)
else
break;
inc(i);
end;
result := SumSize * (1.0 / 1024 * 1000) / FCountTimeSpace;
end;
procedure TSpeedClc.SetCountTimeSpace(const Value: integer);
begin
Assert(Value > 0);
FCountTimeSpace := Value;
end;
procedure TSpeedClc.Inti;
begin
self.FTotalSize := 0;
self.FAllSize := 0;
self.FDataDeque.Clear;
end;
procedure TSpeedClc.SetTotalSize(const Value: integer);
begin
FTotalSize := Value;
end;
constructor TSpeedClc.Create();
begin
inherited;
FCountTimeSpace := 5000;
FDataDeque := TPointDeque.Create();
end;
destructor TSpeedClc.Destroy;
begin
FDataDeque.Free;
inherited;
end;
procedure TDownLoadThread.HTTPStatus(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
begin
//
end;
end.
|
{
This file is part of the AF UDF library for Firebird 1.0 or high.
Copyright (c) 2007-2009 by Arteev Alexei, OAO Pharmacy Tyumen.
See the file COPYING.TXT, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
email: alarteev@yandex.ru, arteev@pharm-tmn.ru, support@pharm-tmn.ru
**********************************************************************}
unit uxmldtd;
{$mode objfpc}
{$H+}
interface
uses
Classes, SysUtils, DOM,XMLRead;
Type
{ TXmlDTD }
TXmlDTD = class
private
FWasError : Boolean;
FTextError : String;
procedure ErrorHandler(E: EXMLReadError);
public
function CreateXmlDocFromStreamDTD(AStream:TStream; Out XmlDoc:TXMLDocument;
Out Error: string):Boolean;
end;
implementation
{ TXmlDTD }
procedure TXmlDTD.ErrorHandler(E: EXMLReadError);
begin
if E.Severity = esError then
begin
FWasError:=true;
if FTextError<>'' then
FTextError:=FTextError+LineEnding
else
FTextError:='ERROR:';
FTextError:=FTextError+E.Message;
end;
end;
function TXmlDTD.CreateXmlDocFromStreamDTD(AStream: TStream; out
XmlDoc: TXMLDocument; out Error: string): Boolean;
var
Parser: TDOMParser;
Src: TXMLInputSource;
begin
Parser := TDOMParser.Create;
FWasError:=false;
FTextError:='';
try
Src := TXMLInputSource.Create(AStream);
Parser.Options.Validate := True;
Parser.OnError := @ErrorHandler;
Parser.Parse(Src, XmlDoc);
if FWasError then
begin
Error:= FTextError;
if XmlDoc<> nil then
XmlDoc.Free;
exit(false);
end;
Error := '';
exit(true);
finally
if Assigned(Src) then
Src.Free;
Parser.Free;
end;
end;
end.
|
unit GMURDOMger;
interface
uses
RDOInterfaces, WinSockRDOConnection, RDOServer, RDOObjectProxy, GameMaster, GMKernel;
const
GMUT_TIME_OUT = 3*60*1000;
type
TGMUtRDOMger =
class
public
destructor Destroy; override;
public
function SetupRDO(ServerAddr : widestring; ServerPort : integer; Name, Password : string) : boolean;
procedure DoneRDO;
procedure getClientInfo( out ClientAddr : widestring; out ClientPort : integer );
private
fRDOConnection : IRDOConnectionInit;
fGMServerProxy : variant;
fGameMaster : TGameMaster;
fEventsServer : TRDOServer;
fOnDisconnect : TRDOClientDisconnectEvent;
procedure OnServerDisconnected( const ClientConnection : IRDOConnection );
procedure syncOnServerDisconnect( const params : array of const );
function GetIsConnected : boolean;
public
property GameMaster : TGameMaster read fGameMaster;
property OnDisconnect : TRDOClientDisconnectEvent read fOnDisconnect write fOnDisconnect;
property IsConnected : boolean read GetIsConnected;
end;
var
TheGMURDOMger : TGMUtRDOMger;
procedure InitRDOMger;
procedure DoneRDOMger;
implementation
uses
SysUtils, Threads, Dialogs;
type
TGMServer =
class(TInterfacedObject, IGMServerConnection)
public
constructor Create( aProxy : variant );
private //IGMServerConnection
function RegisterGameMaster( ClientId : integer; GMId : TGameMasterId; GMName : widestring; GMPassword : widestring ) : OleVariant;
procedure NotifyGMStatus( GMId : TGameMasterId; Status : integer; Customers : integer; Pending : integer );
procedure UserNotification( ISId : TIServerId; CustomerId : TCustomerId; notID : integer; Info : WideString );
function SendMessage( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant;
private
fProxy : variant;
end;
// TGMServer
constructor TGMServer.Create( aProxy : variant );
begin
inherited Create;
fProxy := aProxy;
end;
function TGMServer.RegisterGameMaster( ClientId : integer; GMId : TGameMasterId; GMName : widestring; GMPassword : widestring ) : OleVariant;
begin
try
result := fProxy.RegisterGameMaster( ClientId, GMId, GMName, GMpassword );
except
result := INVALID_GAMEMASTER;
end;
end;
procedure TGMServer.NotifyGMStatus( GMId : TGameMasterId; Status : integer; Customers : integer; Pending : integer );
begin
fProxy.NotifyGMStatus( GMId, Status, Customers, Pending );
end;
procedure TGMServer.UserNotification( ISId : TIServerId; CustomerId : TCustomerId; notID : integer; Info : WideString );
begin
fProxy.UserNotification( ISId, CustomerId, notID, Info );
end;
function TGMServer.SendMessage( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant;
begin
result := fProxy.SendMessage( ISId, CustomerId, Msg, Info );
end;
// TGMUtRDOMger
destructor TGMUtRDOMger.Destroy;
begin
if fRDOConnection <> nil
then
begin
fRDOConnection.Disconnect;
fRDOConnection := nil;
fGMServerProxy := null;
fEventsServer.Free;
end;
inherited;
end;
function TGMUtRDOMger.SetupRDO(ServerAddr : widestring; ServerPort : integer; Name, Password : string) : boolean;
var
ClId : integer;
wfa : boolean;
begin
fRDOConnection := TWinSockRDOConnection.Create('Game Master');
fRDOConnection.Server := ServerAddr;
fRDOConnection.Port := ServerPort;
if fRDOConnection.Connect( GMUT_TIME_OUT )
then
begin
fGMServerProxy := TRDOObjectProxy.Create as IDispatch;
fGMServerProxy.SetConnection( fRDOConnection );
wfa := fGMServerProxy.WaitForAnswer;
try
fGMServerProxy.WaitForAnswer := true;
fGMServerProxy.Timeout := GMUT_TIME_OUT;
if fGMServerProxy.BindTo( tidRDOHook_GMServer )
then
begin
fEventsServer := TRDOServer.Create( fRDOConnection as IRDOServerConnection, 1, nil );
(fRDOConnection as IRDOConnection).OnDisconnect := OnServerDisconnected;
fGameMaster := TGameMaster.Create( Name, Password );
ClId := fGMServerProxy.RDOCnntId;
fGameMaster.setGMConnection(ClId, TGMServer.Create( fGMServerProxy ) );
result := fGameMaster.Valid;
end
else raise Exception.Create( 'Cannot bind to GM Server!' );
finally
fGMServerProxy.WaitForAnswer := wfa;
end;
end
else raise Exception.Create( 'Cannot connect to GM Server!' );
end;
procedure TGMUtRDOMger.DoneRDO;
begin
fRDOConnection := nil;
fGMServerProxy := NULL;
fGameMaster.Free;
fEventsServer.Free;
fEventsServer := nil;
end;
procedure TGMUtRDOMger.getClientInfo( out ClientAddr : widestring; out ClientPort : integer );
begin
ClientAddr := (fRDOConnection as IRDOConnection).LocalAddress;
ClientPort := (fRDOConnection as IRDOConnection).LocalPort;
end;
procedure TGMUtRDOMger.OnServerDisconnected( const ClientConnection : IRDOConnection );
begin
Join( syncOnServerDisconnect, [0] );
end;
function TGMUtRDOMger.GetIsConnected : boolean;
begin
result := fRDOConnection = nil;
end;
procedure TGMUtRDOMger.syncOnServerDisconnect( const params : array of const );
begin
if Assigned(fOnDisconnect)
then fOnDisconnect( nil );
DoneRDO;
end;
procedure InitRDOMger;
begin
TheGMURDOMger := TGMUtRDOMger.Create;
end;
procedure DoneRDOMger;
begin
TheGMURDOMger.Free;
end;
end.
|
unit uPerson;
interface
type
TAnimal = class
public
procedure Talk;
{虚拟方法}
function Run(): Integer; virtual;
{动态方法}
procedure Eat(); dynamic;
{类方法}
class procedure Drink;
{抽象方法,规范,一般指规定}
procedure Sleep;virtual;abstract;
end;
type
TDog = class(TAnimal)
public
function Run(): Integer;
procedure Eat();
constructor Create();
procedure Sleep;
end;
implementation
{ TPerson }
constructor TDog.Create;
begin
Write('构造方法执行了');
end;
class procedure TAnimal.Drink;
begin
Writeln('Drink');
end;
procedure TAnimal.Eat;
begin
end;
function TAnimal.Run: Integer;
begin
{一般情况下,父类的虚方法有一个空实现}
{虚方法一般表示一个类具有这个功能,功能实现根据不同子类有不同实现方法,虚方法是留给子类实现的具体功能}
end;
procedure TAnimal.Talk;
begin
Writeln('Talk');
end;
{ TDog }
procedure TDog.Eat;
begin
Writeln('Dog Eat');
end;
function TDog.Run: Integer;
begin
Writeln('四条腿跑');
end;
procedure TDog.Sleep;
begin
Writeln('TDog Sleep');
end;
end.
|
unit DsRest.com.utl.UEnumerator;
interface
uses
System.TypInfo, System.SysUtils, System.StrUtils, Vcl.StdCtrls;
type
{$SCOPEDENUMS ON}
TTipoAnexo = (Selecione, Cliente, Produto);
{$SCOPEDENUMS OFF}
TTipoAnexoClass = class
end;
TTipoAnexoHelper = class helper for TTipoAnexoClass
class function AnexoToValue(const AValue: TTipoAnexo): string;
class function ValueToAnexo(const AValue: string): TTipoAnexo;
class function AnexoToCompont(const AValue: TTipoAnexo): Integer;
class procedure CarregaComboBox(const AComboBox: TComboBox);
end;
implementation
{ TTipoAnexoHelper }
class function TTipoAnexoHelper.AnexoToCompont(const AValue: TTipoAnexo): Integer;
begin
Result := 0;
case AValue of
TTipoAnexo.Selecione : Result := 0;
TTipoAnexo.Cliente : Result := 1;
TTipoAnexo.Produto : Result := 2;
end;
end;
class function TTipoAnexoHelper.AnexoToValue(const AValue: TTipoAnexo): string;
begin
case AValue of
TTipoAnexo.Cliente,
TTipoAnexo.Produto : Result := GetEnumName(TypeInfo(TTipoAnexo), Integer(AValue));
TTipoAnexo.Selecione : Result := EmptyStr;
end;
end;
class procedure TTipoAnexoHelper.CarregaComboBox(const AComboBox: TComboBox);
var
AtipoAnexo: TTipoAnexo;
begin
AComboBox.Clear;
for AtipoAnexo := TTipoAnexo.Selecione to TTipoAnexo.Produto do
AComboBox.Items.Add(GetEnumName(TypeInfo(TTipoAnexo), Integer(AtipoAnexo)));
end;
class function TTipoAnexoHelper.ValueToAnexo(const AValue: string): TTipoAnexo;
begin
Result := TTipoAnexo.Selecione;
case AnsiIndexStr(AValue, ['Selecione', 'Cliente', 'Produto']) of
0: Result := TTipoAnexo.Selecione;
1: Result := TTipoAnexo.Cliente;
2: Result := TTipoAnexo.Produto;
end;
end;
end.
|
unit BusVal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, AdoDb, Db;
type
TBusValDlg = class(TForm)
GroupBox1: TGroupBox;
cbCampos: TComboBox;
GroupBox2: TGroupBox;
edBuscar: TEdit;
GroupBox3: TGroupBox;
cbCaseSensitive: TCheckBox;
rbExacto: TRadioButton;
rbComienza: TRadioButton;
rbContiene: TRadioButton;
bbBuscar: TBitBtn;
bbSig: TBitBtn;
BitBtn3: TBitBtn;
sbLook: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure bbBuscarClick(Sender: TObject);
procedure bbSigClick(Sender: TObject);
procedure sbLookClick(Sender: TObject);
procedure cbCamposChange(Sender: TObject);
private
{ Private declarations }
FUltimoCampo: boolean;
FUltimoValor: string;
FDataSet: TAdoDataSet;
procedure SetDataSet(const Value: TAdoDataSet);
procedure CargarCampos;
function BuscarValor( DesdeInicio: boolean ): boolean;
procedure Verificar;
public
{ Public declarations }
property DataSet: TAdoDataSet read FDataSet write SetDataSet;
end;
var
BusValDlg: TBusValDlg;
implementation
uses
SelValor;
{$R *.DFM}
procedure TBusValDlg.FormCreate(Sender: TObject);
begin
if cbCampos.Items.Count = 0 then
CargarCampos;
end;
procedure TBusValDlg.bbBuscarClick(Sender: TObject);
var
Opciones: TLocateOptions;
begin
Verificar;
Opciones := [];
if not ( cbCaseSensitive.checked ) then
Opciones := [ loCaseInsensitive ];
if rbComienza.checked then
Opciones := Opciones + [ loPartialKey ];
if rbContiene.checked then
bbSig.Enabled := BuscarValor( true )
else
bbSig.Enabled := FDataSet.Locate( FDataSet.Fields[ cbCampos.ItemIndex ].FieldName, edBuscar.text, Opciones );
{ModalResult := mrOK;}
end;
procedure TBusValDlg.SetDataSet(const Value: TAdoDataSet);
begin
FDataSet := Value;
if Value <> nil then
Self.FreeNotification( Value );
CargarCampos;
end;
procedure TBusValDlg.CargarCampos;
var
x: integer;
begin
cbCampos.Items.Clear;
if Assigned( FDataSet ) then
for x:=0 to FDataSet.FieldCount-1 do
if FDataSet.Fields[ x ].FieldKind = fkData then
cbCampos.Items.Add( FDataSet.Fields[ x ].DisplayLabel );
end;
procedure TBusValDlg.bbSigClick(Sender: TObject);
begin
Verificar;
bbSig.enabled := BuscarValor( false );
{ModalResult := mrOK;}
end;
function TBusValDlg.BuscarValor(DesdeInicio: boolean): boolean;
var
nPos: integer;
FBuscar: string;
begin
FDataSet.DisableControls;
try
Result := true;
if not ( cbCaseSensitive.checked ) then
FBuscar := AnsiUpperCase( edBuscar.text )
else
FBuscar := edBuscar.text;
if DesdeInicio then
FDataSet.first
else
FDataSet.next;
while not FDataSet.eof do
begin
nPos := Pos( FBuscar, FDataSet.Fields[ cbCampos.ItemIndex ].AsString );
if nPos = 1 then
begin
if not ( rbExacto.checked ) or
( FBuscar=FDataSet.Fields[ cbCampos.ItemIndex ].AsString ) then
exit
end
else if ( nPos > 1 ) and ( rbContiene.checked ) then
exit;
FDataSet.next;
end;
Result := false;
finally
FDataSet.EnableControls;
end;
end;
procedure TBusValDlg.Verificar;
begin
if edBuscar.text = '' then
raise exception.create( 'Por favor, complete dato a buscar' );
if cbCampos.itemindex = -1 then
raise exception.create( 'Por favor, indique campo de busqueda' );
end;
procedure TBusValDlg.sbLookClick(Sender: TObject);
var
Res: variant;
begin
// mostrar lookup
with FDataSet.Fields[ cbCampos.ItemIndex ] do
Res := LookupValor( FDataSet.Connection, LookupDataSet, LookupKeyFields, LookupResultField );
if Res <> '' then
edBuscar.Text := Res;
end;
procedure TBusValDlg.cbCamposChange(Sender: TObject);
begin
if Assigned( FDataSet.Fields[ cbCampos.ItemIndex ].LookupDataSet ) then
sbLook.Enabled := true
else
sbLook.enabled := false;
end;
end.
|
unit TestPeopleModuleU;
interface
uses
DUnitX.TestFramework, System.Generics.Collections, FireDAC.Stan.Error, Data.DB,
PeopleModuleU, FireDAC.Stan.Intf, FireDAC.DApt, FireDAC.Stan.Pool,
FireDAC.Comp.Client, FireDAC.Stan.Async, FireDAC.DatS, FireDAC.UI.Intf,
FireDAC.Stan.Param, FireDAC.Phys.IB, FireDAC.Phys, PersonBO, FireDAC.Stan.Option,
System.Classes, System.SysUtils, FireDAC.Phys.IBBase, FireDAC.Stan.Def,
FireDAC.DApt.Intf, FireDAC.Phys.FB, FireDAC.Comp.DataSet, FireDAC.Phys.Intf;
type
// Test methods for class TPeopleModule
TestTPeopleModule = class(TTestCase)
strict private
FPeopleModule: TPeopleModule;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConnBeforeConnect;
procedure TestCreatePerson;
procedure TestDeletePerson;
procedure TestUpdatePerson;
procedure TestGetPersonByID;
procedure TestFindPeople;
procedure TestGetPeople;
end;
implementation
procedure TestTPeopleModule.SetUp;
begin
FPeopleModule := TPeopleModule.Create(nil);
end;
procedure TestTPeopleModule.TearDown;
begin
FPeopleModule.Free;
FPeopleModule := nil;
end;
procedure TestTPeopleModule.TestConnBeforeConnect;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FPeopleModule.ConnBeforeConnect(Sender);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestCreatePerson;
var
APerson: TPerson;
begin
// TODO: Setup method call parameters
FPeopleModule.CreatePerson(APerson);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestDeletePerson;
var
AID: Integer;
begin
// TODO: Setup method call parameters
FPeopleModule.DeletePerson(AID);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestUpdatePerson;
var
APerson: TPerson;
begin
// TODO: Setup method call parameters
FPeopleModule.UpdatePerson(APerson);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestGetPersonByID;
var
ReturnValue: TPerson;
AID: Integer;
begin
// TODO: Setup method call parameters
ReturnValue := FPeopleModule.GetPersonByID(AID);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestFindPeople;
var
ReturnValue: TObjectList<TPerson>;
APage: Integer;
ASearchText: string;
begin
// TODO: Setup method call parameters
ReturnValue := FPeopleModule.FindPeople(ASearchText, APage);
// TODO: Validate method results
end;
procedure TestTPeopleModule.TestGetPeople;
var
ReturnValue: TObjectList<TPerson>;
begin
ReturnValue := FPeopleModule.GetPeople(1);
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
//TDUnitX.RegisterTestFixture(TestTPeopleModule);
end.
|
// Copyright 1999-2000 powered by Alexander Kramarenko
// Copyright 1992-1994 by Mark May
// Converted to Turbo Pascal (tm) V4.0 March, 1988 by J.R.Louvau
// Copyright (C) 1986 Gary S. Brown.
unit crc32;
interface
function GetStringCRC(Str: string): Cardinal;
implementation
const CRC32Polynomial = $EDB88320;
var crc_32_tab: array[byte] of longword;
procedure BuildCRC32Table;
{* (c) Burnashov Alexander alexburn@metrocom.ru *}
var i, j: byte; crc: longword;
begin
for i := 0 to 255 do
begin
crc := i;
for j := 8 downto 1 do
if (crc and 1) <> 0 then
crc := (crc shr 1) xor CRC32Polynomial
else
crc := crc shr 1;
crc_32_tab[i] := crc;
end;
end;
function UpdC32(octet: BYTE; crc: Cardinal): Cardinal;
begin
Result := crc_32_tab[BYTE(crc xor Cardinal(octet))] xor ((crc shr 8) and $00FFFFFF)
end;
function GetStringCRC(Str: string): Cardinal;
const FirstRun: Boolean = true;
type TAr = array[0..3] of byte;
var
l, crc: Cardinal;
counter: SmallInt;
ar: TAr absolute crc;
am: TAr absolute l;
begin
if FirstRun then
begin
BuildCRC32Table;
FirstRun := False;
end;
crc := $FFFFFFFF;
for counter := 1 to Length(Str) do
crc := UpdC32(Byte(Str[counter]), crc);
am[0] := ar[3];
am[1] := ar[2];
am[2] := ar[1];
am[3] := ar[0];
Result := l;
end;
end.
|
unit unEstadoModel;
interface
uses unCidadeModel;
type TEstadoModel = class
private
FIdEstado: Integer;
FSigla: String;
FNome: String;
FCidades: TListaCidade;
procedure SetIdEstado(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetSigla(const Value: String);
procedure SetCidades(const Value: TListaCidade);
published
property IdEstado : Integer read FIdEstado write SetIdEstado;
property Nome : String read FNome write SetNome;
property Sigla : String read FSigla write SetSigla;
property Cidades : TListaCidade read FCidades write SetCidades;
end;
{ criei um tipo de array, pois não é possível transformar um array em JsonObject pela
funcao TObjectToJson.
Poderia ter usado o TObjectList<T>, mas retorna muita sujeira no Json }
type TArrayEstadoModel = array of TEstadoModel;
type TListaEstadoModel = class
private
mEstados : TArrayEstadoModel;
public
procedure Add(VEstadoModel : TEstadoModel);
function GetLength : Integer;
published
property Estados : TArrayEstadoModel read mEstados write mEstados;
end;
implementation
{ TEstadoModel }
procedure TEstadoModel.SetCidades(const Value: TListaCidade);
begin
FCidades := Value;
end;
procedure TEstadoModel.SetIdEstado(const Value: Integer);
begin
FIdEstado := Value;
end;
procedure TEstadoModel.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TEstadoModel.SetSigla(const Value: String);
begin
FSigla := Value;
end;
{ TListaEstadoModel }
procedure TListaEstadoModel.Add(VEstadoModel: TEstadoModel);
begin
SetLength(mEstados,GetLength + 1);//seta o tamanho da array pegando seu tamanho atual e incrementando 1
mEstados[High(mEstados)] := VEstadoModel;//adiciona um TEstadoModel na ultima posição da array
end;
function TListaEstadoModel.GetLength: Integer;
begin
Result := Length(mEstados);//retorna o tamanha da array
end;
end.
|
{ Mark Sattolo 428500 }
{ CSI-1100A DGD-1 TA: Chris Lankester }
{ Assignment 6, Question 1 }
program INSERT (input, output);
{ Take a non-decreasing sorted array X with N numbers, and a number Num, and
find the first position in X where Num can be inserted in the proper order. }
{ Data Dictionary
Givens: Num - a number to be inserted into list X.
Results: none
Modifieds: X - sorted list of N numbers in non-decreasing order. List X will be
modified to have Num added in the correct place.
N - number of values in list X. This will be modified to have value
N+1 for the modified X.
Intermediates: J - the minimum index value where Num could be inserted in list X.
Uses: (J) <-- SEARCH(X,N,Num)
MAKEROOM(X,N,J)
FillArray(X,N) }
type
Markarray = array[1..27] of integer;
var
N, Num, J : integer;
X : Markarray;
{*************************************************************************}
procedure SWAP(var X, Y : integer);
var
Temp : integer;
begin
Temp := X;
X := Y;
Y := Temp
end;
{*************************************************************************}
procedure SEARCH(N, Num : integer; X : Markarray; var J : integer);
var
JNotFound : boolean;
begin { Search }
J := 0;
JNotFound := true;
while ((J < N) and JNotFound) do
begin
J := J + 1;
if (NUM <= X[J]) then
JNotFound := false
else { do nothing }
end; { while }
if JNotFound then
J := N + 1
end; { procedure SEARCH }
{***********************************************************************************}
procedure MAKEROOM(J : integer; var X: Markarray; var N : integer);
var
Pos, Temp : integer;
begin { MAKEROOM }
X[N+1] := 0;
Pos := J;
Temp := 0;
while Pos <= N+1 do
begin
SWAP(X[Pos], Temp);
Pos := Pos + 1
end; { while }
N := N + 1
end; { procedure MAKEROOM }
{*************************************************************************************}
procedure FillArray(var ArrayName : MarkArray; var ArraySize : integer);
var
K : integer; { K - an index in the prompt for values. }
begin { procedure FillArray }
write('Please enter the size of the array? ');
readln(ArraySize);
for K := 1 to ArraySize do
begin
write('Please enter array value #', K, '? ');
read(ArrayName[K])
end { for }
end; { procedure FillArray }
{*************************************************************************************}
begin { program }
{ Get the input values }
writeln('For X:');
FillArray(X, N);
writeln;
write('Please enter the value for Num: ');
Readln(Num);
{ body }
SEARCH(N, Num, X, J);
MAKEROOM(J, X, N);
X[J] := Num;
{ Print out the results. }
writeln;
writeln('*************************************');
writeln('Mark Sattolo 428500');
writeln('CSI-1100A DGD-1 TA: Chris Lankester');
writeln('Assignment 6, Question 1');
writeln('*************************************');
writeln;
writeln('The modified elements in X are: ');
for J := 1 to N do
write(X[J]:6);
writeln;
end.
|
unit WinEnum;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, SysUtils, WinUtils;
type
TEnumWindowsProc = function( Window : HWND; lParam : dword ) : Bool;
// Find a window with 'Owner' as owner
function FindWindowByCaption( const Caption : string;
const ClassNames : array of string; var WinClass : string ) : HWND;
// Find a window with 'Owner' as owner
function FindOwnedWindow( Owner : HWND ) : HWND;
// Crazy stuff: Find a child window with two scrollbars
function FindViewerClient( Viewer : HWND ) : HWND;
implementation
// FindWindowByCaption
type
PClassNameArray = ^TClassNameArray;
TClassNameArray = array[0..0] of string;
type
PEnum1Params = ^TEnum1Params;
TEnum1Params =
record
NeededWindow : HWND;
ClassesLow : integer;
ClassesHigh : integer;
NeededClasses : PClassNameArray;
NeededCaption : string;
WinClassName : string;
end;
function WinEnumerator1( Window : HWND; lParam : dword ) : Bool; stdcall;
var
Params : PEnum1Params absolute lParam;
Caption : string;
ClassName : string;
i : integer;
begin
Caption := UpperCase( GetWindowCaption( Window ) );
ClassName := GetWindowClass( Window );
with Params^ do
begin
if Pos( NeededCaption, Caption ) > 0
then
for i := ClassesLow to ClassesHigh do
if ClassName = NeededClasses[i]
then
begin
NeededWindow := Window;
WinClassName := NeededClasses[i];
end;
Result := ( NeededWindow = 0 );
end;
end;
function FindWindowByCaption( const Caption : string;
const ClassNames : array of string; var WinClass : string ) : HWND;
var
Params : TEnum1Params;
begin
with Params do
begin
NeededWindow := 0;
pointer( NeededClasses ) := @ClassNames;
ClassesLow := Low( ClassNames );
ClassesHigh := High( ClassNames );
NeededCaption := UpperCase( ChangeFileExt( ExtractFilename( Caption ), '.' ) );
SetLength( NeededCaption, length( NeededCaption ) - 1 );
EnumWindows( @WinEnumerator1, dword( @Params ) );
WinClass := WinClassName;
Result := NeededWindow;
end;
end;
// FindOwnedWindow
type
PEnum2Params = ^TEnum2Params;
TEnum2Params =
record
NeededWindow : HWND;
Owner : HWND;
end;
function WinEnumerator2( Window : HWND; lParam : dword ) : Bool; stdcall;
var
Params : PEnum2Params absolute lParam;
Owner : HWND;
begin
Owner := GetWindowOwner( Window );
if Owner = Params.Owner
then
begin
Params.NeededWindow := Window;
Result := false;
end
else Result := true;
end;
function FindOwnedWindow( Owner : HWND ) : HWND;
var
Params : TEnum2Params;
begin
with Params do
begin
NeededWindow := 0;
EnumWindows( @WinEnumerator2, dword( @Params ) );
Result := NeededWindow;
end;
end;
// FindViewerClient
type
PEnum3Params = ^TEnum3Params;
TEnum3Params =
record
NeededWindow : HWND;
ScrollbarCount : integer;
end;
function WinEnumerator3( Window : HWND; lParam : dword ) : Bool; stdcall;
var
Params : PEnum3Params absolute lParam;
WinStyle : integer;
ClassName : string;
begin
ClassName := GetWindowClass( Window );
WinStyle := GetWindowStyle( Window );
if ( ClassName = 'ScrollBar' ) or ( WinStyle and ( WS_VSCROLL or WS_HSCROLL ) <> 0 )
then inc( Params.ScrollbarCount );
Result := true;
end;
function WinEnumerator4( Window : HWND; lParam : dword ) : Bool; stdcall;
var
Params : PEnum3Params absolute lParam;
begin
with Params^ do
begin
ScrollbarCount := 0;
EnumChildWindows( Window, @WinEnumerator3, dword( Params ) );
if ScrollbarCount = 2
then NeededWindow := Window;
Result := ( NeededWindow = 0 );
end;
end;
function FindViewerClient( Viewer : HWND ) : HWND;
var
Params : TEnum3Params;
begin
with Params do
begin
NeededWindow := 0;
EnumChildWindows( Viewer, @WinEnumerator4, dword( @Params ) );
Result := NeededWindow;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.