text stringlengths 14 6.51M |
|---|
unit GX_PasteAs;
interface
uses
Classes, GX_ConfigurationInfo, GX_EditorExpert;
type
TPasteAsType = (paStringArray, paAdd, paSLineBreak,
paChar10, paChar13, paChars1310, paCRLF, paCR_LF);
TPasteAsHandler = class
private
FCreateQuotedString: Boolean;
FPasteAsType: TPasteAsType;
FAddExtraSpaceAtTheEnd: Boolean;
FShowOptions: Boolean;
function DetermineIndent(ALines: TStrings): Integer;
protected
public
constructor Create;
procedure LoadSettings(Settings: TExpertSettings);
procedure SaveSettings(Settings: TExpertSettings);
procedure ConvertToCode(ALines: TStrings; AOnlyUpdateLines: Boolean);
procedure ExtractRawStrings(ALines: TStrings; ADoAddBaseIndent: Boolean);
function ExecuteConfig(AConfigExpert: TEditorExpert; ForceShow: Boolean): Boolean;
class procedure GetTypeText(AList: TStrings);
property CreateQuotedString: Boolean read FCreateQuotedString write FCreateQuotedString default True;
property PasteAsType: TPasteAsType read FPasteAsType write FPasteAsType default paStringArray;
property AddExtraSpaceAtTheEnd: Boolean read FAddExtraSpaceAtTheEnd write FAddExtraSpaceAtTheEnd default True;
property ShowOptions: Boolean read FShowOptions write FShowOptions;
end;
var
PasteAsHandler: TPasteAsHandler;
implementation
uses
Windows, SysUtils, StrUtils, Controls, GX_OtaUtils, GX_ePasteAs,
GX_GenericUtils;
const
cPasteAsTypeText: array[TPasteAsType] of String = (
'%s,', 'Add(%s);', '%s + sLineBreak +',
'%s + #10 +', '%s + #13 +', '%s + #13#10 +', '%s + CRLF +', '%s + CR_LF +');
cStringSep = '''';
{ TPasteAsHandler }
constructor TPasteAsHandler.Create;
begin
inherited Create;
FCreateQuotedString := True;
FPasteAsType := paStringArray;
FAddExtraSpaceAtTheEnd := True;
end;
class procedure TPasteAsHandler.GetTypeText(AList: TStrings);
var
AType: TPasteAsType;
begin
for AType := Low(TPasteAsType) to High(TPasteAsType) do
AList.AddObject(cPasteAsTypeText[AType], TObject(Integer(AType)));
end;
procedure TPasteAsHandler.LoadSettings(Settings: TExpertSettings);
begin
PasteAsType := TPasteAsType(Settings.ReadEnumerated('PasteAsType', TypeInfo(TPasteAsType), Ord(paStringArray)));
CreateQuotedString := Settings.ReadBool('CreateQuotedString', True);
AddExtraSpaceAtTheEnd := Settings.ReadBool('AddExtraSpaceAtTheEnd', True);
ShowOptions := Settings.ReadBool('ShowOptions', True);
end;
procedure TPasteAsHandler.SaveSettings(Settings: TExpertSettings);
begin
Settings.WriteEnumerated('PasteAsType', TypeInfo(TPasteAsType), Ord(FPasteAsType));
Settings.WriteBool('CreateQuotedString', FCreateQuotedString);
Settings.WriteBool('AddExtraSpaceAtTheEnd', FAddExtraSpaceAtTheEnd);
Settings.WriteBool('ShowOptions', FShowOptions);
end;
function TPasteAsHandler.DetermineIndent(ALines: TStrings): Integer;
var
i: Integer;
Line: string;
FCP: Integer;
begin
Result := MaxInt;
for i := 0 to ALines.Count-1 do
begin
Line := ALines[i];
FCP := GetFirstCharPos(Line, [' ', #09], False);
if FCP < Result then
Result := FCP;
end;
end;
procedure TPasteAsHandler.ConvertToCode(ALines: TStrings; AOnlyUpdateLines: Boolean);
var
I, FirstCharPos: Integer;
ALine, BaseIndent, ALineStart, ALineEnd, ALineStartBase, AAddDot: String;
begin
FirstCharPos := DetermineIndent(ALines);
// this works, because FirstCharPos is the smallest Indent for all lines
BaseIndent := LeftStr(ALines[0], FirstCharPos - 1);
ALineStart := '';
ALineEnd := '';
ALineStartBase := '';
AAddDot := '';
case FPasteAsType of
paStringArray: ALineEnd := ',';
paAdd:
begin
if not AOnlyUpdateLines then
begin
ALineStartBase := Trim(GxOtaGetCurrentSelection(False));
if (ALineStartBase <> '') and (ALineStartBase[Length(ALineStartBase)] <> '.') then
AAddDot := '.';
ALineStartBase := ALineStartBase + AAddDot;
end;
ALineStart := 'Add(';
ALineEnd := ');';
end;
paSLineBreak: ALineEnd := ' + sLineBreak +';
paChar10: ALineEnd := '#10 +';
paChar13: ALineEnd := '#13 +';
paChars1310: ALineEnd := '#13#10 +';
paCRLF: ALineEnd := ' + CRLF +';
paCR_LF: ALineEnd := ' + CR_LF +';
end;
for I := 0 to ALines.Count-1 do
begin
ALine := Copy(ALines[I], FirstCharPos, MaxInt);
if FCreateQuotedString then
ALine := AnsiQuotedStr(ALine + IfThen(FAddExtraSpaceAtTheEnd, ' '), cStringSep);
ALine := ALineStart + ALine;
if ALineStartBase <> '' then
ALine := IfThen(I = 0, AAddDot, ALineStartBase) + ALine;
if (I < ALines.Count-1) or (FPasteAsType = paAdd) then
ALine := ALine + ALineEnd;
ALines[I] := BaseIndent + ALine;
if not AOnlyUpdateLines then
GxOtaInsertLineIntoEditor(ALine + sLineBreak);
end;
end;
procedure TPasteAsHandler.ExtractRawStrings(ALines: TStrings; ADoAddBaseIndent: Boolean);
var
i, FirstCharPos, FirstQuotePos, LastQuotePos: Integer;
Line, BaseIndent: String;
sl: TStringList;
begin
FirstCharPos := DetermineIndent(ALines);
// this works, because FirstCharPos is the smallest Indent for all lines
BaseIndent := LeftStr(ALines[0], FirstCharPos - 1);
sl := TStringList.Create;
try
for i := 0 to ALines.Count-1 do
begin
Line := Trim(Copy(ALines[i], FirstCharPos, MaxInt));
FirstQuotePos := GetFirstCharPos(Line, [cStringSep], True);
LastQuotePos := GetLastCharPos(Line, [cStringSep], True);
if (FirstQuotePos > 0) and (LastQuotePos > 0) then
begin
Line := Copy(Line, FirstQuotePos, LastQuotePos - FirstQuotePos + 1);
// It's not "not FCreateQuotedString" because this is the ExtractRawStrings method
// the ConvertToCode will add the quotes again, if FCreateQuotedString is true.
if FCreateQuotedString then
Line := AnsiDequotedStr(Line, cStringSep);
sl.Add(IfThen(ADoAddBaseIndent, BaseIndent) + TrimRight(Line));
end;
end;
ALines.Assign(sl);
finally
FreeAndNil(sl);
end;
end;
function TPasteAsHandler.ExecuteConfig(AConfigExpert: TEditorExpert; ForceShow: Boolean): Boolean;
var
Dlg: TfmPasteAsConfig;
begin
Result := True;
if not FShowOptions and not ForceShow then
Exit;
Dlg := TfmPasteAsConfig.Create(nil);
try
GetTypeText(Dlg.cbPasteAsType.Items);
Dlg.cbPasteAsType.ItemIndex := Integer(PasteAsType);
Dlg.chkCreateQuotedStrings.Checked := CreateQuotedString;
Dlg.chkAddExtraSpaceAtTheEnd.Checked := AddExtraSpaceAtTheEnd;
Dlg.chkShowOptions.Checked := ShowOptions;
Result := Dlg.ShowModal = mrOk;
if Result then
begin
PasteAsType := TPasteAsType(Dlg.cbPasteAsType.ItemIndex);
CreateQuotedString := Dlg.chkCreateQuotedStrings.Checked;
AddExtraSpaceAtTheEnd := Dlg.chkAddExtraSpaceAtTheEnd.Checked;
ShowOptions := Dlg.chkShowOptions.Checked;
if Assigned(AConfigExpert) then
AConfigExpert.SaveSettings;
end;
finally
FreeAndNil(Dlg);
end;
end;
initialization
PasteAsHandler := TPasteAsHandler.Create;
finalization
FreeAndNil(PasteAsHandler);
end.
|
unit FileManager;
interface
uses SysUtils, GlobalVariables, Dos;
Procedure getMainPath();
Function WriteFile(fileToWrite, input : String) : boolean;
Function WriteNewFile(fileToWrite, input : String) : boolean;
Function ReadFile(fileToRead : String) : String;
Function ExistFile(fileToCheck : String) : boolean;
Function ExistTextFile(fileToCheck : String) : boolean;
Procedure DeleteFile(fileToDelete : String);
Procedure CreateDirectory(dirToCreate : String);
Function CreateBlocksCodeFile() : boolean;
implementation
Procedure getMainPath();
var path : String; i : integer; done : boolean;
Begin
done := false;
path := paramstr(0);
for i := length(path) DOWNTO 1 do
Begin
if ((not done) AND(Copy(path, length(path), 1) <> '\')) then Delete(path, length(path), 1)
Else done := true;
End;
gameDirectory := path;
resDirectory := path + 'GameData\';
End;
Function WriteFile(fileToWrite, input : String) : boolean;
var F : TextFile; state : boolean;
Begin
AssignFile(F, fileToWrite + '.txt');
{$I+}
try
Append(F);
Write(F, input);
Flush(F);
CloseFile(F);
state := true;
except
on E: EInOutError do
begin
writeln('Could not write to ', fileToWrite);
state := false;
end;
end;
WriteFile := state;
End;
Function WriteNewFile(fileToWrite, input : String) : boolean;
var F : TextFile; state : boolean;
Begin
AssignFile(F, fileToWrite + '.txt');
{$I+}
try
Rewrite(F);
Write(F, input);
Flush(F);
CloseFile(F);
state := true;
except
on E: EInOutError do
begin
writeln('Could not write to ', fileToWrite);
state := false;
end;
end;
WriteNewFile := state;
End;
Function ReadFile(fileToRead : String) : String;
var F : TextFile; temp, full : String;
Begin
full := '';
temp := '';
AssignFile(F, fileToRead + '.txt');
try
Reset(F);
Repeat
Readln(F, temp);
if (length(full) > 0) then full := full + #13#10 + temp
else full := temp;
temp := '';
Until Eof(F);
CloseFile(F);
except
on E: EInOutError do
Begin
writeln('Could not read ', fileToRead);
End;
End;
ReadFile := full;
End;
Function ExistTextFile(fileToCheck : String) : boolean;
var F : TextFile;
Begin
AssignFile(F, fileToCheck + '.txt');
try
Reset(F);
CloseFile(F);
ExistTextFile := true;
except
on E: EInOutError do
Begin
writeln('Could not find ', fileToCheck);
ExistTextFile := false;
End;
End;
End;
Function ExistFile(fileToCheck : String) : boolean;
var F : TextFile;
Begin
AssignFile(F, fileToCheck);
try
Reset(F);
CloseFile(F);
ExistFile := true;
except
on E: EInOutError do
Begin
writeln('Could not find ', fileToCheck);
ExistFile := false;
End;
End;
End;
Procedure DeleteFile(fileToDelete : String);
var F : TextFile;
Begin
Assign(F, fileToDelete + '.txt');
try
Erase(F);
except
on E: EInOutError do
Begin
writeln('Could not delete ', fileToDelete);
End;
End;
End;
Procedure CreateDirectory(dirToCreate : String);
var NewDir : PathStr;
Begin
NewDir := FSearch(dirToCreate, GetEnv(''));
if NewDir = '' then CreateDir(dirToCreate);
End;
Function CreateBlocksCodeFile : boolean;
var fileCode, f : String; state : boolean;
Begin
f := resDirectory + 'Blocks';
state := WriteNewFile(f, '# Block structure: ID, Text Color, Background Color, Name, Character, Collidable.'#13#10);
if (state) then state := WriteFile(f, '# BlockCollidable Dirt { - BlockType(BlockCollidable or BlockNotCollidable) BlockName'#13#10);
if (state) then state := WriteFile(f, '# 0, - Text Color'#13#10);
if (state) then state := WriteFile(f, '# 0, - Background Color'#13#10);
if (state) then state := WriteFile(f, '# " " - Character'#13#10);
if (state) then state := WriteFile(f, '# }'#13#10);
if (state) then state := WriteFile(f, '#'#13#10);
if (state) then state := WriteFile(f, '# Colors'#13#10);
if (state) then state := WriteFile(f, '# 0 Black'#13#10);
if (state) then state := WriteFile(f, '# 1 Blue'#13#10);
if (state) then state := WriteFile(f, '# 2 Green'#13#10);
if (state) then state := WriteFile(f, '# 3 Cyan'#13#10);
if (state) then state := WriteFile(f, '# 4 Red'#13#10);
if (state) then state := WriteFile(f, '# 5 Magenta'#13#10);
if (state) then state := WriteFile(f, '# 6 Brown'#13#10);
if (state) then state := WriteFile(f, '# 7 White'#13#10);
if (state) then state := WriteFile(f, '# 8 Grey'#13#10);
if (state) then state := WriteFile(f, '# 9 Light Blue'#13#10);
if (state) then state := WriteFile(f, '# 10 Light Green'#13#10);
if (state) then state := WriteFile(f, '# 11 Light Cyan'#13#10);
if (state) then state := WriteFile(f, '# 12 Light Red'#13#10);
if (state) then state := WriteFile(f, '# 13 Light Magenta'#13#10);
if (state) then state := WriteFile(f, '# 14 Yellow'#13#10);
if (state) then state := WriteFile(f, '# 15 High-intensity white'#13#10);
if (state) then state := WriteFile(f, #13#10);
if (state) then state := WriteFile(f, 'BlockNotCollidable Void {'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' " "'#13#10);
if (state) then state := WriteFile(f, '}'#13#10);
if (state) then state := WriteFile(f, #13#10);
if (state) then state := WriteFile(f, 'BlockNotCollidable Grass {'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' 2,'#13#10);
if (state) then state := WriteFile(f, ' " "'#13#10);
if (state) then state := WriteFile(f, '}'#13#10);
if (state) then state := WriteFile(f, #13#10);
if (state) then state := WriteFile(f, 'BlockNotCollidable Dirt {'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' 6,'#13#10);
if (state) then state := WriteFile(f, ' " "'#13#10);
if (state) then state := WriteFile(f, '}'#13#10);
if (state) then state := WriteFile(f, #13#10);
if (state) then state := WriteFile(f, 'BlockCollidable Wall {'#13#10);
if (state) then state := WriteFile(f, ' 6,'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' "|"'#13#10);
if (state) then state := WriteFile(f, '}'#13#10);
if (state) then state := WriteFile(f, #13#10);
if (state) then state := WriteFile(f, 'BlockNotCollidable FinishPoint {'#13#10);
if (state) then state := WriteFile(f, ' 0,'#13#10);
if (state) then state := WriteFile(f, ' 6,'#13#10);
if (state) then state := WriteFile(f, ' " "'#13#10);
if (state) then state := WriteFile(f, '}'#13#10);
CreateBlocksCodeFile := state;
End;
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.32 3/23/2005 8:20:18 AM JPMugaas
Temp fix for a double-free problem causing an AV. I will explain on Core.
Rev 1.31 6/11/2004 8:48:32 AM DSiders
Added "Do not Localize" comments.
Rev 1.30 2004.03.01 5:12:38 PM czhower
-Bug fix for shutdown of servers when connections still existed (AV)
-Implicit HELP support in CMDserver
-Several command handler bugs
-Additional command handler functionality.
Rev 1.29 2004.02.03 4:17:04 PM czhower
For unit name changes.
Rev 1.28 2004.01.22 5:59:14 PM czhower
IdCriticalSection
Rev 1.27 2004.01.20 10:03:32 PM czhower
InitComponent
Rev 1.26 6/11/2003 8:28:42 PM GGrieve
remove wrong call to inherited StartYarn
Rev 1.25 2003.10.24 12:59:18 PM czhower
Name change
Rev 1.24 2003.10.21 12:19:00 AM czhower
TIdTask support and fiber bug fixes.
Rev 1.23 10/15/2003 8:35:30 PM DSiders
Added resource string for exception raised in TIdSchedulerOfThread.NewYarn.
Rev 1.22 2003.10.14 11:18:10 PM czhower
Fix for AV on shutdown and other bugs
Rev 1.21 2003.10.11 5:49:32 PM czhower
-VCL fixes for servers
-Chain suport for servers (Super core)
-Scheduler upgrades
-Full yarn support
Rev 1.20 2003.09.19 10:11:18 PM czhower
Next stage of fiber support in servers.
Rev 1.19 2003.09.19 11:54:30 AM czhower
-Completed more features necessary for servers
-Fixed some bugs
Rev 1.18 2003.09.18 4:43:18 PM czhower
-Removed IdBaseThread
-Threads now have default names
Rev 1.17 2003.09.18 4:10:26 PM czhower
Preliminary changes for Yarn support.
Rev 1.16 2003.07.17 1:08:04 PM czhower
Fixed warning
Rev 1.15 7/6/2003 8:04:06 PM BGooijen
Renamed IdScheduler* to IdSchedulerOf*
Rev 1.14 7/5/2003 11:49:06 PM BGooijen
Cleaned up and fixed av in threadpool
Rev 1.13 2003.06.30 9:39:44 PM czhower
Comments and small change.
Rev 1.12 6/25/2003 3:54:02 PM BGooijen
Destructor waits now until all threads are terminated
Rev 1.11 2003.06.25 4:27:02 PM czhower
Fixed some formatting and fixed one line ifs.
Rev 1.10 4/11/2003 6:35:28 PM BGooijen
Rev 1.9 3/27/2003 5:17:22 PM BGooijen
Moved some code to TIdScheduler, made ThreadPriority published
Rev 1.8 3/22/2003 1:49:38 PM BGooijen
Fixed warnings (.ShouldStop)
Rev 1.7 3/13/2003 10:18:30 AM BGooijen
Server side fibers, bug fixes
Rev 1.6 1/23/2003 11:55:24 PM BGooijen
Rev 1.5 1/23/2003 8:32:40 PM BGooijen
Added termination handler
Rev 1.3 1/23/2003 11:05:58 AM BGooijen
Rev 1.2 1-17-2003 23:22:16 BGooijen
added MaxThreads property
Rev 1.1 1/17/2003 03:43:04 PM JPMugaas
Updated to use new class.
Rev 1.0 1/17/2003 03:29:50 PM JPMugaas
Renamed from ThreadMgr for new design.
Rev 1.0 11/13/2002 09:01:32 AM JPMugaas
02 Oct 2001 - Allen O'Neill
Added support for thread priority - new property Threadpriority,
new line added to OnCreate
}
unit IdSchedulerOfThread;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdException, IdBaseComponent, IdGlobal, IdScheduler,
IdThread, IdTask, IdYarn;
type
TIdYarnOfThread = class(TIdYarn)
protected
FScheduler: TIdScheduler;
FThread: TIdThreadWithTask;
public
constructor Create(AScheduler: TIdScheduler; AThread: TIdThreadWithTask); reintroduce;
destructor Destroy; override;
//
property Thread: TIdThreadWithTask read FThread;
end;
TIdSchedulerOfThread = class(TIdScheduler)
protected
FMaxThreads: Integer;
FThreadPriority: TIdThreadPriority;
FThreadClass: TIdThreadWithTaskClass;
//
procedure InitComponent; override;
public
destructor Destroy; override;
function NewThread: TIdThreadWithTask; virtual;
function NewYarn(AThread: TIdThreadWithTask = nil): TIdYarnOfThread;
procedure StartYarn(AYarn: TIdYarn; ATask: TIdTask); override;
procedure TerminateYarn(AYarn: TIdYarn); override;
property ThreadClass: TIdThreadWithTaskClass read FThreadClass write FThreadClass;
published
property MaxThreads: Integer read FMaxThreads write FMaxThreads;
property ThreadPriority: TIdThreadPriority read FThreadPriority write FThreadPriority default tpNormal;
end;
implementation
uses
{$IFDEF KYLIXCOMPAT}
Libc,
{$ENDIF}
IdResourceStringsCore, IdTCPServer, IdThreadSafe, IdExceptionCore, SysUtils;
{ TIdSchedulerOfThread }
destructor TIdSchedulerOfThread.Destroy;
begin
TerminateAllYarns;
inherited Destroy;
end;
procedure TIdSchedulerOfThread.StartYarn(AYarn: TIdYarn; ATask: TIdTask);
begin
with TIdYarnOfThread(AYarn).Thread do begin
Task := ATask;
Start;
end;
end;
function TIdSchedulerOfThread.NewThread: TIdThreadWithTask;
begin
Assert(FThreadClass<>nil);
if (FMaxThreads <> 0) and (not ActiveYarns.IsCountLessThan(FMaxThreads + 1)) then begin
EIdSchedulerMaxThreadsExceeded.Toss(RSchedMaxThreadEx);
end;
Result := FThreadClass.Create(nil, IndyFormat('%s User', [Name])); {do not localize}
if ThreadPriority <> tpNormal then begin
IndySetThreadPriority(Result, ThreadPriority);
end;
end;
function TIdSchedulerOfThread.NewYarn(AThread: TIdThreadWithTask): TIdYarnOfThread;
begin
if not Assigned(AThread) then begin
EIdException.Toss(RSThreadSchedulerThreadRequired);
end;
// Create Yarn
Result := TIdYarnOfThread.Create(Self, AThread);
end;
procedure TIdSchedulerOfThread.TerminateYarn(AYarn: TIdYarn);
var
LYarn: TIdYarnOfThread;
begin
Assert(AYarn<>nil);
LYarn := TIdYarnOfThread(AYarn);
if (LYarn.Thread <> nil) and (not LYarn.Thread.Suspended) then begin
// Is still running and will free itself
LYarn.Thread.Stop;
// Dont free the yarn. The thread frees it (IdThread.pas)
end else
begin
// If suspended, was created but never started
// ie waiting on connection accept
// RLebeau: free the yarn here as well. This allows TIdSchedulerOfThreadPool
// to put the suspended thread, if present, back in the pool.
FreeAndNil(LYarn);
end;
end;
procedure TIdSchedulerOfThread.InitComponent;
begin
inherited InitComponent;
FThreadPriority := tpNormal;
FMaxThreads := 0;
FThreadClass := TIdThreadWithTask;
end;
{ TIdYarnOfThread }
constructor TIdYarnOfThread.Create(
AScheduler: TIdScheduler;
AThread: TIdThreadWithTask
);
begin
inherited Create;
FScheduler := AScheduler;
FThread := AThread;
AThread.Yarn := Self;
end;
destructor TIdYarnOfThread.Destroy;
begin
FScheduler.ReleaseYarn(Self);
inherited Destroy;
end;
end.
|
unit Providers.Mascara.Celular;
interface
uses
Providers.Mascaras.Intf, System.MaskUtils, System.SysUtils;
type
TMascaraCelular = class(TInterfacedObject, IMascaras)
private
procedure RemoveParenteses(var Value: string);
public
function ExecMask(Value: string): string;
end;
implementation
{ TMascaraTelefone }
function TMascaraCelular.ExecMask(Value: string): string;
begin
RemoveParenteses(Value);
Result := FormatMaskText('\(00\)00000\-0000;0;', Value);
end;
procedure TMascaraCelular.RemoveParenteses(var Value: string);
begin
Delete(Value, AnsiPos('-', Value), 1);
Delete(Value, AnsiPos('-', Value), 1);
Delete(Value, AnsiPos('(', Value), 1);
Delete(Value, AnsiPos(')', Value), 1);
end;
end.
|
unit htDataProviderParams;
// Модуль: "w:\common\components\rtl\Garant\HT\htDataProviderParams.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "ThtDataProviderParams" MUID: (54F9AF6B00DD)
{$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc}
interface
uses
l3IntfUses
, daDataProviderParams
, dt_Types
, k2Base
;
type
ThtDataProviderParams = class(TdaDataProviderParams)
protected
function pm_GetStationName: AnsiString;
procedure pm_SetStationName(const aValue: AnsiString);
function pm_GetTablePath: AnsiString;
procedure pm_SetTablePath(const aValue: AnsiString);
function pm_GetTmpDirPath: AnsiString;
procedure pm_SetTmpDirPath(const aValue: AnsiString);
function pm_GetLockPath: AnsiString;
procedure pm_SetLockPath(const aValue: AnsiString);
public
function MakePathRec: TPathRec;
procedure ChangeBasePath(const aPath: AnsiString); override;
procedure AssignParams(aParams: TdaDataProviderParams); override;
class function GetTaggedDataType: Tk2Type; override;
public
property StationName: AnsiString
read pm_GetStationName
write pm_SetStationName;
property TablePath: AnsiString
read pm_GetTablePath
write pm_SetTablePath;
property TmpDirPath: AnsiString
read pm_GetTmpDirPath
write pm_SetTmpDirPath;
property LockPath: AnsiString
read pm_GetLockPath
write pm_SetLockPath;
end;//ThtDataProviderParams
implementation
uses
l3ImplUses
, l3FileUtils
, ddUtils
, SysUtils
, HyTechProviderParams_Const
//#UC START# *54F9AF6B00DDimpl_uses*
//#UC END# *54F9AF6B00DDimpl_uses*
;
function ThtDataProviderParams.pm_GetStationName: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrStationName]);
end;//ThtDataProviderParams.pm_GetStationName
procedure ThtDataProviderParams.pm_SetStationName(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrStationName, nil] := (aValue);
end;//ThtDataProviderParams.pm_SetStationName
function ThtDataProviderParams.pm_GetTablePath: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrTablePath]);
end;//ThtDataProviderParams.pm_GetTablePath
procedure ThtDataProviderParams.pm_SetTablePath(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrTablePath, nil] := (aValue);
end;//ThtDataProviderParams.pm_SetTablePath
function ThtDataProviderParams.pm_GetTmpDirPath: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrTmpDirPath]);
end;//ThtDataProviderParams.pm_GetTmpDirPath
procedure ThtDataProviderParams.pm_SetTmpDirPath(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrTmpDirPath, nil] := (aValue);
end;//ThtDataProviderParams.pm_SetTmpDirPath
function ThtDataProviderParams.pm_GetLockPath: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrLockPath]);
end;//ThtDataProviderParams.pm_GetLockPath
procedure ThtDataProviderParams.pm_SetLockPath(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrLockPath, nil] := (aValue);
end;//ThtDataProviderParams.pm_SetLockPath
function ThtDataProviderParams.MakePathRec: TPathRec;
//#UC START# *55114DCA0351_54F9AF6B00DD_var*
//#UC END# *55114DCA0351_54F9AF6B00DD_var*
begin
//#UC START# *55114DCA0351_54F9AF6B00DD_impl*
Result.TblPath := TablePath;
Result.HomePath := HomeDirPath;
Result.LockPath := LockPath;
Result.TmpPath := TmpDirPath;
Result.DocImgPath := DocImagePath;
Result.DocImgCachePath := DocImageCachePath;
Result.DocsPath := DocStoragePath;
//#UC END# *55114DCA0351_54F9AF6B00DD_impl*
end;//ThtDataProviderParams.MakePathRec
procedure ThtDataProviderParams.ChangeBasePath(const aPath: AnsiString);
//#UC START# *55195AE803E0_54F9AF6B00DD_var*
//#UC END# *55195AE803E0_54F9AF6B00DD_var*
begin
//#UC START# *55195AE803E0_54F9AF6B00DD_impl*
inherited;
TablePath := ConcatDirName(aPath, 'main');
LockPath:= ConcatDirName(aPath, 'share');
if TmpDirPath = '' then
TmpDirPath := GetWindowsTempFolder;
//#UC END# *55195AE803E0_54F9AF6B00DD_impl*
end;//ThtDataProviderParams.ChangeBasePath
procedure ThtDataProviderParams.AssignParams(aParams: TdaDataProviderParams);
//#UC START# *553A37E902C9_54F9AF6B00DD_var*
//#UC END# *553A37E902C9_54F9AF6B00DD_var*
begin
//#UC START# *553A37E902C9_54F9AF6B00DD_impl*
inherited;
if aParams is ThtDataProviderParams then
begin
StationName := ThtDataProviderParams(aParams).StationName;
TablePath := ThtDataProviderParams(aParams).TablePath;
TmpDirPath := ThtDataProviderParams(aParams).TmpDirPath;
LockPath := ThtDataProviderParams(aParams).LockPath;
end;
//#UC END# *553A37E902C9_54F9AF6B00DD_impl*
end;//ThtDataProviderParams.AssignParams
class function ThtDataProviderParams.GetTaggedDataType: Tk2Type;
begin
Result := k2_typHyTechProviderParams;
end;//ThtDataProviderParams.GetTaggedDataType
end.
|
unit IsppDebug;
interface
implementation
uses Windows, SysUtils, JclHookExcept, JclDebug, TypInfo, IsppTranslate,
IsppExceptWindow, Forms, IsppIdentMan;
procedure NotifyException(ExceptObj: TObject; ExceptAddr: Pointer;
OSException: Boolean);
var
TmpS: string;
ModInfo: TJclLocationInfo;
I: Integer;
ExceptionHandled: Boolean;
HandlerLocation: Pointer;
ExceptFrame: TJclExceptFrame;
begin
if ExceptObj is EPreprocError then Exit;
if ExceptObj is EIdentError then Exit;
with TIsppExceptWnd.Create(nil) do
try
mmLog.Lines.Clear;
TmpS := 'Exception ' + ExceptObj.ClassName;
if ExceptObj is Exception then
TmpS := TmpS + ': ' + Exception(ExceptObj).Message;
if OSException then
TmpS := TmpS + ' (OS Exception)';
mmLog.Lines.Add(TmpS);
ModInfo := GetLocationInfo(ExceptAddr);
mmLog.Lines.Add('');
mmLog.Lines.Add(Format(
' Exception occured at $%p (%s.%s@%d)',
[ModInfo.Address,
ModInfo.UnitName,
ModInfo.ProcedureName,
//ModInfo.SourceName,
ModInfo.LineNumber]));
if stExceptFrame in JclStackTrackingOptions then
begin
mmLog.Lines.Add('');
mmLog.Lines.Add('');
mmLog.Lines.Add(' Except frame-dump:');
mmLog.Lines.Add('');
I := 0;
ExceptionHandled := False;
while not ExceptionHandled and
(I < JclLastExceptFrameList.Count) do
begin
ExceptFrame := JclLastExceptFrameList.Items[I];
ExceptionHandled := ExceptFrame.HandlerInfo(ExceptObj, HandlerLocation);
if (ExceptFrame.FrameKind = efkFinally) or
(ExceptFrame.FrameKind = efkUnknown) or
not ExceptionHandled then
HandlerLocation := ExceptFrame.CodeLocation;
ModInfo := GetLocationInfo(HandlerLocation);
TmpS := Format(
' Frame at $%p (type: %s',
[ExceptFrame.ExcFrame,
GetEnumName(TypeInfo(TExceptFrameKind), Ord(ExceptFrame.FrameKind))]);
if ExceptionHandled then
TmpS := TmpS + ', handles exception)'
else
TmpS := TmpS + ')';
mmLog.Lines.Add(TmpS);
if ExceptionHandled then
mmLog.Lines.Add(Format(
' Handler at $%p',
[HandlerLocation]))
else
mmLog.Lines.Add(Format(
' Code at $%p',
[HandlerLocation]));
mmLog.Lines.Add(Format(
' %s.%s@%d',
[ModInfo.UnitName,
ModInfo.ProcedureName,
//ModInfo.SourceName,
ModInfo.LineNumber]));
Inc(I);
mmLog.Lines.Add('');
end;
end;
mmLog.Lines.Add('');
ShowModal;
finally
Release
end;
end;
initialization
JclStackTrackingOptions := JclStackTrackingOptions + [stExceptFrame];
JclStartExceptionTracking;
JclAddExceptNotifier(NotifyException);
finalization
JclRemoveExceptNotifier(NotifyException);
JclStopExceptionTracking;
end.
|
{*
* Judging program for "Street Directions"
*
* Copyright Chen Mingrei (ZSUCPC 2001)
* Date: May 10, 2001
*
* Comment: This program displays and checks the output of a program to see
* if it correct. The following are checked:
*
* 1. out of range vertex numbers
* 2. duplicate edges in output
* 3. incorrect vertex degree
* 4. solution contains extra streets not in the original map
* 5. some streets have no direction assigned
* 6. incorrect number of two-way streets
* 7. reachability from any intersection to any other intersections
* 8. format error (invalid number)
*
*}
var
InFile, OutFile, StdFile: Text;
NoOutput: Boolean;
function Left(var S: string; N: Integer): string;
var
Temp: string;
begin
Temp := Copy(S, 1, N);
while Length(Temp) < N do Temp := Temp + ' ';
Delete(S, 1, N);
Left := Temp;
end;
procedure Show;
var
InStr, OutStr: string;
begin
Reset(InFile);
{$I-}
Reset(OutFile);
{$I+}
NoOutput := IOResult <> 0;
Write('Judging program for "Street Directions" Copyright Chen Mingrei (ZSUCPC 2001)');
Writeln('Input: street.in ³ Output: street.out');
Write('ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÅÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ');
InStr := '';
if NoOutput then OutStr := 'Fail to open "street.out"!'
else OutStr := '';
repeat
If not Eof(InFile) and (InStr = '') then Readln(InFile, InStr);
If not NoOutput and not Eof(OutFile) and (OutStr = '') then Readln(OutFile, OutStr);
Writeln(Left(InStr, 38) + ' ³ ' + Left(OutStr, 38));
until Eof(InFile) and (NoOutput or Eof(OutFile)) and (InStr = '') and (OutStr = '');
end;
procedure Report(S: string);
begin
if S = '' then Writeln('Judgement: Yes! ^_^')
else Writeln('Judgement: No - ', S, '.');
Close(InFile);
if not NoOutput then Close(OutFile);
Close(StdFile);
Readln;
Halt;
end;
function MyStr(I: Integer): string;
var
S: string;
begin
Str(I, S);
MyStr := S;
end;
const
MAX_N = 1000;
MAX_DEG = 4;
MAX_M = MAX_DEG * MAX_N div 2;
type
Tdeg = array[1 .. MAX_N] of Integer;
Tadj = array[1 .. MAX_N, 0 .. MAX_DEG - 1] of Integer;
Tvisited = array[1 .. MAX_N] of Boolean;
var
n, m: Integer;
deg1, deg2: Tdeg;
adj1, adj2: Tadj;
dfs: array[1 .. MAX_N] of Integer;
back:array [1 .. MAX_N] of Integer;
n_stack, dfn: Integer;
v_stack: array[0 .. MAX_M - 1] of Integer;
w_stack: array[0 .. MAX_M - 1] of Integer;
TwoWay1, TwoWay2: Integer;
function Min(x, y: Integer): Integer;
begin
if x < y then Min := x else Min := y
end;
function DFSearch(var deg: Tdeg; var adj: Tadj; src, prev: Integer; var visited: Tvisited): Boolean;
var
i, w: Integer;
begin
if visited[src] then
begin DFSearch := False; Exit end;
if (1 <= src) and (src <= prev) then
begin DFSearch := True; Exit end;
visited[src] := True;
for i := 0 to deg[src] - 1 do
begin
w := adj[src, i];
if DFSearch(deg, adj, w, prev, visited) then
begin DFSearch := True; Exit end;
end;
DFSearch := False;
end;
function CheckReachability(var deg: Tdeg; var adj: Tadj): Boolean;
var
visited: Tvisited;
i, j: Integer;
begin
for i := 1 to n do visited[i] := False;
DFSearch(deg, adj, 1, 0, visited);
for i :=1 to n do
if not visited[i] then
begin CheckReachability := False; Exit end;
for i := 2 to n do
begin
for j := 1 to n do visited[j] := False;
if not DFSearch(deg, adj, i, i-1, visited) then
begin CheckReachability := False; Exit end
end;
CheckReachability := True;
end;
procedure ReadData(var deg: Tdeg; var adj: Tadj);
var
i, u, v: Integer;
begin
Read(InFile, n, m);
for i := 1 to n do deg[i] := 0;
for i := 0 to m - 1 do
begin
Read(InFile, u, v);
adj[u, deg[u]] := v; Inc(deg[u]);
adj[v, deg[v]] := u; Inc(deg[v]);
end;
end;
procedure ReadSoln(var deg: Tdeg; var adj: Tadj);
var
i, u, v, t: Integer;
begin
for i := 1 to n do deg[i] := 0;
while not eof(OutFile) do
begin
{$I-}
Read(OutFile, u, v);
{$I+}
if IOResult <> 0 then Report('Format error: invalid number');
if (u < 1) or (u > n) or (v < 1) or (v > n) or (u = v) then
Report('Vertices out of range');
for t := 0 to deg[u] - 1 do
if adj[u][t] = v then Report('Duplicate edge');
adj[u][deg[u]] := v; Inc(deg[u]);
if (deg[u] < 0) or (deg[u] > 4) then Report('Wrong degree');
if not Eoln(OutFile) then
Report('Format error: not end of line after an edge')
else
Readln(OutFile);
end;
end;
function CheckEdge(var deg: Tdeg; var adj: Tadj; u, v: Integer): Boolean;
var
i: Integer;
begin
for i := 0 to deg[u] - 1 do
if adj[u, i] = v then
begin CheckEdge := True; Exit end;
CheckEdge := False;
end;
procedure CheckEdges(var deg1: Tdeg; var adj1: Tadj; var deg2: Tdeg; var adj2: Tadj);
var
u, i: Integer;
begin
{ check that all edges in graph 2 are edges in graph 1 }
for u := 1 to n do
for i := 0 to deg2[u] - 1 do
if not CheckEdge(deg1, adj1, u, adj2[u, i]) then { extra edges in graph 2 }
Report('Solution graph contains extra edges');
{ check that edges in graph 1 has been assigned a direction in graph 2 }
for u := 1 to n do
for i := 0 to deg1[u] - 1 do
if not CheckEdge(deg2, adj2, u, adj1[u, i]) and
not CheckEdge(deg2, adj2, adj1[u, i], u) then { unassigned edges }
Report('Unassigned edge');
end;
procedure Bicomp(var deg: Tdeg; var adj: Tadj; v, pred: Integer);
var
i, w, count: Integer;
begin
Inc(dfn);
dfs[v] := dfn; back[v] := dfn;
for i := 0 to deg[v] - 1 do
begin
w := adj[v, i];
if (dfs[w] < dfs[v]) and (w <> pred) then
begin
{ back edge or unexamined forward edge }
v_stack[n_stack] := v;
w_stack[n_stack] := w;
Inc(n_stack);
end;
if dfs[w] = 0 then
begin
bicomp(deg, adj, w, v);
{ back up from recursion }
if back[w] >= dfs[v] then
begin
{ new bicomponent }
count := 0;
while (v_stack[n_stack-1] <> v) or (w_stack[n_stack-1] <> w) do
begin
{ assert(n_stack > 0); }
Dec(n_stack);
Inc(count);
end;
if count = 0 then
{ we have a bicomponent containing only one edge }
Inc(TwoWay1);
Dec(n_stack);
end
else
back[v] := min(back[v], back[w]);
end
else
{ w has been examined already }
back[v] := min(back[v], dfs[w]);
end;
end;
function CountTwoWay(var deg: Tdeg; var adj: Tadj): Integer;
var
res, u, i: Integer;
begin
res := 0;
for u := 1 to n do
for i := 0 to deg[u] - 1 do
if CheckEdge(deg, adj, adj[u, i], u) then Inc(res);
{ assert(res % 2 == 0); }
CountTwoWay := res div 2;
end;
procedure Judge;
var
i: Integer;
begin
Reset(InFile); Reset(StdFile);
If NoOutput then Report('No output file');
Reset(OutFile);
if Eof(OutFile) then Report('No output');
ReadData(deg1, adj1);
ReadSoln(deg2, adj2);
CheckEdges(deg1, adj1, deg2, adj2);
{ compute number of two-way streets }
TwoWay1 := 0; n_stack := 0; dfn := 0;
for i:= 1 to n do dfs[i] := 0;
Bicomp(deg1, adj1, 1, -1);
TwoWay2 := CountTwoWay(deg2, adj2);
if TwoWay1 <> TwoWay2 then { incorrect number of two-way streets }
Report('Incorrect number of two-way streets');
if not CheckReachability(deg2, adj2) then { not reachable }
Report('Not reachable');
Report('');
end;
begin
Assign(InFile, 'street.in');
Assign(OutFile, 'street.out');
Assign(StdFile, 'street.std');
Show;
Judge;
end. |
unit UTwitterDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.TMSCloudBase, FMX.TMSCloudTwitter, FMX.Layouts,
FMX.ListBox, FMX.Edit, IOUtils, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomTwitter;
type
TForm82 = class(TForm)
ToolBar1: TToolBar;
Button1: TButton;
Button2: TButton;
TMSFMXCloudTwitter1: TTMSFMXCloudTwitter;
ListBox1: TListBox;
ListBox2: TListBox;
ListBox3: TListBox;
Button6: TButton;
Button7: TButton;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
SpeedButton3: TSpeedButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure TMSFMXCloudTwitter1ReceivedAccessToken(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button7Click(Sender: TObject);
private
{ Private declarations }
Connected: Boolean;
public
{ Public declarations }
procedure FillFollowers;
procedure FillFriends;
procedure LoadTweets;
procedure ToggleControls;
end;
var
Form82: TForm82;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// TwitterAppKey = 'xxxxxxxxx';
// TwitterAppSecret = 'yyyyyyyyy';
{$I APPIDS.INC}
procedure TForm82.Button1Click(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudTwitter1.App.Key := TwitterAppkey;
TMSFMXCloudTwitter1.App.Secret := TwitterAppSecret;
if TMSFMXCloudTwitter1.App.Key <> '' then
begin
TMSFMXCloudTwitter1.PersistTokens.Key := TPath.GetDocumentsPath + '/twitter.ini';
TMSFMXCloudTwitter1.PersistTokens.Section := 'tokens';
TMSFMXCloudTwitter1.LoadTokens;
acc := TMSFMXCloudTwitter1.TestTokens;
if not acc then
begin
TMSFMXCloudTwitter1.RefreshAccess;
TMSFMXCloudTwitter1.DoAuth;
TMSFMXCloudTwitter1.GetAccountInfo;
end
else
begin
connected := true;
ToggleControls;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm82.Button2Click(Sender: TObject);
begin
TMSFMXCloudTwitter1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm82.Button3Click(Sender: TObject);
begin
FillFollowers;
end;
procedure TForm82.Button4Click(Sender: TObject);
begin
FillFriends;
end;
procedure TForm82.Button5Click(Sender: TObject);
begin
LoadTweets;
end;
procedure TForm82.Button6Click(Sender: TObject);
begin
TMSFMXCloudTwitter1.Tweet(Edit1.Text);
ListBox3.Items.Clear;
TMSFMXCloudTwitter1.Statuses.Clear;
LoadTweets;
end;
procedure TForm82.Button7Click(Sender: TObject);
begin
TMSFMXCloudTwitter1.TweetWithMedia(Edit1.Text, TPath.GetDocumentsPath + '/sample.jpg');
ListBox3.Items.Clear;
TMSFMXCloudTwitter1.Statuses.Clear;
LoadTweets;
end;
procedure TForm82.FillFollowers;
var
i: integer;
begin
TMSFMXCloudTwitter1.GetFollowers;
TMSFMXCloudTwitter1.GetProfileListInfo(TMSFMXCloudTwitter1.Followers);
ListBox1.Items.Clear;
for i := 0 to TMSFMXCloudTwitter1.Followers.Count - 1 do
listbox1.Items.AddObject(TMSFMXCloudTwitter1.Followers.Items[i].Name, TMSFMXCloudTwitter1.Followers.Items[i]);
end;
procedure TForm82.FillFriends;
var
i: integer;
begin
TMSFMXCloudTwitter1.GetFriends;
TMSFMXCloudTwitter1.GetProfileListInfo(TMSFMXCloudTwitter1.Friends);
ListBox2.Items.Clear;
for i := 0 to TMSFMXCloudTwitter1.Friends.Count - 1 do
listbox2.Items.AddObject(TMSFMXCloudTwitter1.Friends.Items[i].Name, TMSFMXCloudTwitter1.Friends.Items[i]);
end;
procedure TForm82.FormCreate(Sender: TObject);
begin
Connected := False;
ToggleControls;
{$IFDEF IOS}
TFile.Copy(ExtractFilePath(Paramstr(0)) + 'sample.jpg', TPath.GetDocumentsPath + '/sample.jpg', True);
{$ENDIF}
end;
procedure TForm82.LoadTweets;
var
i: integer;
TwitterStatus: TTWitterStatus;
begin
if ListBox3.Items.Count = 0 then
TMSFMXCloudTwitter1.GetStatuses(10)
else
begin
TWitterStatus := TTwitterStatus(ListBox3.Items.Objects[ListBox3.Items.Count - 1]);
TMSFMXCloudTwitter1.GetStatuses(10, -1, TwitterStatus.ID);
end;
for i := ListBox3.Items.Count to TMSFMXCloudTwitter1.Statuses.Count - 1 do
ListBox3.Items.AddObject(TMSFMXCloudTwitter1.Statuses.Items[i].Text, TMSFMXCloudTwitter1.Statuses.Items[i]);
end;
procedure TForm82.TMSFMXCloudTwitter1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudTwitter1.SaveTokens;
TMSFMXCloudTwitter1.GetAccountInfo;
Connected := true;
ToggleControls;
end;
procedure TForm82.ToggleControls;
begin
Edit1.Enabled := Connected;
Button1.Enabled := not Connected;
Button2.Enabled := Connected;
SpeedButton3.Enabled := Connected;
SpeedButton1.Enabled := Connected;
SpeedButton2.Enabled := Connected;
Button6.Enabled := Connected;
ListBox1.Enabled := Connected;
ListBox2.Enabled := Connected;
ListBox3.Enabled := Connected;
end;
end.
|
unit UStreamOp;
interface
uses
Classes, UAccountKey, URawBytes;
type
{ TStreamOp }
TStreamOp = Class
public
class Function WriteAnsiString(Stream: TStream; const value: AnsiString): Integer; overload;
class Function ReadAnsiString(Stream: TStream; var value: AnsiString): Integer; overload;
class Function WriteAccountKey(Stream: TStream; const value: TAccountKey): Integer;
class Function ReadAccountKey(Stream: TStream; var value : TAccountKey): Integer;
class Function SaveStreamToRaw(Stream: TStream) : TRawBytes;
class procedure LoadStreamFromRaw(Stream: TStream; const raw : TRawBytes);
End;
implementation
uses
ULog, SysUtils, UECDSA_Public;
{ TStreamOp }
class function TStreamOp.ReadAccountKey(Stream: TStream; var value: TAccountKey): Integer;
begin
if Stream.Size - Stream.Position < 2 then begin
value := CT_TECDSA_Public_Nul;
Result := -1;
exit;
end;
stream.Read(value.EC_OpenSSL_NID,SizeOf(value.EC_OpenSSL_NID));
if (ReadAnsiString(stream,value.x)<=0) then begin
value := CT_TECDSA_Public_Nul;
exit;
end;
if (ReadAnsiString(stream,value.y)<=0) then begin
value := CT_TECDSA_Public_Nul;
exit;
end;
Result := value.EC_OpenSSL_NID;
end;
class function TStreamOp.SaveStreamToRaw(Stream: TStream): TRawBytes;
begin
SetLength(Result,Stream.Size);
Stream.Position:=0;
Stream.ReadBuffer(Result[1],Stream.Size);
end;
class procedure TStreamOp.LoadStreamFromRaw(Stream: TStream; const raw: TRawBytes);
begin
Stream.WriteBuffer(raw[1],Length(raw));
end;
class function TStreamOp.ReadAnsiString(Stream: TStream; var value: AnsiString): Integer;
Var
l: Word;
begin
if Stream.Size - Stream.Position < 2 then begin
value := '';
Result := -1;
exit;
end;
Stream.Read(l, 2);
if Stream.Size - Stream.Position < l then begin
Stream.Position := Stream.Position - 2; // Go back!
value := '';
Result := -1;
exit;
end;
SetLength(value, l);
Stream.ReadBuffer(value[1], l);
Result := l+2;
end;
class function TStreamOp.WriteAccountKey(Stream: TStream; const value: TAccountKey): Integer;
begin
Result := stream.Write(value.EC_OpenSSL_NID, SizeOf(value.EC_OpenSSL_NID));
Result := Result + WriteAnsiString(stream,value.x);
Result := Result + WriteAnsiString(stream,value.y);
end;
class function TStreamOp.WriteAnsiString(Stream: TStream; const value: AnsiString): Integer;
Var
l: Word;
begin
if (Length(value)>(256*256)) then begin
TLog.NewLog(lterror,Classname,'Invalid stream size! '+IntToStr(Length(value)));
raise Exception.Create('Invalid stream size! '+IntToStr(Length(value)));
end;
l := Length(value);
Stream.Write(l, 2);
if (l > 0) then
Stream.WriteBuffer(value[1], Length(value));
Result := l+2;
end;
end.
|
unit BCEditor.Language;
interface {********************************************************************}
resourcestring
{ Messages }
SBCEditorMessageConfirmation = 'Confirmation';
SBCEditorMessageError = 'Error';
SBCEditorMessageInformation = 'Information';
SBCEditorMessageQuestion = 'Question';
SBCEditorOk = 'Ok';
SBCEditorCancel = 'Cancel';
{ BCEditor }
SBCEditorCodeFoldingCollapsedMark = '%d Lines';
SBCEditorScrollInfo = 'Line: %d';
SBCEditorPatternIsEmpty = 'Pattern is empty';
SBCEditorPatternContainsWordBreakChar = 'Pattern contains word break character';
SBCEditorReplaceTextPrompt = 'Replace this occurrence of "%s"?';
SBCEditorSearchNotFound = 'Search string "%s" not found';
SBCEditorSearchWrapAroundTitle = 'Search match not found';
SBCEditorSearchWrapAroundForwards = 'Restart search from the beginning of the file?';
SBCEditorSearchWrapAroundBackwards = 'Restart search from the ending of the file?';
SBCEditorTerminatedByUser = 'Terminated by user';
{ BCEditor.DGotoLine }
SBCEditorGotoLineCaption = 'Go to Line Number';
SBCEditorGotoLineLine = 'Enter new line number';
implementation {***************************************************************}
end.
|
{
Author: William Yang
Website: http://www.pockhero.com
}
unit Graphix.Helpers;
interface
uses System.UITypes, System.Classes, System.Types, System.UIConsts, FMX.Types;
type
TColorHelper = record helper for TAlphaColor
public
function Brighten(AValue: Single): TAlphaColor;
function Darken(AValue: Single): TAlphaColor;
function Brightness: Single;
end;
TBitmapHelper = class helper for TBitmap
public
class function Create: TBitmap; overload;
function ClientRectF: TRectF;
function ClientRect: TRect;
procedure ApplyMask(const Mask: TBitmap); overload;
procedure PlatformCopy(ASrc: TBitmap);
procedure Clear; overload;
end;
function DarkColorChannel(const Channel: Byte; const Pct: Single): Byte; inline;
function BrightColorChannel(const Channel: Byte; const Pct: Single): Byte; inline;
function BrightColor(const Color: TAlphaColor; const Pct: Single): TAlphaColor; inline;
function DarkColor(const Color: TAlphaColor; const Pct: Single): TAlphaColor; inline;
implementation
uses Math;
const
MaxBytePercent = 2.55;
function BrightColor(const Color: TAlphaColor; const Pct: Single): TAlphaColor; inline;
begin
Result := Color;
with TAlphaColorRec(Result) do
begin
R := BrightColorChannel(R, Pct);
G := BrightColorChannel(G, Pct);
B := BrightColorChannel(B, Pct);
end;
end;
function BrightColorChannel(const Channel: Byte; const Pct: Single): Byte; inline;
var
Temp: Integer;
begin
if Pct < 0 then
Result := DarkColorChannel(Channel, -Pct)
else
begin
Temp := Round(Channel + Pct * MaxBytePercent);
if Temp > High(Result) then
Result := High(Result)
else
Result := Temp;
end;
end;
function DarkColor(const Color: TAlphaColor; const Pct: Single): TAlphaColor; inline;
begin
Result := Color;
with TAlphaColorRec(Result) do
begin
R := DarkColorChannel(R, Pct);
G := DarkColorChannel(G, Pct);
B := DarkColorChannel(B, Pct);
end;
end;
function DarkColorChannel(const Channel: Byte; const Pct: Single): Byte; inline;
var
Temp: Integer;
begin
if Pct < 0 then
Result := BrightColorChannel(Channel, -Pct)
else
begin
Temp := Round(Channel - Pct * MaxBytePercent);
if Temp < Low(Result) then
Result := Low(Result)
else
Result := Temp;
end;
end;
{ TColorHelper }
//class operator TColorHelper.Add(a, b: TAlphaColor): TAlphaColor;
//begin
//
// TAlphaColorRec(Result).A := (TAlphaColorRec(A).A + TAlphaColorRec(B).A) div 2;
// TAlphaColorRec(Result).R := TAlphaColorRec(A).R + TAlphaColorRec(B).R;
// TAlphaColorRec(Result).G := TAlphaColorRec(A).G + TAlphaColorRec(B).G;
// TAlphaColorRec(Result).B := TAlphaColorRec(A).B + TAlphaColorRec(B).B;
//end;
function TColorHelper.Brighten(AValue: Single): TAlphaColor;
begin
Result := BrightColor(Self, AValue);
end;
function TColorHelper.Brightness: Single;
var
h, s, l: Single;
begin
RGBtoHSL(Self, h, s, l);
Result := l;
end;
function TColorHelper.Darken(AValue: Single): TAlphaColor;
begin
Result := DarkColor(Self, AValue);
end;
//class operator TColorHelper.Subtract(a, b: TAlphaColor): TAlphaColor;
//begin
// TAlphaColorRec(Result).A := (TAlphaColorRec(A).A - TAlphaColorRec(B).A) div 2;
// TAlphaColorRec(Result).R := TAlphaColorRec(A).R - TAlphaColorRec(B).R;
// TAlphaColorRec(Result).G := TAlphaColorRec(A).G - TAlphaColorRec(B).G;
// TAlphaColorRec(Result).B := TAlphaColorRec(A).B - TAlphaColorRec(B).B;
//end;
{ TBitmapHelper }
procedure TBitmapHelper.ApplyMask(const Mask: TBitmap);
var
I, J: Integer;
D, B, M: TBitmapData;
C, MC: TAlphaColor;
tmp: TBitmap;
begin
if (Self.Width <> Mask.Width) or (Self.Height <> Mask.Height) then
Exit;
tmp := TBitmap.Create(Self.Width, Self.Height);
// tmp.Canvas.Clear($00000000);
if tmp.Map(TMapAccess.maWrite, D) and Self.Map(TMapAccess.maRead, B)
and Mask.Map(TMapAccess.maRead, M) then
begin
try
for I := 0 to Self.Width - 1 do
for J := 0 to Self.Height - 1 do
begin
C := B.GetPixel(I, J);
MC := M.GetPixel(I, j);
if TAlphaColorRec(MC).R > 0 then
begin
TAlphaColorRec(C).A := Trunc(TAlphaColorRec(C).A/255 * TAlphaColorRec(MC).R);
end else
begin
TAlphaColorRec(C).A := TAlphaColorRec(MC).R;
end;
// TAlphaColorRec(C).A := TAlphaColorRec(MC).R;
// TAlphaColorRec(C).A := Max(TAlphaColorRec(MC).R - TAlphaColorRec(C).A, 0);
D.SetPixel(I, J, C);
end;
finally
tmp.Unmap(D);
Self.Unmap(B);
Mask.Unmap(M);
Assign(tmp);
tmp.Free;
end;
end;
end;
procedure TBitmapHelper.Clear;
begin
Self.Canvas.Clear(0);
end;
//var
// n: TBitmap;
//begin
// n := TBitmap.Create(Width, Height);
// Assign(n);
// n.Free;
//end;
function TBitmapHelper.ClientRect: TRect;
begin
Result := Rect(0, 0, Width, Height);
end;
function TBitmapHelper.ClientRectF: TRectF;
begin
Result := RectF(0, 0, Width, Height);
end;
class function TBitmapHelper.Create: TBitmap;
begin
Result := TBitmap.Create(0, 0);
end;
// -------------------
// ** Fixes alpha value lost during copy
// --------------------
procedure TBitmapHelper.PlatformCopy(ASrc: TBitmap);
var
m: TMemoryStream;
begin
m := TMemoryStream.Create;
try
if GlobalUseDX10 then
begin
ASrc.SaveToStream(m);
m.Seek(0, 0);
LoadFromStream(m);
end else
begin
Assign(ASrc);
end;
finally
m.Free;
end;
end;
//begin
// Assign(ASrc);
//end;
end.
|
unit EnviarMailDlg;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, IniFiles, Dialogs, ComCtrls, OleCtrls,
IdTCPConnection,
IdSMTP, IdMessage;
type
TEnviarMail = class(TForm)
Bevel1: TBevel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Enviar: TEdit;
Tema: TEdit;
Contenido: TMemo;
De: TEdit;
Label4: TLabel;
Remitente: TEdit;
Label5: TLabel;
StatusBar1: TStatusBar;
Bevel2: TBevel;
UserID: TEdit;
Srv: TEdit;
Label6: TLabel;
Label7: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MailConnectionFailed(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure MailConnect(Sender: TObject);
procedure MailDisconnect(Sender: TObject);
procedure MailFailure(Sender: TObject);
procedure MailInvalidHost(var Handled: Boolean);
procedure MailSendStart(Sender: TObject);
procedure MailStatus(Sender: TComponent; Status: String);
procedure MailSuccess(Sender: TObject);
procedure MailAuthenticationFailed(var Handled: Boolean);
procedure MailAttachmentNotFound(Filename: String);
procedure MailPacketSent(Sender: TObject);
procedure MailConnectionRequired(var Handled: Boolean);
private
{ Private declarations }
Ini: TIniFile;
public
{ Public declarations }
end;
var
EnviarMail: TEnviarMail;
implementation
{$R *.DFM}
procedure TEnviarMail.FormCreate(Sender: TObject);
begin
Ini := TIniFile.create( 'DatosMail' );
De.Text := Ini.ReadString( 'Mail', 'From', 'admin@trafulsa.com.ar' );
UserID.Text := Ini.ReadString( 'Mail', 'UserID', 'n33712' );
Srv.Text := Ini.ReadString( 'Mail', 'Servidor', 'smtp.datamarkets.com.ar' );
Remitente.Text := Ini.ReadString( 'Mail', 'Remite', 'TRAFUL/administracion' );
end;
procedure TEnviarMail.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Mail.Connected then
Mail.Disconnect;
try
if De.text <> '' then
Ini.WriteString( 'Mail', 'From', De.Text );
if Remitente.Text <> '' then
Ini.WriteString( 'Mail', 'Remite', Remitente.Text );
if UserID.text <> '' then
Ini.WriteString( 'Mail', 'UserID', UserID.Text );
if Srv.Text <> '' then
Ini.WriteString( 'Mail', 'Servidor', Srv.Text );
Ini.free;
except
end;
end;
procedure TEnviarMail.MailConnectionFailed(Sender: TObject);
begin
Screen.Cursor := crDefault;
ShowMessage( 'Coneccion ha fallado' );
end;
procedure TEnviarMail.BitBtn2Click(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
Screen.Cursor := crHourGlass;
with Mail,Msg do
try
From.Address := De.Text;
From.Name := Remitente.Text;
From.Text := De.Text;
Subject := Tema.Text;
Host := Srv.Text;
Recipients.EMailAddresses := Enviar.Text;
Body.Assign(Contenido.Lines);
Date := date;
if Connected then
Disconnect;
Connect;
try
Mail.Send(Msg);
finally
Mail.Disconnect;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TEnviarMail.MailConnect(Sender: TObject);
begin
StatusBar1.SimpleText := 'Conectando a ' + Enviar.Text;
end;
procedure TEnviarMail.MailDisconnect(Sender: TObject);
begin
StatusBar1.SimpleText := 'DesConectando';
end;
procedure TEnviarMail.MailFailure(Sender: TObject);
begin
StatusBar1.SimpleText := 'Error en envio';
Mail.Disconnect;
end;
procedure TEnviarMail.MailInvalidHost(var Handled: Boolean);
begin
StatusBar1.SimpleText := 'Error, Host invalido';
end;
procedure TEnviarMail.MailSendStart(Sender: TObject);
begin
StatusBar1.SimpleText := 'Comenzando envio';
end;
procedure TEnviarMail.MailStatus(Sender: TComponent; Status: String);
begin
StatusBar1.SimpleText := Status;
end;
procedure TEnviarMail.MailSuccess(Sender: TObject);
begin
StatusBar1.SimpleText := 'OK, Mail enviado';
Mail.Disconnect;
ShowMessage( 'Correo ha sido enviado' );
// Contenido.Lines.Clear;
// Close;
end;
procedure TEnviarMail.MailAuthenticationFailed(var Handled: Boolean);
begin
StatusBar1.SimpleText := 'Fallo en autenticacion';
end;
procedure TEnviarMail.MailAttachmentNotFound(Filename: String);
begin
ShowMessage( 'Archivo adosado no fue encontrado' );
end;
procedure TEnviarMail.MailPacketSent(Sender: TObject);
begin
StatusBar1.SimpleText := 'Enviando paquete';
end;
procedure TEnviarMail.MailConnectionRequired(var Handled: Boolean);
begin
StatusBar1.SimpleText := 'Se requiere conección';
end;
end.
|
Unit H2TrackBar;
Interface
Uses
Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32,
gr32_layers,Graphics;
Type
TH2TrackBar = Class(TControl)
Private
fx,
fy,
fwidth,
fheight:Integer;
fvisible:Boolean;
fpos:Integer;
fvolume:Boolean;
fbitmap:tbitmaplayer;
fdrawmode:tdrawmode;
falpha:Cardinal;
fback:tbitmap32;
ffont:tfont;
ffront:tbitmap32;
fmin:Cardinal;
fshowtext:Boolean;
fthumb:Boolean;
fs:String;
fmax:Cardinal;
fborder:Byte;
fposition:Cardinal;
Procedure SetFont(font:tfont);
Procedure Setvisible(value:Boolean);
Procedure SetAlpha(value:Cardinal);
Procedure SetDrawmode(value:tdrawmode);
Procedure Setx(value:Integer);
Procedure Sety(value:Integer);
Procedure SetPosition(value:Cardinal);
Public
Constructor Create(AOwner: TComponent); Override;
Destructor Destroy; Override;
Published
Procedure LoadBackGround(filename:String);
Procedure LoadForeGround(filename:String);
Property Thumb:Boolean Read fthumb Write fthumb;
Property Min:Cardinal Read fmin Write fmin;
Property Max:Cardinal Read fmax Write fmax;
Property Width:Integer Read fwidth;
Property Text:String Read fs Write fs;
Property Volume:Boolean Read fvolume Write fvolume;
Property Position:Cardinal Read fposition Write setposition;
Property Alpha:Cardinal Read falpha Write setalpha;
Property Font:tfont Read ffont Write setfont;
Property DrawMode:tdrawmode Read fdrawmode Write setdrawmode;
Property Border:Byte Read fborder Write fborder;
Property Showtext:Boolean Read fshowtext Write fshowtext;
Property X:Integer Read fx Write setx;
Property Y:Integer Read fy Write sety;
Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap;
Property Visible:Boolean Read fvisible Write setvisible;
End;
Implementation
Uses Unit1;
Constructor TH2TrackBar.Create(AOwner: TComponent);
Var
L: TFloatRect;
alayer:tbitmaplayer;
Begin
Inherited Create(AOwner);
fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers);
fdrawmode:=dmblend;
ffont:=tfont.Create;
fvolume:=False;
fthumb:=False;
falpha:=255;
fvisible:=True;
fs:='';
fshowtext:=True;
fmin:=0;
fmax:=100;
fposition:=0;
fx:=0;
fpos:=0;
fy:=0;
fwidth:=150;
fheight:=150;
fback:=tbitmap32.Create;
fbitmap.Bitmap.Width:=fwidth;
fbitmap.Bitmap.Height:=fheight;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
fbitmap.Tag:=0;
fbitmap.Bitmap.DrawMode:=fdrawmode;
fbitmap.Bitmap.MasterAlpha:=falpha;
fvisible:=True;
ffront:=tbitmap32.Create;
ffront.DrawMode:=dmblend;
ffront.MasterAlpha:=255;
End;
Destructor TH2TrackBar.Destroy;
Begin
//here
fbitmap.Free;
fback.Free;
ffront.free;
ffont.Free;
Inherited Destroy;
End;
Procedure TH2TrackBar.LoadBackGround(filename: String);
Var au:Boolean;
L: TFloatRect;
Begin
If fileexists(filename) Then
Begin
Try
LoadPNGintoBitmap32(fback,filename,au);
fwidth:=fback.Width;
fheight:=fback.Height;
ffront.Width:=fwidth;
ffront.Height:=fheight;
fbitmap.Bitmap.width:=fwidth;
fbitmap.Bitmap.Height:=fheight;
l.Left:=fx;
l.Top :=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
Except
End;
End;
End;
Procedure TH2TrackBar.LoadForeground(filename: String);
Var au:Boolean;
Begin
If fileexists(filename) Then
Begin
Try
LoadPNGintoBitmap32(ffront,filename,au);
Except
End;
End;
End;
Procedure TH2TrackBar.SetAlpha(value: Cardinal);
Begin
falpha:=value;
fbitmap.Bitmap.MasterAlpha:=falpha;
fback.MasterAlpha:=falpha;
ffront.MasterAlpha:=falpha;
End;
Procedure TH2TrackBar.SetDrawmode(value: tdrawmode);
Begin
fdrawmode:=value;
fbitmap.Bitmap.DrawMode:=fdrawmode;
fback.DrawMode:=fdrawmode;
ffront.DrawMode:=fdrawmode;
End;
Procedure TH2TrackBar.SetFont(font: tfont);
Begin
ffont.Assign(font);
End;
Procedure TH2TrackBar.SetPosition(value: Cardinal);
Var
Color: Longint;
r, g, b: Byte;
w,h:Integer;
Begin
fbitmap.Bitmap.Clear($000000);
fbitmap.Bitmap.Font.Assign(ffont);
Color := ColorToRGB(ffont.Color);
r := Color;
g := Color Shr 8;
b := Color Shr 16;
fposition:=value;
fback.DrawTo(fbitmap.Bitmap,0,0);
If fthumb=False Then
ffront.DrawTo(fbitmap.Bitmap,fborder,fborder,rect(fborder,fborder,(fPosition * (fWidth-(fborder*2)))Div fmax,fheight-fborder))
Else
ffront.DrawTo(fbitmap.Bitmap,fborder+((fPosition * (fWidth-(fborder*2)))Div fmax)-(ffront.Width Div 2),fborder);
If showtext Then
Begin
w:=fbitmap.Bitmap.TextWidth(fs);
h:=fbitmap.Bitmap.Textheight(fs);
fBitmap.bitmap.RenderText((fwidth Div 2)-(w Div 2),(fheight Div 2) - (h Div 2),fs,0,color32(r,g,b,falpha));
End;
End;
Procedure TH2TrackBar.Setvisible(value: Boolean);
Begin
fbitmap.Visible:=value;
End;
Procedure TH2TrackBar.Setx(value: Integer);
Var
L: TFloatRect;
Begin
fx:=value;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
End;
Procedure TH2TrackBar.Sety(value: Integer);
Var
L: TFloatRect;
Begin
fy:=value;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
End;
End.
|
unit Contents_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Document/Forms/Contents_Form.pas"
// Начат: 2003/06/20 06:51:14
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMFinalForm::Class>> F1 Работа с документом и списком документов::Document::View::Document::Document::Contents
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
Common_FormDefinitions_Controls,
PrimContentsOptions_Form
{$If not defined(NoScripts)}
,
tfwScriptingInterfaces
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
vtPanel,
vtLister
{$If defined(Nemesis)}
,
nscTreeView
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
,
nscContextFilter
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
,
nscTasksPanelView
{$IfEnd} //Nemesis
,
Classes {a},
l3InterfacedComponent {a},
vcmComponent {a},
vcmBaseEntities {a},
vcmEntities {a},
vcmExternalInterfaces {a},
vcmInterfaces {a},
vcmEntityForm {a}
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
TContentsForm = {final form} class(TvcmEntityFormRef, ContentsFormDef)
Entities : TvcmEntities;
BackgroundPanel: TvtPanel;
ContentsTree: TnscTreeView;
ContextFilter: TnscContextFilter;
end;//TContentsForm
{$IfEnd} //not Admin AND not Monitorings
implementation
{$R *.DFM}
{$If not defined(Admin) AND not defined(Monitorings)}
uses
SysUtils
{$If not defined(NoScripts)}
,
tfwScriptEngine
{$IfEnd} //not NoScripts
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
Tkw_Form_Contents = class(TtfwControlString)
{* Слово словаря для идентификатора формы Contents
----
*Пример использования*:
[code]
'aControl' форма::Contents TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_Form_Contents
// start class Tkw_Form_Contents
{$If not defined(NoScripts)}
function Tkw_Form_Contents.GetString: AnsiString;
{-}
begin
Result := 'ContentsForm';
end;//Tkw_Form_Contents.GetString
{$IfEnd} //not NoScripts
type
Tkw_Contents_BackgroundPanel_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола BackgroundPanel формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_BackgroundPanel_ControlInstance
// start class Tkw_Contents_BackgroundPanel_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_BackgroundPanel_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).BackgroundPanel);
end;//Tkw_Contents_BackgroundPanel_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_lstBookmarks_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола lstBookmarks формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_lstBookmarks_ControlInstance
// start class Tkw_Contents_lstBookmarks_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_lstBookmarks_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).lstBookmarks);
end;//Tkw_Contents_lstBookmarks_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_lstComments_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола lstComments формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_lstComments_ControlInstance
// start class Tkw_Contents_lstComments_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_lstComments_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).lstComments);
end;//Tkw_Contents_lstComments_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_lstExternalObjects_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола lstExternalObjects формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_lstExternalObjects_ControlInstance
// start class Tkw_Contents_lstExternalObjects_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_lstExternalObjects_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).lstExternalObjects);
end;//Tkw_Contents_lstExternalObjects_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_ContentsTree_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола ContentsTree формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_ContentsTree_ControlInstance
// start class Tkw_Contents_ContentsTree_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_ContentsTree_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).ContentsTree);
end;//Tkw_Contents_ContentsTree_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_ContextFilter_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола ContextFilter формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_ContextFilter_ControlInstance
// start class Tkw_Contents_ContextFilter_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_ContextFilter_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).ContextFilter);
end;//Tkw_Contents_ContextFilter_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_Contents_Tasks_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола Tasks формы Contents }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_Contents_Tasks_ControlInstance
// start class Tkw_Contents_Tasks_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_Contents_Tasks_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TContentsForm).Tasks);
end;//Tkw_Contents_Tasks_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
{$IfEnd} //not Admin AND not Monitorings
initialization
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация фабрики формы Contents
fm_ContentsForm.SetFactory(TContentsForm.Make);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Form_Contents
Tkw_Form_Contents.Register('форма::Contents', TContentsForm);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_BackgroundPanel_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.BackgroundPanel', Tkw_Contents_BackgroundPanel_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_lstBookmarks_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.lstBookmarks', Tkw_Contents_lstBookmarks_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_lstComments_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.lstComments', Tkw_Contents_lstComments_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_lstExternalObjects_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.lstExternalObjects', Tkw_Contents_lstExternalObjects_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_ContentsTree_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.ContentsTree', Tkw_Contents_ContentsTree_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_ContextFilter_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.ContextFilter', Tkw_Contents_ContextFilter_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Регистрация Tkw_Contents_Tasks_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TContentsForm.Tasks', Tkw_Contents_Tasks_ControlInstance);
{$IfEnd} //not Admin AND not Monitorings
end. |
unit Recorder;
// the module contains Recorder class, contains Recorder logic.
// implements IInputLineChangedCallback to react to input line changes,
// IRecorderControlCallback to react to gui events.
interface
uses RecorderControl, Controls, Classes, DeviceWrapper, inputLine, SelectChannelForm;
type TRecorder = class(TInterfacedObject, IInputLineChangedCallback, IRecorderControlCallback)
private
FOnRequestToDelete : TNotifyEvent;
public
Constructor Create(connectedDevice : TDevice);
Destructor Destroy; override;
function GetRecorderControl() : TRecorderControl;
procedure CreateRecorderControl(AOwner: TComponent);
procedure SetListenLineFlag(lineIndex : integer; flag : boolean);
function GetListenLineFlag(lineIndex : integer) : boolean;
procedure AddDataFromInputLine(inputLineNumber : integer; secs : double; data : double);
// observer interface
procedure OnInputLineChanged(inputLine : TInputLine);
// control callbacks
procedure SetRelativeMeasure;
procedure SetAbsoluteMeasure;
procedure AddChannel;
procedure RemoveChannel;
procedure DeleteRecorder;
property RequestToDelete : TNotifyEvent read FOnRequestToDelete write FOnRequestToDelete;
procedure UnSubscribeInputLineObservers;
private
recorderControl : TRecorderControl;
listeningInputLines : Array of Byte;
device : TDevice;
recorderControlOwner : TComponent;
relativeMeasure : boolean;
relativeChannelIndex : integer;
relativeData : double;
function ShowChooseChannelForm() : integer;
function ShowChoosePresentChannelForm() : integer;
function ShowChooseAbsentChannelForm() : integer;
end;
implementation
{ TRecorder }
procedure TRecorder.AddChannel;
var lineIndex : integer;
begin
lineIndex := ShowChooseAbsentChannelForm;
if (lineIndex <> -1) then
begin
self.SetListenLineFlag(lineIndex, true);
self.recorderControl.AddGraphLine(lineIndex, device.GetInputLine(lineIndex).GetName, device.GetInputLine(lineIndex).GetGraphColor);
self.recorderControl.SetGraphWidth(lineIndex, device.GetInputLine(lineIndex).GetGraphWidth);
end;
end;
procedure TRecorder.AddDataFromInputLine(inputLineNumber: integer; secs,
data: double);
begin
if not self.GetListenLineFlag(inputLineNumber) then
exit;
if self.relativeMeasure then
begin
if (inputLineNumber = self.relativeChannelIndex) then
begin
self.relativeData := data;
end;
if (relativeData <> 0) and ((inputLineNumber <> self.relativeChannelIndex) or recorderControl.HasInputLineGraph(inputLineNumber)) then
recorderControl.AddPointToGraphLine(inputLineNumber, secs, data / relativeData);
exit;
end;
recorderControl.AddPointToGraphLine(inputLineNumber, secs, data);
end;
constructor TRecorder.Create(connectedDevice: TDevice);
var i : integer;
begin
device := connectedDevice;
relativeMeasure := false;
relativeData := 0;
SetLength(listeningInputLines, device.GetInputLinesNumber);
for i := 0 to device.GetInputLinesNumber - 1 do
begin
device.GetInputLine(i).SubscribeOnInputLineChanged(self);
self.SetListenLineFlag(i, true);
end;
end;
procedure TRecorder.CreateRecorderControl(AOwner: TComponent);
var i : integer;
begin
recorderControl := TRecorderControl.Create(AOwner);
recorderControlOwner := AOwner;
recorderControl.SetGuiCallback(self);
for i := 0 to device.GetInputLinesNumber - 1 do
begin
if (self.GetListenLineFlag(i)) then
self.recorderControl.AddGraphLine(i, device.GetInputLine(i).GetName, device.GetInputLine(i).GetGraphColor);
self.recorderControl.SetGraphWidth(i, device.GetInputLine(i).GetGraphWidth);
end;
end;
procedure TRecorder.DeleteRecorder;
begin
if Assigned(FOnRequestToDelete) then FOnRequestToDelete(Self);
end;
destructor TRecorder.Destroy;
var i : integer;
begin
for i := 0 to device.GetInputLinesNumber - 1 do
begin
self.SetListenLineFlag(i, false);
end;
if Assigned(self.GetRecorderControl()) then
self.GetRecorderControl.Parent := nil;
inherited;
end;
function TRecorder.GetListenLineFlag(lineIndex: integer): boolean;
begin
Result := self.listeningInputLines[lineIndex] > 0;
end;
function TRecorder.GetRecorderControl: TRecorderControl;
begin
Result := recorderControl;
end;
procedure TRecorder.OnInputLineChanged(inputLine: TInputLine);
begin
self.GetRecorderControl.RenameGraphLine(inputLine.GetIndeviceIndex, inputLine.GetName);
self.GetRecorderControl.SetGraphWidth(inputLine.GetIndeviceIndex, inputLine.GetGraphWidth);
self.GetRecorderControl.SetGraphColor(inputLine.GetIndeviceIndex, inputLine.GetGraphColor);
end;
procedure TRecorder.RemoveChannel;
var lineIndex : integer;
begin
lineIndex := ShowChoosePresentChannelForm;
if (lineIndex <> -1) then
begin
if not (self.relativeMeasure and (self.relativeData = lineIndex)) then
self.SetListenLineFlag(lineIndex, false);
self.GetRecorderControl.DeleteGraphLine(lineIndex);
end;
end;
procedure TRecorder.SetAbsoluteMeasure;
var wasRelative : boolean;
begin
wasRelative := self.relativeMeasure;
self.relativeMeasure := false;
if (wasRelative) then begin
if (not self.GetRecorderControl.HasInputLineGraph(self.relativeChannelIndex)) then
self.SetListenLineFlag(self.relativeChannelIndex, false);
end;
end;
procedure TRecorder.SetListenLineFlag(lineIndex: integer; flag: boolean);
var flagBefore : integer;
begin
flagBefore := self.listeningInputLines[lineIndex];
if (flag) then
self.listeningInputLines[lineIndex] := 1
else
self.listeningInputLines[lineIndex] := 0;
if (flagBefore <> self.listeningInputLines[lineIndex]) then
device.GetInputLine(lineIndex).SetListeningFlag(flag);
end;
procedure TRecorder.SetRelativeMeasure;
var lineIndex : integer;
begin
lineIndex := ShowChooseChannelForm;
if (lineIndex <> -1) then
begin
relativeData := 0;
self.relativeMeasure := true;
self.relativeChannelIndex := lineIndex;
self.SetListenLineFlag(lineIndex, true);
self.GetRecorderControl.DeleteGraphLine(lineIndex);
end;
end;
function TRecorder.ShowChooseAbsentChannelForm: integer;
var chooseChannelForm : TChannelsForm;
var i : integer;
var listNotEmpty : boolean;
begin
Result := -1;
listNotEmpty := false;
chooseChannelForm := TChannelsForm.Create(self.recorderControlOwner);
for i := 0 to device.GetInputLinesNumber -1 do
begin
if (not self.GetRecorderControl.HasInputLineGraph(i)) then
begin
chooseChannelForm.AddChannel(device.GetInputLine(i).GetName, device.GetInputLine(i).GetIndeviceIndex);
listNotEmpty := true;
end;
end;
if not listNotEmpty then
exit;
if (chooseChannelForm.ShowModal = MrYes) and chooseChannelForm.ChannelSelected then
begin
Result := chooseChannelForm.SelectedChannelIndex;
end;
end;
function TRecorder.ShowChooseChannelForm: integer;
var chooseChannelForm : TChannelsForm;
var i : integer;
begin
Result := -1;
chooseChannelForm := TChannelsForm.Create(self.recorderControlOwner);
for i := 0 to device.GetInputLinesNumber -1 do
begin
chooseChannelForm.AddChannel(device.GetInputLine(i).GetName, device.GetInputLine(i).GetIndeviceIndex);
end;
if (chooseChannelForm.ShowModal = MrYes) and chooseChannelForm.ChannelSelected then
begin
Result := chooseChannelForm.SelectedChannelIndex;
end;
end;
function TRecorder.ShowChoosePresentChannelForm: integer;
var chooseChannelForm : TChannelsForm;
var i : integer;
var listNotEmpty : boolean;
begin
Result := -1;
listNotEmpty := false;
chooseChannelForm := TChannelsForm.Create(self.recorderControlOwner);
for i := 0 to device.GetInputLinesNumber -1 do
begin
if (self.GetRecorderControl.HasInputLineGraph(i)) then
begin
chooseChannelForm.AddChannel(device.GetInputLine(i).GetName, device.GetInputLine(i).GetIndeviceIndex);
listNotEmpty := true;
end;
end;
if not listNotEmpty then
exit;
if (chooseChannelForm.ShowModal = MrYes) and chooseChannelForm.ChannelSelected then
begin
Result := chooseChannelForm.SelectedChannelIndex;
end;
end;
procedure TRecorder.UnSubscribeInputLineObservers;
var i : integer;
begin
for i := 0 to device.GetInputLinesNumber - 1 do
begin
self.device.GetInputLine(i).UnSubscribeOnInputLineChanged(self);
end;
end;
end.
|
unit nemesis_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine,
sound_engine,ay_8910,vlm_5030,k005289,ym_2151,k007232;
function iniciar_nemesis:boolean;
implementation
type
tipo_sprite=record
width,height,char_type:byte;
mask:word;
end;
const
nemesis_rom:array[0..7] of tipo_roms=(
(n:'456-d01.12a';l:$8000;p:0;crc:$35ff1aaa),(n:'456-d05.12c';l:$8000;p:$1;crc:$23155faa),
(n:'456-d02.13a';l:$8000;p:$10000;crc:$ac0cf163),(n:'456-d06.13c';l:$8000;p:$10001;crc:$023f22a9),
(n:'456-d03.14a';l:$8000;p:$20000;crc:$8cefb25f),(n:'456-d07.14c';l:$8000;p:$20001;crc:$d50b82cb),
(n:'456-d04.15a';l:$8000;p:$30000;crc:$9ca75592),(n:'456-d08.15c';l:$8000;p:$30001;crc:$03c0b7f5));
nemesis_sound:tipo_roms=(n:'456-d09.9c';l:$4000;p:0;crc:$26bf9636);
rom_k005289:array[0..1] of tipo_roms=(
(n:'400-a01.fse';l:$100;p:$0;crc:$5827b1e8),(n:'400-a02.fse';l:$100;p:$100;crc:$2f44f970));
gx400_bios:array[0..1] of tipo_roms=(
(n:'400-a06.15l';l:$8000;p:0;crc:$b99d8cff),(n:'400-a04.10l';l:$8000;p:$1;crc:$d02c9552));
gx400_sound:tipo_roms=(n:'400-e03.5l';l:$2000;p:0;crc:$a5a8e57d);
twinbee_rom:array[0..1] of tipo_roms=(
(n:'412-a07.17l';l:$20000;p:$0;crc:$d93c5499),(n:'412-a05.12l';l:$20000;p:$1;crc:$2b357069));
gwarrior_rom:array[0..1] of tipo_roms=(
(n:'578-a07.17l';l:$20000;p:$0;crc:$0aedacb5),(n:'578-a05.12l';l:$20000;p:$1;crc:$76240e2e));
salamander_rom:array[0..3] of tipo_roms=(
(n:'587-d02.18b';l:$10000;p:0;crc:$a42297f9),(n:'587-d05.18c';l:$10000;p:$1;crc:$f9130b0a),
(n:'587-c03.17b';l:$20000;p:$40000;crc:$e5caf6e6),(n:'587-c06.17c';l:$20000;p:$40001;crc:$c2f567ea));
salamander_sound:tipo_roms=(n:'587-d09.11j';l:$8000;p:0;crc:$5020972c);
salamander_vlm:tipo_roms=(n:'587-d08.8g';l:$4000;p:0;crc:$f9ac6b82);
salamander_k007232:tipo_roms=(n:'587-c01.10a';l:$20000;p:0;crc:$09fe0632);
//Graficos
char_x:array[0..63] of dword=(0*4,1*4,2*4,3*4,4*4,5*4,6*4,7*4,
8*4,9*4,10*4,11*4,12*4,13*4,14*4,15*4,
16*4,17*4,18*4,19*4,20*4,21*4,22*4,23*4,
24*4,25*4,26*4,27*4,28*4,29*4,30*4,31*4,
32*4,33*4,34*4,35*4,36*4,37*4,38*4,39*4,
40*4,41*4,42*4,43*4,44*4,45*4,46*4,47*4,
48*4,49*4,50*4,51*4,52*4,53*4,54*4,55*4,
56*4,57*4,58*4,59*4,60*4,61*4,62*4,63*4);
char_8_y:array[0..15] of dword=(0*4*8,1*4*8,2*4*8,3*4*8,4*4*8,5*4*8,6*4*8,7*4*8,
8*4*8,9*4*8,10*4*8,11*4*8,12*4*8,13*4*8,14*4*8,15*4*8);
char_16_y:array[0..31] of dword=(0*4*16,1*4*16,2*4*16,3*4*16,4*4*16,5*4*16,6*4*16,7*4*16,
8*4*16,9*4*16,10*4*16,11*4*16,12*4*16,13*4*16,14*4*16,15*4*16,
16*4*16,17*4*16,18*4*16,19*4*16,20*4*16,21*4*16,22*4*16,23*4*16,
24*4*16,25*4*16,26*4*16,27*4*16,28*4*16,29*4*16,30*4*16,31*4*16);
char_32_y:array[0..31] of dword=(0*4*32,1*4*32,2*4*32,3*4*32,4*4*32,5*4*32,6*4*32,7*4*32,
8*4*32,9*4*32,10*4*32,11*4*32,12*4*32,13*4*32,14*4*32,15*4*32,
16*4*32,17*4*32,18*4*32,19*4*32,20*4*32,21*4*32,22*4*32,23*4*32,
24*4*32,25*4*32,26*4*32,27*4*32,28*4*32,29*4*32,30*4*32,31*4*32);
char_64_y:array[0..63] of dword=(0*4*64,1*4*64,2*4*64,3*4*64,4*4*64,5*4*64,6*4*64,7*4*64,
8*4*64,9*4*64,10*4*64,11*4*64,12*4*64,13*4*64,14*4*64,15*4*64,
16*4*64,17*4*64,18*4*64,19*4*64,20*4*64,21*4*64,22*4*64,23*4*64,
24*4*64,25*4*64,26*4*64,27*4*64,28*4*64,29*4*64,30*4*64,31*4*64,
32*4*64,33*4*64,34*4*64,35*4*64,36*4*64,37*4*64,38*4*64,39*4*64,
40*4*64,41*4*64,42*4*64,43*4*64,44*4*64,45*4*64,46*4*64,47*4*64,
48*4*64,49*4*64,50*4*64,51*4*64,52*4*64,53*4*64,54*4*64,55*4*64,
56*4*64,57*4*64,58*4*64,59*4*64,60*4*64,61*4*64,62*4*64,63*4*64);
//Sprites
sprite_data:array[0..7] of tipo_sprite=((width:32;height:32;char_type:4;mask:$7f),(width:16;height:32;char_type:5;mask:$ff),(width:32;height:16;char_type:2;mask:$ff),(width:64;height:64;char_type:7;mask:$1f),
(width:8;height:8;char_type:0;mask:$7ff),(width:16;height:8;char_type:6;mask:$3ff),(width:8;height:16;char_type:3;mask:$3ff),(width:16;height:16;char_type:1;mask:$1ff));
pal_look:array[0..$1f] of byte=(0,1,2,4,5,6,8,9,11,13,15,18,20,22,25,28,33,36,41,46,51,57,64,73,
80,91,104,120,142,168,204,255);
var
rom:array[0..$3ffff] of word;
ram3,bios_rom,char_ram:array[0..$7fff] of word;
ram1:array[0..$fff] of word;
ram2:array[0..$3fff] of word;
ram4:array[0..$ffff] of word;
shared_ram:array[0..$3fff] of byte;
xscroll_1,xscroll_2:array[0..$1ff] of word;
yscroll_1,yscroll_2:array[0..$3f] of word;
video1_ram,video2_ram,color1_ram,color2_ram,sprite_ram:array[0..$7ff] of word;
screen_par,irq_on,irq2_on,irq4_on,flipx_scr,flipy_scr,changed_chr:boolean;
sound_latch:byte;
k007232_1_rom:pbyte;
//char buffer
char_8_8:array[0..$7ff] of boolean;
char_16_16:array[0..$1ff] of boolean;
char_32_16:array[0..$ff] of boolean;
char_8_16:array[0..$3ff] of boolean;
char_32_32:array[0..$7f] of boolean;
char_64_64:array[0..$1f] of boolean;
procedure update_video_nemesis;
procedure char_calc;
var
f:word;
begin
//8x8 char
gfx_set_desc_data(4,0,4*8*8,0,1,2,3);
for f:=0 to $7ff do if char_8_8[f] then begin
convert_gfx_single(0,0,@char_ram,@char_x,@char_8_y,false,false,f);
char_8_8[f]:=false;
end;
//16x16
gfx_set_desc_data(4,1,4*16*16,0,1,2,3);
for f:=0 to $1ff do if char_16_16[f] then begin
convert_gfx_single(1,0,@char_ram,@char_x,@char_16_y,false,false,f);
char_16_16[f]:=false;
end;
//32x16 y 16x32
gfx_set_desc_data(4,2,4*32*16,0,1,2,3);
for f:=0 to $ff do if char_32_16[f] then convert_gfx_single(2,0,@char_ram,@char_x,@char_32_y,false,false,f);
gfx_set_desc_data(4,5,4*16*32,0,1,2,3);
for f:=0 to $ff do if char_32_16[f] then begin
convert_gfx_single(5,0,@char_ram,@char_x,@char_16_y,false,false,f);
char_32_16[f]:=false;
end;
//8x16 y 16x8
gfx_set_desc_data(4,3,4*8*16,0,1,2,3);
for f:=0 to $3ff do if char_8_16[f] then convert_gfx_single(3,0,@char_ram,@char_x,@char_8_y,false,false,f);
gfx_set_desc_data(4,6,4*16*8,0,1,2,3);
for f:=0 to $3ff do if char_8_16[f] then begin
convert_gfx_single(6,0,@char_ram,@char_x,@char_16_y,false,false,f);
char_8_16[f]:=false;
end;
//32x32
gfx_set_desc_data(4,4,4*32*32,0,1,2,3);
for f:=0 to $7f do if char_32_32[f] then begin
convert_gfx_single(4,0,@char_ram,@char_x,@char_32_y,false,false,f);
char_32_32[f]:=false;
end;
//64x64
gfx_set_desc_data(4,7,4*64*64,0,1,2,3);
for f:=0 to $1f do if char_64_64[f] then begin
convert_gfx_single(7,0,@char_ram,@char_x,@char_64_y,false,false,f);
char_64_64[f]:=false;
end;
changed_chr:=false;
end;
procedure draw_sprites;
var
f,pri,idx,num_gfx:byte;
zoom,nchar,size,sx,sy,color,atrib,atrib2:word;
flipx,flipy:boolean;
zx:single;
begin
for pri:=0 to $ff do begin //prioridad
for f:=0 to $ff do begin //cantidad de sprites
if((sprite_ram[f*8] and $ff)<>pri) then continue; //si no tiene la prioridad requerida sigo
zoom:=sprite_ram[(f*8)+2] and $ff;
atrib:=sprite_ram[(f*8)+4];
atrib2:=sprite_ram[(f*8)+3];
if (((sprite_ram[(f*8)+2] and $ff00)=0) and ((atrib2 and $ff00)<>$ff00)) then nchar:=atrib2+((atrib and $c0) shl 2)
else nchar:=(atrib2 and $ff)+((atrib and $c0) shl 2);
if (zoom<>$ff) then begin
size:=sprite_ram[(f*8)+1];
zoom:=zoom+((size and $c0) shl 2);
sx:=(sprite_ram[(f*8)+5] and $ff)+((atrib and $1) shl 8);
sy:=sprite_ram[(f*8)+6] and $ff;
color:=(atrib and $1e) shl 3;
flipx:=(size and $01)<>0;
flipy:=(atrib and $20)<>0;
idx:=(size shr 3) and 7;
nchar:=nchar*8*16 div (sprite_data[idx].width*sprite_data[idx].height);
num_gfx:=sprite_data[idx].char_type;
if (zoom<>0) then begin
zx:=$80/zoom;
put_gfx_sprite_zoom(nchar and sprite_data[idx].mask,color,flipx,flipy,num_gfx,zx,zx);
actualiza_gfx_sprite_zoom(sx,sy,9,num_gfx,zx,zx);
end;
end;
end;
end;
end;
var
f,x,y,nchar,color:word;
flipx,flipy:boolean;
mask,layer,pant,h:byte;
scroll_x1,scroll_x2:array[0..$ff] of word;
begin
fill_full_screen(9,0);
if changed_chr then char_calc;
for f:=0 to $7ff do begin
//background
color:=color2_ram[f];
if (gfx[1].buffer[f] or buffer_color[color and $7f]) then begin
nchar:=video2_ram[f];
if flipx_scr then x:=63-(f and $3f)
else x:=f and $3f;
if flipy_scr then y:=31-(f shr 6)
else y:=f shr 6;
flipx:=((color and $80)<>0) xor flipx_scr;
flipy:=((nchar and $800)<>0) xor flipy_scr;
for h:=1 to 4 do put_gfx_block_trans(x*8,y*8,h,8,8);
if (((not(nchar) and $2000)<>0) or ((nchar and $c000)=$4000)) then begin
if (nchar and $f800)<>0 then put_gfx_flip(x*8,y*8,nchar and $7ff,(color and $7f) shl 4,4,0,flipx,flipy);
end else begin
mask:=(nchar and $1000) shr 12;
layer:=(nchar and $4000) shr 14;
if ((mask<>0) and (layer=0)) then layer:=1;
pant:=(mask or (layer shl 1))+1;
if (nchar and $f800)<>0 then put_gfx_trans_flip(x*8,y*8,nchar and $7ff,(color and $7f) shl 4,pant,0,flipx,flipy);
end;
gfx[1].buffer[f]:=false;
end;
//foreground
color:=color1_ram[f];
if (gfx[0].buffer[f] or buffer_color[color and $7f]) then begin
nchar:=video1_ram[f];
if flipx_scr then x:=63-(f and $3f)
else x:=f and $3f;
if flipy_scr then y:=31-(f shr 6)
else y:=f shr 6;
flipx:=((color and $80)<>0) xor flipx_scr;
flipy:=((nchar and $800)<>0) xor flipy_scr;
for h:=5 to 8 do put_gfx_block_trans(x*8,y*8,h,8,8);
if (((not(nchar) and $2000)<>0) or ((nchar and $c000)=$4000)) then begin
if (nchar and $f800)<>0 then put_gfx_flip(x*8,y*8,nchar and $7ff,(color and $7f) shl 4,8,0,flipx,flipy);
end else begin
mask:=(nchar and $1000) shr 12;
layer:=(nchar and $4000) shr 14;
if ((mask<>0) and (layer=0)) then layer:=1;
pant:=(mask or (layer shl 1))+5;
if (nchar and $f800)<>0 then put_gfx_trans_flip(x*8,y*8,nchar and $7ff,(color and $7f) shl 4,pant,0,flipx,flipy);
end;
gfx[0].buffer[f]:=false;
end;
end;
for f:=0 to $ff do begin
scroll_x1[f]:=(xscroll_1[f] and $ff)+((xscroll_1[f+$100] and $1) shl 8);
scroll_x2[f]:=(xscroll_2[f] and $ff)+((xscroll_2[f+$100] and $1) shl 8);
end;
//1
scroll__x_part2(1,9,1,@scroll_x2);
scroll__x_part2(5,9,1,@scroll_x1);
//2
scroll__x_part2(2,9,1,@scroll_x2);
scroll__x_part2(6,9,1,@scroll_x1);
//Sprites
draw_sprites;
//3
scroll__x_part2(3,9,1,@scroll_x2);
scroll__x_part2(7,9,1,@scroll_x1);
//4
scroll__x_part2(4,9,1,@scroll_x2);
scroll__x_part2(8,9,1,@scroll_x1);
actualiza_trozo_final(0,16,256,224,9);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_nemesis;
begin
if event.arcade then begin
//IN0
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fffe);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fffd);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $fff7);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ffef);
//P1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fffe);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fffd);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fffb);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $fff7);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ffef);
if arcade_input.but2[0] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $ffdf);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 or $40) else marcade.in1:=(marcade.in1 and $ffbf);
//P2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fffe);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 or $2) else marcade.in2:=(marcade.in2 and $fffd);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fffb);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $fff7);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ffef);
if arcade_input.but2[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $ffdf);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 or $40) else marcade.in2:=(marcade.in2 and $ffbf);
end;
end;
procedure cambiar_color(tmp_color,numero:word);
var
bit1,bit2,bit3:byte;
color:tcolor;
begin
bit1:=(tmp_color shr 0) and $1f;
bit2:=(tmp_color shr 5) and $1f;
bit3:=(tmp_color shr 10) and $1f;
color.r:=pal_look[bit1];
color.g:=pal_look[bit2];
color.b:=pal_look[bit3];
set_pal_color(color,numero);
buffer_color[numero shr 4]:=true;
end;
function ay0_porta_read:byte;
var
res:byte;
begin
res:=round(z80_0.totalt/1024) and $2f;
ay0_porta_read:=res or $d0 or $20;
end;
procedure ay8910_k005289_1(valor:byte);
begin
k005289_0.control_A_w(valor);
end;
procedure ay8910_k005289_2(valor:byte);
begin
k005289_0.control_B_w(valor);
end;
procedure sound_update;
begin
ay8910_0.update;
ay8910_1.update;
k005289_0.update;
end;
//Nemesis
procedure nemesis_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//Main CPU
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//Sound CPU
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=239 then begin
update_video_nemesis;
if irq_on then m68000_0.irq[1]:=HOLD_LINE;
end;
end;
eventos_nemesis;
video_sync;
end;
end;
function nemesis_getword(direccion:dword):word;
begin
case direccion of
0..$3ffff:nemesis_getword:=rom[direccion shr 1];
$40000..$4ffff:nemesis_getword:=(char_ram[(direccion and $ffff) shr 1] shr 8)+((char_ram[(direccion and $ffff) shr 1] and $ff) shl 8);//char_ram[(direccion+1) and $ffff] or (char_ram[direccion and $ffff] shl 8);
$50000..$51fff:nemesis_getword:=ram1[(direccion and $1fff) shr 1];
$52000..$52fff:nemesis_getword:=video1_ram[(direccion and $fff) shr 1];
$53000..$53fff:nemesis_getword:=video2_ram[(direccion and $fff) shr 1];
$54000..$54fff:nemesis_getword:=color1_ram[(direccion and $fff) shr 1];
$55000..$55fff:nemesis_getword:=color2_ram[(direccion and $fff) shr 1];
$56000..$56fff:nemesis_getword:=sprite_ram[(direccion and $fff) shr 1];
$5a000..$5afff:nemesis_getword:=buffer_paleta[(direccion and $fff) shr 1];
$5c400:nemesis_getword:=$ff;
$5c402:nemesis_getword:=$5b;
$5cc00:nemesis_getword:=marcade.in0;
$5cc02:nemesis_getword:=marcade.in1;
$5cc04:nemesis_getword:=marcade.in2;
$5cc06:nemesis_getword:=$ff;
$60000..$67fff:nemesis_getword:=ram2[(direccion and $7fff) shr 1];
end;
end;
procedure nemesis_putword(direccion:dword;valor:word);
var
dir:word;
begin
case direccion of
0..$3ffff:;
$40000..$4ffff:if char_ram[(direccion and $ffff) shr 1]<>(((valor and $ff) shl 8)+(valor shr 8)) then begin
char_ram[(direccion and $ffff) shr 1]:=((valor and $ff) shl 8)+(valor shr 8);
char_8_8[(direccion and $ffff) div $20]:=true;
char_16_16[(direccion and $ffff) div $80]:=true;
char_32_16[(direccion and $ffff) div $100]:=true;
char_8_16[(direccion and $ffff) div $40]:=true;
char_32_32[(direccion and $ffff) div $200]:=true;
char_64_64[(direccion and $ffff) div $800]:=true;
fillchar(gfx[0].buffer,$800,1);
fillchar(gfx[1].buffer,$800,1);
changed_chr:=true;
end;
$50000..$51fff:begin
dir:=(direccion and $1fff) shr 1;
ram1[dir]:=valor;
case (direccion and $1fff) of
0..$3ff:xscroll_1[dir and $1ff]:=valor;
$400..$7ff:xscroll_2[dir and $1ff]:=valor;
$f00..$f7f:yscroll_2[dir and $3f]:=valor;
$f80..$fff:yscroll_1[dir and $3f]:=valor;
end;
end;
$52000..$52fff:if video1_ram[(direccion and $fff) shr 1]<>valor then begin
video1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$53000..$53fff:if video2_ram[(direccion and $fff) shr 1]<>valor then begin
video2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$54000..$54fff:if color1_ram[(direccion and $fff) shr 1]<>valor then begin
color1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$55000..$55fff:if color2_ram[(direccion and $fff) shr 1]<>valor then begin
color2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$56000..$56fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$5a000..$5afff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor;
cambiar_color(valor,(direccion and $fff) shr 1);
end;
$5c000:sound_latch:=valor and $ff;
$5e000:irq_on:=(valor and $ff)<>0;
$5e004:begin
flipx_scr:=(valor and $1)<>0;
if (valor and $100)<>0 then z80_0.change_irq(HOLD_LINE);
end;
$5e006:flipy_scr:=(valor and $1)<>0;
$60000..$67fff:ram2[(direccion and $7fff) shr 1]:=valor;
end;
end;
function nemesis_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$47ff:nemesis_snd_getbyte:=mem_snd[direccion];
$e001:nemesis_snd_getbyte:=sound_latch;
$e086:nemesis_snd_getbyte:=ay8910_0.Read;
$e205:nemesis_snd_getbyte:=ay8910_1.Read;
end;
end;
procedure nemesis_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$3fff:;
$4000..$47ff:mem_snd[direccion]:=valor;
$a000..$afff:k005289_0.ld1_w(direccion and $fff,valor);
$c000..$cfff:k005289_0.ld2_w(direccion and $fff,valor);
$e003:k005289_0.tg1_w(valor);
$e004:k005289_0.tg2_w(valor);
$e005:ay8910_1.Control(valor);
$e006:ay8910_0.Control(valor);
$e106:ay8910_0.Write(valor);
$e405:ay8910_1.Write(valor);
end;
end;
//GX400
procedure eventos_gx400;
begin
if event.arcade then begin
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
//IN0
if arcade_input.coin[0] then marcade.in0:=marcade.in0 and $fe;
if arcade_input.coin[1] then marcade.in0:=marcade.in0 and $fd;
if arcade_input.start[0] then marcade.in0:=marcade.in0 and $f7;
if arcade_input.start[1] then marcade.in0:=marcade.in0 and $ef;
//P1
if arcade_input.left[0] then marcade.in1:=marcade.in1 and $fe;
if arcade_input.right[0] then marcade.in1:=marcade.in1 and $fd;
if arcade_input.up[0] then marcade.in1:=marcade.in1 and $fb;
if arcade_input.down[0] then marcade.in1:=marcade.in1 and $f7;
if arcade_input.but0[0] then marcade.in1:=marcade.in1 and $ef;
if arcade_input.but2[0] then marcade.in1:=marcade.in1 and $df;
if arcade_input.but1[0] then marcade.in1:=marcade.in1 and $bf;
//P2
if arcade_input.left[1] then marcade.in2:=marcade.in2 and $fe;
if arcade_input.right[1] then marcade.in2:=marcade.in2 and $fd;
if arcade_input.up[1] then marcade.in2:=marcade.in2 and $fb;
if arcade_input.down[1] then marcade.in2:=marcade.in2 and $f7;
if arcade_input.but0[1] then marcade.in2:=marcade.in2 and $ef;
if arcade_input.but2[1] then marcade.in2:=marcade.in2 and $df;
if arcade_input.but1[1] then marcade.in2:=marcade.in2 and $bf;
end;
end;
procedure gx400_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//Main CPU
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//Sound CPU
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
case f of
119:if irq4_on then m68000_0.irq[4]:=HOLD_LINE;
239:begin
update_video_nemesis;
if (irq_on and screen_par) then m68000_0.irq[1]:=HOLD_LINE;
z80_0.change_nmi(PULSE_LINE);
end;
255:if irq2_on then m68000_0.irq[2]:=HOLD_LINE;
end;
end;
screen_par:=not(screen_par);
eventos_gx400;
video_sync;
end;
end;
function gx400_getword(direccion:dword):word;
begin
case direccion of
0..$ffff:gx400_getword:=bios_rom[direccion shr 1];
$10000..$1ffff:gx400_getword:=ram3[(direccion and $ffff) shr 1];
$20000..$27fff:gx400_getword:=shared_ram[(direccion and $7fff) shr 1];
$30000..$3ffff:gx400_getword:=(char_ram[(direccion and $ffff) shr 1] shr 8)+((char_ram[(direccion and $ffff) shr 1] and $ff) shl 8);
$50000..$51fff:gx400_getword:=ram1[(direccion and $1fff) shr 1];
$52000..$52fff:gx400_getword:=video1_ram[(direccion and $fff) shr 1];
$53000..$53fff:gx400_getword:=video2_ram[(direccion and $fff) shr 1];
$54000..$54fff:gx400_getword:=color1_ram[(direccion and $fff) shr 1];
$55000..$55fff:gx400_getword:=color2_ram[(direccion and $fff) shr 1];
$56000..$56fff:gx400_getword:=sprite_ram[(direccion and $fff) shr 1];
$57000..$57fff:gx400_getword:=ram2[(direccion and $fff) shr 1];
$5a000..$5afff:gx400_getword:=buffer_paleta[(direccion and $fff) shr 1];
$5c402:gx400_getword:=$ff;
$5c404:gx400_getword:=$56;
$5c406:gx400_getword:=$fd;
$5cc00:gx400_getword:=marcade.in0;
$5cc02:gx400_getword:=marcade.in1;
$5cc04:gx400_getword:=marcade.in2;
$60000..$7ffff:gx400_getword:=ram4[(direccion and $1ffff) shr 1];
$80000..$bffff:gx400_getword:=rom[(direccion and $3ffff) shr 1];
end;
end;
procedure gx400_putword(direccion:dword;valor:word);
var
dir:word;
begin
case direccion of
0..$ffff,$80000..$bffff:;
$10000..$1ffff:ram3[(direccion and $ffff) shr 1]:=valor;
$20000..$27fff:shared_ram[(direccion and $7fff) shr 1]:=valor and $ff;
$30000..$3ffff:if char_ram[(direccion and $ffff) shr 1]<>(((valor and $ff) shl 8)+(valor shr 8)) then begin
char_ram[(direccion and $ffff) shr 1]:=((valor and $ff) shl 8)+(valor shr 8);
char_8_8[(direccion and $ffff) div $20]:=true;
char_16_16[(direccion and $ffff) div $80]:=true;
char_32_16[(direccion and $ffff) div $100]:=true;
char_8_16[(direccion and $ffff) div $40]:=true;
char_32_32[(direccion and $ffff) div $200]:=true;
char_64_64[(direccion and $ffff) div $800]:=true;
fillchar(gfx[0].buffer,$800,1);
fillchar(gfx[1].buffer,$800,1);
changed_chr:=true;
end;
$50000..$51fff:begin
dir:=(direccion and $1fff) shr 1;
ram1[dir]:=valor;
case (direccion and $1fff) of
0..$3ff:xscroll_1[dir and $1ff]:=valor;
$400..$7ff:xscroll_2[dir and $1ff]:=valor;
$f00..$f7f:yscroll_2[dir and $3f]:=valor;
$f80..$fff:yscroll_1[dir and $3f]:=valor;
end;
end;
$52000..$52fff:if video1_ram[(direccion and $fff) shr 1]<>valor then begin
video1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$53000..$53fff:if video2_ram[(direccion and $fff) shr 1]<>valor then begin
video2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$54000..$54fff:if color1_ram[(direccion and $fff) shr 1]<>valor then begin
color1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$55000..$55fff:if color2_ram[(direccion and $fff) shr 1]<>valor then begin
color2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$56000..$56fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$57000..$57fff:ram2[(direccion and $fff) shr 1]:=valor;
$5a000..$5afff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor;
cambiar_color(valor,(direccion and $fff) shr 1);
end;
$5c000:sound_latch:=valor and $ff;
$5e000:irq2_on:=(valor and $1)<>0;
$5e002:irq_on:=(valor and $1)<>0;
$5e004:begin
flipx_scr:=(valor and $1)<>0;
if (valor and $100)<>0 then z80_0.change_irq(HOLD_LINE);
end;
$5e006:flipy_scr:=(valor and $1)<>0;
$5e00e:irq4_on:=(valor and $100)<>0;
$60000..$7ffff:ram4[(direccion and $1ffff) shr 1]:=valor;
end;
end;
function gx400_snd_getbyte(direccion:word):byte;
var
ptemp:pbyte;
begin
case direccion of
0..$1fff:gx400_snd_getbyte:=mem_snd[direccion];
$4000..$7fff:gx400_snd_getbyte:=shared_ram[direccion and $3fff];
$8000..$87ff:begin
ptemp:=vlm5030_0.get_rom_addr;
inc(ptemp,direccion and $7ff);
gx400_snd_getbyte:=ptemp^;
end;
$e001:gx400_snd_getbyte:=sound_latch;
$e086:gx400_snd_getbyte:=ay8910_0.Read;
$e205:gx400_snd_getbyte:=ay8910_1.Read;
end;
end;
procedure gx400_snd_putbyte(direccion:word;valor:byte);
var
ptemp:pbyte;
begin
case direccion of
0..$1fff:;
$4000..$7fff:shared_ram[direccion and $3fff]:=valor;
$8000..$87ff:begin
ptemp:=vlm5030_0.get_rom_addr;
inc(ptemp,direccion and $7ff);
ptemp^:=valor;
end;
$a000..$afff:k005289_0.ld1_w(direccion and $fff,valor);
$c000..$cfff:k005289_0.ld2_w(direccion and $fff,valor);
$e000:vlm5030_0.data_w(valor);
$e003:k005289_0.tg1_w(valor);
$e004:k005289_0.tg2_w(valor);
$e005:ay8910_1.Control(valor);
$e006:ay8910_0.Control(valor);
$e030:begin
vlm5030_0.set_st(1);
vlm5030_0.set_st(0);
end;
$e106:ay8910_0.Write(valor);
$e405:ay8910_1.Write(valor);
end;
end;
function ay0_porta_read_gx400:byte;
var
res:byte;
begin
res:=round(z80_0.totalt/1024) and $2f;
ay0_porta_read_gx400:=res or $d0 or ($20*vlm5030_0.get_bsy);
end;
procedure sound_update_gx400;
begin
ay8910_0.update;
ay8910_1.update;
vlm5030_0.update;
k005289_0.update;
end;
//Salamander
function salamander_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:salamander_getword:=rom[direccion shr 1];
$80000..$87fff:salamander_getword:=ram3[(direccion and $7fff) shr 1];
$90000..$91fff:salamander_getword:=buffer_paleta[(direccion and $1fff) shr 1];
$c0002:salamander_getword:=$ff; //dsw0
$c2000:salamander_getword:=marcade.in0; //in0
$c2002:salamander_getword:=marcade.in1; //in1
$c2004:salamander_getword:=marcade.in2; //in2
$c2006:salamander_getword:=$42; //dsw1
$100000..$100fff:salamander_getword:=video2_ram[(direccion and $fff) shr 1];
$101000..$101fff:salamander_getword:=video1_ram[(direccion and $fff) shr 1];
$102000..$102fff:salamander_getword:=color2_ram[(direccion and $fff) shr 1];
$103000..$103fff:salamander_getword:=color1_ram[(direccion and $fff) shr 1];
$120000..$12ffff:salamander_getword:=(char_ram[(direccion and $ffff) shr 1] shr 8)+((char_ram[(direccion and $ffff) shr 1] and $ff) shl 8);
$180000..$180fff:salamander_getword:=sprite_ram[(direccion and $fff) shr 1];
$190000..$191fff:salamander_getword:=ram1[(direccion and $1fff) shr 1];
end;
end;
procedure salamander_putword(direccion:dword;valor:word);
var
dir:word;
procedure cambiar_color_salamander(numero:word);
var
color:tcolor;
tmp_color:word;
begin
numero:=numero shr 1;
tmp_color:=(buffer_paleta[numero*2] shl 8) or buffer_paleta[(numero*2)+1];
color.r:=pal5bit(tmp_color shr 0);
color.g:=pal5bit(tmp_color shr 5);
color.b:=pal5bit(tmp_color shr 10);
set_pal_color(color,numero);
buffer_color[numero shr 4]:=true;
end;
begin
case direccion of
0..$7ffff:;
$80000..$87fff:ram3[(direccion and $7fff) shr 1]:=valor;
$90000..$91fff:if buffer_paleta[(direccion and $1fff) shr 1]<>(valor and $ff) then begin
buffer_paleta[(direccion and $1fff) shr 1]:=valor and $ff;
cambiar_color_salamander((direccion and $1fff) shr 1);
end;
$a0000:begin
irq_on:=(valor and 1)<>0;
flipx_scr:=(valor and 4)<>0;
flipy_scr:=(valor and 8)<>0;
if (valor and $800)<>0 then z80_0.change_irq(HOLD_LINE);
end;
$c0000:sound_latch:=valor and $ff;
$100000..$100fff:if video2_ram[(direccion and $fff) shr 1]<>valor then begin
video2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$101000..$101fff:if video1_ram[(direccion and $fff) shr 1]<>valor then begin
video1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$102000..$102fff:if color2_ram[(direccion and $fff) shr 1]<>valor then begin
color2_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
end;
$103000..$103fff:if color1_ram[(direccion and $fff) shr 1]<>valor then begin
color1_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$120000..$12ffff:if char_ram[(direccion and $ffff) shr 1]<>(((valor and $ff) shl 8)+(valor shr 8)) then begin
dir:=direccion and $ffff;
char_ram[dir shr 1]:=((valor and $ff) shl 8)+(valor shr 8);
char_8_8[dir div $20]:=true;
char_16_16[dir div $80]:=true;
char_32_16[dir div $100]:=true;
char_8_16[dir div $40]:=true;
char_32_32[dir div $200]:=true;
char_64_64[dir div $800]:=true;
fillchar(gfx[0].buffer,$800,1);
fillchar(gfx[1].buffer,$800,1);
changed_chr:=true;
end;
$180000..$180fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$190000..$191fff:begin
dir:=(direccion and $1fff) shr 1;
ram1[dir]:=valor;
case (direccion and $1fff) of
0..$3ff:xscroll_2[dir and $1ff]:=valor;
$400..$7ff:xscroll_1[dir and $1ff]:=valor;
$f00..$f7f:yscroll_1[dir and $3f]:=valor;
$f80..$fff:yscroll_2[dir and $3f]:=valor;
end;
end;
end;
end;
function salamander_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff:salamander_snd_getbyte:=mem_snd[direccion];
$a000:salamander_snd_getbyte:=sound_latch;
$b000..$b00d:salamander_snd_getbyte:=k007232_0.read(direccion and $f);
$c001:salamander_snd_getbyte:=ym2151_0.status;
$e000:begin
screen_par:=not(screen_par);
salamander_snd_getbyte:=byte(screen_par);
end;
end;
end;
procedure salamander_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:;
$8000..$87ff:mem_snd[direccion]:=valor;
$b000..$b00d:k007232_0.write(direccion and $f,valor);
$c000:ym2151_0.reg(valor);
$c001:ym2151_0.write(valor);
$d000:vlm5030_0.data_w(valor);
$f000:begin
vlm5030_0.set_rst(valor and 1);
vlm5030_0.set_st(((valor and 2) shr 1));
end;
end;
end;
procedure nemesis_k007232_cb_0(valor:byte);
begin
k007232_0.set_volume(0,(valor shr 4)*$11,0);
k007232_0.set_volume(1,0,(valor and $f)*$11);
end;
procedure sound_update_salamand;
begin
ym2151_0.update;
k007232_0.update;
vlm5030_0.update;
end;
//Main
procedure reset_nemesis;
begin
m68000_0.reset;
z80_0.reset;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
case main_vars.tipo_maquina of
204:begin
ay8910_0.reset;
ay8910_1.reset;
k005289_0.reset;
marcade.in0:=0;
marcade.in1:=0;
marcade.in2:=0;
end;
205,260:begin
ay8910_0.reset;
ay8910_1.reset;
k005289_0.reset;
vlm5030_0.reset;
end;
261:begin
ym2151_0.reset;
vlm5030_0.reset;
marcade.in0:=$e0;
marcade.in1:=0;
marcade.in2:=0;
end;
end;
reset_audio;
irq_on:=false;
irq2_on:=false;
irq4_on:=false;
screen_par:=false;
flipy_scr:=false;
flipx_scr:=false;
fillchar(char_8_8,$800,1);
fillchar(char_16_16,$200,1);
fillchar(char_32_16,$100,1);
fillchar(char_8_16,$400,1);
fillchar(char_32_32,$80,1);
fillchar(char_64_64,$20,1);
changed_chr:=true;
end;
procedure cerrar_nemesis;
begin
if k007232_1_rom<>nil then freemem(k007232_1_rom);
k007232_1_rom:=nil;
end;
function iniciar_nemesis:boolean;
var
f:byte;
procedure init_ay_sound;
begin
ay8910_0:=ay8910_chip.create(18432000 div 8,AY8910,1);
ay8910_1:=ay8910_chip.create(18432000 div 8,AY8910,1);
ay8910_1.change_io_calls(nil,nil,ay8910_k005289_1,ay8910_k005289_2);
//IMPORTANTE: Necesito que ya este inicializado el sonido para crear este chip!!!
k005289_0:=k005289_snd_chip.create(3579545,0.5);
if not(roms_load(@k005289_0.sound_prom,rom_k005289)) then exit;
end;
procedure init_ay_vlm_sound;
begin
init_ay_sound;
vlm5030_0:=vlm5030_chip.Create(3579545,$800,2);
end;
begin
llamadas_maquina.close:=cerrar_nemesis;
case main_vars.tipo_maquina of
204,261:llamadas_maquina.bucle_general:=nemesis_principal;
205,260:llamadas_maquina.bucle_general:=gx400_principal;
end;
llamadas_maquina.reset:=reset_nemesis;
llamadas_maquina.fps_max:=60.60606060606060;
iniciar_nemesis:=false;
iniciar_audio(false);
for f:=1 to 8 do begin
screen_init(f,512,256,true);
screen_mod_scroll(f,512,512,511,256,256,255);
end;
screen_init(9,512,512,false,true);
if main_vars.tipo_maquina=205 then main_screen.rot90_screen:=true;
iniciar_video(256,224);
//Main CPU
m68000_0:=cpu_m68000.create(18432000 div 2,256);
//Sound CPU
z80_0:=cpu_z80.create(14318180 div 4,256);
case main_vars.tipo_maquina of
204:begin //nemesis
if not(roms_load16w(@rom,nemesis_rom)) then exit;
m68000_0.change_ram16_calls(nemesis_getword,nemesis_putword);
if not(roms_load(@mem_snd,nemesis_sound)) then exit;
z80_0.change_ram_calls(nemesis_snd_getbyte,nemesis_snd_putbyte);
z80_0.init_sound(sound_update);
init_ay_sound;
ay8910_0.change_io_calls(ay0_porta_read,nil,nil,nil);
end;
205:begin //twinbee
if not(roms_load16w(@bios_rom,gx400_bios)) then exit;
if not(roms_load16w(@rom,twinbee_rom)) then exit;
m68000_0.change_ram16_calls(gx400_getword,gx400_putword);
if not(roms_load(@mem_snd,gx400_sound)) then exit;
z80_0.change_ram_calls(gx400_snd_getbyte,gx400_snd_putbyte);
z80_0.init_sound(sound_update_gx400);
init_ay_vlm_sound;
ay8910_0.change_io_calls(ay0_porta_read_gx400,nil,nil,nil);
end;
260:begin //Galactic Warriors
if not(roms_load16w(@bios_rom,gx400_bios)) then exit;
if not(roms_load16w(@rom,gwarrior_rom)) then exit;
m68000_0.change_ram16_calls(gx400_getword,gx400_putword);
if not(roms_load(@mem_snd,gx400_sound)) then exit;
z80_0.change_ram_calls(gx400_snd_getbyte,gx400_snd_putbyte);
z80_0.init_sound(sound_update_gx400);
init_ay_vlm_sound;
ay8910_0.change_io_calls(ay0_porta_read_gx400,nil,nil,nil);
end;
261:begin //Salamander
if not(roms_load16w(@rom,salamander_rom)) then exit;
m68000_0.change_ram16_calls(salamander_getword,salamander_putword);
if not(roms_load(@mem_snd,salamander_sound)) then exit;
z80_0.change_ram_calls(salamander_snd_getbyte,salamander_snd_putbyte);
z80_0.init_sound(sound_update_salamand);
ym2151_0:=ym2151_chip.create(3579545);
vlm5030_0:=vlm5030_chip.Create(3579545,$4000,1);
if not(roms_load(vlm5030_0.get_rom_addr,salamander_vlm)) then exit;
getmem(k007232_1_rom,$20000);
if not(roms_load(k007232_1_rom,salamander_k007232)) then exit;
k007232_0:=k007232_chip.create(3579545,k007232_1_rom,$20000,0.20,nemesis_k007232_cb_0);
end;
end;
//graficos, solo los inicio, los cambia en tiempo real...
init_gfx(0,8,8,$800);
init_gfx(1,16,16,$200);
init_gfx(2,32,16,$100);
init_gfx(3,8,16,$400);
init_gfx(4,32,32,$80);
init_gfx(5,16,32,$100);
init_gfx(6,16,8,$400);
init_gfx(7,64,64,$20);
for f:=0 to 7 do gfx[f].trans[0]:=true;
//final
reset_nemesis;
iniciar_nemesis:=true;
end;
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$
}
unit IdStruct;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal;
type
TIdStruct = class(TObject)
protected
function GetBytesLen: LongWord; virtual;
public
constructor Create; virtual;
//done this way in case we also need to advance an index pointer
//after a read or write
procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); virtual;
procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); virtual;
property BytesLen: LongWord read GetBytesLen;
end;
TIdUnion = class(TIdStruct)
protected
FBuffer: TIdBytes;
function GetBytesLen: LongWord; override;
procedure SetBytesLen(const ABytesLen: LongWord);
public
procedure ReadStruct(const ABytes : TIdBytes; var VIndex : LongWord); override;
procedure WriteStruct(var VBytes : TIdBytes; var VIndex : LongWord); override;
end;
TIdLongWord = class(TIdUnion)
protected
function Get_l: LongWord;
function Gets_b1: Byte;
function Gets_b2: Byte;
function Gets_b3: Byte;
function Gets_b4: Byte;
function Gets_w1: Word;
function Gets_w2: Word;
procedure Set_l(const Value: LongWord);
procedure Sets_b1(const Value: Byte);
procedure Sets_b2(const Value: Byte);
procedure Sets_b3(const Value: Byte);
procedure Sets_b4(const Value: Byte);
procedure SetS_w1(const Value: Word);
procedure SetS_w2(const Value: Word);
public
constructor Create; override;
property s_b1 : Byte read Gets_b1 write Sets_b1;
property s_b2 : Byte read Gets_b2 write Sets_b2;
property s_b3 : Byte read Gets_b3 write Sets_b3;
property s_b4 : Byte read Gets_b4 write Sets_b4;
property s_w1 : Word read Gets_w1 write SetS_w1;
property s_w2 : Word read Gets_w2 write SetS_w2;
property s_l : LongWord read Get_l write Set_l;
end;
implementation
// This is here to facilitate inlining
{$IFDEF WINDOWS}
{$IFDEF USE_INLINE}
uses
Windows;
{$ENDIF}
{$ENDIF}
{ TIdStruct }
constructor TIdStruct.Create;
begin
inherited Create;
end;
function TIdStruct.GetBytesLen: LongWord;
begin
Result := 0;
end;
procedure TIdStruct.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord);
begin
Assert(LongWord(Length(ABytes)) >= VIndex + BytesLen, 'not enough bytes'); {do not localize}
end;
procedure TIdStruct.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord);
var
Len: LongWord;
begin
Len := VIndex + BytesLen;
if LongWord(Length(VBytes)) < Len then begin
SetLength(VBytes, Len);
end;
end;
{ TIdUnion }
function TIdUnion.GetBytesLen : LongWord;
begin
Result := LongWord(Length(FBuffer));
end;
procedure TIdUnion.SetBytesLen(const ABytesLen: LongWord);
begin
SetLength(FBuffer, ABytesLen);
end;
procedure TIdUnion.ReadStruct(const ABytes: TIdBytes; var VIndex: LongWord);
begin
inherited ReadStruct(ABytes, VIndex);
CopyTIdBytes(ABytes, VIndex, FBuffer, 0, Length(FBuffer));
Inc(VIndex, Length(FBuffer));
end;
procedure TIdUnion.WriteStruct(var VBytes: TIdBytes; var VIndex: LongWord);
begin
inherited WriteStruct(VBytes, VIndex);
CopyTIdBytes(FBuffer, 0, VBytes, VIndex, Length(FBuffer));
Inc(VIndex, Length(FBuffer));
end;
{ TIdLongWord }
constructor TIdLongWord.Create;
begin
inherited Create;
SetBytesLen(4);
end;
function TIdLongWord.Gets_w1: Word;
begin
Result := BytesToWord(FBuffer, 0);
end;
procedure TIdLongWord.SetS_w1(const Value: Word);
begin
CopyTIdWord(Value, FBuffer, 0);
end;
function TIdLongWord.Gets_b1: Byte;
begin
Result := FBuffer[0];
end;
procedure TIdLongWord.Sets_b1(const Value: Byte);
begin
FBuffer[0] := Value;
end;
function TIdLongWord.Gets_b2: Byte;
begin
Result := FBuffer[1];
end;
procedure TIdLongWord.Sets_b2(const Value: Byte);
begin
FBuffer[1] := Value;
end;
function TIdLongWord.Gets_b3: Byte;
begin
Result := FBuffer[2];
end;
procedure TIdLongWord.Sets_b3(const Value: Byte);
begin
FBuffer[2] := Value;
end;
function TIdLongWord.Gets_b4: Byte;
begin
Result := FBuffer[3];
end;
procedure TIdLongWord.Sets_b4(const Value: Byte);
begin
FBuffer[3] := Value;
end;
function TIdLongWord.Get_l: LongWord;
begin
Result := BytesToLongWord(FBuffer, 0);
end;
procedure TIdLongWord.Set_l(const Value: LongWord);
begin
CopyTIdLongWord(Value, FBuffer, 0);
end;
function TIdLongWord.Gets_w2: Word;
begin
Result := BytesToWord(FBuffer, 2);
end;
procedure TIdLongWord.SetS_w2(const Value: Word);
begin
CopyTIdWord(Value, FBuffer, 2);
end;
end.
|
unit IRCUtils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TIRCUtils }
TIRCUtils = class
class function RemoveOPVoicePrefix(const Username: string): string;
class function IsOpVoice(const NickName: string): Boolean;
class function IsOp(const NickName: string): Boolean;
class function IsVoice(const NickName: string): Boolean;
end;
implementation
{ TIRCUtils }
class function TIRCUtils.RemoveOPVoicePrefix(const Username: string): string;
begin
if IsOpVoice(Username) then
Result := Copy(Username, 2, MaxInt)
else
Result := Username;
end;
class function TIRCUtils.IsOpVoice(const NickName: string): Boolean;
begin
Result := IsOp(NickName) or IsVoice(NickName);
end;
class function TIRCUtils.IsOp(const NickName: string): Boolean;
begin
Result := NickName[1] = '@';
end;
class function TIRCUtils.IsVoice(const NickName: string): Boolean;
begin
Result := NickName[1] = '+';
end;
end.
|
program TesteSortiereListe(input, output);
type
tNatZahl = 0..maxint;
tRefListe = ^tListe;
tListe = record
info : tNatZahl;
next : tRefListe;
end;
var
RefListe : tRefListe;
procedure SortiereListe (var ioRefListe : tRefListe);
{ sortiert eine lineare Liste aufsteigend }
var
Anfang,
Ende : tRefListe;
procedure AnfangSortieren (var ioRefListe : tRefListe);
{Sortiert die ersten zwei Elemente einer linearen Liste}
var
Zweites : tRefListe;
begin
Zweites := ioRefListe^.next;
if (Zweites^.info < ioRefListe^.info) then
begin
ioRefListe^.next := Zweites^.next;
Zweites^.next := ioRefListe;
ioRefListe := Zweites;
end {if}
end; {procedure AnfangSortieren}
procedure SortierDurchlauf (var ioAnfang,
ioEnde : tRefListe);
{Sortiert das Element nach ioEnde in die Liste ioAnfang ein}
var
Sort,
Suche : tRefListe;
begin
Sort := ioEnde^.next;
if (Sort^.info > ioEnde^.info) then
{Sortiert das nächste unsortierte Element am Ende ein}
ioEnde := ioEnde^.next
else
if (Sort^.info < ioAnfang^.info) then
{Sortiert das nächste unsortierte Element am Anfang ein}
begin
ioEnde^.next := Sort^.next;
Sort^.next := ioAnfang;
ioAnfang := Sort;
end {if}
else
{sortiert das nächste unsortierte Element an passender Stelle ein.}
begin
ioEnde^.next := Sort^.next;
Suche := ioAnfang;
while (Suche^.next^.info < Sort^.info) do
Suche := Suche^.next;
Sort^.next :=Suche^.next;
Suche^.next := Sort;
end {else}
end; {procedure SortierDurchlauf}
begin
if (ioRefListe <> nil) and (ioRefListe^.next <> nil) then
{Liste wir sortiert, wenn sie weder leer ist noch nur ein Element hat}
begin
AnfangSortieren(ioRefListe);
Anfang := ioRefListe;
Ende := ioRefListe^.next;
while (Ende^.next <> nil) do
{Liste sortieren, bis das Ende erreicht ist}
SortierDurchlauf(Anfang,Ende);
ioRefListe := Anfang;
end; {if}
end; {procedure SortiereListe}
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 GibListeAus(inListe : tRefListe);
{ Gibt die Elemente von inListe aus }
var Zeiger : tRefListe;
begin
Zeiger := inListe;
while Zeiger <> nil do
begin
writeln(Zeiger^.info);
Zeiger := Zeiger^.next;
end; { while }
end; { GibListeAus }
begin
ListeEinlesen(RefListe);
SortiereListe(RefListe);
GibListeAus(RefListe)
end.
|
unit CleanArch_EmbrConf.Core.Entity.Impl.ParkedCar;
interface
uses
CleanArch_EmbrConf.Core.Entity.Interfaces,
System.RegularExpressions,
System.SysUtils;
type
TParkedCar = class(TInterfacedObject, iParkedCar)
private
FCode: string;
FPlate: String;
Fdata: string;
public
constructor Create;
destructor Destroy; override;
class function New: iParkedCar;
function Code(Value: String): iParkedCar; overload;
function Code: String; overload;
function Plate(Value: String): iParkedCar; overload;
function Plate: String; overload;
function Data(Value: String): iParkedCar; overload;
function Data: String; overload;
end;
implementation
function TParkedCar.Code(Value: String): iParkedCar;
begin
result := self;
FCode := Value;
end;
function TParkedCar.Code: String;
begin
result := FCode;
end;
constructor TParkedCar.Create;
begin
end;
function TParkedCar.Data: String;
begin
result := Fdata;
end;
function TParkedCar.Data(Value: String): iParkedCar;
begin
result := self;
Fdata := Value;
end;
destructor TParkedCar.Destroy;
begin
inherited;
end;
class function TParkedCar.New: iParkedCar;
begin
result := self.Create;
end;
function TParkedCar.Plate(Value: String): iParkedCar;
begin
result := self;
FPlate := Value;
end;
function TParkedCar.Plate: String;
begin
if not TRegEx.IsMatch(FPlate, '\w[A-Z]{1,3}-[0-9]{1,4}') then
raise Exception.Create('Invalid Plate');
result := FPlate;
end;
end.
|
Unit TERRA_Localization;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Application, TERRA_Utils, TERRA_Stream, TERRA_FileUtils,
TERRA_Collections, TERRA_Hashmap;
Const
language_English = 'EN';
language_German = 'DE';
language_French = 'FR';
language_Portuguese= 'PT';
language_Spanish = 'ES';
language_Italian = 'IT';
language_Japanese = 'JP';
language_Chinese = 'ZH';
language_Russian = 'RU';
language_Korean = 'KO';
invalidString = '???';
Translation_Extension = 'ltx';
Translation_Header: FileHeader = 'LTX1';
MaxPinyinSuggestions = 64;
Type
StringEntry = Class(HashMapObject)
Protected
_Value:TERRAString;
_Group:Integer;
Public
Constructor Create(Const Key, Value:TERRAString; Group:Integer);
End;
LocalizationManager = Class(ApplicationComponent)
Protected
_Lang:TERRAString;
_Strings:Hashmap;
Function GetLang:TERRAString;
Public
Procedure Init; Override;
Procedure Release; Override;
Class Function Instance:LocalizationManager;
Procedure SetLanguage(Lang:TERRAString);
Function GetString(Const Key:TERRAString):TERRAString;
Function HasString(Const Key:TERRAString):Boolean;
Procedure SetString(Const Key, Value:TERRAString; Group:Integer = -1);
Function EmptyString():TERRAString;
Procedure Reload();
Procedure RemoveGroup(GroupID:Integer);
Procedure MergeGroup(Source:Stream; GroupID:Integer; Const Prefix:TERRAString);
Property Language:TERRAString Read GetLang Write SetLanguage;
Property Strings[Const Key:TERRAString]:TERRAString Read GetString; Default;
End;
PinyinSuggestion = Record
ID:Word;
Text:TERRAString;
End;
PinyinConverter = Class(TERRAObject)
Protected
_Suggestions:Array Of PinyinSuggestion;
_SuggestionCount:Integer;
Procedure Match(S:TERRAString);
Public
Constructor Create();
Procedure GetSuggestions(Text:TERRAString);
Function GetResult(Index:Integer):Word;
Function Replace(Var Text:TERRAString; Index:Integer):Boolean;
Property Results:Integer Read _SuggestionCount;
End;
Function GetKoreanInitialJamo(N:TERRAChar):Integer;
Function GetKoreanMedialJamo(N:TERRAChar):Integer;
Function GetKoreanFinalJamo(N:TERRAChar):Integer;
Function MemoryToString(Const N:Cardinal):TERRAString;
Function IsSupportedLanguage(Const Lang:TERRAString):Boolean;
Function GetCurrencyForCountry(Const Country:TERRAString):TERRAString;
Function GetLanguageDescription(Lang:TERRAString):TERRAString;
Implementation
Uses TERRA_FileManager, TERRA_Log, TERRA_OS;
Var
_LocalizationManager_Instance:ApplicationObject = Nil;
Function IsSupportedLanguage(Const Lang:TERRAString):Boolean;
Begin
Result := (Lang = language_English) Or (Lang = language_German)
Or (Lang = language_French) Or (Lang = language_Portuguese)
Or (Lang = language_Spanish) Or (Lang = language_Italian)
Or (Lang = language_Japanese) Or (Lang = language_Chinese)
Or (Lang = language_Russian) Or (Lang = language_Korean);
End;
Function GetCurrencyForCountry(Const Country:TERRAString):TERRAString;
Begin
If (Country = 'GB') Then
Begin
Result := 'GBP';
End Else
If (Country = 'RU') Then
Begin
Result := 'RUB';
End Else
If (Country = 'BR') Then
Begin
Result := 'BRL';
End Else
If (Country = 'US') Then
Begin
Result := 'USD';
End Else
If (Country = 'JP') Then
Begin
Result := 'JPY';
End Else
If (Country = 'KR') Then
Begin
Result := 'KRW';
End Else
If (Country = 'UA') Then
Begin
Result := 'UAH';
End Else
If (Country = 'AU') Then
Begin
Result := 'AUD';
End Else
If (Country = 'CA') Then
Begin
Result := 'CAD';
End Else
If (Country = 'ID') Then
Begin
Result := 'IDR';
End Else
If (Country = 'MY') Then
Begin
Result := 'MYR';
End Else
If (Country = 'MX') Then
Begin
Result := 'MXN';
End Else
If (Country = 'NZ') Then
Begin
Result := 'NZD';
End Else
If (Country = 'NO') Then
Begin
Result := 'NOK';
End Else
If (Country = 'PH') Then
Begin
Result := 'PHP';
End Else
If (Country = 'SG') Then
Begin
Result := 'SGD';
End Else
If (Country = 'TH') Then
Begin
Result := 'THB';
End Else
If (Country = 'TR') Then
Begin
Result := 'TRY';
End Else
Begin
Result := 'USD';
End;
End;
Function GetKoreanInitialJamo(N:TERRAChar):Integer;
Begin
Case N Of
12593: Result := 0;
12594: Result := 1;
12596: Result := 2;
12599: Result := 3;
12600: Result := 4;
12601: Result := 5;
12609: Result := 6;
12610: Result := 7;
12611: Result := 8;
12613: Result := 9;
12614: Result := 10;
12615: Result := 11;
12616: Result := 12;
12617: Result := 13;
12618: Result := 14;
12619: Result := 15;
12620: Result := 16;
12621: Result := 17;
12622: Result := 18;
Else
Result := -1;
End;
End;
Function GetKoreanMedialJamo(N:TERRAChar):Integer;
Begin
Case N Of
12623: Result := 0;
12624: Result := 1;
12625: Result := 2;
12626: Result := 3;
12627: Result := 4;
12628: Result := 5;
12629: Result := 6;
12630: Result := 7;
12631: Result := 8;
12632: Result := 9;
12633: Result := 10;
12634: Result := 11;
12635: Result := 12;
12636: Result := 13;
12637: Result := 14;
12638: Result := 15;
12639: Result := 16;
12640: Result := 17;
12641: Result := 18;
12642: Result := 19;
12643: Result := 20;
Else
Result := -1;
End;
End;
Function GetKoreanFinalJamo(N:TERRAChar):Integer;
Begin
Case N Of
12593: Result := 1;
12594: Result := 2;
12595: Result := 3;
12596: Result := 4;
12597: Result := 5;
12598: Result := 6;
12599: Result := 7;
12601: Result := 8;
12602: Result := 9;
12603: Result := 10;
12604: Result := 11;
12605: Result := 12;
12606: Result := 13;
12607: Result := 14;
12608: Result := 15;
12609: Result := 16;
12610: Result := 17;
12612: Result := 18;
12613: Result := 19;
12614: Result := 20;
12615: Result := 21;
12616: Result := 22;
12618: Result := 23;
12619: Result := 24;
12620: Result := 25;
12621: Result := 26;
12622: Result := 27;
Else
Result := -1;
End;
End;
Function MemoryToString(Const N:Cardinal):TERRAString;
Var
Ext:Char;
X:Single;
Int,Rem:Integer;
Begin
If (N>=1 Shl 30)Then
Begin
X:=N/(1 Shl 30);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext := 'G';
End Else
If (N>=1 Shl 20)Then
Begin
X:=N/(1 Shl 20);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext:='M';
End Else
If (N>=1 Shl 10)Then
Begin
X:=N/(1 Shl 10);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext:='K';
End Else
Begin
Int:=N;
Rem:=0;
Ext:=#0;
End;
Result:=IntToString(Int);
If Rem>0 Then
Result:=Result+'.'+IntToString(Rem);
Result:=Result+' ';
If Ext<>#0 Then
Result:=Result+Ext;
If (Application.Instance.Language = language_Russian) Then
StringAppendChar(Result, 1073)
Else
Result := Result + 'b';
End;
{ LocalizationManager }
Procedure LocalizationManager.Init();
Begin
_Lang := '';
_Strings := HashMap.Create(1024);
If Assigned(Application.Instance()) Then
SetLanguage(Application.Instance.Language)
Else
SetLanguage('EN');
End;
Procedure LocalizationManager.Release();
Begin
ReleaseObject(_Strings);
End;
Function LocalizationManager.EmptyString:TERRAString;
Begin
Result := InvalidString;
End;
Function LocalizationManager.GetLang:TERRAString;
Begin
If (_Lang ='') And (Assigned(Application.Instance())) Then
SetLanguage(Application.Instance.Language);
Result := _Lang;
End;
Procedure LocalizationManager.SetString(Const Key, Value:TERRAString; Group:Integer = -1);
Var
I:Integer;
Entry:StringEntry;
Begin
Entry := StringEntry(_Strings.GetItemByKey(Key));
If Assigned(Entry) Then
Begin
Entry._Value := Value;
Entry._Group := Group;
Exit;
End;
Entry := StringEntry.Create(Key, Value, Group);
_Strings.Add(Entry);
End;
Function LocalizationManager.GetString(Const Key:TERRAString):TERRAString;
Var
Entry:StringEntry;
Begin
If (_Lang ='') And (Assigned(Application.Instance())) Then
SetLanguage(Application.Instance.Language);
Entry := StringEntry(_Strings.GetItemByKey(Key));
If Assigned(Entry) Then
Begin
Result := Entry._Value;
Exit;
End;
Log(logWarning, 'Strings', 'String value for ['+Key+'] not found!');
Result := Self.EmptyString;
End;
Class Function LocalizationManager.Instance:LocalizationManager;
Begin
If _LocalizationManager_Instance = Nil Then
_LocalizationManager_Instance := InitializeApplicationComponent(LocalizationManager, Nil);
Result := LocalizationManager(_LocalizationManager_Instance.Instance);
End;
Procedure LocalizationManager.MergeGroup(Source: Stream; GroupID:Integer; Const Prefix:TERRAString);
Var
Ofs, Count, I:Integer;
Header:FileHeader;
Value, Key:TERRAString;
Begin
If (Source = Nil ) Then
Exit;
Log(logDebug, 'Strings', 'Merging strings from '+Source.Name);
Ofs := _Strings.Count;
Source.ReadHeader(Header);
If Not CompareFileHeader(Header, Translation_Header) Then
Begin
Log(logError, 'Strings', 'Invalid file header in '+Source.Name);
Exit;
End;
Source.ReadInteger(Count);
For I:=0 To Pred(Count) Do
Begin
Source.ReadString(Key);
Source.ReadString(Value);
If Prefix<>'' Then
Key := Prefix + Key;
Self.SetString(Key, Value, GroupID);
//Log(logDebug, 'Strings', 'Found '+_Strings[I+Ofs].Key +' = '+_Strings[I+Ofs].Value);
End;
End;
Procedure LocalizationManager.SetLanguage(Lang:TERRAString);
Var
S, S2:TERRAString;
Source:Stream;
I:Integer;
Begin
Lang := StringUpper(Lang);
If (Lang = 'CH') Or (Lang='CN') Then
Lang := 'ZH';
If (Lang = 'JA') Then
Lang := 'JP';
If (_Lang = Lang) Then
Exit;
S := 'translation_'+ StringLower(Lang)+'.'+ Translation_Extension;
S := FileManager.Instance.SearchResourceFile(S);
If S='' Then
Begin
Log(logWarning, 'Strings', 'Could not find translation file for lang='+Lang);
If (Lang<>language_English) Then
SetLanguage(language_English);
Exit;
End;
_Strings.Clear();
Source := FileManager.Instance.OpenStream(S);
_Lang := Lang;
Self.MergeGroup(Source, -1, '');
ReleaseObject(Source);
End;
Procedure LocalizationManager.Reload();
Var
S:TERRAString;
Begin
S := _Lang;
_Lang := '';
SetLanguage(S);
End;
Procedure LocalizationManager.RemoveGroup(GroupID: Integer);
Var
It:Iterator;
Entry:StringEntry;
Begin
It := _Strings.GetIterator();
While (It.HasNext) Do
Begin
Entry := StringEntry(It.Value);
If (Entry._Group = GroupID) Then
Entry.Discard();
End;
End;
Function LocalizationManager.HasString(Const Key:TERRAString): Boolean;
Var
Temp:StringEntry;
Begin
Temp := StringEntry(_Strings.GetItemByKey(Key));
Result := (Assigned(Temp)) And (Temp._Value<>'');
End;
Type
PinyinEntry = Record
ID:Word;
Text:TERRAString;
End;
Var
_PinyinCount:Integer;
_PinyinData:Array Of PinyinEntry;
{ PinyinConverter }
Constructor PinyinConverter.Create;
Var
Src:Stream;
I:Integer;
Begin
If (_PinyinCount>0) Then
Exit;
Src := FileManager.Instance.OpenStream('pinyin.dat');
If Src = Nil Then
Exit;
Src.Read(@_PinyinCount, 4);
SetLength(_PinyinData ,_PinyinCount);
I := 0;
While (Not Src.EOF) And (I<_PinyinCount) Do
Begin
Src.Read(@_PinyinData[I].ID, 2);
Src.ReadString(_PinyinData[I].Text);
Inc(I);
End;
End;
Procedure PinyinConverter.GetSuggestions(Text:TERRAString);
Const
MaxLength = 7;
Var
It:StringIterator;
N:Integer;
Temp:TERRAString;
C:TERRAChar;
Begin
_SuggestionCount :=0 ;
N := -1;
StringCreateIterator(Text, It);
While It.HasNext() Do
Begin
C := It.GetNext();
If (C>255) Then
Begin
N := It.Position + 1;
Break;
End;
End;
If (N>0) Then
Text := StringCopy(Text, N, MaxInt);
If (Text='') Then
Exit;
If StringLength(Text)>MaxLength Then
Text := StringCopy(Text, StringLength(Text )- MaxLength, MaxInt);
Text := StringLower(Text);
Temp := Text;
While Text<>'' Do
Begin
Match(Text);
Text := StringCopy(Text, 2, MaxInt);
End;
Text := Temp;
While Text<>'' Do
Begin
Match(Text);
Text := StringCopy(Text, 1, Pred(Length(Text)));
End;
End;
Function PinyinConverter.GetResult(Index: Integer): Word;
Begin
If (Index>=0) And (Index<Self.Results) Then
Result := _Suggestions[Index].ID
Else
Result := 0;
End;
Procedure PinyinConverter.Match(S:TERRAString);
Var
I:Integer;
Begin
If (_SuggestionCount>=MaxPinyinSuggestions) Then
Exit;
For I:=0 To Pred(_PinyinCount) Do
If (_PinyinData[I].Text = S) Then
Begin
Inc(_SuggestionCount);
SetLength(_Suggestions, _SuggestionCount);
_Suggestions[Pred(_SuggestionCount)].ID := _PinyinData[I].ID;
_Suggestions[Pred(_SuggestionCount)].Text := S;
End;
End;
Function PinyinConverter.Replace(var Text:TERRAString; Index: Integer):Boolean;
Var
I:Integer;
S,S2:TERRAString;
Begin
Result := False;
I := StringPosReverse(_Suggestions[Index].Text, Text);
If (I<=0) Then
Exit;
S := Copy(Text, 1, Pred(I));
S2 := Copy(Text, I+Length(_Suggestions[Index].Text), MaxInt);
Text := S;
StringAppendChar(Text, _Suggestions[Index].ID);
Text := Text + S2;
Result := True;
End;
Function GetLanguageDescription(Lang:TERRAString):TERRAString;
Begin
Lang := StringUpper(Lang);
If Lang = language_English Then
Result := 'English'
Else
If Lang = language_German Then
Result := 'Deutsch'
Else
If Lang = language_Spanish Then
Result := 'Espa'+StringFromChar(Ord('ñ'))+'ol'
Else
If Lang = language_Portuguese Then
Result := 'Portugu'+StringFromChar(Ord('ê'))+'s'
Else
If Lang = language_French Then
Result := 'Fran'+StringFromChar(Ord('ç'))+'ais'
Else
If Lang = language_Italian Then
Result := 'Italiano'
Else
If Lang = language_Russian Then
Result := StringFromChar(1056)+ StringFromChar(1091) + StringFromChar(1089) + StringFromChar(1089) + StringFromChar(1082) + StringFromChar(1080) + StringFromChar(1081)
Else
If Lang = language_Korean Then
Result := StringFromChar(54620) + StringFromChar(44544)
Else
If Lang = language_Japanese Then
Result := StringFromChar(26085) + StringFromChar(26412) + StringFromChar(35486)
Else
If Lang = language_Chinese Then
Result := StringFromChar(20013) + StringFromChar(22269)
Else
Result := invalidString;
End;
{ StringEntry }
Constructor StringEntry.Create(const Key, Value: TERRAString; Group: Integer);
Begin
Self._Key := Key;
Self._Value := Value;
Self._Group := Group;
End;
End. |
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Maurizio Lotauro <Lotauro.Maurizio@dnet.it>
Code donated to the ICS project
Creation: July 2005
Version: 6.00
Description: This unit contains the class used by THttpCli to handle the
Accept-Encoding and Content-Encoding header fields.
It also contains the THttpContentCoding class needed to implement
a class able to handle a specific encoding.
How to create a class to handle a specific encoding
- define in a separate unit a class inherited from THttpContentCoding
- if the class name start with THttpContentCoding followed by the coding
identifier (for example THttpContentCodingGzip) then that part is taken
automatically as coding identifier. Otherwise you must override the
GetCoding method. This must return the name of the coding.
- most probably you must override the Create constructor to initialize
the structure to handle the decoding process.
Remember to call the inherited.
The same for Destroy.
- override the WriteBuffer method. This will called right before the
THttpCli.TriggerDocData. The parameters are the same.
There you could do two different think. If it is possible to decode on the
fly then call OutputWriteBuffer passing the decoded data. Otherwise store
the data somewhere to decode the whole at the end.
- if there is not possible to decode on the fly then you must override the
Complete method. This will called right before the THttpCli.TriggerDocEnd.
Like for WriteBuffer there you must call OutputWriteBuffer.
- add an inizialization section where you call
THttpContCodHandler.RegisterContentCoding
The first parameter is the default quality (greater than 0 and less or equal
than 1) and the second is the class.
To use it the unit must be added to the uses clause of one unit of the project
History
Jan 08, 2006 V1.01 Maurizio fixed GetCoding
Francois Piette reformated the code to fit the ICS rules,
added compilation directives.
Mar 26, 2006 V6.00 New version 6 started
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsHttpContCod;
interface
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFDEF COMPILER2_UP} { Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
uses
Classes, SysUtils;
type
EHttpContentCodingException = class(Exception);
PStream = ^TStream;
TWriteBufferProcedure = procedure(Buffer: Pointer; Count: Integer) of object;
THttpContentCodingClass = class of THttpContentCoding;
THttpContentCoding = class(TObject)
private
FOutputWriteBuffer: TWriteBufferProcedure;
protected
class function GetActive: Boolean; virtual;
class function GetCoding: String; virtual;
property OutputWriteBuffer: TWriteBufferProcedure read FOutputWriteBuffer;
public
constructor Create(WriteBufferProc: TWriteBufferProcedure); virtual;
procedure Complete; virtual;
procedure WriteBuffer(Buffer: Pointer; Count: Integer); virtual; abstract;
property Active: Boolean read GetActive;
property Coding: String read GetCoding;
end;
THttpCCodIdentity = class(THttpContentCoding)
protected
class function GetCoding: String; override;
end;
THttpCCodStar = class(THttpContentCoding)
protected
class function GetCoding: String; override;
end;
THttpContCodItem = class(TObject)
private
FCodingClass: THttpContentCodingClass;
FEnabled : Boolean;
FQuality : Single;
function GetCoding: String;
function GetEnabled: Boolean;
public
constructor Create(const ACodingClass : THttpContentCodingClass;
const AQuality : Single);
property Coding: String read GetCoding;
property Enabled: Boolean read GetEnabled
write FEnabled;
property Quality: Single read FQuality
write FQuality;
end;
THttpContCodHandler = class(TObject)
private
FCodingList : TList;
FCodingParams : TList;
FOutputStream : PStream;
FInputWriteBuffer : TWriteBufferProcedure;
FOutputWriteBuffer : TWriteBufferProcedure;
FHeaderText : String;
FRecalcHeader : Boolean;
FEnabled : Boolean;
FUseQuality : Boolean;
function GetCodingItem(const Coding: String): THttpContCodItem;
function GetCodingEnabled(const Coding: String): Boolean;
procedure SetCodingEnabled(const Coding: String; const Value: Boolean);
function GetCodingQuality(const Coding: String): Single;
procedure SetCodingQuality(const Coding: String; const Value: Single);
function GetHeaderText: String;
function GetOutputStream: TStream;
procedure SetUseQuality(const Value: Boolean);
procedure ClearCodingList;
procedure InputWriteBuffer(Buffer: Pointer; Count: Integer);
public
constructor Create(OutStream : PStream;
WriteBufferProc : TWriteBufferProcedure);
destructor Destroy; override;
class procedure RegisterContentCoding(
const DefaultQuality : Single;
ContCodClass : THttpContentCodingClass);
class procedure UnregisterAuthenticateClass(
ContCodClass: THttpContentCodingClass);
procedure Complete;
function Prepare(const Encodings: String): Boolean;
property CodingEnabled[const Coding: String] : Boolean
read GetCodingEnabled
write SetCodingEnabled;
property CodingQuality[const Coding: String] : Single
read GetCodingQuality
write SetCodingQuality;
property OutputStream : TStream read GetOutputStream;
property HeaderText : String read GetHeaderText;
property Enabled : Boolean read FEnabled
write FEnabled;
property UseQuality : Boolean read FUseQuality
write SetUseQuality;
property WriteBuffer : TWriteBufferProcedure
read FInputWriteBuffer;
end;
implementation
resourcestring
ERR_GETCODING_OVERRIDE = 'GetCoding must be overriden in %s';
type
PContCoding = ^TContCoding;
TContCoding = record
ContClass : THttpContentCodingClass;
Quality : Single;
end;
TContCodingsList = class(TList)
public
constructor Create;
destructor Destroy; override;
procedure Add(const Quality: Single; AClass: THttpContentCodingClass);
function FindCoding(Coding: String): THttpContentCodingClass;
procedure Remove(AClass: THttpContentCodingClass);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TContCodingsList.Create;
begin
inherited Create;
Add(0, THttpCCodIdentity);
Add(0, THttpCCodStar);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TContCodingsList.Destroy;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Dispose(PContCoding(Items[I]));
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TContCodingsList.Add(
const Quality : Single;
AClass : THttpContentCodingClass);
var
NewRec: PContCoding;
begin
New(NewRec);
NewRec.Quality := Quality;
NewRec.ContClass := AClass;
inherited Add(NewRec);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TContCodingsList.FindCoding(Coding: String): THttpContentCodingClass;
var
I: Integer;
begin
for I := Count - 1 downto 0 do begin
if SameText(PContCoding(Items[I])^.ContClass.GetCoding,
Coding) then begin
Result := PContCoding(Items[I])^.ContClass;
Exit;
end;
end;
Result := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TContCodingsList.Remove(AClass: THttpContentCodingClass);
var
I : Integer;
P : PContCoding;
begin
for I := Count - 1 downto 0 do begin
P := PContCoding(Items[I]);
if P^.ContClass.InheritsFrom(AClass) then begin
Dispose(P);
Delete(I);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
var
ContCodings: TContCodingsList = nil;
function GetContentCodings: TContCodingsList;
begin
if ContCodings = nil then
ContCodings := TContCodingsList.Create;
Result := ContCodings;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpContentCoding.Create(WriteBufferProc: TWriteBufferProcedure);
begin
inherited Create;
FOutputWriteBuffer := WriteBufferProc;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class function THttpContentCoding.GetActive: Boolean;
begin
Result := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class function THttpContentCoding.GetCoding: String;
const
BASE_CLASS_NAME = 'THttpContentCoding';
begin
if Pos(BASE_CLASS_NAME, ClassName) = 1 then
Result := Copy(ClassName, Length(BASE_CLASS_NAME) + 1, MAXINT)
else
raise EHttpContentCodingException.CreateFmt(ERR_GETCODING_OVERRIDE,
[ClassName]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContentCoding.Complete;
begin
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class function THttpCCodIdentity.GetCoding: String;
begin
Result := 'identity';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class function THttpCCodStar.GetCoding: String;
begin
Result := '*';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpContCodItem.Create(
const ACodingClass : THttpContentCodingClass;
const AQuality : Single);
begin
inherited Create;
FCodingClass := ACodingClass;
FEnabled := TRUE;
FQuality := AQuality;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodItem.GetCoding: String;
begin
Result := FCodingClass.GetCoding;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodItem.GetEnabled: Boolean;
begin
Result := FEnabled and FCodingClass.GetActive;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpContCodHandler.Create(
OutStream : PStream;
WriteBufferProc : TWriteBufferProcedure);
var
I: Integer;
begin
inherited Create;
FOutputStream := OutStream;
FInputWriteBuffer := InputWriteBuffer;
FOutputWriteBuffer := WriteBufferProc;
FHeaderText := '';
FRecalcHeader := TRUE;
FEnabled := FALSE;
FUseQuality := FALSE;
FCodingList := TList.Create;
FCodingParams := TList.Create;
GetContentCodings;
for I := 0 to ContCodings.Count - 1 do begin
FCodingParams.Add(THttpContCodItem.Create(
PContCoding(ContCodings.Items[I])^.ContClass,
PContCoding(ContCodings.Items[I])^.Quality));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpContCodHandler.Destroy;
var
I: Integer;
begin
ClearCodingList;
FCodingList.Free;
if FCodingParams <> nil then begin
for I := FCodingParams.Count - 1 downto 0 do
THttpContCodItem(FCodingParams.Items[I]).Free;
FCodingParams.Free;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.GetCodingItem(
const Coding: String): THttpContCodItem;
var
I: Integer;
begin
for I := FCodingParams.Count - 1 downto 0 do
if SameText(THttpContCodItem(FCodingParams.Items[I]).Coding,
Coding) then begin
Result := THttpContCodItem(FCodingParams.Items[I]);
Exit;
end;
Result := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.GetCodingEnabled(
const Coding: String): Boolean;
var
AItem: THttpContCodItem;
begin
AItem := GetCodingItem(Coding);
Result := (AItem <> nil) and AItem.Enabled;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.SetCodingEnabled(
const Coding : String;
const Value : Boolean);
var
AItem: THttpContCodItem;
begin
AItem := GetCodingItem(Coding);
if (AItem <> nil) and (AItem.Enabled <> Value) then begin
AItem.Enabled := Value;
FRecalcHeader := TRUE;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.GetCodingQuality(
const Coding: String): Single;
var
AItem: THttpContCodItem;
begin
AItem := GetCodingItem(Coding);
if AItem <> nil then
Result := AItem.Quality
else
Result := -1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.SetCodingQuality(
const Coding : String;
const Value : Single);
var
AItem: THttpContCodItem;
begin
AItem := GetCodingItem(Coding);
if (AItem <> nil) and (AItem.Quality <> Value) then begin
AItem.Quality := Value;
FRecalcHeader := TRUE;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.GetHeaderText: String;
var
ContItem : THttpContCodItem;
AddQuality : Boolean;
DecPos : Integer;
QualStr : String;
I : Integer;
begin
if not FEnabled then begin
Result := '';
Exit;
end;
if FRecalcHeader then begin
if UseQuality then begin
{ Quality will be added only if there are more than one coding enabled }
AddQuality := FCodingParams.Count > 0;
for I := FCodingParams.Count - 1 downto 0 do begin
if THttpContCodItem(FCodingParams.Items[I]).Enabled then begin
if AddQuality then
AddQuality := FALSE
else begin
AddQuality := TRUE;
Break;
end;
end;
end;
end
else
AddQuality := FALSE;
FHeaderText := '';
for I := 0 to FCodingParams.Count - 1 do begin
ContItem := THttpContCodItem(FCodingParams.Items[I]);
if ContItem.Enabled then begin
if AddQuality then begin
QualStr := FormatFloat('0.###', ContItem.Quality);
{ Force the point as decimal separator }
if DecimalSeparator <> '.' then begin
DecPos := Pos(DecimalSeparator, QualStr);
if DecPos > 0 then
QualStr[DecPos] := '.';
end;
if FHeaderText = '' then
FHeaderText := Format('%s;q=%s', [ContItem.Coding, QualStr])
else
FHeaderText := Format('%s, %s;q=%s',
[FHeaderText, ContItem.Coding,
QualStr]);
end
else if ContItem.Quality > 0 then begin
if FHeaderText = '' then
FHeaderText := ContItem.Coding
else
FHeaderText := Format('%s, %s',
[FHeaderText, ContItem.Coding]);
end;
end;
end;
FRecalcHeader := FALSE;
end;
Result := FHeaderText;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.GetOutputStream: TStream;
begin
Result := FOutputStream^;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.SetUseQuality(const Value: Boolean);
begin
if FUseQuality = Value then
Exit;
FUseQuality := Value;
FRecalcHeader := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure THttpContCodHandler.RegisterContentCoding(
const DefaultQuality : Single;
ContCodClass : THttpContentCodingClass);
begin
GetContentCodings.Add(DefaultQuality, ContCodClass);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure THttpContCodHandler.UnregisterAuthenticateClass(
ContCodClass: THttpContentCodingClass);
begin
if ContCodings <> nil then
ContCodings.Remove(ContCodClass);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.ClearCodingList;
var
I: Integer;
begin
if FCodingList <> nil then begin
for I := FCodingList.Count - 1 downto 0 do
THttpContentCoding(FCodingList.Items[I]).Free;
FCodingList.Clear;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.InputWriteBuffer(Buffer: Pointer; Count: Integer);
begin
if Assigned(OutputStream) then
OutputStream.WriteBuffer(Buffer^, Count);
FOutputWriteBuffer(Buffer, Count);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpContCodHandler.Complete;
var
I: Integer;
begin
for I := FCodingList.Count - 1 downto 0 do
THttpContentCoding(FCodingList[I]).Complete;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpContCodHandler.Prepare(const Encodings: String): Boolean;
var
EncList : TStringList;
AClass : THttpContentCodingClass;
ContCod : THttpContentCoding;
I : Integer;
begin
Result := TRUE;
ClearCodingList;
FInputWriteBuffer := InputWriteBuffer;
if not FEnabled or (Encodings = '') then
Exit;
EncList := TStringList.Create;
try
EncList.CommaText := Encodings;
for I := 0 to EncList.Count - 1 do begin
AClass := GetContentCodings.FindCoding(EncList[I]);
if AClass = nil then begin
Result := FALSE;
Break;
end;
ContCod := AClass.Create(FInputWriteBuffer);
FCodingList.Add(ContCod);
FInputWriteBuffer := ContCod.WriteBuffer;
end;
finally
EncList.Free;
end;
if not Result then begin
ClearCodingList;
FInputWriteBuffer := InputWriteBuffer;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
initialization
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
finalization
ContCodings.Free;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit uMukafaah;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics,
Controls, Forms, Dialogs, uModel,uPengurus,
System.Generics.Collections;
type
TMukafaahItem = class;
TMukafaah = class(TAppObject)
private
FBulan: Integer;
FMukafaahItems: TObjectList<TMukafaahItem>;
FNoBukti: string;
FTahun: Integer;
FTglBukti: TDateTime;
published
property Bulan: Integer read FBulan write FBulan;
property MukafaahItems: TObjectList<TMukafaahItem> read FMukafaahItems
write FMukafaahItems;
property NoBukti: string read FNoBukti write FNoBukti;
property Tahun: Integer read FTahun write FTahun;
property TglBukti: TDateTime read FTglBukti write FTglBukti;
end;
TMukafaahItem = class(TAppObjectItem)
private
FJabatan: string;
FJamDiniyah: Double;
FJamHifdh: Double;
FPengurus: TPengurus;
FPokok: Double;
FTunjanganJabatan: Double;
FTunjanganTransport: Double;
public
property Pengurus: TPengurus read FPengurus write FPengurus;
published
property Jabatan: string read FJabatan write FJabatan;
property JamDiniyah: Double read FJamDiniyah write FJamDiniyah;
property JamHifdh: Double read FJamHifdh write FJamHifdh;
property Pokok: Double read FPokok write FPokok;
property TunjanganJabatan: Double read FTunjanganJabatan write
FTunjanganJabatan;
property TunjanganTransport: Double read FTunjanganTransport write
FTunjanganTransport;
end;
implementation
end.
|
Unit TERRA_VertexFormat;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_Collections, TERRA_Stream,
TERRA_Vector2D, TERRA_Vector3D, TERRA_Vector4D, TERRA_Color;
Const
vertexPosition = 0;
vertexNormal = 1;
vertexTangent = 2;
vertexBone = 3;
vertexColor = 4;
vertexHue = 5;
vertexUV0 = 6;
vertexUV1 = 7;
vertexUV2 = 8;
vertexUV3 = 9;
vertexUV4 = 10;
MaxVertexAttributes = 11;
Type
VertexFormatAttribute = (
vertexFormatPosition,
vertexFormatNormal,
vertexFormatTangent,
vertexFormatBone,
vertexFormatHue,
vertexFormatColor,
vertexFormatUV0,
vertexFormatUV1,
vertexFormatUV2,
vertexFormatUV3,
vertexFormatUV4
);
VertexFormat = Set Of VertexFormatAttribute;
DataFormat = (typeNull, typeFloat, typeByte, typeVector2D, typeVector3D, typeVector4D, typeColor);
VertexData = Class;
Vertex = Class(CollectionObject)
Private
{$IFNDEF DISABLEALLOCOPTIMIZATIONS}
Class Function NewInstance:TObject; Override;
Procedure FreeInstance; Override;
{$ENDIF}
Protected
_Target:VertexData;
_VertexID:Integer;
Procedure Release(); Override;
Procedure GetFloat(Attribute:Cardinal; Out Value:Single);
Procedure GetColor(Attribute:Cardinal; Out Value:Color);
Procedure GetVector2D(Attribute:Cardinal; Out Value:Vector2D);
Procedure GetVector3D(Attribute:Cardinal; Out Value:Vector3D);
Procedure GetVector4D(Attribute:Cardinal; Out Value:Vector4D);
Procedure SetFloat(Attribute:Cardinal; Const Value:Single);
Procedure SetColor(Attribute:Cardinal; Const Value:Color);
Procedure SetVector2D(Attribute:Cardinal; Const Value:Vector2D);
Procedure SetVector3D(Attribute:Cardinal; Const Value:Vector3D);
Procedure SetVector4D(Attribute:Cardinal; Const Value:Vector4D);
Procedure Load(); Virtual; Abstract;
Procedure Save(); Virtual; Abstract;
Public
Constructor Create();
Function HasAttribute(Attribute:Cardinal):Boolean;
End;
SimpleVertex = Class(Vertex)
Protected
Procedure Load(); Override;
Procedure Save(); Override;
Public
Position:Vector3D;
End;
VertexClass = Class Of Vertex;
VertexIterator = Class(Iterator)
Protected
_Target:VertexData;
_LastIndex:Integer;
_CurrentVertex:Vertex;
Procedure Init(Target:VertexData; V:VertexClass);
Function ObtainNext():CollectionObject; Override;
Procedure Release(); Override;
Procedure JumpToIndex(Position: Integer); Override;
Public
Procedure Reset(); Override;
End;
VertexData = Class(Collection)
Protected
_Values:Array Of Single;
_Format:VertexFormat;
_VertexSize:Cardinal;
_ElementsPerVertex:Cardinal;
_Names:Array[0..Pred(MaxVertexAttributes)] Of TERRAString;
_Formats:Array[0..Pred(MaxVertexAttributes)] Of DataFormat;
_Offsets:Array[0..Pred(MaxVertexAttributes)] Of Integer;
Function GetAttributeOffsetInBytes(Attribute:Cardinal):Integer;
Function GetAttributeOffsetInFloats(Attribute:Cardinal):Integer;
Function GetAttributeSizeInBytes(Attribute:Cardinal):Integer;
Function GetAttributeSizeInFloats(Attribute:Cardinal):Integer;
Function GetAttributePosition(Index, Attribute:Cardinal):Integer;
Function GetVertexPosition(Index:Cardinal):Integer;
Procedure ExpectAttributeFormat(Attribute:Cardinal; Format:DataFormat);
Function GetBuffer:Pointer;
Public
Constructor Create(Format:VertexFormat; VertexCount:Integer);
Procedure Release(); Override;
Procedure ConvertToFormat(NewFormat:VertexFormat);
Procedure Read(Source:Stream);
Procedure Write(Dest:Stream);
Function HasAttribute(Attribute:Cardinal):Boolean;
Function HasAttributeWithName(Const Name:TERRAString):Boolean;
Procedure AddAttribute(Attribute:VertexFormatAttribute);
Procedure SetAttributeFormat(Attribute:Cardinal; Value:DataFormat);
Procedure SetAttributeName(Attribute:Cardinal; Const Value:TERRAString);
Function Bind(AbsoluteOffsets:Boolean):Boolean;
Function Clone():VertexData;
Procedure GetFloat(Index:Integer; Attribute:Cardinal; Out Value:Single);
Procedure GetColor(Index:Integer; Attribute:Cardinal; Out Value:Color);
Procedure GetVector2D(Index:Integer; Attribute:Cardinal; Out Value:Vector2D);
Procedure GetVector3D(Index:Integer; Attribute:Cardinal; Out Value:Vector3D);
Procedure GetVector4D(Index:Integer; Attribute:Cardinal; Out Value:Vector4D);
Procedure SetFloat(Index:Integer; Attribute:Cardinal; Const Value:Single);
Procedure SetColor(Index:Integer; Attribute:Cardinal; Const Value:Color);
Procedure SetVector2D(Index:Integer; Attribute:Cardinal; Const Value:Vector2D);
Procedure SetVector3D(Index:Integer; Attribute:Cardinal; Const Value:Vector3D);
Procedure SetVector4D(Index:Integer; Attribute:Cardinal; Const Value:Vector4D);
Function GetIterator():Iterator; Override;
Function GetIteratorForClass(V:VertexClass):VertexIterator;
Function GetVertex(V:VertexClass; Index:Integer):Vertex;
Procedure CopyBuffer(Other:VertexData);
Procedure CopyVertex(SourceIndex, DestIndex:Cardinal; SourceData:VertexData = Nil);
Procedure Resize(NewSize:Cardinal);
{Procedure SetFloat(Index, Attribute:Cardinal; Value:Single);
Procedure SetColor(Index, Attribute:Cardinal; Const Value:Color);
Procedure SetVector2D(Index, Attribute:Cardinal; Const Value:Vector2D);
Procedure SetVector3D(Index, Attribute:Cardinal; Const Value:Vector3D);
Procedure SetVector4D(Index, Attribute:Cardinal; Const Value:Vector4D);}
Property Format:VertexFormat Read _Format;
Property Size:Cardinal Read _VertexSize;
Property Buffer:Pointer Read GetBuffer;
End;
Function VertexFormatFromFlags(Value:Cardinal):VertexFormat;
Function VertexFormatToFlags(Const Value:VertexFormat):Cardinal;
Implementation
Uses TERRA_Error, TERRA_Log, TERRA_GraphicsManager, TERRA_Renderer
{$IFNDEF DISABLEALLOCOPTIMIZATIONS}, TERRA_StackObject{$ENDIF};
Const
DefaultAttributeNames:Array[0..Pred(MaxVertexAttributes)] Of TERRAString =
('terra_position',
'terra_normal',
'terra_tangent',
'terra_bone',
'terra_color',
'terra_hue',
'terra_UV0',
'terra_UV1',
'terra_UV2',
'terra_UV3',
'terra_UV4');
Function VertexFormatFromFlags(Value:Cardinal):VertexFormat;
Begin
Result := [];
Move(Value, Result, SizeOf(VertexFormat));
End;
Function VertexFormatToFlags(Const Value:VertexFormat):Cardinal;
Begin
Result := 0;
Move(Value, Result, SizeOf(VertexFormat));
End;
Function VertexFormatAttributeValue(Attr:VertexFormatAttribute):Cardinal;
Begin
Case Attr Of
vertexFormatPosition: Result := vertexPosition;
vertexFormatNormal: Result := vertexNormal;
vertexFormatTangent: Result := vertexTangent;
vertexFormatBone: Result := vertexBone;
vertexFormatHue: Result := vertexHue;
vertexFormatColor: Result := vertexColor;
vertexFormatUV0: Result := vertexUV0;
vertexFormatUV1: Result := vertexUV1;
vertexFormatUV2: Result := vertexUV2;
vertexFormatUV3: Result := vertexUV3;
vertexFormatUV4: Result := vertexUV4;
Else
Result := 0;
End;
End;
Function GetFormatSizeInBytes(Format:DataFormat):Integer;
Begin
Case Format Of
typeVector2D: Result := SizeOf(Vector2D);
typeVector3D: Result := SizeOf(Vector3D);
typeVector4D: Result := SizeOf(Vector4D);
typeFloat: Result := SizeOf(Single);
typeColor: Result := SizeOf(Color);
typeByte: Result := SizeOf(Byte);
Else
Result := 0;
End;
End;
Function GetFormatSizeInFloats(Format:DataFormat):Integer;
Begin
Case Format Of
typeNull: Result := 0;
typeVector2D: Result := 2;
typeVector3D: Result := 3;
typeVector4D: Result := 4;
Else
Result := 1;
End;
End;
Function GetDefaultAttributeFormat(Attribute:Cardinal):DataFormat;
Begin
Case Attribute Of
vertexPosition: Result := typeVector3D;
vertexNormal: Result := typeVector3D;
vertexTangent: Result := typeVector4D;
vertexColor: Result := typeColor;
vertexUV0,
vertexUV1,
vertexUV2,
vertexUV3,
vertexUV4: Result := typeVector2D;
Else
Result := typeFloat;
End;
End;
{ VertexData }
Constructor VertexData.Create(Format:VertexFormat; VertexCount:Integer);
Var
I:Integer;
VF:VertexFormatAttribute;
Begin
Self._Format := Format;
_ElementsPerVertex := 0;
_VertexSize := 0;
For VF:=vertexFormatPosition To vertexFormatUV4 Do
Begin
I := VertexFormatAttributeValue(VF);
_Names[I] := '';
If (VF In Format) Then
Begin
_Formats[I] := GetDefaultAttributeFormat(I);
_Offsets[I] := _ElementsPerVertex;
Inc(_ElementsPerVertex, Self.GetAttributeSizeInFloats(I));
Inc(_VertexSize, Self.GetAttributeSizeInBytes(I));
End Else
Begin
_Offsets[I] := -1;
_Formats[I] := typeNull;
End;
End;
Self._ItemCount := 0;
Self.Resize(VertexCount);
End;
Procedure VertexData.Release();
Begin
If (Assigned(_Values)) Then
Begin
SetLength(_Values, 0);
_Values := Nil;
End;
End;
Procedure VertexData.ExpectAttributeFormat(Attribute: Cardinal; Format: DataFormat);
Begin
{$IFDEF PC}
If (Attribute<MaxVertexAttributes)Then
Begin
If (_Formats[Attribute] <> Format) And (_Formats[Attribute] <> typeNull) Then
RaiseError('Trying to access attribute '+DefaultAttributeNames[Attribute]+' using invalid format!');
End;
{$ENDIF}
End;
Procedure VertexData.SetAttributeFormat(Attribute:Cardinal; Value:DataFormat);
Begin
If (Attribute<MaxVertexAttributes)Then
_Formats[Attribute] := Value;
End;
Procedure VertexData.SetAttributeName(Attribute: Cardinal; const Value:TERRAString);
Begin
If (Attribute<MaxVertexAttributes)Then
_Names[Attribute] := Value;
End;
Function VertexData.HasAttributeWithName(Const Name:TERRAString):Boolean;
Var
I:Integer;
Begin
For I:=0 To Pred(MaxVertexAttributes) Do
Begin
If ((Self._Names[I]<>'') And (StringEquals(_Names[I], Name))) Or (StringEquals(Name, DefaultAttributeNames[I])) Then
Begin
Result := True;
Exit;
End;
End;
Result := False;
End;
Function VertexData.HasAttribute(Attribute: Cardinal): Boolean;
Begin
Result := (GetAttributeOffsetInFloats(Attribute)>=0);
End;
Procedure VertexData.AddAttribute(Attribute:VertexFormatAttribute);
Var
NewFormat:VertexFormat;
Begin
If Self.HasAttribute(VertexFormatAttributeValue(Attribute)) Then
Exit;
NewFormat := Self.Format;
Include(NewFormat, Attribute);
Self.ConvertToFormat(NewFormat);
End;
Function VertexData.GetAttributeOffsetInFloats(Attribute: Cardinal): Integer;
Begin
If (Attribute<MaxVertexAttributes)Then
Result := _Offsets[Attribute]
Else
Result := -1;
End;
Function VertexData.GetAttributeOffsetInBytes(Attribute: Cardinal): Integer;
Begin
Result := GetAttributeOffsetInFloats(Attribute) * 4;
End;
Function VertexData.GetAttributeSizeInFloats(Attribute: Cardinal): Integer;
Begin
If (Attribute<MaxVertexAttributes)Then
Result := GetFormatSizeInFloats(_Formats[Attribute])
Else
Begin
Result := 0;
RaiseError('Invalid attribute: '+CardinalToString(Attribute));
End;
End;
Function VertexData.GetAttributeSizeInBytes(Attribute: Cardinal): Integer;
Begin
If (Attribute<MaxVertexAttributes)Then
Result := GetFormatSizeInBytes(_Formats[Attribute])
Else
Begin
Result := 0;
RaiseError('Invalid attribute: '+CardinalToString(Attribute));
End;
End;
Function VertexData.GetAttributePosition(Index, Attribute: Cardinal):Integer;
Var
Ofs:Cardinal;
Begin
Result := -1;
If (Index>=_ItemCount) Or (_Values = Nil) Then
Exit;
If (Attribute<MaxVertexAttributes)Then
Begin
If _Offsets[Attribute]>=0 Then
Begin
Result := Index * _ElementsPerVertex + _Offsets[Attribute];
Exit;
End;
End;
// IntToString(2);
//RaiseError('Attribute '+GetDefaultAttributeName(Attribute) +' does not exist in this buffer!');
End;
Procedure VertexData.Read(Source:Stream);
Var
NewSize:Integer;
Begin
Source.ReadInteger(NewSize);
Self.Resize(NewSize);
If Self.Count>0 Then
Source.Read(@_Values[0], Self._VertexSize * Self.Count);
End;
Procedure VertexData.Write(Dest:Stream);
Begin
Dest.WriteInteger(Self.Count);
If Self.Count>0 Then
Dest.Write(@_Values[0], Self._VertexSize * Self.Count);
End;
Function VertexData.GetVertexPosition(Index: Cardinal):Integer;
Begin
If Index>=_ItemCount Then
Result := -1
Else
Result := Index * _ElementsPerVertex;
End;
Procedure VertexData.GetFloat(Index:Integer; Attribute:Cardinal; Out Value:Single);
Var
Pos:Integer;
Begin
Pos := Self.GetAttributePosition(Index, Attribute);
If (Pos>=0) And (Pos<Length(_Values)) Then
Value := _Values[Pos]
Else
Value := 0.0;
End;
Procedure VertexData.SetFloat(Index:Integer; Attribute:Cardinal; Const Value:Single);
Var
Pos:Integer;
Begin
Pos := Self.GetAttributePosition(Index, Attribute);
If (Pos>=0) And (Pos<Length(_Values)) Then
_Values[Pos] := Value;
End;
Procedure VertexData.GetColor(Index:Integer; Attribute:Cardinal; Out Value:Color);
Begin
// ExpectAttributeFormat(Attribute, typeColor);
Self.GetFloat(Index, Attribute, Single(Value));
End;
Procedure VertexData.SetColor(Index:Integer; Attribute:Cardinal; Const Value:Color);
Begin
// ExpectAttributeFormat(Attribute, typeColor);
Self.SetFloat(Index, Attribute, Single(Value));
End;
Procedure VertexData.GetVector2D(Index:Integer; Attribute:Cardinal; Out Value:Vector2D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector2D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Begin
Value := VectorCreate2D(0.0, 0.0);
Exit;
End;
If (Pos<Length(_Values)) Then
Value.X := _Values[Pos]
Else
Value.X := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.Y := _Values[Pos]
Else
Value.Y := 0.0;
End;
Procedure VertexData.SetVector2D(Index:Integer; Attribute:Cardinal; Const Value:Vector2D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector2D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Exit;
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.X;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.Y;
End;
Procedure VertexData.GetVector3D(Index:Integer; Attribute:Cardinal; Out Value:Vector3D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector3D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Begin
Value := VectorCreate(0.0, 0.0, 0.0);
Exit;
End;
If (Pos<Length(_Values)) Then
Value.X := _Values[Pos]
Else
Value.X := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.Y := _Values[Pos]
Else
Value.Y := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.Z := _Values[Pos]
Else
Value.Z := 0.0;
End;
Procedure VertexData.SetVector3D(Index:Integer; Attribute:Cardinal; Const Value:Vector3D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector3D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Exit;
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.X;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.Y;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.Z;
End;
Procedure VertexData.GetVector4D(Index:Integer; Attribute:Cardinal; Out Value:Vector4D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector4D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Begin
Value := VectorCreate4D(0.0, 0.0, 0.0, 1.0);
Exit;
End;
If (Pos<Length(_Values)) Then
Value.X := _Values[Pos]
Else
Value.X := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.Y := _Values[Pos]
Else
Value.Y := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.Z := _Values[Pos]
Else
Value.Z := 0.0;
Inc(Pos);
If (Pos<Length(_Values)) Then
Value.W := _Values[Pos]
Else
Value.W := 1.0;
End;
Procedure VertexData.SetVector4D(Index:Integer; Attribute:Cardinal; Const Value:Vector4D);
Var
Pos:Integer;
Begin
// ExpectAttributeFormat(Attribute, typeVector4D);
Pos := Self.GetAttributePosition(Index, Attribute);
If Pos<0 Then
Exit;
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.X;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.Y;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.Z;
Inc(Pos);
If (Pos<Length(_Values)) Then
_Values[Pos] := Value.W;
End;
Function VertexData.Bind(AbsoluteOffsets:Boolean):Boolean;
Var
I:Integer;
BaseOfs:PtrUInt;
AttrOfs:Pointer;
Name:TERRAString;
Shader:ShaderInterface;
Begin
Result := False;
If Self._Values = Nil Then
Exit;
GraphicsManager.Instance.Renderer.SetVertexSource(Self);
Shader := GraphicsManager.Instance.Renderer.ActiveShader;
If Not Assigned(Shader) Then
Begin
Log(logWarning, 'VBO', 'No shader!');
Exit;
End;
{If Self.HasAttribute(vertexHue) then
IntToString(2);}
{ For I:=0 To Pred(_AttributeCount) Do
Begin
_Attributes[I].Handle := Shader.GetAttributeHandle(_Attributes[I].Name);
If (_Attributes[I].Handle<0) Then
Log(logDebug, 'VBO', 'Attribute '+_Attributes[I].Name+' is missing from the shader.');
End;}
For I:=0 To Pred(MaxVertexAttributes) Do
Begin
If (_Offsets[I]<0) Then
Continue;
If (_Names[I] <> '' ) Then
Name := _Names[I]
Else
Name := DefaultAttributeNames[I];
BaseOfs := _Offsets[I] * 4;
If AbsoluteOffsets Then
AttrOfs := Pointer(PtrUInt(@(_Values[0])) + BaseOfs)
Else
AttrOfs := Pointer(BaseOfs);
GraphicsManager.Instance.Renderer.SetAttributeSource(Name, I, _Formats[I], AttrOfs);
End;
Result := True;
End;
Function VertexData.Clone: VertexData;
Var
I:Integer;
Begin
Result := VertexData.Create(Self._Format, Self._ItemCount);
If Assigned(_Values) Then
Move(_Values[0], Result._Values[0], Self._ItemCount * Self._VertexSize);
For I:=0 To Pred(MaxVertexAttributes) Do
Begin
Result._Names[I] := Self._Names[I];
Result._Formats[I] := Self._Formats[I];
Result._Offsets[I] := Self._Offsets[I];
End;
End;
Function VertexData.GetIteratorForClass(V:VertexClass):VertexIterator;
Begin
Result := VertexIterator.Create(Self);
Result.Init(Self, V);
End;
Function VertexData.GetIterator():Iterator;
Begin
Result := Self.GetIteratorForClass(SimpleVertex);
End;
Procedure VertexData.Resize(NewSize: Cardinal);
Var
NewLen, ExpectedLen:Integer;
Begin
If _ItemCount = NewSize Then
Exit;
_ItemCount := NewSize;
ExpectedLen := _ItemCount * _ElementsPerVertex;
If (_Values = Nil) Then
SetLength(_Values, ExpectedLen)
Else
Begin
NewLen := Length(_Values);
If NewLen<ExpectedLen Then
Begin
Repeat
SetLength(_Values, NewLen * 2);
NewLen := Length(_Values);
Until (NewLen >= ExpectedLen) Or (NewLen>65500);
End;
End;
End;
Procedure VertexData.CopyBuffer(Other: VertexData);
Begin
Move(Other._Values[0], Self._Values[0], _VertexSize * _ItemCount);
End;
Procedure VertexData.CopyVertex(SourceIndex, DestIndex:Cardinal; SourceData:VertexData);
Var
I:Integer;
A:Single;
B:Vector2D;
C:Vector3D;
D:Vector4D;
Begin
If SourceData = Nil Then
SourceData := Self;
For I:=0 To Pred(MaxVertexAttributes) Do
If (Self._Offsets[I]<0) Then
Continue // we don't need this attribute, skip it
Else
Begin
If (SourceData._Offsets[I]<0) Then
Begin
Continue; // source does not contain this!
End Else
Begin
Case Self._Formats[I] Of
typeVector4D:
Begin
SourceData.GetVector4D(SourceIndex, I, D);
Self.SetVector4D(DestIndex, I, D);
End;
typeVector3D:
Begin
SourceData.GetVector3D(SourceIndex, I, C);
Self.SetVector3D(DestIndex, I, C);
End;
typeVector2D:
Begin
SourceData.GetVector2D(SourceIndex, I, B);
Self.SetVector2D(DestIndex, I, B);
End;
Else
Begin
SourceData.GetFloat(SourceIndex, I, A);
Self.SetFloat(DestIndex, I, A);
End;
End;
End;
End;
End;
Function VertexData.GetVertex(V: VertexClass; Index: Integer): Vertex;
Begin
Result := V.Create();
Result._Target := Self;
Result._VertexID := Index;
Result.Load();
End;
Function VertexData.GetBuffer: Pointer;
Begin
If Assigned(_Values) Then
Result := @(_Values[0])
Else
Result := Nil;
End;
Procedure VertexData.ConvertToFormat(NewFormat: VertexFormat);
Var
Temp:VertexData;
I,J:Integer;
A:Single;
B:Vector2D;
C:Vector3D;
D:Vector4D;
E:Color;
Begin
If NewFormat = Self.Format Then
Exit;
Temp := VertexData.Create(NewFormat, Self.Count);
For I:=0 To Pred(Self.Count) Do
Begin
For J:=0 To Pred(MaxVertexAttributes) Do
If (Temp.HasAttribute(J)) Then
Begin
Case Temp._Formats[J] Of
typeVector2D:
Begin
Self.GetVector2D(I, J, B);
Temp.SetVector2D(I,J, B);
End;
typeVector3D:
Begin
Self.GetVector3D(I, J, C);
Temp.SetVector3D(I,J, C);
End;
typeVector4D:
Begin
Self.GetVector4D(I, J, D);
Temp.SetVector4D(I,J, D);
End;
typeFloat:
Begin
Self.GetFloat(I, J, A);
Temp.SetFloat(I,J, A);
End;
typeColor:
Begin
Self.GetColor(I, J, E);
Temp.SetColor(I,J, E);
End;
End;
End;
End;
SetLength(_Values, 0);
_Values := Temp._Values;
Temp._Values := Nil;
Temp._ItemCount := 0;
Self._Format := Temp._Format;
Self._VertexSize := Temp._VertexSize;
Self._ElementsPerVertex := Temp._ElementsPerVertex;
For J:=0 To Pred(MaxVertexAttributes) Do
Begin
Self._Formats[J] := Temp._Formats[J];
Self._Names[J] := Temp._Names[J];
Self._Offsets[J] := Temp._Offsets[J];
End;
ReleaseObject(Temp);
End;
{ VertexIterator }
Procedure VertexIterator.Init(Target:VertexData; V:VertexClass);
Begin
Self._Target := Target;
Self._LastIndex := 0;
Self._CurrentVertex := V.Create();
Self._CurrentVertex._Target := Target;
Self.JumpToIndex(0);
End;
Function VertexIterator.ObtainNext:CollectionObject;
Begin
If (Self.Index<_Target.Count) Then
Begin
Self.JumpToIndex(Self.Index);
Result := Self._CurrentVertex;
End Else
Result := Nil;
End;
Procedure VertexIterator.JumpToIndex(Position:Integer);
Var
ShouldLoad:Boolean;
Begin
If _CurrentVertex = Nil then
Begin
IntToString(2);
Exit;
End;
If _LastIndex <> Position Then
Begin
If (Self._CurrentVertex._VertexID>=0) Then
Self._CurrentVertex.Save();
ShouldLoad := True;
End Else
ShouldLoad := (Position=0);
If ShouldLoad Then
Begin
Self._CurrentVertex._VertexID := Position;
If Position>=0 Then
Self._CurrentVertex.Load();
_LastIndex := Position;
End;
// _CurrentVertex := Pointer(PtrUInt(_Target._Data) + VertexIndex * _Target._VertexSize);
End;
Procedure VertexIterator.Reset;
Begin
_LastIndex := 0;
End;
Procedure VertexIterator.Release;
Begin
ReleaseObject(Self._CurrentVertex);
Self._LastIndex := 0;
Inherited Release();
End;
{ Vertex }
Constructor Vertex.Create;
Begin
Self._VertexID := -1;
End;
Procedure Vertex.GetColor(Attribute:Cardinal; Out Value:Color);
Begin
_Target.GetColor(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.SetColor(Attribute:Cardinal; Const Value:Color);
Begin
_Target.SetColor(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.GetFloat(Attribute:Cardinal; Out Value:Single);
Begin
_Target.GetFloat(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.SetFloat(Attribute:Cardinal; Const Value:Single);
Begin
_Target.SetFloat(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.GetVector2D(Attribute:Cardinal; Out Value:Vector2D);
Begin
_Target.GetVector2D(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.SetVector2D(Attribute:Cardinal; Const Value:Vector2D);
Begin
_Target.SetVector2D(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.GetVector3D(Attribute:Cardinal; Out Value:Vector3D);
Begin
_Target.GetVector3D(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.SetVector3D(Attribute:Cardinal; Const Value:Vector3D);
Begin
_Target.SetVector3D(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.GetVector4D(Attribute:Cardinal; Out Value:Vector4D);
Begin
_Target.GetVector4D(Self._VertexID, Attribute, Value);
End;
Procedure Vertex.SetVector4D(Attribute:Cardinal; Const Value:Vector4D);
Begin
_Target.SetVector4D(Self._VertexID, Attribute, Value);
End;
Function Vertex.HasAttribute(Attribute: Cardinal): Boolean;
Begin
Result := _Target.HasAttribute(Attribute);
End;
Procedure Vertex.Release;
Begin
If (Self._VertexID>=0) Then
Begin
Self.Save();
_VertexID := -1;
End;
End;
{$IFNDEF DISABLEALLOCOPTIMIZATIONS}
Class Function Vertex.NewInstance: TObject;
Var
ObjSize, GlobalSize:Integer;
Begin
ObjSize := InstanceSize();
Result := StackAlloc(ObjSize);
InitInstance(Result);
End;
Procedure Vertex.FreeInstance;
Begin
End;
{$ENDIF}
{ SimpleVertex }
Procedure SimpleVertex.Load;
Begin
Self.GetVector3D(vertexPosition, Position);
End;
Procedure SimpleVertex.Save;
Begin
Self.SetVector3D(vertexPosition, Position);
End;
End.
|
unit ObjdsSampleClass;
interface
uses
SysUtils, Classes;
type
TDemo = class (TPersistent)
private
FAmount: Double;
FAge: Integer;
FName: string;
FValue: INteger;
procedure SetAge(const Value: Integer);
procedure SetName(const Value: string);
procedure SetAmount(const Value: Double);
procedure SetValue(const Value: INteger);
public
function Description: string;
published
property Name: string read FName write SetName;
property Age: Integer read FAge write SetAge;
property Amount: Double read FAmount write SetAmount;
property Value: INteger read FValue write SetValue;
end;
implementation
{ TDemo }
function TDemo.Description: string;
begin
Result := Format ('Name: %s, Age: %d, Value: %n',
[fName, FAge, FAmount]);
end;
procedure TDemo.SetAge(const Value: Integer);
begin
if Value < 100 then
FAge := Value
else
Raise Exception.Create ('more than 100 years');
end;
procedure TDemo.SetName(const Value: string);
begin
FName := Value;
end;
procedure TDemo.SetAmount(const Value: Double);
begin
FAmount := Value;
end;
procedure TDemo.SetValue(const Value: INteger);
begin
if Value > 1000 then
raise exception.Create ('too large');
FValue := Value;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.CloudStorage.Provider.Amazon
Description : CloudStorage Amazon provider
Author : Kike Pérez
Version : 1.8
Created : 14/10/2018
Modified : 07/10/2019
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.CloudStorage.Provider.Amazon;
{$i QuickLib.inc}
interface
uses
Classes,
System.SysUtils,
Quick.Commons,
Quick.CloudStorage,
Quick.Amazon;
type
TCloudStorageAmazonProvider = class(TCloudStorageProvider)
private
fAmazon : TQuickAmazon;
fAmazonID : string;
fAmazonKey: string;
fAmazonRegion : string;
fSecure : Boolean;
fCurrentBuckeet: string;
procedure SetSecure(const Value: Boolean);
public
constructor Create; overload;
constructor Create(const aAccountID, aAccountKey, aAWSRegion : string); overload;
destructor Destroy; override;
property Secure : Boolean read fSecure write SetSecure;
procedure OpenDir(const aPath : string); override;
function GetFile(const aPath: string; out stream : TStream) : Boolean; override;
end;
implementation
{ TCloudExplorerProvider }
constructor TCloudStorageAmazonProvider.Create;
begin
fAmazon := TQuickAmazon.Create;
fAmazon.AmazonProtocol := amHTTPS;
end;
constructor TCloudStorageAmazonProvider.Create(const aAccountID, aAccountKey, aAWSRegion : string);
begin
Create;
fAmazonID := aAccountID;
fAmazonKey := aAccountKey;
fAmazonRegion := aAWSRegion;
fAmazon.AccountName := fAmazonID;
fAmazon.AccountKey := fAmazonKey;
fAmazon.AWSRegion := TQuickAmazon.GetAWSRegion(fAmazonRegion);
end;
destructor TCloudStorageAmazonProvider.Destroy;
begin
if Assigned(fAmazon) then fAmazon.Free;
inherited;
end;
function TCloudStorageAmazonProvider.GetFile(const aPath: string; out stream : TStream) : Boolean;
begin
end;
procedure TCloudStorageAmazonProvider.OpenDir(const aPath : string);
var
lista : TAmazonObjects;
Blob : TAmazonObject;
i : Integer;
azurefilter : string;
DirItem : TCloudItem;
respinfo : TAmazonResponseInfo;
begin
if aPath = '..' then
begin
CurrentPath := RemoveLastPathSegment(CurrentPath);
end
else
begin
if CurrentPath = '' then CurrentPath := aPath
else CurrentPath := CurrentPath + aPath;
end;
if Assigned(OnBeginReadDir) then OnBeginReadDir(CurrentPath);
if CurrentPath.StartsWith('/') then CurrentPath := Copy(CurrentPath,2,CurrentPath.Length);
if (not CurrentPath.IsEmpty) and (not CurrentPath.EndsWith('/')) then CurrentPath := CurrentPath + '/';
Status := stRetrieving;
lista := fAmazon.ListObjects(RootFolder,CurrentPath,fAmazon.AWSRegion,respinfo);
try
if CurrentPath <> '' then
begin
if Assigned(OnGetListItem) then
begin
DirItem := TCloudItem.Create;
try
DirItem.Name := '..';
DirItem.IsDir := True;
DirItem.Date := 0;
OnGetListItem(DirItem);
finally
DirItem.Free;
end;
end;
end;
if respinfo.StatusCode = 200 then
begin
for Blob in lista do
begin
DirItem := TCloudItem.Create;
try
if Blob.Name.StartsWith(CurrentPath) then Blob.Name := StringReplace(Blob.Name,CurrentPath,'',[]);
if Blob.Name.Contains('/') then
begin
DirItem.IsDir := True;
DirItem.Name := Copy(Blob.Name,1,Blob.Name.IndexOf('/'));
end
else
begin
DirItem.IsDir := False;
DirItem.Name := Blob.Name;
DirItem.Size := Blob.Size;
DirItem.Date := Blob.Modified;
end;
if Assigned(OnGetListItem) then OnGetListItem(DirItem);
finally
DirItem.Free;
end;
end;
Status := stDone;
end
else Status := stFailed;
finally
lista.Free;
ResponseInfo.Get(respinfo.StatusCode,respinfo.StatusMsg);
end;
end;
procedure TCloudStorageAmazonProvider.SetSecure(const Value: Boolean);
begin
fSecure := Value;
if Value then fAmazon.AmazonProtocol := TAmazonProtocol.amHTTPS
else fAmazon.AmazonProtocol := TAmazonProtocol.amHTTP;
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Francois Piette
Original code by Arno Garrels, used with his permission.
Contact address <arno.garrels@gmx.de>
Description: WinSock2 API subset for Delphi.
Creation: October 2006
Version: 1.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
Apr 12, 2008 *Temporary, non-breaking Unicode changes* AG.
Aug 05, 2008 F. Piette added a cast to avoid warning for AnsiString to
String implicit convertion
Sep 21, 2008 Arno - Removed $EXTERNALSYM from some winsock2 symbols
(CBuilder compat.)
Jun 07, 2010 Arno fixed a late Unicode bug in WSocket2GetInterfaceList()
Apr 10, 2011 Another Unicode bug in record sockaddr.
May 06, 2011 Prepared for 64-bit.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsWinsock2;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFDEF COMPILER12_UP}
{ These are usefull for debugging !}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS ON}
{$WARN EXPLICIT_STRING_CAST OFF}
{$WARN EXPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
{$IFDEF COMPILER2_UP}{ Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
{ If NO_ADV_MT is defined, then there is less multithread code compiled. }
{$IFDEF DELPHI1}
{$DEFINE NO_ADV_MT}
{$ENDIF}
interface
uses
{$IFDEF CLR}
System.Text,
System.Runtime.InteropServices,
//Borland.VCL.Classes,
{$ENDIF}
{$IFNDEF CLR}
SysUtils,
{$IFDEF BCB}
Windows, Winsock,
{$ENDIF}
{$ENDIF}
OverbyteIcsLibrary,
OverbyteIcsTypes,
OverbyteIcsWinsock,
OverbyteIcsWSocket;
const
WSocket2Version = 100;
{$EXTERNALSYM SIO_GET_INTERFACE_LIST}
SIO_GET_INTERFACE_LIST = $4004747F;
{$EXTERNALSYM IFF_UP}
IFF_UP = $00000001;
{$EXTERNALSYM IFF_BROADCAST}
IFF_BROADCAST = $00000002;
{$EXTERNALSYM IFF_LOOPBACK}
IFF_LOOPBACK = $00000004;
{$EXTERNALSYM IFF_POINTTOPOINT}
IFF_POINTTOPOINT = $00000008;
{$EXTERNALSYM IFF_MULTICAST}
IFF_MULTICAST = $00000010;
type
{$EXTERNALSYM sockaddr}
sockaddr = record
sa_family : u_short; // address family
sa_data : array [0..13] of u_char; // up to 14 bytes of direct address
end;
{$IFDEF COMPILER16_UP} {$EXTERNALSYM in6_addr} {$ENDIF}
in6_addr = record
case Integer of
0: (Byte : array [0..15] of u_char);
1: (Word : array [0..7] of u_short);
2: (s6_bytes : array [0..15] of u_char);
3: (s6_addr : array [0..15] of u_char);
4: (s6_words : array [0..7] of u_short);
end;
TIn6Addr = in6_addr;
PIn6Addr = ^in6_addr;
//{$EXTERNALSYM sockaddr_in6_old}
sockaddr_in6_old = record
sin6_family : short; // AF_INET6
sin6_port : u_short; // Transport level port number
sin6_flowinfo : u_long; // IPv6 flow information
sin6_addr : in6_addr; // IPv6 address
end;
TSockAddrIn6Old = sockaddr_in6_old;
PSockAddrIn6Old = ^sockaddr_in6_old;
//{$EXTERNALSYM sockaddr_gen}
sockaddr_gen = record
case Integer of
0: (Address : sockaddr);
1: (AddressIn : sockaddr_in);
2: (AddressIn6 : sockaddr_in6_old);
end;
TSockAddrGen = sockaddr_gen;
PSockAddrGen = ^sockaddr_gen;
//{$EXTERNALSYM _INTERFACE_INFO}
_INTERFACE_INFO = record
iiFlags : u_long; // Interface flags
iiAddress : sockaddr_gen; // Interface address
iiBroadcastAddress : sockaddr_gen; // Broadcast address
iiNetmask : sockaddr_gen; // Network mask
end;
//{$EXTERNALSYM INTERFACE_INFO}
INTERFACE_INFO = _INTERFACE_INFO;
TInterfaceInfo = INTERFACE_INFO;
PInterfaceInfo = ^INTERFACE_INFO;
// Winsock2 utilities //
TInterfaceList = class(TList)
private
FOwnsObjects: Boolean;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
function GetItem(Index: Integer): PInterfaceInfo;
procedure SetItem(Index: Integer; IInfo: PInterfaceInfo);
public
constructor Create; overload;
constructor Create(AOwnsObjects: Boolean); overload;
function Add(IInfo: PInterfaceInfo): Integer;
function Extract(IInfo: PInterfaceInfo): PInterfaceInfo;
function Remove(IInfo: PInterfaceInfo): Integer;
function IndexOf(IInfo: PInterfaceInfo): Integer;
procedure Insert(Index: Integer; IInfo: PInterfaceInfo);
function First: PInterfaceInfo;
function Last: PInterfaceInfo;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
property Items[Index: Integer]: PInterfaceInfo read GetItem write SetItem; default;
end;
procedure WSocket2GetInterfaceList(InterfaceList : TInterfaceList); overload;
procedure WSocket2GetInterfaceList(StrList : TStrings); overload;
function WSocket2IsAddrInSubNet(saddr : TInAddr) : Boolean; overload;
function WSocket2IsAddrInSubNet(IpAddr : AnsiString) : Boolean; overload;
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.Add(IInfo: PInterfaceInfo): Integer;
begin
Result := inherited Add(IInfo);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TInterfaceList.Create;
begin
inherited Create;
FOwnsObjects := True;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TInterfaceList.Create(AOwnsObjects: Boolean);
begin
inherited Create;
FOwnsObjects := AOwnsObjects;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF Compiler17_UP}
{$HINTS OFF} // H2443 Inline function not expanded..
{$ENDIF}
function TInterfaceList.Extract(IInfo: PInterfaceInfo): PInterfaceInfo;
begin
Result := PInterfaceInfo(inherited Extract(IInfo));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.First: PInterfaceInfo;
begin
Result := PInterfaceInfo(inherited First);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.Remove(IInfo: PInterfaceInfo): Integer;
begin
Result := inherited Remove(IInfo);
end;
{$IFDEF Compiler17_UP}
{$HINTS ON}
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.GetItem(Index: Integer): PInterfaceInfo;
begin
Result := PInterfaceInfo(inherited Items[Index]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.IndexOf(IInfo: PInterfaceInfo): Integer;
begin
Result := inherited IndexOf(IInfo);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TInterfaceList.Insert(Index: Integer; IInfo: PInterfaceInfo);
begin
inherited Insert(Index, IInfo);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TInterfaceList.Last: PInterfaceInfo;
begin
Result := PInterfaceInfo(inherited Last);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TInterfaceList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if OwnsObjects then
if Action = lnDeleted then
Dispose(PInterfaceInfo(Ptr));
inherited Notify(Ptr, Action);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TInterfaceList.SetItem(Index: Integer; IInfo: PInterfaceInfo);
begin
inherited Items[Index] := IInfo;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure WSocket2GetInterfaceList(InterfaceList : TInterfaceList);
var
NumInterfaces : Integer;
BytesReturned : Cardinal;
PBuf : PAnsiChar;
P : PAnsiChar;
I : Integer;
Err : Integer;
BufSize : Cardinal;
PInfo : PInterfaceInfo;
s : TSocket;
begin
if not Assigned(InterfaceList) then
Exit;
InterfaceList.Clear;
BufSize := 20 * SizeOf(TInterfaceInfo);
GetMem(PBuf, BufSize);
try
s := WSocket_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s = INVALID_SOCKET) then
raise ESocketException.Create(
'WSocket2 GetInterfaceList: Socket creation failed');
try
while True do
begin
Err := WSocket_WSAIoCtl(s, SIO_GET_INTERFACE_LIST, nil, 0,
PBuf, BufSize, BytesReturned,
nil, nil);
if Err = SOCKET_ERROR then
Err := WSocket_WSAGetLastError;
case Err of
0 : Break;
WSAEFAULT :
begin
// How many interfaces make sense ??
if BufSize >= 10000 * SizeOf(TInterfaceInfo) then
raise ESocketException.Create(
'WSocket2 GetInterfaceList: Too many interfaces');
// No chance to get correct buffer size w/o probing
Inc(BufSize, 100 * SizeOf(TInterfaceInfo));
FreeMem(PBuf);
GetMem(PBuf, BufSize);
end;
else
raise ESocketException.Create('WSocket2 GetInterfaceList: ' +
GetWinsockErr(Err) + ' Error #' + IntToStr(Err));
end;
end;
finally
WSocket_Closesocket(s);
end;
if BytesReturned < SizeOf(TInterfaceInfo) then
Exit;
P := PBuf;
NumInterfaces := BytesReturned div SizeOf(TInterfaceInfo);
for I := 0 to NumInterfaces - 1 do
begin
New(PInfo);
PInfo^ := PInterfaceInfo(P)^;
InterfaceList.Add(PInfo);
Inc(P, SizeOf(TInterfaceInfo));
end;
finally
FreeMem(PBuf);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure WSocket2GetInterfaceList(StrList : TStrings); overload;
var
iList : TInterfaceList;
I : Integer;
begin
if not Assigned(StrList) then
Exit;
StrList.Clear;
iList := TInterfaceList.Create;
try
WSocket2GetInterfaceList(iList);
for I := 0 to IList.Count -1 do
StrList.Add(String(WSocket_inet_ntoa(
IList[I]^.iiAddress.AddressIn.sin_addr)));
finally
iList.Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WSocket2IsAddrInSubNet(saddr : TInAddr) : Boolean;
var
iList : TInterfaceList;
I : Integer;
iInfo : TInterfaceInfo;
begin
Result := FALSE;
iList := TInterfaceList.Create;
try
WSocket2GetInterfaceList(iList);
for I := 0 to iList.Count -1 do
begin
iInfo := IList[I]^;
if (iInfo.iiAddress.addressIn.sin_addr.S_addr and
iInfo.iiNetMask.addressIn.sin_addr.S_addr) =
(saddr.S_addr and iInfo.iiNetMask.addressIn.sin_addr.S_addr) then
begin
Result := TRUE;
Exit;
end;
end;
finally
iList.Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WSocket2IsAddrInSubNet(IpAddr : AnsiString) : Boolean;
var
saddr : TInAddr;
begin
if Length(IpAddr) = 0 then
raise ESocketException.Create('Invalid address');
saddr.S_addr := WSocket_inet_addr(PAnsiChar(IpAddr));
Result := WSocket2IsAddrInSubNet(saddr);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit TipTypes;
interface
uses
Graphics;
const
clUpBest = TColor($B0DCB0);
clUpGood = TColor($D0DCD0);
clDownBad = TColor($DCD0F0);
clDownWorst = TColor($DCA0F0);
type
TLeagueType = (ltIceHockey, ltFootball);
TMatchStatus = (msWillPlay, msPlayed);
TTableInfo = record
Team: integer;
Matchs: integer;
Wins: integer;
DrawWins: integer;
Draws: integer;
DrawLoss: integer;
Loss: integer;
GoalsPut: integer;
GoalsGot: integer;
Points: integer;
end;
TMatch = record
MatchNumber: integer;
MatchDate: TDateTime;
Round: integer;
TeamHome: integer;
TeamGuest: integer;
Status: TMatchStatus;
GoalsHome: array[1..4] of integer;
GoalsGuest: array[1..4] of integer;
GoalsATHome: integer;
GoalsATGuest: integer;
end;
TLeague = record
LeagueType: TLeagueType;
IsHome: boolean;
Level: integer;
Name: string[63];
RoundCount: integer;
TeamsUpBest: integer;
TeamsUpGood: integer;
TeamsDownBad: integer;
TeamsDownWorst: integer;
NameUpBest: string[15];
NameUpGood: string[15];
NameDownBad: string[15];
NameDownWorst: string[15];
PointsWins: integer;
PointsDrWi: integer;
PointsDraw: integer;
PointsDrLo: integer;
PointsLoss: integer;
TeamCount: integer;
TeamNames: array of string[63];
TableAll: array of TTableInfo;
TableHome: array of TTableInfo;
TableOut: array of TTableInfo;
Matchs: array of TMatch;
end;
TMatchTicket = record
TipNumber: integer;
TipMatchNumber: integer;
Team1Number: integer;
Team2Number: integer;
Tips: array[1..5] of double;
TipsValue: array[1..5] of double;
Tip: integer;
IsScore: boolean;
ScoreMatchNumber: integer;
end;
TTicket = record
TicketNumber: integer;
tiConst: array[1..40] of TMatchTicket;
tiGroup: array[1..10, 1..4] of TMatchTicket;
Bets: array[1..10] of integer;
end;
var
Leagues: array of TLeague;
implementation
end.
|
unit K493324121;
{* [Requestlink:493324121] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K493324121.pas"
// Стереотип: "TestCase"
// Элемент модели: "K493324121" MUID: (5260E08F0378)
// Имя типа: "TK493324121"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK493324121 = class(TRTFtoEVDWriterTest)
{* [Requestlink:493324121] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK493324121
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *5260E08F0378impl_uses*
//#UC END# *5260E08F0378impl_uses*
;
function TK493324121.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.10';
end;//TK493324121.GetFolder
function TK493324121.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '5260E08F0378';
end;//TK493324121.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK493324121.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Danila Manapsal, Don Craven, Joel Ivey
Description: Functions that emulate MUMPS functions.
Current Release: Version 1.1 Patch 40 (January 7, 2005))
*************************************************************** }
unit MFunStr;
interface
uses SysUtils, Dialogs;
{procedure and function prototypes}
function Piece(x: string; del: string; piece1: integer = 1; piece2: integer=0): string;
function Translate(passedString, identifier, associator: string): string;
const
U: string = '^';
implementation
function Translate(passedString, identifier, associator: string): string;
{TRANSLATE(string,identifier,associator)
Performs a character-for-character replacement within a string.}
var
index, position: integer;
newString: string;
substring: string;
begin
newString := ''; {initialize NewString}
for index := 1 to length(passedString) do begin
substring := copy(passedString,index,1);
position := pos(substring,identifier);
if position > 0 then
newString := newString + copy(associator,position,1)
else
newString := newString + copy(passedString,index,1)
end;
result := newString;
end;
function Piece(x: string; del: string; piece1: integer = 1; piece2: integer=0) : string;
{PIECE(string,delimiter,piece number)
Returns a field within a string using the specified delimiter.}
var
delIndex,pieceNumber: integer;
Resval: String;
Str: String;
begin
{initialize variables}
pieceNumber := 1;
Str := x;
{delIndex :=1;}
if piece2 = 0 then
piece2 := piece1;
Resval := '';
repeat
delIndex := Pos(del,Str);
if (delIndex > 0) or ((pieceNumber > Pred(piece1)) and (pieceNumber < (piece2+1))) then begin
if (pieceNumber > Pred(piece1)) and (pieceNumber < (piece2+1)) then
begin
if (pieceNumber > piece1) and (Str <> '') then
Resval := Resval + del;
if delIndex > 0 then
begin
Resval := Resval + Copy(Str,1,delIndex-1);
Str := Copy(Str,delIndex+Length(del),Length(Str));
end
else
begin
Resval := Resval + Str;
Str := '';
end;
end
else
Str := Copy(Str,delIndex+Length(del),Length(Str));
end
else if Str <> '' then
Str := '';
inc(pieceNumber);
until (pieceNumber > piece2);
Result := Resval;
end;
end.
|
unit MazeWork;
interface
uses
MazeMain, MazeGen, MazeSolve, MazePrint;
Procedure CreateMaze(var MazetoCreate: TMaze; var StatToWrite: TMazeStat; MazeSize: TMazeSize; MazeGenAlg: TMazeGenAlg);
Procedure SetMazeDefIOCells(const MazeToFind: TMaze; var StatToWrite: TMazeStat);
Procedure SolveMaze(const MazeSolve: TMaze; var Route, VisitedCells: TRoute; var StatToWrite: TMazeStat);
Procedure SetNewStartPos(const MazeToFind: TMaze; var StatToWrite: TMazeStat; Height, Width: Integer; X, Y: Integer);
Procedure SetNewExitPos(const MazeToFind: TMaze; var StatToWrite: TMazeStat; Height, Width: Integer; X, Y: Integer);
procedure GenMazeFromStat(var MazeToGen: TMaze; const Stat: TMazeStat);
implementation
uses
SysUtils, Windows;
//Set Array Size
Procedure SetMazeSize(var MazeToUse: TMaze; SizeMaze: TMazeSize);
begin
SetLength(MazeToUse, MazeSize[SizeMaze, 0], MazeSize[SizeMaze, 1])
end;
//Choose alg to generate maze
Procedure GenMaze(var MazeToGen: TMaze; const GenAlg: TMazeGenAlg; const EntryCell: TPos);
begin
case GenAlg of
HuntAKill: GenMazeHuntAKill(MazeToGen, EntryCell);
BackTrack: GenMazeBackTrack(MazeToGen, EntryCell);
Prim: GenMazePrim(MazeToGen, EntryCell);
end;
end;
//Choose alg to solve maze
procedure FindRoute(const MazeToAnalyze: TMaze; var ExitRoute, FullRoute: TRoute; Start, ExitC: TPos; SolveAlg: TMazeSolveAlg);
begin
case SolveAlg of
BFS: ExitRoute := SolveBFS(MazeToAnalyze, Start, ExitC, FullRoute);
DFS: ExitRoute := SolveDFS(MazeToAnalyze, Start, ExitC, FullRoute);
LeftHand: ExitRoute := SolveLeftHand(MazeToAnalyze, Start, ExitC, FullRoute);
RightHand: ExitRoute := SolveRightHand(MazeToAnalyze, Start, ExitC, FullRoute);
end;
end;
//Random Cell from maze
Function GetRandStartCell(SizeInd: TMazeSize): TPos;
begin
Result.PosX := Random(MazeSize[SizeInd, 1]);
Result.PosY := Random(MazeSize[SizeInd, 0]);
end;
//Create maze and write Statistic
Procedure CreateMaze(var MazeToCreate: TMaze; var StatToWrite: TMazeStat; MazeSize: TMazeSize; MazeGenAlg: TMazeGenAlg);
Var
Start, Stop: Cardinal;
begin
//Randomize;
//Write Stat
StatToWrite.DateTime := Now;
StatToWrite.MazeSize := MazeSize;
StatToWrite.GenStartPos := GetRandStartCell(MazeSize);
StatToWrite.MazeGenAlg := MazeGenAlg;
//Generate maze
SetMazeSize(MazeToCreate, MazeSize);
CleanMaze(MazeToCreate);
Start := GetTickCount;
StatToWrite.MazeSeed := RandSeed;
GenMaze(MazeToCreate, MazeGenAlg, StatToWrite.GenStartPos);
Stop := GetTickCount;
StatToWrite.TotalTime.GenTime := Stop-Start;
end;
//Write to statistic default Entry and Exit Points
procedure SetMazeDefIOCells(const MazeToFind: TMaze; var StatToWrite: TMazeStat);
begin
StatToWrite.StartPoint := GetStartCell(MazeToFind);
StatToWrite.EndPoint := GetExitCell(MazeToFind);
end;
//Solve maze and write statistic
Procedure SolveMaze(const MazeSolve: TMaze; var Route, VisitedCells: TRoute; var StatToWrite: TMazeStat);
Var
//Start, Stop: Cardinal;
iCounterPerSec: TLargeInteger;
T1, T2: TLargeInteger;
begin
//Write Stat
QueryPerformanceFrequency(iCounterPerSec);
//Start := GetTickCount;
QueryPerformanceCounter(T1);
//Find route
FindRoute(MazeSolve, Route, VisitedCells, StatToWrite.StartPoint, StatToWrite.EndPoint, StatToWrite.MazeSolveAlg);
QueryPerformanceCounter(T2);
//Stop := GetTickCount;
StatToWrite.TotalTime.SolvingTime := Round((T2-T1)/iCounterPerSec * 1000);
StatToWrite.VisitedCells.Route := Length(Route)-1;
StatToWrite.VisitedCells.FullRoute := Length(VisitedCells)-1;
end;
//Set new Entry and Exit pos. Chec for avilebels
Function SetMazeNewIOPos(const MazeToFind: TMaze; SizeMaze: TMazeSize; MazeDefPos: TPos;
Height, Width: Integer; PosX, PosY: Integer): TPos;
var
NewPos: TPos;
BlockSizeX, BlockSizeY: Integer;
begin
Result := MazeDefPos;
//Calc size of cell
CalcCellSize(Width, Height, SizeMaze, BlockSizeX, BlockSizeY);
//Calc New Pos
NewPos.PosX := PosX div BlockSizeX - 2;
NewPos.PosY := PosY div BlockSizeY - 2;
//Check for availability
if (NewPos.PosX >= 0) and (NewPos.PosY >= 0) and (NewPos.PosX < MazeSize[SizeMaze, 1])
and (NewPos.PosY < MazeSize[SizeMaze, 0])and (MazeToFind[NewPos.PosY, NewPos.PosX] = Pass) then
Result := NewPos;
end;
//Get user Entry point
Procedure SetNewStartPos(const MazeToFind: TMaze; var StatToWrite: TMazeStat; Height, Width: Integer; X, Y: Integer);
begin
StatToWrite.StartPoint := SetMazeNewIOPos(MazeToFind, StatToWrite.MazeSize, StatToWrite.StartPoint, Height, Width, X, Y);
end;
//Get user out point
Procedure SetNewExitPos(const MazeToFind: TMaze; var StatToWrite: TMazeStat; Height, Width: Integer; X, Y: Integer);
begin
StatToWrite.EndPoint := SetMazeNewIOPos(MazeToFind, StatToWrite.MazeSize, StatToWrite.EndPoint, Height, Width, X, Y);
end;
//Generate maze using statistic
procedure GenMazeFromStat(var MazeToGen: TMaze; const Stat: TMazeStat);
begin
SetMazeSize(MazeToGen, Stat.MazeSize);
CleanMaze(MazeToGen);
RandSeed := Stat.MazeSeed;
GenMaze(MazeToGen, Stat.MazeGenAlg, Stat.GenStartPos);
end;
end.
|
unit SettingsUnit;
// Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\SettingsUnit.pas"
// Стереотип: "Interfaces"
// Элемент модели: "Settings" MUID: (45EEAA69036E)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, IOUnit
, BaseTypesUnit
;
type
TPropertyStringID = PAnsiChar;
TPropertyType = (
PT_LONG
, PT_STRING
, PT_INT64
, PT_ULONG
, PT_BOOLEAN
);//TPropertyType
TPropertyDefinition = record
{* Интерфейс доступа к аттрибутам настройки. }
is_unique: ByteBool;
{* Определяет "уникальность" своства. Уникальные свойства имеют одинаковое значение во всех конфигурациях, другими словами, уникальное свойство всегда присутствует как бы в одном экземпляре.
Уникальные своства должны использоваться для настроек не зависящих от конфигурации.
Значение по умолчанию: false }
is_constant: ByteBool;
{* Определяет возможность изменения значения настройки.
Значение по умолчанию: false }
type: TPropertyType;
end;//TPropertyDefinition
TDefaultValuesChangesState = (
{* Статус проверки обновления значений настроек в предустановленных конфигурациях }
NO_CHANGES
{* значения не изменялись }
, UPDATED_WITH_COPY_ACTIVE_CONFIGURATION
{* Пользователь в момент смены настроек по умолчанию работает с одной из стандартных (предустановленных) конфигураций.
- Делается копия текущей конфигурации. Имя: <имя конфигурации> + (сохраненная). Если конфигурация с таким именем уже cуществует -- то (сохраненная 2).
- Для всех стандартных конфигураций настройки сбрасываются в значения по умолчанию. }
, UPDATED_WITH_ACTIVATE_PREDEFINED_CONFIGURATION
{* Пользователь в момент смены настроек работает с собственной конфигурацией (копией стандартной).
- Для всех стандартных конфигураций настройки сбрасываются в значения по умолчанию
- Пользователь переключается с его собственной конфигурации на "Стандартную" (первую в списке предустановленных) }
);//TDefaultValuesChangesState
InvalidValueType = class
{* Возвращается при попытке прочитать или присвоить через интерфейс ParameterValues значение по типу, который не совпадает с реальным типом значения (реальный тип можно получить через свойство value_type). }
end;//InvalidValueType
TConfigurationType = (
{* тип конфигурации, различаем две предустановленные: Стандартная и ГАРАНТ 5x, все остальные - пользовательские }
CT_STANDARD
, CT_GARANT5X
, CT_USER
);//TConfigurationType
IPropertyStringIDList = array of IString;
IBaseSettingsManager = interface
['{6BC8FA39-42F0-45D2-8211-D14043AD16DD}']
function GetBool(id: TPropertyStringID;
out value: Boolean): ByteBool; stdcall; { can raise InvalidValueType }
{* Чтение свойства типа Boolean.
При успехе возвращает true.
Если свойство не существует возвращает false.
Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType }
function GetInt64(id: TPropertyStringID;
out value: Int64): ByteBool; stdcall; { can raise InvalidValueType }
{* Чтение свойства типа int64.
При успехе возвращает true.
Если свойство не существует возвращает false.
Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType }
function GetLong(id: TPropertyStringID;
out value: Integer): ByteBool; stdcall; { can raise InvalidValueType }
{* Чтение свойства типа long.
При успехе возвращает true.
Если свойство не существует возвращает false.
Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType }
function GetString(id: TPropertyStringID;
out value: IString): ByteBool; stdcall; { can raise InvalidValueType }
{* Чтение свойства типа String.
При успехе возвращает true.
Если свойство не существует возвращает false.
Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType }
function GetUlong(id: TPropertyStringID;
out value: Cardinal): ByteBool; stdcall; { can raise InvalidValueType }
{* Чтение свойства типа unsigned long.
При успехе возвращает true.
Если свойство не существует возвращает false.
Если тип свойства не соответствует требуемому поднимается исключение InvalidValueType }
procedure SetBool(id: TPropertyStringID;
value: Boolean); stdcall; { can raise InvalidValueType }
{* Запись свойства типа Boolean.
Если свойство не существует, то оно создается в текущей конфигурации, value записывается как значение по умолчанию и как текущее значение.
Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType }
procedure SetInt64(id: TPropertyStringID;
value: Int64); stdcall; { can raise InvalidValueType }
{* Запись свойства типа int64.
Если свойство не существует, то оно создается в текущей конфигурации, value записывается как значение по умолчанию и как текущее значение.
Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType }
procedure SetLong(id: TPropertyStringID;
value: Integer); stdcall; { can raise InvalidValueType }
{* Запись свойства типа long.
Если свойство не существует, то оно создается в текущей конфигурации, value записывается как значение по умолчанию и как текущее значение.
Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType }
procedure SetString(id: TPropertyStringID;
value: PAnsiChar); stdcall; { can raise InvalidValueType }
{* Запись свойства типа String.
Если свойство не существует, то оно создается в текущей конфигурации, value записывается как значение по умолчанию и как текущее значение.
Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType }
procedure SetUlong(id: TPropertyStringID;
value: Cardinal); stdcall; { can raise InvalidValueType }
{* Запись свойства типа unsigned long.
Если свойство не существует, то оно создается в текущей конфигурации, value записывается как значение по умолчанию и как текущее значение.
Если тип свойства не соответствует устанавливаемому поднимается исключение InvalidValueType }
function IsExist(id: TPropertyStringID): ByteBool; stdcall;
{* возвращает true, если параметр с таким именем существует }
end;//IBaseSettingsManager
ISettingsManager = interface(IBaseSettingsManager)
{* Интерфейс работы с настройками. Обеспечивает создание новых свойств и их получение. Свойство характеризуется строковым идентификатором.
Интерфейс может быть получен
1. Из интерфейса Common, в этом случае он обеспечивает доступ к свойствам активной конфигурации.
2. Из интерфейса Configuration, в этом случае обеспечивается работа со свойствами конкретной конфигурации. }
['{C2012FB8-DEC6-408A-8937-3D7E13CBC830}']
procedure RestoreDefault(id: TPropertyStringID); stdcall; { can raise CanNotFindData }
{* Устанавливает указанному свойству текущее значение равными значению по умолчанию }
procedure SaveAsDefault(id: TPropertyStringID); stdcall; { can raise CanNotFindData }
{* записывает текущее значение свойства в качестве его значения по умолчанию }
function GetDefinition(id: TPropertyStringID;
var definition: TPropertyDefinition): ByteBool; stdcall;
{* возвращает структуру с атрибутами настройки }
function IsChanged(id: TPropertyStringID): ByteBool; stdcall;
{* возвращает true, если текущее значение НЕ равно значению по умолчанию, в противном случае возвращает false }
function IsChangedSet(const id_list: IPropertyStringIDList): ByteBool; stdcall;
end;//ISettingsManager
ConfigurationIsActiveNow = class
end;//ConfigurationIsActiveNow
IConfiguration = interface
{* Интерфейс обеспечивающий работу с конкретной конфигурацией, является элементом списка конфигураций. }
['{CB09ACB5-D582-477A-8D4F-98FC3766A1F9}']
procedure GetName; stdcall;
procedure SetName(const aValue); stdcall;
procedure GetHint; stdcall;
procedure SetHint(const aValue); stdcall;
function GetType: TConfigurationType; stdcall;
function GetIsReadonly: ByteBool; stdcall;
function GetId: Cardinal; stdcall;
procedure RestoreDefaultValues; stdcall;
{* устанавливает для всех свойств конфигурации начальные значения }
procedure SaveValuesAsDefault; stdcall;
{* записывает текущие значения для всех свойств в качестве значений по умолчанию }
procedure Copy(out aRet
{* IConfiguration }); stdcall;
{* возвращает копию конфигурации }
procedure GetSettings(out aRet
{* ISettingsManager }); stdcall;
property Name:
read GetName
write SetName;
{* Имя конфигурации }
property Hint:
read GetHint
write SetHint;
{* Комментарий или пояснение к конфигурации }
property Type: TConfigurationType
read GetType;
property IsReadonly: ByteBool
read GetIsReadonly;
{* определяет возможность изменения значений по умолчанию для конфигурации }
property Id: Cardinal
read GetId;
end;//IConfiguration
ConfigurationsNotDefined = class
end;//ConfigurationsNotDefined
IDefaultValuesChangesIndicator = interface
{* Результат проверки обновления значений настроек в предустановленных конфигурациях
если sate == UPDATED_WITH_COPY_ACTIVE_CONFIGURATION, то configuration содержит вновь созданную пользовательскую конфигурацию - копию активной предустановленной
если state == UPDATED_WITH_ACTIVATE_PREDEFINED_CONFIGURATION, то configuration содержит предустановленную, на которую переключили пользователя }
['{168D579E-071E-4626-93BD-7566FCAB780E}']
function GetState: TDefaultValuesChangesState; stdcall;
procedure GetConfiguration; stdcall;
property State: TDefaultValuesChangesState
read GetState;
property Configuration:
read GetConfiguration;
end;//IDefaultValuesChangesIndicator
IConfigurations = array of IConfiguration;
IConfigurationManager = interface
{* Интерфейс обеспечивающий работу со списком конфигураций. Доступен через интерфейс Common. }
['{C0C7A25C-7378-40EA-9593-32B590CC6D8E}']
procedure GetConfigurations; stdcall;
procedure SetActive(const configuration: IConfiguration); stdcall;
{* Устанавливает заданную конфигурацией активной (текущей для интерфейса Settings, полученного через Common) }
procedure Remove(const configuration: IConfiguration); stdcall; { can raise ConstantModify, ConfigurationIsActiveNow }
{* Удаляет заданную конфигурацию. В случае попытки удалить активную конфигурацию возбуждает исключение ConfigurationIsActiveNow }
procedure GetActive(out aRet
{* IConfiguration }); stdcall;
{* возвращает активную конфигурацию }
procedure DefaultValuesUpdateCheck(out aRet
{* IDefaultValuesChangesIndicator }); stdcall;
function GetActiveId: Integer; stdcall;
{* возвращает идентификатор активной конфигурации }
procedure Logout; stdcall;
{* метод дёргается при выходе из системы }
property Configurations:
read GetConfigurations;
end;//IConfigurationManager
IPermanentSettingsManager = interface(IBaseSettingsManager)
{* настройки, не зависящие от конфигураций }
['{4983A1B9-5021-4CE1-8C13-912831395FB8}']
end;//IPermanentSettingsManager
implementation
uses
l3ImplUses
;
end.
|
unit GX_BackupOptions;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, GX_BaseForm;
type
TfmBackupOptions = class(TfmBaseForm)
gbBackupOptions: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
cbPassword: TCheckBox;
lPassword: TLabel;
edPassword: TEdit;
rgScope: TRadioGroup;
cbSearchLibraryPath: TCheckBox;
procedure cbPasswordClick(Sender: TObject);
end;
implementation
uses Graphics, GX_GenericUtils;
{$R *.dfm}
procedure TfmBackupOptions.cbPasswordClick(Sender: TObject);
begin
edPassword.Enabled := cbPassword.Checked;
if edPassword.Enabled then
begin
edPassword.Color := clWindow;
TryFocusControl(edPassword);
end
else
edPassword.Color := clBtnface;
edPassword.Refresh;
end;
end.
|
unit TTSCOLLTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSCOLLRecord = record
PLenderNum: String[4];
PCollCode: String[8];
PAutoApplyItems: Boolean;
PDescription: String[30];
PRate: Currency;
End;
TTTSCOLLBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSCOLLRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSCOLL = (TTSCOLLPrimaryKey);
TTTSCOLLTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCollCode: TStringField;
FDFAutoApplyItems: TBooleanField;
FDFDescription: TStringField;
FDFRate: TCurrencyField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCollCode(const Value: String);
function GetPCollCode:String;
procedure SetPAutoApplyItems(const Value: Boolean);
function GetPAutoApplyItems:Boolean;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPRate(const Value: Currency);
function GetPRate:Currency;
procedure SetEnumIndex(Value: TEITTSCOLL);
function GetEnumIndex: TEITTSCOLL;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSCOLLRecord;
procedure StoreDataBuffer(ABuffer:TTTSCOLLRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCollCode: TStringField read FDFCollCode;
property DFAutoApplyItems: TBooleanField read FDFAutoApplyItems;
property DFDescription: TStringField read FDFDescription;
property DFRate: TCurrencyField read FDFRate;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCollCode: String read GetPCollCode write SetPCollCode;
property PAutoApplyItems: Boolean read GetPAutoApplyItems write SetPAutoApplyItems;
property PDescription: String read GetPDescription write SetPDescription;
property PRate: Currency read GetPRate write SetPRate;
published
property Active write SetActive;
property EnumIndex: TEITTSCOLL read GetEnumIndex write SetEnumIndex;
end; { TTTSCOLLTable }
procedure Register;
implementation
procedure TTTSCOLLTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCollCode := CreateField( 'CollCode' ) as TStringField;
FDFAutoApplyItems := CreateField( 'AutoApplyItems' ) as TBooleanField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFRate := CreateField( 'Rate' ) as TCurrencyField;
end; { TTTSCOLLTable.CreateFields }
procedure TTTSCOLLTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSCOLLTable.SetActive }
procedure TTTSCOLLTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSCOLLTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSCOLLTable.SetPCollCode(const Value: String);
begin
DFCollCode.Value := Value;
end;
function TTTSCOLLTable.GetPCollCode:String;
begin
result := DFCollCode.Value;
end;
procedure TTTSCOLLTable.SetPAutoApplyItems(const Value: Boolean);
begin
DFAutoApplyItems.Value := Value;
end;
function TTTSCOLLTable.GetPAutoApplyItems:Boolean;
begin
result := DFAutoApplyItems.Value;
end;
procedure TTTSCOLLTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TTTSCOLLTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TTTSCOLLTable.SetPRate(const Value: Currency);
begin
DFRate.Value := Value;
end;
function TTTSCOLLTable.GetPRate:Currency;
begin
result := DFRate.Value;
end;
procedure TTTSCOLLTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CollCode, String, 8, N');
Add('AutoApplyItems, Boolean, 0, N');
Add('Description, String, 30, N');
Add('Rate, Currency, 0, N');
end;
end;
procedure TTTSCOLLTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CollCode, Y, Y, N, N');
end;
end;
procedure TTTSCOLLTable.SetEnumIndex(Value: TEITTSCOLL);
begin
case Value of
TTSCOLLPrimaryKey : IndexName := '';
end;
end;
function TTTSCOLLTable.GetDataBuffer:TTTSCOLLRecord;
var buf: TTTSCOLLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCollCode := DFCollCode.Value;
buf.PAutoApplyItems := DFAutoApplyItems.Value;
buf.PDescription := DFDescription.Value;
buf.PRate := DFRate.Value;
result := buf;
end;
procedure TTTSCOLLTable.StoreDataBuffer(ABuffer:TTTSCOLLRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCollCode.Value := ABuffer.PCollCode;
DFAutoApplyItems.Value := ABuffer.PAutoApplyItems;
DFDescription.Value := ABuffer.PDescription;
DFRate.Value := ABuffer.PRate;
end;
function TTTSCOLLTable.GetEnumIndex: TEITTSCOLL;
var iname : string;
begin
result := TTSCOLLPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSCOLLPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSCOLLTable, TTTSCOLLBuffer ] );
end; { Register }
function TTTSCOLLBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..5] of string = ('LENDERNUM','COLLCODE','AUTOAPPLYITEMS','DESCRIPTION','RATE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 5) and (flist[x] <> s) do inc(x);
if x <= 5 then result := x else result := 0;
end;
function TTTSCOLLBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftBoolean;
4 : result := ftString;
5 : result := ftCurrency;
end;
end;
function TTTSCOLLBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCollCode;
3 : result := @Data.PAutoApplyItems;
4 : result := @Data.PDescription;
5 : result := @Data.PRate;
end;
end;
end.
|
unit TTSLogin;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, TicklerTypes, sBitBtn, sEdit, sGroupBox,
sCheckBox ;
type
TfrmTTSLogin = class(TForm)
GroupBox1: TsGroupBox;
edtLoginName: TsEdit;
GroupBox2: TsGroupBox;
edtPassword: TsEdit;
btnOK: TsBitBtn;
btnCancel: TsBitBtn;
chkAutologin: TsCheckBox;
procedure FormShow(Sender: TObject);
procedure edtLoginNameChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
FLoginName: string;
FLoginPass: string;
{ Private declarations }
public
{ Public declarations }
property LoginName:string read FLoginName;
property LoginPass:string read FLoginPass;
end;
implementation
{$R *.DFM}
procedure TfrmTTSLogin.FormShow(Sender: TObject);
begin
edtLoginName.SetFocus;
end;
procedure TfrmTTSLogin.edtLoginNameChange(Sender: TObject);
begin
btnOk.Enabled := trim(edtLoginName.text) <> '';
end;
procedure TfrmTTSLogin.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
FLoginName := trim(edtLoginName.text);
FLoginPass := trim(edtPassword.text);
if not applySecurity then
begin
FLoginName := Uppercase(FLoginName);
FLoginPass := Uppercase(FloginPass);
end;
end;
end.
|
{-----------------------------------------------------------------------------
hpp_events (historypp project)
Version: 1.0
Created: 05.08.2004
Author: Oxygen
[ Description ]
Some refactoring we have here, so now all event reading
routines are here. By event reading I mean getting usefull
info out of DB and translating it into human words,
like reading different types of messages and such.
[ History ]
1.5 (05.08.2004)
First version
[ Modifications ]
none
[ Known Issues ]
none
Copyright (c) Art Fedorov, 2004
-----------------------------------------------------------------------------}
unit hpp_events;
interface
uses
Windows, TntSystem, SysUtils, TntSysUtils, TntWideStrUtils,
m_globaldefs, m_api,
hpp_global, hpp_contacts;
function TimestampToString(Timestamp: DWord): WideString;
function ReadEvent(hDBEvent: THandle; UseCP: Cardinal = CP_ACP): THistoryItem;
//function MessageTypeToEventType(mt: TMessageTypes): Word;
// general routine
function GetEventText(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
// specific routines
function GetEventTextForMessage(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForFile(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForUrl(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForAuthRequest(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForYouWereAdded(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForSms(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForContacts(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForWebPager(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForEmailExpress(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForStatusChange(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
function GetEventTextForOther(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
implementation
function TimestampToString(Timestamp: DWord): WideString;
var
strdatetime: array [0..64] of Char;
dbtts: TDBTimeToString;
begin
dbtts.cbDest := sizeof(strdatetime);
dbtts.szDest := @strdatetime;
dbtts.szFormat := 'd s';
PluginLink.CallService(MS_DB_TIME_TIMESTAMPTOString,timestamp,Integer(@dbtts));
Result := strdatetime;
end;
procedure ReadStringTillZero(Text: PChar; TextLength: LongWord; var Result: String; var Pos: LongWord);
begin
while ((Text+Pos)^ <> #0) and (Pos < TextLength) do begin
Result := Result + (Text+Pos)^;
Inc(Pos);
end;
Inc(Pos);
end;
function GetEventTextForMessage(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
//PEnd: PWideChar;
lenW,lenA : Cardinal;
//buf: String;
PBlobEnd: Pointer;
PWideStart,
PWideEnd: PWideChar;
FoundWideEnd: Boolean;
begin
PBlobEnd := PChar(EventInfo.pBlob) + EventInfo.cbBlob;
PWideStart := Pointer(StrEnd(PChar(EventInfo.pBlob))+1);
lenA := PChar(PWideStart) - PChar(EventInfo.pBlob)-1;
PWideEnd := PWideStart;
FoundWideEnd := false;
While PWideEnd < PBlobEnd do begin
if PWideEnd^ = #0 then begin
FoundWideEnd := true;
break;
end;
Inc(PWideEnd);
end;
if FoundWideEnd then begin
lenW := PWideEnd - PWideStart;
if lenA = lenW then
SetString(Result,PWideStart,lenW)
else
Result := AnsiToWideString(PChar(EventInfo.pBlob),UseCP);
end else
Result := AnsiToWideString(PChar(EventInfo.pBlob),UseCP);
end;
function GetEventTextForUrl(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
BytePos:LongWord;
Url,Desc: String;
begin
BytePos:=0;
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Url,BytePos);
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Desc,BytePos);
Result := WideFormat(AnsiToWideString(Translate('URL: %s'),hppCodepage),[AnsiToWideString(url+#13#10+desc,UseCP)]);
end;
function GetEventTextForFile(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
BytePos: LongWord;
FileName,Desc: String;
begin
//blob is: sequenceid(DWORD),filename(ASCIIZ),description(ASCIIZ)
BytePos:=4;
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Filename,BytePos);
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Desc,BytePos);
if (EventInfo.Flags and DBEF_SENT)>0 then
Result := AnsiToWideString(Translate('Outgoing file transfer: %s'),hppCodepage)
else
Result := AnsiToWideString(Translate('Incoming file transfer: %s'),hppCodepage);
Result := WideFormat(Result,[AnsiToWideString(FileName+#13#10+Desc,UseCP)]);
end;
function GetEventTextForAuthRequest(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
BytePos: LongWord;
uin,hContact: integer;
Nick,Name,Email,Reason: String;
NickW,ReasonW,ReasonUTF,ReasonACP: WideString;
begin
//blob is: uin(DWORD), hContact(DWORD), nick(ASCIIZ), first(ASCIIZ), last(ASCIIZ), email(ASCIIZ)
uin := PDWord(EventInfo.pBlob)^;
hContact := PInteger(Integer(Pointer(EventInfo.pBlob))+SizeOf(Integer))^;
BytePos:=8;
// read nick
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Nick,BytePos);
if Nick='' then
NickW := GetContactDisplayName(hContact)
else
NickW := AnsiToWideString(Nick,CP_ACP);
// read first name
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Name,BytePos);
Name := Name+' ';
// read last name
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Name,BytePos);
Name := Trim(Name);
if Name <> '' then Name:=Name + ', ';
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Email,BytePos);
if Email <> '' then Email := Email + ', ';
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Reason,BytePos);
ReasonUTF := AnsiToWideString(Reason,CP_UTF8);
ReasonACP := AnsiToWideString(Reason,hppCodepage);
if (Length(ReasonUTF) > 0) and (Length(ReasonUTF) < Length(ReasonACP)) then
ReasonW := ReasonUTF
else
ReasonW := ReasonACP;
Result := WideFormat(AnsiToWideString(Translate('Authorisation request by %s (%s%d): %s'),hppCodepage),
[NickW,AnsiToWideString(Name+Email,hppCodepage),uin,ReasonW]);
end;
function GetEventTextForYouWereAdded(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
BytePos: LongWord;
uin,hContact: integer;
Nick,Name,Email: String;
NickW: WideString;
begin
//blob is: uin(DWORD), hContact(DWORD), nick(ASCIIZ), first(ASCIIZ), last(ASCIIZ), email(ASCIIZ)
Uin := PDWord(EventInfo.pBlob)^;
hContact := PInteger(Integer(Pointer(EventInfo.pBlob))+SizeOf(Integer))^;
BytePos:=8;
// read nick
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Nick,BytePos);
if Nick='' then
NickW := GetContactDisplayName(hContact)
else
NickW := AnsiToWideString(Nick,CP_ACP);
// read first name
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Name,BytePos);
Name := Name+' ';
// read last name
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Name,BytePos);
Name := Trim(Name);
if Name <> '' then Name:=Name + ', ';
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Email,BytePos);
if Email <> '' then Email := Email + ', ';
Result := WideFormat(AnsiToWideString(Translate('You were added by %s (%s%d)'),hppCodepage),
[NickW,AnsiToWideString(Name+Email,hppCodepage),uin]);
end;
function GetEventTextForSms(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
Result := AnsiToWideString(PChar(EventInfo.pBlob),UseCP);
end;
function GetEventTextForContacts(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
var
BytePos: LongWord;
Contacts: String;
begin
BytePos := 0;
Contacts := '';
While BytePos < EventInfo.cbBlob do begin
Contacts := Contacts + #13#10;
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Contacts,BytePos);
Contacts := Contacts + ' (';
ReadStringTillZero(Pointer(EventInfo.pBlob),EventInfo.cbBlob,Contacts,BytePos);
Contacts := Contacts + ')';
end;
if (EventInfo.Flags and DBEF_SENT)>0 then
Result := AnsiToWideString(Translate('Outgoing contacts: %s'),hppCodepage)
else
Result := AnsiToWideString(Translate('Incoming contacts: %s'),hppCodepage);
Result := WideFormat(Result ,[AnsiToWideString(Contacts,UseCP)]);
end;
function GetEventTextForWebPager(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
Result := AnsiToWideString(PChar(EventInfo.pBlob),hppCodepage);
end;
function GetEventTextForEmailExpress(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
Result := AnsiToWideString(PChar(EventInfo.pBlob),hppCodepage);
end;
function GetEventTextForStatusChange(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
Result := WideFormat(AnsiToWideString(Translate('Status change: %s'),hppCodePage),[GetEventTextForMessage(EventInfo,UseCP)]);
end;
function GetEventTextForOther(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
Result := AnsiToWideString(PChar(EventInfo.pBlob),UseCP);
end;
function GetEventText(EventInfo: TDBEventInfo; UseCP: Cardinal): WideString;
begin
case EventInfo.eventType of
EVENTTYPE_MESSAGE:
Result := GetEventTextForMessage(EventInfo,UseCP);
EVENTTYPE_URL:
Result := GetEventTextForUrl(EventInfo,UseCP);
EVENTTYPE_AUTHREQUEST:
Result := GetEventTextForAuthRequest(EventInfo,UseCP);
EVENTTYPE_ADDED:
Result := GetEventTextForYouWereAdded(EventInfo,UseCP);
EVENTTYPE_FILE:
Result := GetEventTextForFile(EventInfo,UseCP);
EVENTTYPE_CONTACTS:
Result := GetEventTextForContacts(EventInfo,UseCP);
ICQEVENTTYPE_SMS:
Result := GetEventTextForSms(EventInfo,UseCP);
ICQEVENTTYPE_WEBPAGER:
Result := GetEventTextForWebPager(EventInfo,UseCP);
ICQEVENTTYPE_EMAILEXPRESS:
Result := GetEventTextForEmailExpress(EventInfo,UseCP);
EVENTTYPE_STATUSCHANGE:
//Result := GetEventTextForStatusChange(EventInfo,UseCP);
Result := GetEventTextForStatusChange(EventInfo,hppCodepage);
else
Result := GetEventTextForOther(EventInfo,UseCP);
end;
end;
function GetEventInfo(hDBEvent: DWord): TDBEventInfo;
var
BlobSize:Integer;
begin
ZeroMemory(@Result,SizeOf(Result));
Result.cbSize:=SizeOf(Result);
BlobSize:=PluginLink.CallService(MS_DB_EVENT_GETBLOBSIZE,hDBEvent,0);
GetMem(Result.pBlob,BlobSize);
Result.cbBlob:=BlobSize;
PluginLink.CallService(MS_DB_EVENT_GET,hDBEvent,Integer(@Result));
end;
{function MessageTypeToEventType(mt: TMessageTypes): Word;
begin
Result := 9999;
if mtMessage in mt then begin
Result := EVENTTYPE_MESSAGE; exit; end;
if mtAdded in mt then begin
Result := EVENTTYPE_ADDED; exit; end;
if mtAuthRequest in mt then begin
Result := EVENTTYPE_AUTHREQUEST; exit; end;
if mtUrl in mt then begin
Result := EVENTTYPE_URL; exit; end;
if mtAuthRequest in mt then begin
Result := EVENTTYPE_AUTHREQUEST; exit; end;
if mtContacts in mt then begin
Result := EVENTTYPE_CONTACTS; exit; end;
if mtSMS in mt then begin
Result := ICQEVENTTYPE_SMS; exit; end;
if mtWebPager in mt then begin
Result := ICQEVENTTYPE_WEBPAGER; exit; end;
if mtEmailExpress in mt then begin
Result := ICQEVENTTYPE_EMAILEXPRESS; exit; end;
end;}
// reads event from hDbEvent handle
// reads all THistoryItem fields
// *EXCEPT* Proto field. Fill it manually, plz
function ReadEvent(hDBEvent: THandle; UseCP: Cardinal = CP_ACP): THistoryItem;
var
EventInfo: TDBEventInfo;
begin
ZeroMemory(@Result,SizeOf(Result));
Result.Height := -1;
// get details
EventInfo := GetEventInfo(hDBEvent);
// get module
Result.Module := EventInfo.szModule;
// get proto
Result.Proto := '';
// read text
Result.Text := GetEventText(EventInfo,UseCP);
Result.Text := TntAdjustLineBreaks(Result.Text);
Result.Text := TrimRight(Result.Text);
// free mememory for message
if Assigned(EventInfo.pBlob) then
FreeMem(EventInfo.pBlob);
// get incoming or outgoing
if ((EventInfo.flags and DBEF_SENT)=0) then
Result.MessageType := [mtIncoming]
else
Result.MessageType := [mtOutgoing];
// MS_DB_TIMESTAMPTOLOCAL should fix some issues
Result.Time := EventInfo.timestamp;
//Time := PluginLink.CallService(MS_DB_TIME_TIMESTAMPTOLOCAL,Time,0);
Result.EventType := EventInfo.EventType;
case EventInfo.EventType of
EVENTTYPE_MESSAGE:
Include(Result.MessageType,mtMessage);
EVENTTYPE_FILE:
Include(Result.MessageType,mtFile);
EVENTTYPE_URL:
Include(Result.MessageType,mtUrl);
EVENTTYPE_AUTHREQUEST:
Include(Result.MessageType,mtSystem);
EVENTTYPE_ADDED:
Include(Result.MessageType,mtSystem);
EVENTTYPE_CONTACTS:
Include(Result.MessageType,mtContacts);
ICQEVENTTYPE_SMS:
Include(Result.MessageType,mtSMS);
ICQEVENTTYPE_WEBPAGER:
//Include(Result.MessageType,mtWebPager);
Include(Result.MessageType,mtOther);
ICQEVENTTYPE_EMAILEXPRESS:
//Include(Result.MessageType,mtEmailExpress);
Include(Result.MessageType,mtOther);
EVENTTYPE_STATUSCHANGE:
Include(Result.MessageType,mtStatus);
else
Include(Result.MessageType,mtOther);
end;
end;
end.
|
unit table_func_with_units;
interface
uses table_func_lib,new_phys_unit_lib;
type
TVariantTableFunc = class (table_func)
private
fXUnitConv,fYUnitConv: TPhysUnit;
function GetVariantValue(xi: Variant): Variant;
function GetInverseVariantValue(yi: Variant): Variant;
procedure SetXUnit(value: string);
procedure SetYUnit(value: string);
public
function GetInverse: TVariantTableFunc; reintroduce; overload;
property value[xi: Variant]: Variant read GetVariantValue; default;
property inverse[yi: Variant]: Variant read GetInverseVariantValue;
published
property XUnit: string read fXUnit write SetXUnit;
property YUnit: string read fYUnit write SetYUnit;
end;
implementation
uses variants,sysUtils;
function TVariantTableFunc.GetVariantValue(xi: Variant): Variant;
var axi: Real;
tmp: Variant;
begin
tmp:=PhysUnitGetNumberIn(xi,fXUnitConv);
if VarIsNumeric(tmp) then
axi:=tmp
else Raise Exception.Create('argument of table function should be real');
Result:=PhysUnitCreateFromVariant(GetValue(axi),fYUnitConv);
end;
function TVariantTableFunc.GetInverseVariantValue(yi: Variant): Variant;
var ayi: Real;
tmp: Variant;
begin
tmp:=PhysUnitGetNumberIn(yi,fYUnitConv);
if VarIsNumeric(tmp) then
ayi:=tmp
else Raise Exception.Create('right now we work with real-valued table functions');
Result:=PhysUnitCreateFromVariant(InverseValue(ayi),fXUnitConv);
end;
procedure TVariantTableFunc.SetXUnit(value: string);
begin
fXUnit:=value;
fXUnitConv:=StrToPhysUnit(value);
end;
procedure TVariantTableFunc.SetYUnit(value: string);
begin
fYUnit:=value;
fYUnitConv:=StrToPhysUnit(value);
end;
function TVariantTableFunc.GetInverse: TVariantTableFunc;
var i: Integer;
begin
Result:=TVariantTableFunc.Create;
Result.zero_out_of_bounds:=zero_out_of_bounds;
Result.order:=order;
Result.XUnit:=YUnit;
Result.YUnit:=XUnit;
for i:=0 to count-1 do
Result.addpoint(Y[i],X[i]);
end;
end.
|
unit k2DocumentBuffer;
{ Библиотека "Эверест" }
{ Автор: Люлин А.В. © }
{ Модуль: k2DocumentBuffer - }
{ Начат: 16.03.2004 17:53 }
{ $Id: k2DocumentBuffer.pas,v 1.9 2014/04/29 13:38:56 lulin Exp $ }
// $Log: k2DocumentBuffer.pas,v $
// Revision 1.9 2014/04/29 13:38:56 lulin
// - вычищаем ненужные зависимости.
//
// Revision 1.8 2014/04/09 14:19:32 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.7 2014/04/08 17:13:26 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.6 2014/04/08 14:17:06 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.5 2009/12/23 19:13:24 lulin
// - сделан тест разбивщика на разделы.
//
// Revision 1.4 2009/09/07 10:17:49 voba
// - opt. Убрали ненужную буфферизацию бинарных данных
//
// Revision 1.3 2006/12/21 14:39:08 voba
// - new methods in Tk2DocumentBuffer: _FinishAll, IsFinished
//
// Revision 1.2 2006/01/10 08:42:20 lulin
// - не компилировался Эверест.
//
// Revision 1.1 2005/06/23 13:42:57 lulin
// - буфер документа переехал в папку K2.
//
// Revision 1.8.4.4 2005/06/22 17:53:03 lulin
// - типы переименованы в соответствии с названием библиотеки.
//
// Revision 1.8.4.3 2005/06/22 17:34:09 lulin
// - генератор документа в памяти перенесен в "правильную" библиотеку.
//
// Revision 1.8.4.2 2005/06/22 17:06:34 lulin
// - cleanup.
//
// Revision 1.8.4.1 2005/05/18 12:42:46 lulin
// - отвел новую ветку.
//
// Revision 1.7.2.1 2005/04/28 09:18:28 lulin
// - объединил с веткой B_Tag_Box.
//
// Revision 1.7.4.1 2005/04/21 15:36:39 lulin
// - окончательно избавился от необходимости обертки.
//
// Revision 1.7 2005/03/28 11:32:07 lulin
// - интерфейсы переехали в "правильный" модуль.
//
// Revision 1.6 2005/03/16 19:21:53 lulin
// - переходим к _Ik2Tag.
//
// Revision 1.5 2004/11/04 14:40:35 lulin
// - bug fix: не падаем с AV если поток не был корректно открыт, а сообщаем об этом пользователю.
//
// Revision 1.4 2004/09/21 12:55:40 lulin
// - Release заменил на Cleanup.
//
// Revision 1.3 2004/06/30 12:04:06 law
// - изменен тип свойства TevDocumentBuffer.Root - Ik2TagWrap -> _Ik2Tag.
//
// Revision 1.2 2004/06/29 14:26:41 law
// - избавляемся от метода Tk2AtomR._Set.
//
// Revision 1.1 2004/03/16 15:20:47 law
// - new unit: evDocumentBuffer.
//
{$Include k2Define.inc }
interface
uses
k2InternalInterfaces,
k2Interfaces,
k2TagGen,
k2DocumentGenerator
;
type
Tk2DocumentBuffer = class(Tk2DocumentGenerator)
{*! Буфер образа документа. }
private
// property fields
f_Root : Tl3Variant;
protected
// property methods
procedure pm_SetRoot(Value: Tl3Variant);
{-}
protected
// internal methods
procedure Cleanup;
override;
{-}
procedure CloseStructure(NeedUndo: Boolean);
override;
{-вызывается на закрывающуюся скобку}
public
procedure FinishAll;
{-закрывает все открытые структуры}
function IsFinished : Boolean;
{-все открытые структуры закрыты?}
// public properties
property Root: Tl3Variant
read f_Root
write pm_SetRoot;
{* - корневой тег. }
property Tags;
end;//Tk2DocumentBuffer
implementation
uses
k2NullTagImpl
;
// start class Tk2DocumentBuffer
procedure Tk2DocumentBuffer.Cleanup;
{override;}
{-}
begin
Root := nil;
inherited;
end;
procedure Tk2DocumentBuffer.pm_SetRoot(Value: Tl3Variant);
{-}
begin
Value.SetRef(f_Root);
end;
procedure Tk2DocumentBuffer.CloseStructure(NeedUndo: Boolean);
{override;}
{-вызывается на закрывающуюся скобку}
begin
if (f_Tags <> nil) AND (f_Tags.Count = 1) then
begin
if not NeedUndo {AND not f_Tags.Empty }then
Root := f_Tags.Top^.Box
else
Root := nil;
end;//f_Tags <> nil..
inherited;
end;
procedure Tk2DocumentBuffer.FinishAll;
{-закрывает все открытые структуры}
begin
if (f_Tags <> nil) then
while f_Tags.Count > 0 do
Finish;
end;
function Tk2DocumentBuffer.IsFinished : Boolean;
{-все открытые структуры закрыты?}
begin
Result := (f_Tags = nil) or (f_Tags.Count = 0);
end;
end.
|
unit evDataObject;
{* Реализация интерфейса IDataObject для выделения текста редактора }
// Модуль: "w:\common\components\gui\Garant\Everest\evDataObject.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevDataObject" MUID: (48EF3978008D)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, l3StorableDataObject
, evdInterfaces
, nevBase
, l3Interfaces
, l3IID
;
type
TevDataObject = class(Tl3StorableDataObject)
{* Реализация интерфейса IDataObject для выделения текста редактора }
private
f_Filters: InevTagGenerator;
f_Block: IevdDataObject;
protected
function Store(aFormat: Tl3ClipboardFormat;
const aPool: IStream): Boolean; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function DoQueryGetData(const aFormatEtc: TFormatEtc): HResult; override;
function COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult; override;
{* Реализация запроса интерфейса }
procedure ClearFields; override;
public
constructor Create(const aBlock: IevdDataObject;
const aFormats: Tl3ClipboardFormats;
const aFilters: InevTagGenerator); reintroduce;
public
property Block: IevdDataObject
read f_Block;
end;//TevDataObject
implementation
uses
l3ImplUses
//#UC START# *48EF3978008Dimpl_uses*
//#UC END# *48EF3978008Dimpl_uses*
;
constructor TevDataObject.Create(const aBlock: IevdDataObject;
const aFormats: Tl3ClipboardFormats;
const aFilters: InevTagGenerator);
//#UC START# *48F4687B02D0_48EF3978008D_var*
//#UC END# *48F4687B02D0_48EF3978008D_var*
begin
//#UC START# *48F4687B02D0_48EF3978008D_impl*
inherited Create(aFormats);
f_Block := aBlock;
f_Filters := aFilters;
//#UC END# *48F4687B02D0_48EF3978008D_impl*
end;//TevDataObject.Create
function TevDataObject.Store(aFormat: Tl3ClipboardFormat;
const aPool: IStream): Boolean;
//#UC START# *48F37AC50290_48EF3978008D_var*
//#UC END# *48F37AC50290_48EF3978008D_var*
begin
//#UC START# *48F37AC50290_48EF3978008D_impl*
Result := f_Block.Store(aFormat, aPool, f_Filters);
//#UC END# *48F37AC50290_48EF3978008D_impl*
end;//TevDataObject.Store
procedure TevDataObject.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_48EF3978008D_var*
//#UC END# *479731C50290_48EF3978008D_var*
begin
//#UC START# *479731C50290_48EF3978008D_impl*
f_Block := nil;
f_Filters := nil;
inherited;
//#UC END# *479731C50290_48EF3978008D_impl*
end;//TevDataObject.Cleanup
function TevDataObject.DoQueryGetData(const aFormatEtc: TFormatEtc): HResult;
//#UC START# *48F359680368_48EF3978008D_var*
//#UC END# *48F359680368_48EF3978008D_var*
begin
//#UC START# *48F359680368_48EF3978008D_impl*
if (f_Block = nil) then
Result := OLE_E_NotRunning
else
Result := inherited DoQueryGetData(aFormatEtc);
//#UC END# *48F359680368_48EF3978008D_impl*
end;//TevDataObject.DoQueryGetData
function TevDataObject.COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult;
{* Реализация запроса интерфейса }
//#UC START# *4A60B23E00C3_48EF3978008D_var*
//#UC END# *4A60B23E00C3_48EF3978008D_var*
begin
//#UC START# *4A60B23E00C3_48EF3978008D_impl*
Result.SetOk;
if IID.EQ(IevdDataObject) then
IevdDataObject(Obj) := f_Block
else
if IID.EQ(IStream) then
Result := Tl3HResult_C(f_Block.QueryInterface(IID.IID, Obj))
else
if IID.EQ(Il3DataObjectInfo) then
Result := Tl3HResult_C(f_Block.QueryInterface(IID.IID, Obj))
else
Result := inherited COMQueryInterface(IID, Obj);
//#UC END# *4A60B23E00C3_48EF3978008D_impl*
end;//TevDataObject.COMQueryInterface
procedure TevDataObject.ClearFields;
begin
f_Block := nil;
inherited;
end;//TevDataObject.ClearFields
end.
|
unit konversi;
interface
uses tipe_data;
function isKabisat (t : integer) : boolean;
(*Mengembalikan nilai true bila tahun kabisat*)
function toHari (t : ttanggal) : integer;
(*Mengonversi dd/mm/yyyy menjadi jumlah hari*)
function selisihHari (t2,t1: ttanggal) : integer;
(*Menghitung selisih hari dari dua tanggal*)
function toStr (n : integer) : string;
(*Mengubah tipe data integer menjadi string*)
function toInt (s : string) : integer;
(*Mengonversi tipe data string menjadi integer*)
function stringToTanggal (s : string) : ttanggal;
(*Mengonversi string 'dd/mm/yyyy' menjadi type ttanggal*)
function tanggalToString (t : ttanggal) : string ;
(*Mengonversi type ttanggal menjadi string 'dd/mm/yyyy'*)
function batas (t: ttanggal ; n: integer) : ttanggal;
(*Menentukan tanggal batas untuk pengumpulan*)
function hash (t : string) : string;
(*Melakukan hash pada suatu string (password)*)
function unhash (t: string) : string;
(*Mengembalikan password dari bentuk hashnya ke semula*)
implementation
function isKabisat (t : integer) : boolean;
(*Mengembalikan nilai true bila tahun kabisat*)
(*Algoritma*)
begin
if ((t mod 4 = 0) and (t mod 100 <> 0)) or (t mod 400 = 0) then
begin
isKabisat := True;
end else
begin
isKabisat := False;
end;
end;
function toHari (t : ttanggal) : integer;
(*Mengonversi dd/mm/yyyy menjadi jumlah hari*)
(*Kamus Lokal*)
var
i : integer;
(*Algoritma*)
begin
toHari := 0; {Inisialisasi}
for i:=0 to t.tahun - 1 do
begin
if (isKabisat(i)) then
begin
toHari := toHari + 366;
end else
begin
toHari := toHari + 365;
end;
end;
if (isKabisat(t.tahun)) then
begin
case t.bulan of
1 : toHari:= toHari + t.tanggal;
2 : toHari:= tohari + 31 + t.tanggal;
3 : toHari:= tohari + 60 + t.tanggal;
4 : toHari:= toHari + 91 + t.tanggal;
5 : toHari:= toHari + 121 + t.tanggal;
6 : toHari:= toHari + 152 + t.tanggal;
7 : toHari:= toHari + 182 + t.tanggal;
8 : toHari:= toHari + 213 + t.tanggal;
9 : toHari:= toHari + 244 + t.tanggal;
10 : toHari:= toHari + 274 + t.tanggal;
11 : toHari:= toHari + 305 + t.tanggal;
12 : toHari:= toHari + 335 + t.tanggal;
end;
end else
begin
case t.bulan of
1 : toHari:= toHari + t.tanggal;
2 : toHari:= toHari + 31 + t.tanggal;
3 : toHari:= toHari + 59 + t.tanggal;
4 : toHari:= toHari + 90 + t.tanggal;
5 : toHari:= toHari + 120 + t.tanggal;
6 : toHari:= toHari + 151 + t.tanggal;
7 : toHari:= toHari + 181 + t.tanggal;
8 : toHari:= toHari + 212 + t.tanggal;
9 : toHari:= toHari + 243 + t.tanggal;
10 : toHari:= toHari + 273 + t.tanggal;
11 : toHari:= toHari + 304 + t.tanggal;
12 : toHari:= toHari + 334 + t.tanggal;
end;
end;
end;
function selisihHari (t2,t1: ttanggal) : integer;
(*Menghitung selisih hari dari dua tanggal*)
(*Algoritma*)
begin
selisihHari:= toHari(t2) - toHari(t1);
end;
function toStr (n : integer) : string;
(*Mengubah tipe data integer menjadi string*)
(*Kamus Lokal*)
var
s : string;
(*Algoritma*)
begin
str(n,s);
toStr := s;
end;
function toInt (s : string) : integer;
(*Mengonversi tipe data string menjadi integer*)
(*Kamus Lokal*)
var
num , error : integer;
(*Algoritma*)
begin
val(s,num,error);
if (error = 0) then
begin
toInt:= num;
end;
end;
function stringToTanggal (s : string) : ttanggal;
(*Mengonversi string 'dd/mm/yyyy' menjadi type ttanggal*)
(*Anggap masukan valid dd/mm/yyyy*)
(*Algoritma*)
begin
stringToTanggal.tanggal:= toInt(copy(s,1,2));
stringToTanggal.bulan:= toInt(copy(s,4,2));
stringToTanggal.tahun:= toInt(copy(s,7,4));
end;
function tanggalToString (t : ttanggal) : string ;
(*Mengonversi type ttanggal menjadi string 'dd/mm/yyyy'*)
(*Algoritma*)
begin
tanggalToString:='';
if (t.tanggal<10) then
begin
tanggalToString:= tanggaltoString + '0' + toStr(t.tanggal) + '/';
end else
begin
tanggalToString:= tanggaltoString + toStr(t.tanggal) + '/';
end;
if(t.bulan<10) then
begin
tanggalToString:= tanggaltoString + '0' + toStr(t.bulan) + '/';
end else
begin
tanggalToString:= tanggaltoString + toStr(t.bulan) + '/';
end;
tanggalToString:= tanggaltoString + toStr(t.tahun);
end;
function batas (t: ttanggal ; n: integer) : ttanggal;
(*Menentukan tanggal batas untuk pengumpulan*)
(*Algoritma*)
begin
batas.tanggal := t.tanggal + n;
if (t.bulan= 1) or (t.bulan= 3) or (t.bulan= 5) or (t.bulan= 7) or (t.bulan= 8) or (t.bulan= 10) or (t.bulan= 12) then
begin
if (batas.tanggal > 31) then
begin
batas.tanggal:= batas.tanggal-31;
if(t.bulan = 12) then
begin
batas.bulan:= 1;
batas.tahun:= t.tahun + 1;
end else
begin
batas.bulan:= t.bulan + 1;
batas.tahun:= t.tahun + 1;
end;
end else (*batas.tanggal <= 31*)
begin
batas.bulan:= t.bulan;
batas.tahun:= t.tahun;
end;
end else if (t.bulan= 4) or (t.bulan= 6) or (t.bulan= 9) or (t.bulan = 11) then
begin
if(batas.tanggal > 30) then
begin
batas.bulan:= t.bulan + 1;
batas.tanggal:= batas.tanggal - 30;
batas.tahun:= t.tahun;
end else
begin
batas.bulan:= t.bulan;
batas.tahun:= t.tahun;
end;
end else if (t.bulan = 2) then
begin
if(isKabisat(t.tahun)) then
begin
if (batas.tanggal>29) then
begin
batas.tanggal := batas.tanggal - 29;
batas.bulan := t.bulan +1;
batas.tahun:= t.tahun;
end else
begin
batas.bulan:= t.bulan;
batas.tahun:= t.tahun;
end;
end else
begin
if (batas.tanggal>28) then
begin
batas.tanggal := batas.tanggal - 28;
batas.bulan := t.bulan + 1;
batas.tahun:= t.tahun;
end else
begin
batas.bulan:= t.bulan;
batas.tahun:= t.tahun;
end;
end;
end;
end;
function hash(t: string) : string;
(*Mengubah suatu string ke dalam hashnya dengan teknik menggeser urutan karakter sebanyak 13*)
{Kamus Lokal}
var
i : integer;
d : string;
{Algoritma}
begin
d := '';
for i:=1 to Length(t) do begin
d := d + char(13 + ord(t[i]));
end;
hash := d;
end;
function unhash (t: string) : string;
(*Mengembalikan string dari hasil hash ke dalam bentuk semula (Invers fungsi hash) *)
{Kamus Lokal}
var
i : integer;
d : string;
{Algoritma}
begin
d := '';
for i:=1 to Length(t) do begin
d := d + char(ord(t[i])-13);
end;
unhash := d;
end;
end.
|
unit Unit_Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, TeePeg, ComCtrls;
type
TForm1 = class(TForm)
Memo2: TMemo;
Button1: TButton;
Memo3: TMemo;
PageControl1: TPageControl;
TabPEG: TTabSheet;
TabMath: TTabSheet;
MathPEG: TMemo;
PEGPEG: TMemo;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
PEG : TPEG;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
TeePEG_Rules;
procedure AddTokens(const PEG:TPeg; const AStrings:TStrings);
procedure ShowStack(const AParser:TParser);
procedure ShowRules(const AIdent:String; const ARules:Array of TRule; const APos:Integer);
var t : Integer;
tmp : String;
begin
for t:=0 to High(ARules) do
begin
if ARules[t] is TNamedRule then
tmp:=TNamedRule(ARules[t]).Name
else
tmp:=ARules[t].ClassName;
AStrings.Add(AIdent+tmp+' -> '+IntToStr(APos));
end;
end;
var Ident : String;
t : Integer;
begin
Ident:='';
for t:=Low(AParser.Stack) to High(AParser.Stack) do
begin
ShowRules(Ident,AParser.Stack[t].Rules,AParser.Stack[t].Position);
Ident:=Ident+' ';
end;
end;
begin
AStrings.BeginUpdate;
try
AStrings.Clear;
ShowStack(Peg.Rules.Parser);
finally
AStrings.EndUpdate;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
PEG_Log:=Memo3.Lines;
PEG:=TPEG.Create;
Memo2.Lines.Text:=PEG.Rules.AsString;
end;
procedure TForm1.Button1Click(Sender: TObject);
function FirstLines(const Quantity:Integer):String;
var t : Integer;
begin
result:='';
for t:=0 to Quantity-1 do
begin
if t>0 then
result:=result+#13#10;
result:=result+PEGPEG.Lines[t];
end;
end;
var tmp : String;
begin
PEG_Log.BeginUpdate;
try
PEG_Log.Clear;
//tmp:=Memo1.Lines[21]; //FirstLines(22);
// tmp:='11';
if PageControl1.ActivePage=TabPEG then
tmp:=PEGPEG.Text
else
tmp:=MathPEG.Text;
//tmp:='\t';
try
PEG.Load(tmp{Memo1.Lines});
finally
AddTokens(PEG, Memo2.Lines);
Memo2.Lines.Add('');
Memo2.Lines.Add('Parsed: '+tmp);
end;
finally
PEG_Log.EndUpdate;
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
PEG.Free;
end;
end.
|
unit xcodeproj;
{--------------------------------------------------------------------------------
* by Dmitry Boyarintsev - Oct 2014 *
* *
* license: free for use, but please leave a note to the origin of the library *
* *
* PBXcontainer unit is a library to read/write the pbx formatter file as a *
* whole The file structure is made to keep the reference in a complex objects *
* *
* Memory Management. *
* Cocoa is reference - counted library, thus the usage of an object *
* controlled natively by ref counting. *
* A bit trickier for pascal *
* Following rules are applied *
* * read-only property objects are freed by the host (obviously) *
* * other "freeing" operations are noted at "mmgr" comments *
* * any objects within key-value tables are freed *
* Alternative solution - implement ref counting! *
* *
--------------------------------------------------------------------------------}
interface
uses
Classes, SysUtils,
typinfo, pbxcontainer;
type
{ XCBuildConfiguration }
XCBuildConfiguration = class(PBXObject)
private
fname : string;
fbuildSettings: TPBXKeyValue;
public
constructor Create; override;
destructor Destroy; override;
published
property buildSettings : TPBXKeyValue read fbuildSettings;
property name: string read fname write fname;
end;
{ XCConfigurationList }
// mmgr: XCConfigurationList frees
// * content of buildConfigurations
XCConfigurationList = class(PBXObject)
private
fdefaultConfigurationIsVisible: string;
fdefaultConfigurationName: string;
fbuildConfigurations: TPBXObjectsList;
public
constructor Create; override;
destructor Destroy; override;
function addConfig(const aname: string): XCBuildConfiguration;
published
property buildConfigurations: TPBXObjectsList read fbuildConfigurations;
property defaultConfigurationIsVisible: string read fdefaultConfigurationIsVisible write fdefaultConfigurationIsVisible;
property defaultConfigurationName: string read fdefaultConfigurationName write fdefaultConfigurationName;
end;
{ PBXContainerItemProxy }
PBXContainerItemProxy = class(PBXObject)
private
FcontainerPortal : PBXObject;
fproxyType : string;
fremoteGlobalIDString: string;
fremoteInfo: string;
published
property containerPortal: PBXObject read fcontainerPortal write fcontainerPortal; // Object = 0AFA6EA519F60EFD004C8FD9 /* Project object */;
property proxyType: string read FproxyType write fproxyType;
property remoteGlobalIDString: string read fremoteGlobalIDString write fremoteGlobalIDString; //object = 0AFA6EAC19F60EFD004C8FD9;
property remoteInfo : string read fremoteInfo write fremoteInfo; // ttestGame;
end;
{ PBXFileReference }
PBXFileReference = class(PBXObject)
private
FexplicitFileType: string;
FincludeInIndex: string;
FlastKnownFileType: string;
Fname: string;
Fpath: string;
FsourceTree: string;
published
property explicitFileType: string read FexplicitFileType write FexplicitFileType;
property includeInIndex: string read FincludeInIndex write FincludeInIndex;
property lastKnownFileType: string read flastKnownFileType write flastKnownFileType;
property name: string read Fname write Fname;
property path: string read Fpath write Fpath;
property sourceTree: string read FsourceTree write FsourceTree;
end;
{ PBXBuildFile }
PBXBuildFile = class(PBXObject)
private
fFileRef : PBXFileReference;
published
property fileRef : PBXFileReference read ffileRef write ffileRef; // obj
end;
{ PBXBuildPhase }
// mmgr: on free
// * content of files
PBXBuildPhase = class(PBXObject)
private
fbuildActionMask : Integer;
ffiles: TPBXObjectsList;
frunOnlyForDeploymentPostprocessing: Boolean;
fname: string;
public
constructor Create; override;
destructor Destroy; override;
published
property buildActionMask: Integer read fbuildActionMask write fbuildActionMask;
property files: TPBXObjectsList read ffiles;
property name: string read fname write fname;
property runOnlyForDeploymentPostprocessing: Boolean read frunOnlyForDeploymentPostprocessing write frunOnlyForDeploymentPostprocessing;
end;
{ PBXFrameworksBuildPhase }
PBXFrameworksBuildPhase = class(PBXBuildPhase);
PBXResourcesBuildPhase = class(PBXBuildPhase);
PBXSourcesBuildPhase = class(PBXBuildPhase);
{ PBXShellScriptBuildPhase }
PBXShellScriptBuildPhase = class(PBXBuildPhase)
private
finputPaths: TPBXStringArray;
foutputPaths: TPBXStringArray;
fshellpath: string;
fshellScript: string;
public
constructor Create; override;
destructor Destroy; override;
published
property inputPaths: TPBXStringArray read finputPaths;
property outputPaths: TPBXStringArray read foutputPaths;
property shellPath: string read fshellpath write fshellPath;
property shellScript: string read fshellScript write fshellScript;
end;
{ PBXGroup }
// mmgt: PBXGroup owns children object (PBXGroup and PBXFileRefernece)
// and would free then on release;
// note, that PBXFileReference objects might be used in other places
PBXGroup = class(PBXObject)
private
fsourceTree : string;
fchildren: TPBXObjectsList;
fname: string;
fpath: string;
public
constructor Create; override;
destructor Destroy; override;
function addSubGroup(const aname: string): PBXGroup;
function findGroup(const aname: string): PBXGroup;
published
property children: TPBXObjectsList read fchildren;
property name: string read fname write fname;
property path: string read fpath write fpath;
property sourceTree: string read fsourceTree write fsourceTree;
end;
PBXVariantGroup = class(PBXGroup);
{ PBXNativeTarget }
// mmgr: PBXNativeTarget
// * buildConfigurationList
// * contents of buildPhases
// * contents of buildRules
// * content of dependencies
PBXNativeTarget = class(PBXObject)
private
fbuildConfigurationList: XCConfigurationList;
fname : string;
fproductName : string;
fproductReference : PBXObject;
fproductType : string;
fbuildPhases : TPBXObjectsList;
fbuildRules : TPBXObjectsList;
fdependencies : TPBXObjectsList;
public
constructor Create; override;
destructor Destroy; override;
published
property buildConfigurationList : XCConfigurationList read fbuildConfigurationList write fbuildConfigurationList; //= 0AFA6ED419F60F01004C8FD9 /* Build configuration list for PBXNativeTarget "ttestGame" */;
property buildPhases: TPBXObjectsList read fbuildPhases;
property buildRules: TPBXObjectsList read fbuildRules;
property dependencies: TPBXObjectsList read fdependencies;
property name: string read fname write fname;
property productName: string read fproductName write fproductName; // = ttestGame;
property productReference: PBXObject read fproductReference write fproductReference; // = 0AFA6EAD19F60EFE004C8FD9 /* ttestGame.app */;
property productType: string read fproductType write fproductType; // = "com.apple.product-type.application";
end;
{ PBXTargetDependency }
// mmgt:
// targetProxy - is freed
PBXTargetDependency = class(PBXObject)
private
ftargetProxy: PBXContainerItemProxy;
ftarget: PBXNativeTarget;
public
destructor Destroy; override;
published
property target : PBXNativeTarget read ftarget write ftarget;
property targetProxy: PBXContainerItemProxy read ftargetProxy write ftargetProxy; {* PBXContainerItemProxy *}
end;
{ PBXProject }
// mmgt: PBXProject frees the following property objects, if assigned:
// * mainGroup
// * buildConfigurationList
// * contents of targets
PBXProject = class(PBXObject)
private
fattributes : TPBXKeyValue;
fcompatibilityVersion : string;
fdevelopmentRegion : string;
fhasScannedForEncodings: Boolean;
fmainGroup: PBXGroup;
fknownRegions: TPBXStringArray;
fproductRefGroup: PBXGroup;
fprojectDirPath: string;
fprojectRoot : string;
ftargets: TPBXObjectsList;
fbuildConfigurationList: XCConfigurationList;
protected
class procedure _WriteEmpty(propnames: TStrings); override;
public
constructor Create; override;
destructor Destroy; override;
function addTarget(const aname: string): PBXNativeTarget;
published
property attributes: TPBXKeyValue read fattributes;
property buildConfigurationList: XCConfigurationList read fbuildConfigurationList write fbuildConfigurationList;
property compatibilityVersion: string read fcompatibilityVersion write fcompatibilityVersion;
property developmentRegion: string read fdevelopmentRegion write fdevelopmentRegion;
property hasScannedForEncodings: Boolean read fhasScannedForEncodings write fhasScannedForEncodings;
property knownRegions: TPBXStringArray read fknownRegions;
property mainGroup: PBXGroup read fmainGroup write fmainGroup;
property productRefGroup: PBXGroup read fproductRefGroup write fproductRefGroup;
property projectDirPath: string read fprojectDirPath write fprojectDirPath;
property projectRoot: string read fprojectRoot write fprojectRoot;
property targets: TPBXObjectsList read ftargets;
end;
function ProjectLoadFromStream(st: TStream; var prj: PBXProject): Boolean;
function ProjectLoadFromFile(const fn: string; var prj: PBXProject): Boolean;
// serializes a PBX project to the string, using PBXContainer structure
function ProjectWrite(prj: PBXProject): string;
// creates a minimum possible project
function ProjectCreateMin: PBXProject;
// creates main group and product groups
procedure ProjectDefaultGroups(prj: PBXProject);
// adds necessary flags for Xcode3.2 not to throw any warnings
procedure ProjectUpdateForXcode3_2(prj: PBXProject);
// creates a minimum project, defaults the structure and sets Xcode 3.2 compat flags
function ProjectCreate3_2: PBXProject;
function ProjectAddTarget(prj: PBXProject; const ATargetName: string): PBXNativeTarget;
const
SCRIPT_RUNPATH = '/bin/sh';
SCRIPT_DEFAULT = '';
SCRIPT_DEFNAME = 'Run Script';
function TargetAddRunScript(atarget: PBXNativeTarget): PBXShellScriptBuildPhase;
const
//FILETYPE_SCRIPT = 'text.script.sh';
FILETYPE_EXEC = 'compiled.mach-o.executable';
FILETYPE_MACHO = FILETYPE_EXEC;
function FileRefCreate(const afilename: string; const filetype: string = ''): PBXFileReference;
const
GROUPSRC_ABSOLUTE = '<absolute>';
GROUPSRC_GROUP = '<group>';
function GroupCreate(const aname: string; const srcTree: string = GROUPSRC_GROUP): PBXGroup;
//todo: need a rountine to update the path whenever the project is saved
function GroupCreateRoot(const projectfolder: string = ''): PBXGroup;
const
PRODTYPE_TOOL = 'com.apple.product-type.tool';
//
// PBXSourcesBuildPhase (sources) - is part of a PBXNativeTarget
// PBXNativeTarget - is part of Target
// PBXNativeTarget
//buildPhases = (
//0AA67B651A04929900CF0DD7 /* Sources */,
//0AA67B661A04929900CF0DD7 /* Frameworks */,
//0AA67B671A04929900CF0DD7 /* CopyFiles */,
//);
implementation
{ PBXTargetDependency }
destructor PBXTargetDependency.Destroy;
begin
ftargetProxy.Free;
inherited Destroy;
end;
{ PBXShellScriptBuildPhase }
constructor PBXShellScriptBuildPhase.Create;
begin
inherited Create;
finputPaths:=TPBXStringArray.Create;
foutputPaths:=TPBXStringArray.Create;
end;
destructor PBXShellScriptBuildPhase.Destroy;
begin
finputPaths.Free;
foutputPaths.Free;
inherited Destroy;
end;
{ PBXNativeTarget }
constructor PBXNativeTarget.Create;
begin
inherited Create;
fbuildPhases := TPBXObjectsList.Create(true);
fdependencies := TPBXObjectsList.Create(true);
fbuildRules := TPBXObjectsList.Create(true);
end;
destructor PBXNativeTarget.Destroy;
begin
fbuildConfigurationList.Free;
fbuildRules.Free;
fbuildPhases.Free;
fdependencies.Free;
inherited Destroy;
end;
{ PBXProject }
class procedure PBXProject._WriteEmpty(propnames: TStrings);
begin
propnames.Add('projectDirPath');
propnames.Add('projectRoot');
end;
constructor PBXProject.Create;
begin
inherited Create;
ftargets:=TPBXObjectsList.create(true);
fknownRegions:=TPBXStringArray.Create;
fattributes:=TPBXKeyValue.Create(true);
end;
destructor PBXProject.Destroy;
begin
fattributes.Free;
fknownRegions.Free;
ftargets.Free;
fmainGroup.Free;
fbuildConfigurationList.Free;
inherited Destroy;
end;
function PBXProject.addTarget(const aname: string): PBXNativeTarget;
begin
Result:=PBXNativeTarget.Create;
targets.Add(Result);
Result._headerComment:=aname;
Result.name:=aname;
// productName?
// productReference - is a resulting file
end;
{ XCConfigurationList }
constructor XCConfigurationList.Create;
begin
inherited Create;
fbuildConfigurations:=TPBXObjectsList.Create(true);
end;
destructor XCConfigurationList.Destroy;
begin
fbuildConfigurations.Free;
inherited Destroy;
end;
function XCConfigurationList.AddConfig(const aname: string): XCBuildConfiguration;
begin
Result:=XCBuildConfiguration.Create;
Result.name:=aname;
Result._headerComment:=aname;
fbuildConfigurations.Add(Result);
end;
{ XCBuildConfiguration }
constructor XCBuildConfiguration.Create;
begin
inherited Create;
fbuildSettings:=TPBXKeyValue.Create(true);
end;
destructor XCBuildConfiguration.Destroy;
begin
fbuildSettings.Free;
inherited Destroy;
end;
{ PBXGroup }
constructor PBXGroup.Create;
begin
inherited Create;
fchildren:=TPBXObjectsList.Create(true);
end;
destructor PBXGroup.Destroy;
begin
fchildren.Free;
inherited Destroy;
end;
function PBXGroup.addSubGroup(const aname: string): PBXGroup;
begin
Result:=PBXGroup.Create;
fchildren.Add(Result);
Result.name:=aname;
Result._headerComment:=aname;
Result.sourceTree:=GROUPSRC_GROUP;
end;
function PBXGroup.findGroup(const aname: string): PBXGroup;
var
i : integer;
obj : TObject;
begin
for i:=0 to fchildren.Count-1 do begin
obj:=fchildren[i];
if (obj is PBXGroup) and (PBXGroup(obj).name=aname) then begin
Result:=PBXGroup(obj);
Exit;
end;
end;
Result:=nil;
end;
{ PBXBuildPhase }
constructor PBXBuildPhase.Create;
begin
inherited Create;
ffiles:=TPBXObjectsList.Create(true);
end;
destructor PBXBuildPhase.Destroy;
begin
ffiles.Free;
end;
function ProjectLoadFromStream(st: TStream; var prj: PBXProject): Boolean;
var
c : TPBXContainer;
info : TPBXFileInfo;
begin
prj:=nil;
c:= TPBXContainer.Create;
try
Result:=c.ReadFile(st, info);
if Result then begin
if not (info.rootObject is PBXProject) then begin
info.rootObject.Free;
end else begin
prj:=PBXProject(info.rootObject);
end;
end
finally
c.Free;
end;
end;
function ProjectLoadFromFile(const fn: string; var prj: PBXProject): Boolean;
var
fs :TFileStream;
begin
fs:=TFileStream.Create(fn, fmOpenRead or fmShareDenyNone);
try
Result:=ProjectLoadFromStream(fs, prj);
finally
fs.Free;
end;
end;
function ProjectWrite(prj: PBXProject): string;
var
info : TPBXFileInfo;
begin
info.archiveVersion:='1';
info.objectVersion:='46';
info.rootObject:=prj;
Result:=PBXWriteContainer(info);
end;
function ProjectCreateMin: PBXProject;
var
p : PBXProject;
cfg : XCBuildConfiguration;
begin
// requirements:
// * at least one build configuration
p := PBXProject.Create;
p._headerComment:='Project object';
p.buildConfigurationList:=XCConfigurationList.Create;
p.buildConfigurationList._headerComment:='Build configuration list for PBXProject';
p.buildConfigurationList.defaultConfigurationIsVisible:='0';
cfg:=p.buildConfigurationList.addConfig('Default');
cfg:=p.buildConfigurationList.addConfig('Release');
// default name must be present
p.buildConfigurationList.defaultConfigurationName:='Release';
Result:=p;
end;
procedure ProjectDefaultGroups(prj: PBXProject);
var
prd : PBXGroup;
begin
if not Assigned(prj) then Exit;
if not Assigned(prj.mainGroup) then
prj.mainGroup:=GroupCreateRoot;
if not Assigned(prj.productRefGroup) then begin
prd:=prj.mainGroup.findGroup('Products');
if not Assigned(prd) then
prd:=prj.mainGroup.addSubGroup('Products');
prj.productRefGroup:=prd;
end;
end;
procedure ProjectUpdateForXcode3_2(prj: PBXProject);
begin
if not Assigned(prj) then Exit;
// without the attribute Xcode complains aboutt updating settings
prj.attributes.AddStr('LastUpgradeCheck','0600');
prj.compatibilityVersion:='Xcode 3.2';
end;
function ProjectCreate3_2: PBXProject;
begin
Result:=ProjectCreateMin;
ProjectDefaultGroups(Result);
ProjectUpdateForXcode3_2(Result);
end;
function ProjectAddTarget(prj: PBXProject; const ATargetName: string): PBXNativeTarget;
begin
Result:=nil;
if not Assigned(prj) then Exit;
Result:=prj.addTarget(ATargetName);
end;
function TargetAddRunScript(atarget: PBXNativeTarget): PBXShellScriptBuildPhase;
begin
Result:=PBXShellScriptBuildPhase.Create;
Result.name:=SCRIPT_DEFNAME;
Result._headerComment:=SCRIPT_DEFNAME;
Result.shellScript:=SCRIPT_DEFAULT;
Result.shellPath:=SCRIPT_RUNPATH;
atarget.buildPhases.Add(Result);
end;
function FileRefCreate(const afilename: string; const filetype: string ): PBXFileReference;
begin
Result:=PBXFileReference.Create;
Result.path:=afilename;
Result._headerComment:=afilename;
Result.explicitFileType:=FILETYPE_EXEC;
end;
function GroupCreate(const aname, srcTree: string): PBXGroup;
begin
Result:=PBXGroup.Create;
Result.name:=aname;
Result.sourceTree:=srcTree;
Result._headerComment:=aname;
end;
function GroupCreateRoot(const projectfolder: string): PBXGroup;
begin
Result:=GroupCreate('', GROUPSRC_ABSOLUTE);
Result.path:=projectfolder;
Result._headerComment:=projectfolder;
end;
initialization
PBXRegisterClass(PBXBuildFile);
PBXRegisterClass(PBXContainerItemProxy);
PBXRegisterClass(PBXFileReference);
PBXRegisterClass(PBXFrameworksBuildPhase);
PBXRegisterClass(PBXGroup);
PBXRegisterClass(PBXNativeTarget);
PBXRegisterClass(PBXProject);
PBXRegisterClass(PBXResourcesBuildPhase);
PBXRegisterClass(PBXSourcesBuildPhase);
PBXRegisterClass(PBXTargetDependency);
PBXRegisterClass(PBXVariantGroup);
PBXRegisterClass(XCBuildConfiguration);
PBXRegisterClass(XCConfigurationList);
end.
|
unit CreateLocationUnit;
interface
uses SysUtils, BaseExampleUnit, AddressBookContactUnit;
type
TCreateLocation = class(TBaseExample)
public
function Execute(FirstName, Address: String): TAddressBookContact;
end;
implementation
function TCreateLocation.Execute(FirstName, Address: String): TAddressBookContact;
var
ErrorString: String;
Contact: TAddressBookContact;
begin
Contact := TAddressBookContact.Create();
try
Contact.FirstName := FirstName;
Contact.Address := Address;
Contact.Latitude := 38.024654;
Contact.Longitude := -77.338814;
Result := Route4MeManager.AddressBookContact.Add(Contact, ErrorString);
WriteLn('');
if (Result <> nil) then
begin
WriteLn('CreateLocation executed successfully');
WriteLn(Format('AddressId: %d', [Result.Id.Value]));
end
else
WriteLn(Format('CreateLocation error: "%s"', [ErrorString]));
finally
FreeAndNil(Contact);
end;
end;
end.
|
unit mnSynHighlighterXHTML;
{$mode objfpc}{$H+}
{**
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
Classes, SysUtils, Controls, Graphics,
SynEdit, SynEditHighlighter, mnSynHighlighterMultiProc;
type
{ TSynXHTMLSyn }
TSynXHTMLSyn = class(TSynMultiProcSyn)
private
protected
function GetSampleSource: string; override;
public
class function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
procedure InitProcessors; override;
published
end;
const
SYNS_LangXHTML = 'HTML/PHP';
SYNS_FilterXHTML = 'HTML/PHP Files (*.php;*.html;*.phtml;*.inc)|*.php;*.html;*.phtml;*.inc';
implementation
uses
PHPProcessor, HTMLProcessor;
constructor TSynXHTMLSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDefaultFilter := SYNS_FilterXHTML;
end;
procedure TSynXHTMLSyn.InitProcessors;
begin
inherited;
Processors.Add(THTMLProcessor.Create(Self, 'html'));
Processors.Add(TPHPProcessor.Create(Self, 'php'));
Processors.Add(TPHPProcessor.Create(Self, 'hh')); //<-- same php temporary ^.^
Processors.Add(TPlainProcessor.Create(Self, ''));
Processors.MainProcessor := 'html';
Processors.DefaultProcessor := 'php';
end;
class function TSynXHTMLSyn.GetLanguageName: string;
begin
Result := SYNS_LangXHTML;
end;
function TSynXHTMLSyn.GetSampleSource: string;
begin
Result := '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'#13#10 +
'<html dir="ltr">'#13#10 +
' <body class="normal">'#13#10 +
' HTML and PHP syntax editor'#13#10 +
'<?php'#13#10 +
'// Syntax highlighting'#13#10 +
'/**'#13#10 +
' It is a Documentation comments'#13#10 +
'*/'#13#10 +
' function printNumber()'#13#10 +
' {'#13#10 +
' $number = 1234;'#13#10 +
' print "The number is $number";'#13#10 +
' /* '#13#10 +
' Multi line comment '#13#10 +
' */ '#13#10 +
' for ($i = 0; $i <= $number; $i++)'#13#10 +
' {'#13#10 +
' $x++;'#13#10 +
' $x--;'#13#10 +
' $x += 1.0;'#13#10 +
' }'#13#10 +
' }'#13#10 +
'?>'#13#10 +
' </body>'#13#10 +
'</html>'#13#10;
end;
end.
|
unit Model.PlanilhaEntradaEntregas;
interface
uses Generics.Collections;
type
TPlanilhaEntradaEntregas = class
private
var
FCodigoDestino : String;
FNomeDestiono : String;
FNossoNumero: String;
FCodigoCliente: String;
FNumeroNF: String;
FNomeConsumidor: String;
FAosCuidados: String;
FLogradouro: String;
FComplemento: String;
FBairro: String;
FCidade: String;
FCEP: STring;
FTelefone: String;
FExpedicao: String;
FPrevisao: String;
FStatus: String;
FDescricaoStatus: String;
FNomeEntregador: String;
FContainer: String;
FValorProuto: String;
FValorVerba: String;
FAltura: String;
FLargura: String;
FComprimento: String;
FPeso: String;
FVolume: String;
public
property CodigoDestino : String read FCodigoDestino write FCodigoDestino;
property NomeDestino : String read FNomeDestiono write FNomeDestiono;
property NossoNumero: String read FNossoNumero write FNossoNumero;
property CodigoCliente: String read FCodigoCliente write FCodigoCliente;
property NumeroNF: String read FNumeroNF write FNumeroNF;
property NomeConsumidor: String read FNomeConsumidor write FNomeConsumidor;
property AosCuidados: String read FAosCuidados write FAosCuidados;
property Logradouro: String read FLogradouro write FLogradouro;
property Complemento: String read FComplemento write FComplemento;
property Bairro: String read FBairro write FBairro;
property Cidade: String read FCidade write FCidade;
property CEP: STring read FCEP write FCEP;
property Telefone: String read FTelefone write FTelefone;
property Expedicao: String read FExpedicao write FExpedicao;
property Previsao: String read FPrevisao write FPrevisao;
property Status: String read FStatus write FStatus;
property DescricaoStatus: String read FDescricaoStatus write FDescricaoStatus;
property NomeEntregador: String read FNomeEntregador write FNomeEntregador;
property Container: String read FContainer write FContainer;
property ValorProuto: String read FValorProuto write FValorProuto;
property ValorVerba: String read FValorVerba write FValorVerba;
property Altura: String read FAltura write FAltura;
property Largura: String read FLargura write FLargura;
property Comprimento: String read FComprimento write FComprimento;
property Peso: String read FPeso write FPeso;
property Volume: String read FVolume write FVolume;
function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaEntregas>;
end;
implementation
{ TPlanilhaEntradaEntregas }
uses DAO.PlanilhaEntradaEntregas;
function TPlanilhaEntradaEntregas.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaEntregas>;
var
planilha : TPlanilhaEntradaEntregasDAO;
begin
try
planilha := TPlanilhaEntradaEntregasDAO.Create;
Result := planilha.GetPlanilha(sFile);
finally
planilha.Free;
end;
end;
end.
|
unit KernelBackup;
interface
uses
BackupObjects;
type
TFacilityBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TBlockBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TGateBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TInputBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TOutputBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TTaxInfoBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TClusterBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TCompanyBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TTownBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TTycoonBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
TWorldBackupAgent =
class(TBackupAgent)
protected
class procedure Write(Stream : TBackupWriter; Obj : TObject); override;
class procedure Read (Stream : TBackupReader; Obj : TObject); override;
end;
procedure RegisterBackup;
implementation
uses
Kernel, World;
// TFacilityBackupAgent
class procedure TFacilityBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TFacility(Obj).StoreToBackup(Stream);
end;
class procedure TFacilityBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TFacility(Obj).LoadFromBackup(Stream);
end;
// TBlockBackupAgent
class procedure TBlockBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TBlock(Obj).StoreToBackup(Stream);
end;
class procedure TBlockBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TBlock(Obj).LoadFromBackup(Stream);
end;
// TGateBackupAgent
class procedure TGateBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TGate(Obj).StoreToBackup(Stream);
end;
class procedure TGateBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TGate(Obj).LoadFromBackup(Stream);
end;
// TInputBackupAgent
class procedure TInputBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TInput(Obj).StoreToBackup(Stream);
end;
class procedure TInputBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TInput(Obj).LoadFromBackup(Stream);
end;
// TOutputBackupAgent
class procedure TOutputBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TOutput(Obj).StoreToBackup(Stream);
end;
class procedure TOutputBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TOutput(Obj).LoadFromBackup(Stream);
end;
// TTaxInfoBackupAgent
class procedure TTaxInfoBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TTaxInfo(Obj).StoreToBackup(Stream);
end;
class procedure TTaxInfoBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TTaxInfo(Obj).LoadFromBackup(Stream);
end;
// TClusterBackupAgent
class procedure TClusterBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TCluster(Obj).StoreToBackup(Stream);
end;
class procedure TClusterBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TCluster(Obj).LoadFromBackup(Stream);
end;
// TCompanyBackupAgent
class procedure TCompanyBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TCompany(Obj).StoreToBackup(Stream);
end;
class procedure TCompanyBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TCompany(Obj).LoadFromBackup(Stream);
end;
// TTownBackupAgent
class procedure TTownBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TTown(Obj).StoreToBackup(Stream);
end;
class procedure TTownBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TTown(Obj).LoadFromBackup(Stream);
end;
// TTycoonBackupAgent
class procedure TTycoonBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TTycoon(Obj).StoreToBackup(Stream);
end;
class procedure TTycoonBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TTycoon(Obj).LoadFromBackup(Stream);
end;
// TWorldBackupAgent
class procedure TWorldBackupAgent.Write(Stream : TBackupWriter; Obj : TObject);
begin
TWorld(Obj).StoreToBackup(Stream);
end;
class procedure TWorldBackupAgent.Read(Stream : TBackupReader; Obj : TObject);
begin
TWorld(Obj).LoadFromBackup(Stream);
end;
// Registration
procedure RegisterBackup;
begin
TFacilityBackupAgent.Register([TFacility]);
TBlockBackupAgent.Register([TBlock]);
TGateBackupAgent.Register([TGate]);
TInputBackupAgent.Register([TInput]);
TOutputBackupAgent.Register([TOutput]);
TTaxInfoBackupAgent.Register([TTaxInfo]);
RegisterClass(TPushInput);
RegisterClass(TPullInput);
RegisterClass(TPushOutput);
RegisterClass(TPullOutput);
TClusterBackupAgent.Register([TCluster]);
TCompanyBackupAgent.Register([TCompany]);
TTownBackupAgent.Register([TTown]);
TTycoonBackupAgent.Register([TTycoon]);
TWorldBackupAgent.Register([TWorld]);
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ 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 Plugin.Interf;
interface
uses {$IFDEF FMX} FMX.Controls {$ELSE} VCL.Controls {$ENDIF};
const
constPluginInterfaceVersion = 1;
type
{
DLL - implements some plugins
|--IPluginItems
|----------IPluginInfo 1
|-----------------IPluginMenuItem
|----------IPluginInfo 2
|-----------------IPluginMenuItem
|----------IPluginInfo 3
|-----------------IPluginExecute
|----------IPluginInfo 4
|-----------------IPluginToolbarItem
Host (main application) - Implements IPluginApplication
}
IPluginExecuteBase = interface;
// ---------------------------------------------------------------------------
// Plugin Controls
// ---------------------------------------------------------------------------
// with plugin implements an interface
IPluginInfo = interface
['{1BBC2D91-BF8A-4976-9EF5-201A518D62A3}']
procedure DoStart;
function PluginName: string;
function GetTypeID: Int64;
function GetAuthor: string;
function GetInterface: IPluginExecuteBase;
// retorna a interface que implementa.
end;
// list of plugins interface in the same DLL
// a DLL can implement a lot of IPluginInfo (interfaces)
// return by DLL function LoadPlugin
IPluginItems = interface
['{756E63BE-4C02-46AF-85AD-87BDB657201F}']
function Count: integer;
function GetItem(idx: integer): IPluginInfo;
procedure Connection(const AConnectionString: string);
procedure Add(AInfo: IPluginInfo);
procedure Install;
procedure UnInstall;
end;
// ---------------------------------------------------------------------------
// Interfaces Plugins implments
// ---------------------------------------------------------------------------
IPluginExecuteSync = interface
['{9AD34563-BA02-45C7-B821-5BAD712EF2AD}']
procedure Sync(const AJson: string);
end;
IPluginExecuteConnection = interface(IPluginExecuteSync)
['{C45E1B77-4CAF-462D-A031-26292B7D854A}']
procedure Connection(const AConnectionString: string);
procedure User(const AFilial: integer; const AAppUser: string);
end;
IPluginExecuteBase = interface(IPluginExecuteConnection)
['{4F0858A2-A92A-4705-9E74-5C4BEBB68F02}']
function GetVersion:integer;
function GetCaption: string;
function GetTypeID: Int64;
procedure SetTypeID(const ATypeID: Int64);
procedure SetParams(AJsonParams: String);
procedure SetPosition( ATop,ALeft,AWidth,AHeight:Integer);
procedure Perform(AMsg: Cardinal; WParam: NativeUInt; LParam: NativeUInt);
function CanClose: Boolean;
end;
IPluginExecute = interface(IPluginExecuteBase)
['{73D9055C-56B3-4ADC-98E6-4F5F0B2D930F}']
procedure Execute(const AModal: Boolean);
procedure Embedded(const AParent: THandle);overload;
end;
IPluginControl = interface(IPluginExecute)
['{84B1D051-D13D-4D72-BE63-26757FED98AB}']
function GetSubTypeID: Int64;
end;
IPluginMenuItem = interface(IPluginExecuteBase)
['{7188528B-A818-4739-9FA4-F3A383305C56}']
function GetPath: string;
procedure DoClick(const AParent: THandle);
procedure Embedded(const AParent: THandle);
function CanClose: Boolean;
function GetResourceName: String;
end;
IPluginToolbarItem = interface(IPluginMenuItem)
end;
// ----------------------------------------------------------------------------
// Host interface (Main Application)
// ----------------------------------------------------------------------------
IPluginApplication = interface
['{6ED989EA-E8B5-4435-A0BC-33685CFE7EEB}']
procedure RegisterMenuItem(const AParentMenuItemName, ACaption: string;
ADoExecute: IPluginMenuItem);
procedure RegisterToolbarItem(const AParentItemName, ACaption: string;
ADoExecute: IPluginToolbarItem);
procedure RegisterAttributeControl(const AType, ASubType: Int64;
ADoExecute: IPluginControl);
end;
var
PluginApplication: IPluginApplication; // both plugin and host can set value
implementation
initialization
finalization
PluginApplication := nil;
end.
|
{ behavior3delphi v1.0 - a Behavior3 client library (Behavior Trees)
based on behavior3js <https://github.com/behavior3/behavior3js/>
for Delphi 10.1 Berlin+ by Dennis D. Spreen
http://blog.spreendigital.de/2016/07/01/behavior3delphi/
(c) Copyrights 2016 Dennis D. Spreen <dennis@spreendigital.de>
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
unit Behavior3;
interface
{
This code was translated from behavior3js with these modifications:
- Used "Behavoir3" as the unit namespace
- Used Delphi-like capitalization on variables, procedure, unit and object names
- Prefixed any objects with TB3
- BaseNode: as "parameter" is deprecated, it is not included, thus any reference is not included
- BaseNode: properties completely removed, as this was only useful for the behavior3editor
- BaseNode: Exit() changed to Exit_()
- BaseNode: added load/save via JSON object
- BaseNode: added a BehaviorTree reference (as Tree: TB3BehaviorTree)
- BehaviorTree: added all linked nodes as a node dictionary (Nodes: TB3BaseNodeDictionary)
- BehaviorTree: removed properties
- Node types are either given during the loading of the behavior tree or managed globally (in Behavior3.NodeTypes.pas)
- Register your custom node types in the B3NodeTypes dictionary
- used Behavior3.Helper.pas to prevent circular unit reference
- added BehaviorTreeDictionary
- added Behavior3.Project with behavior3editor support
}
uses
System.SysUtils;
const
TB3Version = '0.2.0';
type
TB3Category = (Composite, Decorator, Action, Condition);
TB3Status = (Success = 1, Failure, Running, Error);
EB3ParameterMissingException = class(Exception);
EB3RootMissingException = class(Exception);
EB3NodeclassMissingException = class(Exception);
implementation
end.
|
unit Model.VerbasExpressas;
interface
uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, System.SysUtils, Control.Sistema,
System.Variants;
type
TVerbasExpressas = class
private
FID: Integer;
FTipo: Integer;
FGrupo: Integer;
FVigencia: TDateTime;
FVerba: Double;
FPerformance: Double;
FCEPInicial: String;
FCEPFinal: String;
FPesoInicial: Double;
FPesoFinal: Double;
FAcao: TAcao;
FConexao : TConexao;
FCliente: Integer;
FRoteiro: Integer;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
property ID: Integer read FID write FID;
property Tipo: Integer read FTipo write FTipo;
property Grupo: Integer read FGrupo write FGrupo;
property Vigencia: TDateTime read FVigencia write FVigencia;
property Verba: Double read FVerba write FVerba;
property Performance: Double read FPerformance write FPerformance;
property CEPInicial: String read FCEPInicial write FCEPInicial;
property CEPFinal: String read FCEPFinal write FCEPFinal;
property PesoInicial: Double read FPesoInicial write FPesoInicial;
property PesoFinal: Double read FPesoFinal write FPesoFinal;
property Cliente: Integer read FCliente write FCliente;
property Roteiro: Integer read FRoteiro write FRoteiro;
property Acao: TAcao read FAcao write FAcao;
function GetID(): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function LocalizarExato(aParam: array of variant): Boolean;
function Gravar(): Boolean;
function SetupModel(FDQuery: TFDQuery): Boolean;
procedure ClearModel;
function RetornaVerba(): double;
function RetornaListaSimples(iTabela: integer; memTable: TFDMemTable): boolean;
function RetornaValorFaixa(iCliente, iTabela, iFaixa: integer): string;
constructor Create();
end;
const
TABLENAME = 'expressas_verbas';
implementation
{ TVerbasExpressas }
function TVerbasExpressas.Alterar: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set ' +
'cod_tipo = :pcod_tipo, cod_cliente = :cod_cliente, id_grupo = :pid_grupo, dat_vigencia = :pdat_vigencia, ' +
'val_verba = :pval_verba, val_performance = :pval_performance, num_cep_inicial = :pnum_cep_inicial, ' +
'num_cep_final = :pnum_cep_final, qtd_peso_inicial = :pqtd_peso_inicial, qtd_peso_final = :pqtd_peso_final, ' +
'cod_roteiro = :cod_roteiro ' +
'where id_verba = :pid_verba;', [Tipo, Cliente, Grupo, Vigencia, Verba, Performance, CEPInicial, CEPFinal, PesoInicial,
PesoFinal, Roteiro, ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
procedure TVerbasExpressas.ClearModel;
begin
FID := 0;
FTipo := 0;
FGrupo := 0;
FVigencia := StrtoDate('31/12/1899');
FVerba := 0;
FPerformance := 0;
FCEPInicial := '';
FCEPFinal := '';
FPesoInicial := 0;
FPesoFinal := 0;
FCliente := 0;
FRoteiro := 0;
end;
constructor TVerbasExpressas.Create;
begin
FConexao := TConexao.Create;
end;
function TVerbasExpressas.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_verba = :pid_verba', [ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TVerbasExpressas.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_verba),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TVerbasExpressas.Gravar: Boolean;
begin
Result := False;
case FAcao of
tacAlterar: Result := Alterar();
tacIncluir: Result := Inserir();
tacExcluir: Result := Excluir();
end;
end;
function TVerbasExpressas.Inserir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
ID := GetID();
FDQuery.ExecSQL('insert into ' + TABLENAME + '(id_verba, cod_cliente, cod_tipo, id_grupo, dat_vigencia, val_verba, ' +
'val_performance, num_cep_inicial, num_cep_final, qtd_peso_inicial, qtd_peso_final, cod_roteiro) ' +
'values ' +
'(:pid_verba, :pcod_cliente, :pcod_tipo, :pid_grupo, :pdat_vigencia, :pval_verba, :pval_performance, ' +
':pnum_cep_inicial, :pnum_cep_final, :pqtd_peso_inicial, :pqtd_peso_final, :cod_roteiro);',
[ID, Cliente, Tipo, Grupo, Vigencia, Verba, Performance, CEPInicial, CEPFinal, PesoInicial, PesoFinal,
Roteiro]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TVerbasExpressas.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select id_verba, cod_cliente, cod_tipo, id_grupo, dat_vigencia, val_verba, ' +
'val_performance, num_cep_inicial, num_cep_final, qtd_peso_inicial, qtd_peso_final, cod_roteiro from ' +
TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_verba = :pid_verba');
FDQuery.ParamByName('pid_verba').AsInteger := aParam[1];
end;
if aParam[0] = 'TIPO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
end;
if aParam[0] = 'CLIENTE' then
begin
FDQuery.SQL.Add('where cod_cliente = :pcod_cliente');
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[1];
end;
if aParam[0] = 'TIPOCLIENTE' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
end;
if aParam[0] = 'FIXA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia ' +
'order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
end;
if aParam[0] = 'FIXACEP' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pnum_cep').AsString := aParam[5];
end;
if aParam[0] = 'FIXAPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'SLA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'val_performance = :pval_performance order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pval_performance').AsFloat := aParam[8];
end;
if aParam[0] = 'CEPPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDate := aParam[4];
FDQuery.ParamByName('pnum_cep').AsString := aParam[5];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'ROTEIROPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pcod_roteiro').AsInteger := aParam[7];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'ROTEIROFIXA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDate :=aParam[4];
FDQuery.ParamByName('pcod_roteiro').AsInteger := aParam[7];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
if FDQuery.RecordCount > 0 then
begin
FDQuery.First;
SetupModel(FDQuery);
end;
Result := FDQuery;
end;
function TVerbasExpressas.LocalizarExato(aParam: array of variant): Boolean;
var
FDQuery: TFDQuery;
begin
try
if aParam[0] = 'NONE' then
begin
ClearModel;
Result := True;
Exit;
end;
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select id_verba, cod_cliente, cod_tipo, id_grupo, dat_vigencia, val_verba, ' +
'val_performance, num_cep_inicial, num_cep_final, qtd_peso_inicial, qtd_peso_final, cod_roteiro from ' +
TABLENAME);
if aParam[0] = 'FIXA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia ' +
'order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
end;
if aParam[0] = 'FIXACEP' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pnum_cep').AsString := aParam[5];
end;
if aParam[0] = 'FIXAPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'SLA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'val_performance = :pval_performance order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pval_performance').AsFloat := aParam[8];
end;
if aParam[0] = 'CEPPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDate := aParam[4];
FDQuery.ParamByName('pnum_cep').AsString := aParam[5];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'ROTEIROPESO' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDateTime := aParam[4];
FDQuery.ParamByName('pcod_roteiro').AsInteger := aParam[7];
FDQuery.ParamByName('pqtd_peso').AsFloat := aParam[6];
end;
if aParam[0] = 'ROTEIROFIXA' then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1];
FDQuery.ParamByName('pcod_cliente').AsInteger := aParam[2];
FDQuery.ParamByName('pid_grupo').AsInteger := aParam[3];
FDQuery.ParamByName('pdat_vigencia').AsDate :=aParam[4];
FDQuery.ParamByName('pcod_roteiro').AsInteger := aParam[7];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
FDQuery.Open();
if FDQuery.RecordCount > 0 then
begin
FDQuery.First;
SetupModel(FDQuery);
end
else
begin
ClearModel;
end;
Result := True;
finally
FDquery.Connection.Close;
FDQuery.Free;
end;
end;
function TVerbasExpressas.RetornaListaSimples(iTabela: integer; memTable: TFDMemTable): boolean;
var
sSQL : String;
sWhere: String;
aParam: array of variant;
fdQuery: TFDQuery;
begin
try
Result := False;
fdQuery := FConexao.ReturnQuery;
sSQL := 'distinct id_grupo as cod_faixa, concat(format(val_verba,2,"de_DE"), ' +
'if(num_cep_inicial<>"",concat(" - CEP Inicial ", num_cep_inicial, " - ", "CEP Final ", num_cep_final),""), ' +
'if(qtd_peso_inicial<>0,concat(" - PESO Inicial ", format(qtd_peso_inicial,3,"de_DE"), " - ", "PESO Final ", ' +
'format(qtd_peso_final,3,"de_DE")),"")) as des_faixa';
sWhere := ' where cod_tipo = ' + iTabela.ToString;
SetLength(aParam,3);
aParam := ['APOIO',sSQL, sWhere];
fdQuery := Self.Localizar(aParam);
Finalize(aParam);
if not fdQuery.IsEmpty then
begin
memTable.Data := fdQuery.Data;
end;
Result := True;
finally
fdQuery.Close;
fdQuery.Connection.Close;
fdQuery.Free;
end;
end;
function TVerbasExpressas.RetornaValorFaixa(iCliente, iTabela, iFaixa: integer): string;
var
FDQuery: TFDQuery;
sSQL : string;
begin
try
Result := '';
sSQL := 'select val_verba from ' + TABLENAME +
' where cod_cliente = :cod_clinte and cod_tipo = :cod_tipo and cod_faixa = :faixa';
FDQuery := FConexao.ReturnQuery;
FDQuery.SQL.Clear;
FDQuery.SQL.Add(sSQL);
FDQuery.ParamByName(':cod_cliente').AsInteger := iCliente;
FDQuery.ParamByName(':cod_tipo').AsInteger := iTabela;
FDQuery.ParamByName(':cod_faixa').AsInteger := iFaixa;
FDQuery.Open();
if not FDQuery.IsEmpty then
begin
FDQuery.First;
end
else
begin
Exit;
end;
Result := FormatFloat('###,##0.00', FDQuery.FieldByName('val_verba').AsFloat);
finally
FDQuery.Close;
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TVerbasExpressas.RetornaVerba(): double;
var
FDQuery: TFDQuery;
begin
try
Result := 0;
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select id_verba, cod_cliente, cod_tipo, id_grupo, dat_vigencia, val_verba, ' +
'val_performance, num_cep_inicial, num_cep_final, qtd_peso_inicial, qtd_peso_final, cod_roteiro from ' +
TABLENAME);
if Self.Tipo = 0 then
begin
Exit;
end;
if Self.Tipo = 1 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and ' +
'dat_vigencia <= :pdat_vigencia order by dat_vigencia desc');
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDateTime := Self.Vigencia;
end;
if Self.Tipo = 2 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDateTime := Self.Vigencia;
FDQuery.ParamByName('pnum_cep').AsString := Self.CEPInicial;
end;
if Self.Tipo = 3 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDateTime := Self.Vigencia;
FDQuery.ParamByName('pqtd_peso').AsFloat := Self.PesoInicial;
end;
if Self.Tipo = 4 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'val_performance = :pval_performance order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDateTime := Self.Vigencia;
FDQuery.ParamByName('pval_performance').AsFloat := Self.Performance;
end;
if Self.Tipo = 5 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'num_cep_inicial <= :pnum_cep and num_cep_final >= :pnum_cep and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDate := Self.Vigencia;
FDQuery.ParamByName('pnum_cep').AsString := Self.CEPInicial;
FDQuery.ParamByName('pqtd_peso').AsFloat := Self.PesoInicial;
end;
if Self.Tipo = 7 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro and ' +
'qtd_peso_inicial <= :pqtd_peso and qtd_peso_final >= :pqtd_peso order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDateTime := Self.Vigencia;
FDQuery.ParamByName('pcod_roteiro').AsInteger := Self.Roteiro;
FDQuery.ParamByName('pqtd_peso').AsFloat := Self.PesoInicial;
end;
if Self.Tipo = 6 then
begin
FDQuery.SQL.Add('where cod_tipo = :pcod_tipo and cod_cliente = :pcod_cliente and id_grupo = :pid_grupo and dat_vigencia <= :pdat_vigencia and ' +
'cod_roteiro = :pcod_roteiro order by dat_vigencia desc');
FDQuery.ParamByName('pcod_tipo').AsInteger := Self.Tipo;
FDQuery.ParamByName('pcod_cliente').AsInteger := Self.Cliente;
FDQuery.ParamByName('pid_grupo').AsInteger := Self.Grupo;
FDQuery.ParamByName('pdat_vigencia').AsDate := Self.Vigencia;
FDQuery.ParamByName('pcod_roteiro').AsInteger := Self.Roteiro;
end;
FDQuery.Open();
if FDQuery.RecordCount > 0 then
begin
FDQuery.First;
Result := FDQuery.FieldByName('val_verba').AsFloat;
end;
finally
FDQuery.Close;
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TVerbasExpressas.SetupModel(FDQuery: TFDQuery): Boolean;
begin
try
Result := False;
FID := FDQuery.FieldByName('id_verba').AsInteger;
FTipo := FDQuery.FieldByName('cod_tipo').AsInteger;
FGrupo := FDQuery.FieldByName('id_grupo').AsInteger;
FVigencia := FDQuery.FieldByName('dat_vigencia').AsDateTime;
FVerba := FDQuery.FieldByName('val_verba').AsFloat;
FPerformance := FDQuery.FieldByName('val_performance').AsFloat;
FCEPInicial := FDQuery.FieldByName('num_cep_inicial').AsString;
FCEPFinal := FDQuery.FieldByName('num_cep_final').AsString;
FPesoInicial := FDQuery.FieldByName('qtd_peso_inicial').AsFloat;
FPesoFinal := FDQuery.FieldByName('qtd_peso_final').AsFloat;
FCliente := FDQuery.FieldByName('cod_cliente').AsInteger;
FRoteiro := FDQuery.FieldByName('cod_roteiro').AsInteger;
finally
Result := True;
end;
end;
end.
|
unit clFTPSimples;
interface
uses
IdFTP, IdFTPCommon,System.Classes, Vcl.Dialogs, Vcl.Forms, System.SysUtils;
type
TFTPSimples = Class(TObject)
private
function getFileFrom: String;
function getFileTo: String;
function getHost: String;
function getPassword: String;
function getUsername: String;
procedure setFileFrom(const Value: String);
procedure setFileTo(const Value: String);
procedure setHost(const Value: String);
procedure setPassword(const Value: String);
procedure setUsername(const Value: String);
function getPort: Integer;
procedure setPort(const Value: Integer);
protected
_host: String;
_username: String;
_password: String;
_filefrom: String;
_fileto: String;
_port: Integer;
public
property Servidor: String read getHost write setHost;
property Usuario: String read getUsername write setUsername;
property Senha: String read getPassword write setPassword;
property Origem: String read getFileFrom write setFileFrom;
property Destino: String read getFileTo write setFileTo;
property Porta: Integer read getPort write setPort;
procedure FTPSend(sDir: String);
procedure FTPGet(sDir: String);
function FTPList(sDir: String): TStringList;
procedure FTPDelete(sDir: String);
end;
const
PASTA = '/Docs';
implementation
{ TFTPSimples }
procedure TFTPSimples.FTPGet(sDir: String);
var
ftpDownStream: TFileStream;
ftp: TIdFTP;
ms: TMemoryStream;
begin
ftpDownStream := TFileStream.Create(Self.Destino, fmCreate);
ftp := TIdFTP.Create(Application);
ms := TMemoryStream.Create;
try
try
ftp.AUTHCmd := tAuto;
ftp.Passive := True;
ftp.ReadTimeout := 120 * 1000;
ftp.ListenTimeout := 120 * 1000;
ftp.host := Self.Servidor; // Endereço do servidor FTP
ftp.port := Self.Porta;
ftp.username := Self.Usuario;
ftp.password := Self.Senha;
ftp.TransferType := ftBinary;
ftp.Connect();
AssErt(ftp.Connected);
ftp.List;
ftp.ChangeDir(PASTA + '/' + sDir); // Definir a pasta no servidor
ftp.Get(Self.Origem, ftpDownStream, True);
// Receber o arquivo do servidor
MessageDlg('Arquivo Recebido.', mtInformation, [mbOK], 0);
ftp.Disconnect;
finally
ms.Free;
ftp.Free;
ftpDownStream.Free;
end;
except
MessageDlg('Uma tentativa de receber um arquivo do servidor com falha!',
mtError, [mbOK], 0);
end;
end;
procedure TFTPSimples.FTPSend(sDir: String);
var
ftpUpStream: TFileStream;
ftp: TIdFTP;
ms: TMemoryStream;
i: Integer;
bExiste: Boolean;
Lista: TStringList;
begin
ftpUpStream := TFileStream.Create(Self.Origem, fmOpenRead);
ftp := TIdFTP.Create(Application);
ms := TMemoryStream.Create;
bExiste := False;
try
try
Lista := TStringList.Create;
ftp.AUTHCmd := tAuto;
ftp.Passive := True;
ftp.ReadTimeout := 120 * 1000;
ftp.ListenTimeout := 120 * 1000;
ftp.host := Self.Servidor; // Endereço do servidor FTP
ftp.port := Self.Porta;
ftp.username := Self.Usuario; // Parametro nome usuario servidor FTP
ftp.password := Self.Senha; // Parametro senha servidor FTP
ftp.TransferType := ftBinary;
ftp.Connect();
AssErt(ftp.Connected);
ftp.ChangeDir(PASTA);
ftp.List(Lista, PASTA, False);
for i := 0 to Lista.Count - 1 do
begin
if Lista[i] = (PASTA + '/' + sDir) then
begin
bExiste := True;
end;
end;
if not bExiste then
begin
ftp.MakeDir(PASTA + '/' + sDir);
end;
ftp.ChangeDir(PASTA + '/' + sDir); // Definir a pasta no servidor
ftp.Put(ftpUpStream, PASTA + '/' + sDir + '/' + Self.Destino, False);
// Transferir o arquivo para o servidor
MessageDlg('Transferido.', mtInformation, [mbOK], 0);
ftp.Disconnect;
finally
ftpUpStream.Free;
ms.Free;
ftp.Free;
end;
except
MessageDlg('Uma tentativa de enviar um arquivo para o servidor falhou!',
mtError, [mbOK], 0);
end;
end;
function TFTPSimples.FTPList(sDir: String): TStringList;
var
Lista: TStringList;
ftp: TIdFTP;
bExiste: Boolean;
sCompara: String;
i: Integer;
begin
Lista := TStringList.Create;
ftp := TIdFTP.Create(Application);
bExiste := False;
try
try
ftp.AUTHCmd := tAuto;
ftp.Passive := True;
ftp.host := Self.Servidor; // Endereço do servidor FTP
ftp.port := Self.Porta;
ftp.username := Self.Usuario; // Parametro nome usuario servidor FTP
ftp.password := Self.Senha; // Parametro senha servidor FTP
ftp.Connect();
AssErt(ftp.Connected);
ftp.List(Lista, PASTA, False);
for i := 0 to Lista.Count - 1 do
begin
if Lista[i] = (PASTA + '/' + sDir) then
begin
bExiste := True;
end;
end;
if bExiste then
begin
ftp.ChangeDir(PASTA + '/' + sDir); // Definir a pasta no servidor
ftp.List(Lista, PASTA + '/' + sDir + '/*.*', False);
ftp.Disconnect;
end
else
begin
Lista.Free;
end;
finally
ftp.Free;
end;
except
MessageDlg('Uma tentativa de listar os documentos do servidor falhou!',
mtError, [mbOK], 0);
end;
Result := Lista;
end;
procedure TFTPSimples.FTPDelete(sDir: String);
var
ftp: TIdFTP;
ms: TMemoryStream;
begin
ftp := TIdFTP.Create(Application);
ms := TMemoryStream.Create;
try
try
ftp.AUTHCmd := tAuto;
ftp.Passive := True;
ftp.ReadTimeout := 120 * 1000;
ftp.ListenTimeout := 120 * 1000;
ftp.host := Self.Servidor; // Endereço do servidor FTP
ftp.port := Self.Porta;
ftp.username := Self.Usuario; // Parametro nome usuario servidor FTP
ftp.password := Self.Senha; // Parametro senha servidor FTP
ftp.Connect();
AssErt(ftp.Connected);
ftp.ChangeDir(PASTA + '/' + sDir); // Definir a pasta no servidor
ftp.Delete(Self.Origem); // Exluir o arquivo do servidor
MessageDlg('Arquivo Excluído.', mtInformation, [mbOK], 0);
ftp.Disconnect;
finally
ms.Free;
ftp.Free;
end;
except
MessageDlg('Uma tentativa de excluir um arquivo do servidor falhou!',
mtError, [mbOK], 0);
end;
end;
function TFTPSimples.getFileFrom: String;
begin
Result := _filefrom;
end;
function TFTPSimples.getFileTo: String;
begin
Result := _fileto;
end;
function TFTPSimples.getHost: String;
begin
Result := _host;
end;
function TFTPSimples.getPassword: String;
begin
Result := _password;
end;
function TFTPSimples.getPort: Integer;
begin
Result := _port;
end;
function TFTPSimples.getUsername: String;
begin
Result := _username;
end;
procedure TFTPSimples.setFileFrom(const Value: String);
begin
_filefrom := Value;
end;
procedure TFTPSimples.setFileTo(const Value: String);
begin
_fileto := Value;
end;
procedure TFTPSimples.setHost(const Value: String);
begin
_host := Value;
end;
procedure TFTPSimples.setPassword(const Value: String);
begin
_password := Value;
end;
procedure TFTPSimples.setPort(const Value: Integer);
begin
_port := Value;
end;
procedure TFTPSimples.setUsername(const Value: String);
begin
_username := Value;
end;
end.
|
{$MODE OBJFPC}
Uses Math;
Const ginp='cwater.inp';
gout='cwater.out';
Var st:longint;
a,b,c,x,p:int64;
Procedure Enter;
Var tmp:int64;
Begin
readln(a,b,c);
if a>b then
begin
tmp:=a; a:=b; b:=tmp;
end;
End;
Function Diophante(a,b,c:int64; var x,p:int64):boolean;
Var m,n,r,xm,xn,xr,q:int64;
Begin
m:=a; n:=b;
xm:=1; xn:=0;
while n<>0 do
begin
q:=m div n;
r:=m-q*n;
xr:=xm-q*xn;
m:=n; xm:=xn;
n:=r; xn:=xr;
end;
result:=c mod m=0;
if not result then exit;
q:=c div m;
p:=abs(b div m);
x:=xm*q mod p;
if x<=0 then x:=x+p;
End;
Function Process:int64;
Begin
if not diophante(a,b,c,x,p) then result:=-1 else
result:=min(x+abs((c-a*x) div b),abs(x-p)+(c-a*(x-p)) div b);
End;
Begin
Assign(input,ginp); Assign(output,gout);
Reset(input); Rewrite(output);
readln(st);
for st:=1 to st do
begin
Enter;
writeln(Process);
end;
Close(input); Close(output);
End.
|
{
Inno Setup Preprocessor
Copyright (C) 2001-2002 Alex Yackimoff
}
unit IsppSessions;
interface
uses IsppTranslate;
procedure PushPreproc(APreproc: TPreprocessor);
function PopPreproc: TPreprocessor;
function PeekPreproc: TPreprocessor;
procedure Warning(const Msg: string; const Args: array of const);
procedure VerboseMsg(Level: Byte; const Msg: string; const Args: array of const);
procedure QueueFileForDeletion(const FileName: string);
implementation
{$I ..\Version.inc}
uses SysUtils, Classes, IsppStacks {$IFDEF IS_D12}, Windows{$ENDIF};
procedure Warning(const Msg: string; const Args: array of const);
var
P: TPreprocessor;
begin
P := PeekPreproc;
if Assigned(P) then
P.Warning(Msg, Args)
end;
procedure VerboseMsg(Level: Byte; const Msg: string; const Args: array of const);
var
P: TPreprocessor;
begin
P := PeekPreproc;
if Assigned(P) then
P.VerboseMsg(Level, Msg, Args);
end;
{ TPreprocessorFlowStack }
type
TPreprocessorFlowStack = class(TStack)
private
FReference: Pointer;
FTempFiles: TStringList;
public
constructor Create(var Reference);
destructor Destroy; override;
procedure Push(APreproc: TPreprocessor);
function Pop: TPreprocessor;
function Peek: TPreprocessor;
procedure QueueFile(const FileName: string);
end;
constructor TPreprocessorFlowStack.Create(var Reference);
begin
inherited Create;
TPreprocessorFlowStack(Reference) := Self;
FReference := @Reference
end;
destructor TPreprocessorFlowStack.Destroy;
var
I: Integer;
begin
TPreprocessorFlowStack(FReference^) := nil;
if FTempFiles <> nil then
begin
for I := 0 to FTempFiles.Count - 1 do
DeleteFile(PChar(FTempFiles[I]));
FTempFiles.Free;
end;
inherited Destroy;
end;
function TPreprocessorFlowStack.Peek: TPreprocessor;
begin
Result := TPreprocessor(inherited Peek);
end;
function TPreprocessorFlowStack.Pop: TPreprocessor;
begin
Result := TPreprocessor(inherited Pop);
if not AtLeast(1) then Free;
end;
procedure TPreprocessorFlowStack.Push(APreproc: TPreprocessor);
begin
inherited Push(APreproc);
end;
procedure TPreprocessorFlowStack.QueueFile(const FileName: string);
begin
if FTempFiles = nil then
begin
FTempFiles := TStringList.Create;
FTempFiles.Duplicates := dupIgnore;
end;
FTempFiles.Add(FileName);
end;
var
FlowStack: TPreprocessorFlowStack;
procedure PushPreproc(APreproc: TPreprocessor);
begin
if FlowStack = nil then
TPreprocessorFlowStack.Create(FlowStack);
FlowStack.Push(APreproc)
end;
function PopPreproc: TPreprocessor;
begin
if FlowStack <> nil then
Result := FlowStack.Pop
else
Result := nil;
end;
function PeekPreproc: TPreprocessor;
begin
if FlowStack <> nil then
Result := FlowStack.Peek
else
Result := nil;
end;
procedure QueueFileForDeletion(const FileName: string);
begin
if FlowStack <> nil then
FlowStack.QueueFile(FileName)
else
DeleteFile(PChar(FileName));
end;
end.
|
unit uInscricaoEstadual;
interface
uses
System.SysUtils, Winapi.Windows;
type
TConsisteInscricaoEstadual = function (const Insc, UF: AnsiString): Integer; stdcall;
type
TValidaIE = class
public
class function InscEstadual(Inscricao,Estado: string): Boolean;
end;
implementation
{ TValidaIE }
class function TValidaIE.InscEstadual(Inscricao, Estado: string): Boolean;
var
IRet: Integer;
IOk, IErro, IPar : Integer;
LibHandle : THandle;
ConsisteInscricaoEstadual : TConsisteInscricaoEstadual;
vinsc: string;
//CInsc:TInscEstadual;
begin
vinsc:='';
for iret:=1 to length(Inscricao) do
begin
if copy(inscricao,Iret,1) = '/' then
continue;
vinsc:=vinsc+copy(inscricao,Iret,1);
end;
//------------------------------------------------------------------------------
// inscricao Estadual pernambuco
if trim(Estado) = 'PE' then
begin
{
if length(trim(Inscricao)) = 9 then
begin
CInsc:=TInscEstadual.Create;
if CInsc.Insc_Estadual_PE(Inscricao) = false then
begin
MessageDlg ('Inscrição inválida para '+Estado+', Deixe em branco para sair',mtError,[mbOk],0);
FreeAndNil(CInsc);
exit;
end;
FreeAndNil(CInsc);
exit;
end;
}
end;
//------------------------------------------------------------------------------
try
LibHandle := LoadLibrary (PWideChar (Trim ('DllInscE32.Dll')));
if LibHandle <= HINSTANCE_ERROR then
raise Exception.Create ('Dll não carregada');
@ConsisteInscricaoEstadual := GetProcAddress (LibHandle,
'ConsisteInscricaoEstadual');
if @ConsisteInscricaoEstadual = nil then
raise Exception.Create('Entrypoint Download não encontrado na Dll');
IRet := ConsisteInscricaoEstadual (pAnsiChar(Ansistring(vinsc)),pAnsiChar(Ansistring(Estado)));
if Iret = 0 then
Result := True
// MessageDlg ('Inscrição válida para '+Estado,mtInformation,[mbOk],0)
else if Iret = 1 then
Result := False
// MessageDlg ('Inscrição inválida para '+Estado+', Deixe em branco para sair',mtError,[mbOk],0)
else
raise Exception.Create('Parâmetros inválidos');
finally
FreeLibrary (LibHandle);
end;
end;
end.
|
(*
* Copyright (c) 2010-2020, Alexandru Ciobanu (alex+git@ciobanu.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of this library nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$INCLUDE '..\TZDBPK\Version.inc'}
unit KnownTZCases;
interface
uses
SysUtils,
DateUtils,
TZDB;
type
{ Special record containing decomposed stuff }
TDecomposedPeriod = record
FStartsAt, FEndsAt: TDateTime;
FType: TLocalTimeType;
FAbbrv_AsDST,
FAbbrv_AsSTD,
FName_AsDST,
FName_AsSTD: string;
FBias_AsDST,
FBias_AsSTD: Int64;
{$IFDEF FPC}
class operator Equal(const ALeft, ARight: TDecomposedPeriod): Boolean;
{$ENDIF}
end;
const
CEurope_Bucharest_2010: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 40179; FEndsAt: 40265.1249999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 40265.1250115625; FEndsAt: 40265.1666666551; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 40265.1666782292; FEndsAt: 40482.1249999884; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'EEST'; FName_AsSTD: 'EEST'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 40482.1250115625; FEndsAt: 40482.1666666551; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EEST'; FName_AsSTD: 'EET'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 40482.1666782292; FEndsAt: 40543.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200)
);
const
CEtc_GMT12_2010: array[0 .. 0] of TDecomposedPeriod = (
(FStartsAt: 40179; FEndsAt: 40543.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT-12'; FAbbrv_AsSTD: 'GMT-12';
FName_AsDST: '-12'; FName_AsSTD: '-12'; FBias_AsDST: -43200; FBias_AsSTD: -43200)
);
const
CEtc_GMTMin9_1991: array[0 .. 0] of TDecomposedPeriod = (
(FStartsAt: 33239; FEndsAt: 33603.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+09'; FAbbrv_AsSTD: 'GMT+09';
FName_AsDST: '+09'; FName_AsSTD: '+09'; FBias_AsDST: 32400; FBias_AsSTD: 32400)
);
const
CAfrica_Accra_1997: array[0 .. 0] of TDecomposedPeriod = (
(FStartsAt: 35431; FEndsAt: 35795.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT'; FAbbrv_AsSTD: 'GMT';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0)
);
const
CAmerica_Araguaina_1950: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 18264; FEndsAt: 18368.9999999884; FType: lttDaylight; FAbbrv_AsDST: 'GMT-02'; FAbbrv_AsSTD: 'GMT-02';
FName_AsDST: '-02'; FName_AsSTD: '-02'; FBias_AsDST: -7200; FBias_AsSTD: -7200),
(FStartsAt: 18369.0000115625; FEndsAt: 18369.0416666551; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT-02'; FAbbrv_AsSTD: 'GMT-03';
FName_AsDST: '-02'; FName_AsSTD: '-03'; FBias_AsDST: -7200; FBias_AsSTD: -10800),
(FStartsAt: 18369.0416782292; FEndsAt: 18597.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT-03'; FAbbrv_AsSTD: 'GMT-03';
FName_AsDST: '-03'; FName_AsSTD: '-03'; FBias_AsDST: -10800; FBias_AsSTD: -10800),
(FStartsAt: 18598.0000115625; FEndsAt: 18598.0416666551; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 18598.0416782292; FEndsAt: 18628.9999999884; FType: lttDaylight; FAbbrv_AsDST: 'GMT-02'; FAbbrv_AsSTD: 'GMT-02';
FName_AsDST: '-02'; FName_AsSTD: '-02'; FBias_AsDST: -7200; FBias_AsSTD: -7200)
);
const
CAfrica_Cairo_2009: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 39814; FEndsAt: 39926.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 39927.0000115625; FEndsAt: 39927.0416666551; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 39927.0416782292; FEndsAt: 40045.9583333218; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'EEST'; FName_AsSTD: 'EEST'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 40045.9583448958; FEndsAt: 40045.9999999884; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EEST'; FName_AsSTD: 'EET'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 40046.0000115625; FEndsAt: 40178.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200)
);
const
CAfrica_Cairo_2010: array[0 .. 8] of TDecomposedPeriod = (
(FStartsAt: 40179; FEndsAt: 40297.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 40298.0000115625; FEndsAt: 40298.0416666551; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 40298.0416782292; FEndsAt: 40400.9583333218; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'EEST'; FName_AsSTD: 'EEST'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 40400.9583448958; FEndsAt: 40400.9999999884; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EEST'; FName_AsSTD: 'EET'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 40401.0000115625; FEndsAt: 40430.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 40431.0000115625; FEndsAt: 40431.0416666551; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 40431.0416782292; FEndsAt: 40451.9583333218; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'EEST'; FName_AsSTD: 'EEST'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 40451.9583448958; FEndsAt: 40451.9999999884; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EEST'; FName_AsSTD: 'EET'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 40452.0000115625; FEndsAt: 40543.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'EET'; FName_AsSTD: 'EET'; FBias_AsDST: 7200; FBias_AsSTD: 7200)
);
const
CEurope_London_2018: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 43101; FEndsAt: 43184.0416666551; FType: lttStandard; FAbbrv_AsDST: 'GMT'; FAbbrv_AsSTD: 'GMT';
FName_AsDST: 'GMT'; FName_AsSTD: 'GMT'; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 43184.0416782292; FEndsAt: 43184.0833333218; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 43184.0833448958; FEndsAt: 43401.0416666551; FType: lttDaylight; FAbbrv_AsDST: 'GMT+01'; FAbbrv_AsSTD: 'GMT+01';
FName_AsDST: 'BST'; FName_AsSTD: 'BST'; FBias_AsDST: 3600; FBias_AsSTD: 3600),
(FStartsAt: 43401.0416782292; FEndsAt: 43401.0833333218; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+01'; FAbbrv_AsSTD: 'GMT';
FName_AsDST: 'BST'; FName_AsSTD: 'GMT'; FBias_AsDST: 3600; FBias_AsSTD: 0),
(FStartsAt: 43401.0833448958; FEndsAt: 43465.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT'; FAbbrv_AsSTD: 'GMT';
FName_AsDST: 'GMT'; FName_AsSTD: 'GMT'; FBias_AsDST: 0; FBias_AsSTD: 0)
);
const
CAmerica_St_Johns_2018: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 43101; FEndsAt: 43170.0833333218; FType: lttStandard; FAbbrv_AsDST: 'GMT-03:30'; FAbbrv_AsSTD: 'GMT-03:30';
FName_AsDST: 'NST'; FName_AsSTD: 'NST'; FBias_AsDST: -12600; FBias_AsSTD: -12600),
(FStartsAt: 43170.0833448958; FEndsAt: 43170.1249999884; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 43170.1250115625; FEndsAt: 43408.0416666551; FType: lttDaylight; FAbbrv_AsDST: 'GMT-02:30'; FAbbrv_AsSTD: 'GMT-02:30';
FName_AsDST: 'NDT'; FName_AsSTD: 'NDT'; FBias_AsDST: -9000; FBias_AsSTD: -9000),
(FStartsAt: 43408.0416782292; FEndsAt: 43408.0833333218; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT-02:30'; FAbbrv_AsSTD: 'GMT-03:30';
FName_AsDST: 'NDT'; FName_AsSTD: 'NST'; FBias_AsDST: -9000; FBias_AsSTD: -12600),
(FStartsAt: 43408.0833448958; FEndsAt: 43465.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT-03:30'; FAbbrv_AsSTD: 'GMT-03:30';
FName_AsDST: 'NST'; FName_AsSTD: 'NST'; FBias_AsDST: -12600; FBias_AsSTD: -12600)
);
const
CAsia_Jerusalem_2005: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 38353; FEndsAt: 38443.0833333218; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IST'; FName_AsSTD: 'IST'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 38443.0833448958; FEndsAt: 38443.1249999884; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 38443.1250115625; FEndsAt: 38634.0416666551; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'IDT'; FName_AsSTD: 'IDT'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 38634.0416782292; FEndsAt: 38634.0833333218; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IDT'; FName_AsSTD: 'IST'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 38634.0833448958; FEndsAt: 38717.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IST'; FName_AsSTD: 'IST'; FBias_AsDST: 7200; FBias_AsSTD: 7200)
);
const
CAsia_Jerusalem_2006: array[0 .. 4] of TDecomposedPeriod = (
(FStartsAt: 38718; FEndsAt: 38807.0833333218; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IST'; FName_AsSTD: 'IST'; FBias_AsDST: 7200; FBias_AsSTD: 7200),
(FStartsAt: 38807.0833448958; FEndsAt: 38807.1249999884; FType: lttInvalid; FAbbrv_AsDST: ''; FAbbrv_AsSTD: '';
FName_AsDST: ''; FName_AsSTD: ''; FBias_AsDST: 0; FBias_AsSTD: 0),
(FStartsAt: 38807.1250115625; FEndsAt: 38991.0416666551; FType: lttDaylight; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+03';
FName_AsDST: 'IDT'; FName_AsSTD: 'IDT'; FBias_AsDST: 10800; FBias_AsSTD: 10800),
(FStartsAt: 38991.0416782292; FEndsAt: 38991.0833333218; FType: lttAmbiguous; FAbbrv_AsDST: 'GMT+03'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IDT'; FName_AsSTD: 'IST'; FBias_AsDST: 10800; FBias_AsSTD: 7200),
(FStartsAt: 38991.0833448958; FEndsAt: 39082.9999999884; FType: lttStandard; FAbbrv_AsDST: 'GMT+02'; FAbbrv_AsSTD: 'GMT+02';
FName_AsDST: 'IST'; FName_AsSTD: 'IST'; FBias_AsDST: 7200; FBias_AsSTD: 7200)
);
implementation
{$IFDEF FPC}
class operator TDecomposedPeriod.Equal(const ALeft, ARight: TDecomposedPeriod): Boolean;
begin
Result :=
(ALeft.FStartsAt = ARight.FStartsAt) and
(ALeft.FEndsAt = ARight.FEndsAt) and
(ALeft.FType = ARight.FType) and
(ALeft.FAbbrv_AsDST = ARight.FAbbrv_AsDST) and
(ALeft.FAbbrv_AsSTD = ARight.FAbbrv_AsSTD) and
(ALeft.FName_AsDST = ARight.FName_AsDST) and
(ALeft.FName_AsSTD = ARight.FName_AsSTD) and
(ALeft.FBias_AsDST = ARight.FBias_AsDST) and
(ALeft.FBias_AsSTD = ARight.FBias_AsSTD);
end;
{$ENDIF}
end.
|
unit Vittee.RecordArray;
interface
uses
TypInfo, RTTI, SysUtils, Classes;
type
IRecordArray<T> = interface
['{8B71B837-E9F6-40B0-AFFB-882F436F287B}']
procedure SetLength(const Value: Integer);
function GetElement(Index: Integer): T;
function GetData: T;
function GetLength: Integer;
function ElementSize: Integer;
function DataSize: Integer;
procedure Wipe;
//
procedure Append(AOther: IRecordArray<T>);
//
property Length: Integer read GetLength write SetLength;
property Data: T read GetData;
property Elements[Index: Integer]: T read GetElement; default;
end;
TRecordArray<T> = class(TInterfacedObject, IRecordArray<T>)
private
FPtr: Pointer;
FData: T;
FElementSize: Integer;
FDataSize: Integer;
FLength: Integer;
procedure SetLength(const Value: Integer);
function GetElement(Index: Integer): T;
function GetData: T;
function GetLength: Integer;
public
constructor Create(ALength: Integer);
destructor Destroy; override;
//
procedure Append(AOther: IRecordArray<T>);
function ElementSize: Integer;
function DataSize: Integer;
procedure Wipe;
//
property Length: Integer read GetLength write SetLength;
property Data: T read GetData;
property Elements[Index: Integer]: T read GetElement; default;
end;
implementation
{ TRecordArray<T> }
procedure TRecordArray<T>.Append(AOther: IRecordArray<T>);
var
Other: TRecordArray<T>;
JointIndex: Integer;
Joint: T;
begin
Other := AOther as TRecordArray<T>;
JointIndex := Length;
Length := Length + Other.Length;
Joint := Self[Length];
//
Move(Pointer(Other.FPtr)^, PPointer(@Joint)^, Other.FDataSize);
end;
constructor TRecordArray<T>.Create(ALength: Integer);
var
Info: PTypeInfo;
RttiType: TRttiPointerType;
begin
Info := TypeInfo(T);
if (Info.Kind = tkPointer) and (Info.TypeData.RefType = nil) then
begin
raise EInvalidPointer.CreateFmt('%s is not a typed pointer', [Info.Name]);
end else
if Info.Kind <> tkPointer then
begin
raise EInvalidOperation.CreateFmt('%s is not a pointer', [Info.Name]);
end;
with TRttiContext.Create do
begin
RttiType := TRttiPointerType(GetType(Info));
FElementSize := RttiType.ReferredType.TypeSize;
end;
FData := default(T);
FPtr := nil;
SetLength(ALength);
end;
function TRecordArray<T>.DataSize: Integer;
begin
Result := FDataSize;
end;
destructor TRecordArray<T>.Destroy;
begin
if FPtr <> nil then
begin
FreeMem(FPtr);
end;
inherited;
end;
function TRecordArray<T>.ElementSize: Integer;
begin
Result := FElementSize;
end;
function TRecordArray<T>.GetData: T;
begin
Result := FData;
end;
function TRecordArray<T>.GetElement(Index: Integer): T;
begin
PPointer(@Result)^ := Pointer(NativeInt(FPtr) + Index * FElementSize);
end;
function TRecordArray<T>.GetLength: Integer;
begin
Result := FLength;
end;
procedure TRecordArray<T>.SetLength(const Value: Integer);
begin
if FLength = Value then
Exit;
FLength := Value;
FDataSize := FElementSize * Value;
if FPtr = nil then
begin
FPtr := AllocMem(FDataSize);
end else
begin
ReallocMem(FPtr, FDataSize);
end;
PPointer(@FData)^ := FPtr;
end;
procedure TRecordArray<T>.Wipe;
begin
FillChar(FPtr^, FDataSize, 0);
end;
end.
|
unit ADLSConnector.Presenter;
interface
uses
ADLSConnector.Interfaces, REST.Client, REST.Authenticator.OAuth;
type
TADLSConnectorPresenter = class(TInterfacedObject, IADLSConnectorPresenter)
private
FRESTClient: TRESTClient;
FRESTRequest: TRESTRequest;
FRESTResponse: TRESTResponse;
FOAuth2_AzureDataLake: TOAuth2Authenticator;
/// <summary>
/// Reset all of the rest-components for a new request
/// </summary>
procedure ResetRESTComponentsToDefaults;
procedure InitComponents;
procedure LocalRESTRequestAfterExecute(Sender: TCustomRESTRequest);
protected
FADLSConnector: IADLSConnectorView;
FAccessToken: string;
function GetToken: string;
public
constructor Create(AADLSConnectorView: IADLSConnectorView);
destructor Destroy; override;
procedure GetAccessToken;
function GetBaseURL: string;
function GetClientID: string;
property AccessToken: string read GetToken;
//property Authenticator: TOAuth2Authenticator read FOAuth2_AzureDataLake;
end;
implementation
uses
System.SysUtils, REST.Types, REST.Json;
{ TADLSPresenter }
constructor TADLSConnectorPresenter.Create(AADLSConnectorView: IADLSConnectorView);
begin
FADLSConnector := AADLSConnectorView;
FRESTClient := TRESTClient.Create(''{FADLSConnector.GetBaseURL});
FRESTRequest := TRESTRequest.Create(nil);
FRESTResponse := TRESTResponse.Create(nil);
FOAuth2_AzureDataLake := TOAuth2Authenticator.Create(nil);
FRESTRequest.OnAfterExecute := LocalRESTRequestAfterExecute;
end;
destructor TADLSConnectorPresenter.Destroy;
begin
FOAuth2_AzureDataLake.Free;
FRESTResponse.Free;
FRESTRequest.Free;
FRESTClient.Free;
end;
procedure TADLSConnectorPresenter.GetAccessToken;
begin
ResetRESTComponentsToDefaults;
InitComponents;
FRESTClient.BaseURL := FADLSConnector.GetAccessTokenEndpoint;
FRESTRequest.Method := TRESTRequestMethod.rmPOST;
FRESTRequest.Params.AddItem('client_id', FADLSConnector.GetClientID, TRESTRequestParameterKind.pkGETorPOST);
FRESTRequest.Params.AddItem('client_secret', FADLSConnector.GetClientSecret, TRESTRequestParameterKind.pkGETorPOST);
FRESTRequest.Params.AddItem('grant_type', 'client_credentials', TRESTRequestParameterKind.pkGETorPOST);
FRESTRequest.Params.AddItem('resource', 'https://management.core.windows.net/');
FRESTRequest.Execute;
if FRESTRequest.Response.GetSimpleValue('access_token', FAccessToken) then
begin
FOAuth2_AzureDataLake.AccessToken := FAccessToken;
FADLSConnector.SetAccessToken(FAccessToken);
end;
end;
function TADLSConnectorPresenter.GetBaseURL: string;
begin
Result := FADLSConnector.GetBaseURL;
end;
function TADLSConnectorPresenter.GetClientID: string;
begin
FADLSConnector.GetClientID;
end;
function TADLSConnectorPresenter.GetToken: string;
begin
Result := FAccessToken;
end;
procedure TADLSConnectorPresenter.InitComponents;
begin
FOAuth2_AzureDataLake.AccessTokenEndpoint := FADLSConnector.GetAccessTokenEndpoint;
FOAuth2_AzureDataLake.AuthorizationEndpoint := FADLSConnector.GetAuthorizationEndpoint;
FOAuth2_AzureDataLake.ResponseType := TOAuth2ResponseType(0);
FOAuth2_AzureDataLake.TokenType := TOAuth2TokenType(0);
FRESTClient.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
FRESTClient.Authenticator := FOAuth2_AzureDataLake;
FRESTRequest.Client := FRESTClient;
FRESTRequest.Response := FRESTResponse;
end;
procedure TADLSConnectorPresenter.LocalRESTRequestAfterExecute(
Sender: TCustomRESTRequest);
begin
FADLSConnector.SetResponseData('');
//lbl_status.Caption := 'URI: ' + Sender.GetFullRequestURL + ' Execution time: ' +
// IntToStr(Sender.ExecutionPerformance.TotalExecutionTime) + 'ms';
if Assigned(FRESTResponse.JSONValue) then
begin
FADLSConnector.SetResponseData(TJson.Format(FRESTResponse.JSONValue));
end
else
begin
FADLSConnector.AddResponseData(FRESTResponse.Content);
end;
end;
procedure TADLSConnectorPresenter.ResetRESTComponentsToDefaults;
begin
FRESTClient.ResetToDefaults;
FRESTRequest.ResetToDefaults;
FRESTResponse.ResetToDefaults;
end;
end.
|
unit U_Organizer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.StdCtrls,
Vcl.Buttons, Vcl.DBGrids, Data.DB, Data.SqlExpr, Data.DbxSqlite, Vcl.Menus;
type
TF_Organizer = class(TForm)
Panel1: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
BitBtn4: TBitBtn;
DBConnection: TSQLConnection;
DBGrid1: TDBGrid;
Menu: TMainMenu;
M_Database: TMenuItem;
M_NewCustomer: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
// procedure ShowCustomers();
end;
TDatabase = class
private
Connector: TSQLConnection;
function IsNumeric(Value: string; const AllowFloat: Boolean;
const TrimWhiteSpace: Boolean = True): Boolean;
public
Constructor Create(DBConn : TSQLConnection);
procedure Connect(DBFile: String);
procedure Disconnect;
procedure RebuildStructure;
procedure Query(QString: String);
procedure AddCustomer(name, address, address_city, address_province, contact_phone,
contact_fax, contact_mail, tax_code, iban_code, deadline, notes: String;
address_number, address_zip: Word);
function QueryRes(QString: String): TDataSet;
function CheckStructure: Boolean;
function FieldValueExists(field, value: String): Boolean;
end;
var
Database: TDatabase;
F_Organizer: TF_Organizer;
implementation
uses
U_Customer;
{$R *.dfm}
// Implementation of TDatabase Class
//------------------------------------------------------------------------------
constructor TDatabase.Create(DBConn : TSQLConnection);
begin
Self.Connector := DBConn;
end;
function TDatabase.IsNumeric(Value: string; const AllowFloat: Boolean;
const TrimWhiteSpace: Boolean = True): Boolean;
var
ValueInt: Int64; // dummy integer value
ValueFloat: Extended; // dummy float value
begin
if TrimWhiteSpace then
Value := Trim(Value);
// Check for valid integer
Result := TryStrToInt64(Value, ValueInt);
if not Result and AllowFloat then
// Wasn't valid as integer, try float
Result := TryStrToFloat(Value, ValueFloat);
end;
procedure TDatabase.Connect(DBFile: String);
begin
try
Self.Connector.Params.Add('Database=' + DBFile);
Self.Connector.Connected := True;
except
on E: EDatabaseError do
begin
MessageDlg('Impossibile aprire il Database (' + E.Message +')', mtError, [mbOK], 0);
Application.Terminate;
end;
end;
end;
procedure TDatabase.Disconnect;
begin
Self.Connector.Connected:= False;
end;
procedure TDatabase.Query(QString: String);
begin
try
Self.Connector.Execute(QString, nil, nil);
except
on E: Exception do
MessageDlg('Impossibile eseguire la Query (' + E.Message +')', mtError, [mbOK], 0);
end;
end;
function TDatabase.QueryRes(QString: String): TDataSet;
begin
try
Self.Connector.Execute(QString, nil, Result);
except
on E: Exception do
MessageDlg('Impossibile eseguire la Query (' + E.Message +')', mtError, [mbOK], 0);
end;
end;
function TDatabase.CheckStructure: Boolean;
var
Query: String;
QueryRes: TDataSet;
begin
Query:= 'SELECT COUNT(*) FROM sqlite_master WHERE type=''table'' AND (name = ''customers'' OR name = ''customer_history'');';
QueryRes:= Self.QueryRes(Query);
if (QueryRes.Fields[0].AsInteger >= 2) then
Result:= True
else
Result:= False;
end;
function TDatabase.FieldValueExists(Field, Value: String): Boolean;
var
Query: String;
QueryRes: TDataSet;
begin
if not( IsNumeric(Value, False, True) ) then
Query:= 'SELECT COUNT(*) FROM customers WHERE ' + Field + ' = ''' + Value + ''';'
else
Query:= 'SELECT COUNT(*) FROM customers WHERE ' + Field + ' = ' + Value + ';';
QueryRes:= Self.QueryRes(Query);
if (QueryRes.Fields[0].AsInteger >= 1) then
Result:= True
else
Result:= False;
end;
procedure TDatabase.RebuildStructure;
var
Query : String;
begin
// Eventually rebuild Customers Table
Query:= 'CREATE TABLE IF NOT EXISTS customers ( '
+ 'id INTEGER AUTO_INCREMENT, '
+ 'name varchar(50) NOT NULL, '
+ 'address varchar(50) NOT NULL, '
+ 'address_number int(4) NOT NULL, '
+ 'address_zip int(5) NOT NULL, '
+ 'address_city varchar(25) NOT NULL, '
+ 'address_province char(2) NOT NULL, '
+ 'contact_phone varchar(15) NOT NULL, '
+ 'contact_fax varchar(15) DEFAULT NULL, '
+ 'contact_mail varchar(50) DEFAULT NULL, '
+ 'tax_code varchar(16) DEFAULT NULL, '
+ 'iban_code char(27) DEFAULT NULL, '
+ 'deadline date DEFAULT NULL, '
+ 'notes text, '
+ 'PRIMARY KEY (id), '
+ 'UNIQUE (name), '
+ 'UNIQUE (address,address_number,address_zip,address_city,address_province) '
+ ');';
Self.Query(Query);
// Eventually rebuild Customer History Table
Query:= 'CREATE TABLE IF NOT EXISTS customer_history ( '
+ 'cid INTEGER AUTO_INCREMENT, '
+ 'work_date date NOT NULL, '
+ 'work_notes text, '
+ 'PRIMARY KEY (cid), '
+ 'FOREIGN KEY (cid) REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE '
+ ');';
Self.Query(Query);
end;
procedure TDatabase.AddCustomer(name, address, address_city, address_province, contact_phone,
contact_fax, contact_mail, tax_code, iban_code, deadline, notes: String;
address_number, address_zip: Word);
var
Query : String;
begin
// Insert new Customer
Query:= 'INSERT INTO customers ( '
+ 'name, address, address_number, address_zip, address_city, address_province, '
+ 'contact_phone, contact_fax, contact_mail, tax_code, iban_code, deadline, notes ) '
+ 'VALUES ( '
+ '''' + Trim(name) + ''', '
+ '''' + Trim(address) + ''', '
+ '''' + IntToStr(address_number) + ''', '
+ '''' + IntToStr(address_zip) + ''', '
+ '''' + Trim(address_city) + ''', '
+ '''' + Trim(address_province) + ''', '
+ '''' + Trim(contact_phone) + ''', '
+ '''' + Trim(contact_fax) + ''', '
+ '''' + Trim(contact_mail) + ''', '
+ '''' + Trim(tax_code) + ''', '
+ '''' + Trim(iban_code) + ''', '
+ '''' + Trim(deadline) + ''', '
+ '''' + Trim(notes) + ''' '
+ ' );';
Self.Query(Query);
MessageDlg('Il nuovo cliente č stato inserito correttamente', mtInformation, [mbOK], 0);
end;
//------------------------------------------------------------------------------
procedure ShowCustomers();
begin
end;
procedure TF_Organizer.BitBtn1Click(Sender: TObject);
begin
F_Customer.Show;
end;
procedure TF_Organizer.FormCreate(Sender: TObject);
var
ProgramDataFolder: String;
begin
ProgramDataFolder:= GetEnvironmentVariable('PROGRAMDATA');
// Verifica struttura directory dati programma
if not( DirectoryExists(ProgramDataFolder + '\Wally') ) then
CreateDir(ProgramDataFolder + '\Wally\');
// Verifica esistenza file Database
if not( FileExists(ProgramDataFolder + '\Wally\Wally.db') ) then
MessageDlg('Database non trovato, ne verrā creato uno di nuovo', mtWarning, [mbOK], 0);
Database:= TDatabase.Create(DBConnection);
Database.Connect(ProgramDataFolder + '\Wally\Wally.db');
// Verifica struttura Database
if not(Database.CheckStructure) then
begin
MessageDlg('Database vuoto o corrotto, la struttura verrā rispristinata', mtWarning, [mbOK], 0);
Database.RebuildStructure;
end;
//Center application on screen
F_Organizer.Left:= (Screen.Width - F_Organizer.Width) div 2;
F_Organizer.Top:= (Screen.Height - F_Organizer.Height) div 2;
end;
procedure TF_Organizer.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Database.Disconnect;
end;
end.
|
unit FRegistration;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniEdit,
uniGUIBaseClasses, uniLabel, uniButton, FireDAC.Stan.Intf, uniBasicGrid,
uniDBGrid, uniCheckBox, uniPanel, uniDBNavigator, FireDAC.Stan.Param,
FireDAC.Phys.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageBin, uniMultiItem, uniComboBox,
uniDBComboBox, uniDBLookupComboBox;
type
TfrmRegistration = class(TUniForm)
undbgrd1: TUniDBGrid;
lbNameTab: TUniLabel;
btnExit: TUniButton;
undbnvgtrTb1: TUniDBNavigator;
dsUsers: TDataSource;
fdpdtsqlUsers: TFDUpdateSQL;
fdqryUsers: TFDQuery;
fdqryCheckLogin: TFDQuery;
unhdnpnlSuperUser: TUniHiddenPanel;
cbbStatus: TUniDBLookupComboBox;
cbbBlock: TUniDBLookupComboBox;
lrgntfldUsersID: TLargeintField;
strngfldUsersNAME: TStringField;
strngfldUsersLOGIN: TStringField;
strngfldUsersPASSWORD: TStringField;
smlntfldUsersSUPERUSER: TSmallintField;
smlntfldUsersBLOCKED: TSmallintField;
strngfldUsersStrStatus: TStringField;
strngfldUsersStrBlock: TStringField;
procedure btnExitClick(Sender: TObject);
procedure fdqryUsersBeforePost(DataSet: TDataSet);
procedure UniFormShow(Sender: TObject);
procedure undbgrd1ColumnFilter(Sender: TUniDBGrid; const Column: TUniDBGridColumn;
const Value: Variant);
private
{ Private declarations }
public
{ Public declarations }
FilterStrStatus : string;
FilterStrBlock : string;
end;
function frmRegistration: TfrmRegistration;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication, Main, FormLogin, FAdmin;
function frmRegistration: TfrmRegistration;
begin
Result := TfrmRegistration(UniMainModule.GetFormInstance(TfrmRegistration));
end;
procedure TfrmRegistration.btnExitClick(Sender: TObject);
begin
frmRegistration.Close;
frmAdmin.Show(nil);
end;
procedure TfrmRegistration.fdqryUsersBeforePost(DataSet: TDataSet);
begin
if fdqryUsers.State in [dsInsert] then
begin
fdqryCheckLogin.ParamByName('login').Value := DataSet.FieldByName('login').Value;
fdqryCheckLogin.Open;
if fdqryCheckLogin.RecordCount > 0 then
begin
fdqryCheckLogin.Close;
raise UniErrorException.Create('Такой логин уже существует!');
end
else
fdqryCheckLogin.Close;
end;
end;
procedure TfrmRegistration.undbgrd1ColumnFilter(Sender: TUniDBGrid; const Column: TUniDBGridColumn; const Value: Variant);
var
S: string;
begin
S := Value;
if Column.FieldName = 'StrStatus' then
begin
if S = '' then
FilterStrStatus := ''
else
begin
FilterStrStatus := '(SUPERUSER = ' + S + ')';
end;
end;
if Column.FieldName = 'StrBlock' then
begin
if S = '' then
FilterStrBlock := ''
else
begin
FilterStrBlock := '(BLOCKED = ' + S + ')';
end;
end;
fdqryUsers.Filter := '';
if FilterStrStatus <> '' then
fdqryUsers.Filter := FilterStrStatus;
if FilterStrBlock <> '' then
if fdqryUsers.Filter <> '' then
fdqryUsers.Filter := fdqryUsers.Filter + ' AND ' + FilterStrBlock
else
fdqryUsers.Filter := FilterStrBlock;
if (FilterStrStatus <> '') or (FilterStrBlock <> '') then
fdqryUsers.Filtered := True;
end;
procedure TfrmRegistration.UniFormShow(Sender: TObject);
begin
fdqryUsers.Active := True;
FilterStrStatus := '';
FilterStrBlock := '';
fdqryUsers.Filter := '';
fdqryUsers.Filtered := False;
end;
end.
|
unit MFichas.Model.Item.Interfaces;
interface
uses
MFichas.Model.Entidade.VENDAITENS;
type
iModelItem = interface;
iModelItemMetodos = interface;
iModelItemMetodosVender = interface;
iModelItemMetodosCancelar = interface;
iModelItemMetodosDevolver = interface;
iModelItemGravarNoBanco = interface;
iModelItemIterator = interface;
iModelItem = interface
['{5B8DF055-DE04-4F76-9FE8-2FCF25CA52A8}']
function Metodos : iModelItemMetodos;
function Entidade : TVENDAITENS; overload;
function Entidade(AEntidade: TVENDAITENS): iModelItem; overload;
function Iterator : iModelItemIterator;
function GravarNoBanco : iModelItemGravarNoBanco;
function ValorTotal : Currency;
end;
iModelItemMetodos = interface
['{19104467-5F17-4446-8955-479F0EF22859}']
function Vender : iModelItemMetodosVender;
function Cancelar : iModelItemMetodosCancelar;
function Devolver : iModelItemMetodosDevolver;
function &End : iModelItem;
end;
iModelItemMetodosVender = interface
['{074EC8C6-BC20-4B2B-81D7-3BAB3422F5ED}']
function Codigo(ACodigo: String) : iModelItemMetodosVender;
function Quantidade(AQuantidade: Double) : iModelItemMetodosVender;
function Valor(AValor: Currency) : iModelItemMetodosVender;
function &End : iModelItemMetodos;
end;
iModelItemMetodosCancelar = interface
['{FAF10726-6CEA-4531-BB55-D6213F8C6FC1}']
function Index(AIndex: Integer): iModelItemMetodosCancelar;
function &End : iModelItemMetodos;
end;
iModelItemMetodosDevolver = interface
['{45A37434-3D88-4453-AF80-1B9D6F7040EF}']
function Codigo(ACodigo: String) : iModelItemMetodosDevolver;
function Quantidade(AQuantidade: Double) : iModelItemMetodosDevolver;
function Valor(AValor: Currency) : iModelItemMetodosDevolver;
function &End : iModelItemMetodos;
end;
iModelItemGravarNoBanco = interface
['{852B1824-F8DB-409D-B00C-9ECBB4E8F240}']
function Executar: iModelItemGravarNoBanco;
function &End : iModelItem;
end;
iModelItemIterator = interface
['{803BC0B9-1FB8-4D1E-841E-557541A3CA25}']
function hasNext: Boolean;
function Next: iModelItem;
function Add(AItem: iModelItem) : iModelItemIterator;
function Remove(AIndex: Integer): iModelItemIterator;
function ClearIterator : iModelItemIterator;
function &End : iModelItem;
end;
implementation
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 ClpX9ECPoint;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
ClpCryptoLibTypes,
ClpDerOctetString,
ClpIAsn1OctetString,
ClpIProxiedInterface,
ClpIECInterface,
ClpIX9ECPoint,
ClpAsn1Encodable;
type
// /**
// * class for describing an ECPoint as a Der object.
// */
TX9ECPoint = class sealed(TAsn1Encodable, IX9ECPoint)
strict private
var
Fencoding: IAsn1OctetString;
Fc: IECCurve;
Fp: IECPoint;
function GetIsPointCompressed: Boolean; inline;
function GetPoint: IECPoint; inline;
public
constructor Create(const p: IECPoint); overload;
constructor Create(const p: IECPoint; compressed: Boolean); overload;
constructor Create(const c: IECCurve;
const encoding: TCryptoLibByteArray); overload;
constructor Create(const c: IECCurve; const s: IAsn1OctetString); overload;
property Point: IECPoint read GetPoint;
property IsPointCompressed: Boolean read GetIsPointCompressed;
function GetPointEncoding(): TCryptoLibByteArray; inline;
// /**
// * Produce an object suitable for an Asn1OutputStream.
// * <pre>
// * ECPoint ::= OCTET STRING
// * </pre>
// * <p>
// * Octet string produced using ECPoint.GetEncoded().</p>
// */
function ToAsn1Object(): IAsn1Object; override;
end;
implementation
{ TX9ECPoint }
constructor TX9ECPoint.Create(const c: IECCurve;
const encoding: TCryptoLibByteArray);
begin
inherited Create();
Fc := c;
Fencoding := TDerOctetString.Create(System.Copy(encoding));
end;
constructor TX9ECPoint.Create(const p: IECPoint; compressed: Boolean);
begin
inherited Create();
Fp := p.Normalize();
Fencoding := TDerOctetString.Create(p.GetEncoded(compressed));
end;
constructor TX9ECPoint.Create(const p: IECPoint);
begin
Create(p, false);
end;
constructor TX9ECPoint.Create(const c: IECCurve; const s: IAsn1OctetString);
begin
Create(c, s.GetOctets());
end;
function TX9ECPoint.GetPointEncoding(): TCryptoLibByteArray;
begin
Result := Fencoding.GetOctets();
end;
function TX9ECPoint.GetIsPointCompressed: Boolean;
var
octets: TCryptoLibByteArray;
begin
octets := Fencoding.GetOctets();
Result := (octets <> Nil) and (System.Length(octets) > 0) and
((octets[0] = 2) or (octets[0] = 3));
end;
function TX9ECPoint.GetPoint: IECPoint;
begin
if (Fp = Nil) then
begin
Fp := Fc.DecodePoint(Fencoding.GetOctets()).Normalize();
end;
Result := Fp;
end;
function TX9ECPoint.ToAsn1Object: IAsn1Object;
begin
Result := Fencoding;
end;
end.
|
(*
* icop 对象池、哈希表等
*)
unit iocp_objPools;
interface
{$I in_iocp.inc}
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, {$ELSE}
Windows, Classes, SysUtils, {$ENDIF}
iocp_api, iocp_base, iocp_lists, iocp_utils, iocp_baseObjs;
type
// ===================== 对象管理池 类 =====================
// 遍历对象池的回调方法
TScanListEvent = procedure(ObjType: TObjectType; var FromObject: Pointer;
const Data: TObject; var CancelScan: Boolean) of object;
TObjectPool = class(TObject)
private
FLock: TThreadLock; // 锁
FObjectType: TObjectType; // 对象类型
FBuffer: Array of TLinkRec; // 自动分配的内存块 FBuffer
FAutoAllocate: Boolean; // 自动分配 FBuffer
FFirstNode: PLinkRec; // 当前 在用 链表顶
FFreeNode: PLinkRec; // 当前 空闲 链表顶
// 统计数字
FIniCount: Integer; // 初始大小
FNodeCount: Integer; // 全部节点数(对象数)
FUsedCount: Integer; // 在用节点数(对象数)
function AddNode: PLinkRec;
function GetFull: Boolean;
procedure CreateObjLink(ASize: Integer);
procedure DeleteObjLink(var FirstNode: PLinkRec; FreeObject: Boolean);
procedure DefaultFreeResources;
procedure FreeNodeObject(ANode: PLinkRec);
protected
procedure CreateObjData(const ALinkNode: PLinkRec); virtual;
procedure FreeListObjects(List: TInDataList);
procedure OptimizeDetail(List: TInDataList);
public
constructor Create(AObjectType: TObjectType; ASize: Integer);
destructor Destroy; override;
public
procedure Clear;
function Pop: PLinkRec; overload; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Push(const ANode: PLinkRec); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Lock; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure UnLock; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Optimize; virtual;
procedure Scan(var FromObject: Pointer; Callback: TScanListEvent);
public
property FirstNode: PLinkRec read FFirstNode;
property Full: Boolean read GetFull;
property IniCount: Integer read FIniCount;
property NodeCount: Integer read FNodeCount;
property ObjectType: TObjectType read FObjectType;
property UsedCount: Integer read FUsedCount;
end;
// ====================== 带列表的池 类 ======================
TDataListPool = class(TObjectPool)
private
FNodeList: TInDataList; // 资源节点列表
protected
procedure CreateObjData(const ALinkNode: PLinkRec); override;
public
constructor Create(AObjectType: TObjectType; ASize: Integer);
destructor Destroy; override;
public
procedure Optimize; override;
end;
// ====================== 服务端 Socket 管理 类 ======================
TIOCPSocketPool = class(TDataListPool)
private
FSocketClass: TClass; // TBaseSocket 类
protected
procedure CreateObjData(const ALinkNode: PLinkRec); override;
public
constructor Create(AObjectType: TObjectType; ASize: Integer);
public
function Clone(Source: TObject): TObject;
procedure GetSockets(List: TInList; IngoreSocket: TObject = nil;
AdminType: Boolean = False; Group: string = '');
end;
// ===================== 收、发内存管理 类 =====================
TIODataPool = class(TDataListPool)
protected
procedure CreateObjData(const ALinkNode: PLinkRec); override;
public
constructor Create(ASize: Integer);
destructor Destroy; override;
end;
// ====================== TStringHash 表 ======================
// 用 Delphi 2007 的 TStringHash 修改
PHashItem = ^THashItem;
PPHashItem = ^PHashItem;
THashItem = record
Key: AnsiString; // 用单字节
Value: Pointer; // 改!存放指针
Next: PHashItem;
end;
TScanHashEvent = procedure(var Data: Pointer) of object;
TStringHash = class(TObject)
private
FLock: TThreadLock; // 增加锁
FCount: Integer;
FBuckets: array of PHashItem;
function Find(const Key: AnsiString): PPHashItem;
protected
function HashOf(const Key: AnsiString): Cardinal; virtual;
procedure FreeItemData(Item: PHashItem); virtual;
public
constructor Create(Size: Cardinal = 256);
destructor Destroy; override;
function Modify(const Key: AnsiString; Value: Pointer): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF}
function ValueOf(const Key: AnsiString): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF}
function ValueOf2(const Key: AnsiString): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF}
function ValueOf3(const Key: AnsiString; var Item: PPHashItem): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Add(const Key: AnsiString; Value: Pointer); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Clear;
procedure Lock; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure UnLock; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Remove(const Key: AnsiString); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Remove2(Item: PPHashItem); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Scan(var Dest: Pointer; CallEvent: TScanListEvent); overload;
procedure Scan(CallEvent: TScanHashEvent); overload;
public
property Count: Integer read FCount;
end;
// ================== 防攻击 管理 ==================
TPreventAttack = class(TStringHash)
protected
procedure FreeItemData(Item: PHashItem); override;
public
function CheckAttack(const PeerIP: String; MSecond, InterCount: Integer): Boolean;
procedure DecRef(const PeerIP: String);
end;
implementation
uses
iocp_sockets;
type
TBaseSocketRef = class(TBaseSocket);
{ TObjectPool }
function TObjectPool.AddNode: PLinkRec;
begin
// 增加新节点, 加到空闲链表顶
Inc(FNodeCount);
Result := New(PLinkRec);
Result^.Auto := False;
{$IFDEF DEBUG_MODE}
Result^.No := FNodeCount;
{$ENDIF}
CreateObjData(Result); // 建关联的对象
Result^.Prev := Nil;
Result^.Next := FFreeNode;
if (FFreeNode <> Nil) then
FFreeNode^.Prev := Result;
FFreeNode := Result;
end;
procedure TObjectPool.Clear;
begin
FLock.Acquire;
try
DefaultFreeResources;
finally
FLock.Release;
end;
end;
constructor TObjectPool.Create(AObjectType: TObjectType; ASize: Integer);
begin
inherited Create;
FIniCount := ASize;
FObjectType := AObjectType;
FLock := TThreadLock.Create;
CreateObjLink(ASize);
end;
procedure TObjectPool.CreateObjLink(ASize: Integer);
var
i: Integer;
PNode: PLinkRec;
begin
// 建链表
FFreeNode := nil;
FFirstNode := Nil;
FUsedCount := 0;
FNodeCount := ASize;
FAutoAllocate := ASize > 0; // > 0 自动分配节点空间
if FAutoAllocate then
begin
// 分配节点空间
SetLength(FBuffer, ASize);
FFreeNode := @FBuffer[0];
for i := 0 to ASize - 1 do // 建双链表
begin
PNode := @FBuffer[i]; // 0...
PNode^.Auto := True; // 自动分配
PNode^.InUsed := False;
{$IFDEF DEBUG_MODE}
PNode^.No := i + 1;
{$ENDIF}
if (i = 0) then // 首
PNode^.Prev := Nil
else
PNode^.Prev := @FBuffer[i - 1];
if (i < ASize - 1) then // 尾
PNode^.Next := @FBuffer[i + 1]
else
PNode^.Next := Nil;
CreateObjData(PNode); // 建关联对象
end;
end;
end;
procedure TObjectPool.CreateObjData(const ALinkNode: PLinkRec);
begin
// Empty
end;
procedure TObjectPool.DefaultFreeResources;
begin
// 默认释放方法:遍历链表释放节点及关联对象
if Assigned(FFirstNode) then
DeleteObjLink(FFirstNode, True);
if Assigned(FFreeNode) then
DeleteObjLink(FFreeNode, True);
if FAutoAllocate then
begin
SetLength(FBuffer, 0);
FAutoAllocate := False;
end;
FNodeCount := 0;
FUsedCount := 0;
end;
procedure TObjectPool.DeleteObjLink(var FirstNode: PLinkRec; FreeObject: Boolean);
var
PToFree, PNode: PLinkRec;
begin
// 删除 TopNode 的链表空间及关联对象
FLock.Acquire;
try
PNode := FirstNode;
while (PNode <> Nil) do // 遍历链表
begin
if Assigned(PNode^.Data) then
FreeNodeObject(PNode);
PToFree := PNode;
PNode := PNode^.Next;
if (PToFree^.Auto = False) then // 用 AddNode() 新增的节点
Dispose(PToFree);
end;
FirstNode := nil;
finally
FLock.Release;
end;
end;
destructor TObjectPool.Destroy;
begin
DefaultFreeResources;
FLock.Free;
inherited;
end;
procedure TObjectPool.FreeListObjects(List: TInDataList);
var
i: Integer;
Node: PLinkRec;
begin
// 额外的释放方法:遍历列表释放节点及关联对象
for i := 0 to List.Count - 1 do
begin
Node := List.Items[i];
if Assigned(Node) then
begin
if Assigned(Node^.Data) then
FreeNodeObject(Node);
if (Node^.Auto = False) then // 用 AddNode() 新增的节点
Dispose(Node);
end;
end;
FFirstNode := nil; // 防止 DefaultFreeResources 重复释放链表
FFreeNode := nil;
DefaultFreeResources;
end;
procedure TObjectPool.FreeNodeObject(ANode: PLinkRec);
begin
// 释放节点 ANode 关联的对象/内存空间
case FObjectType of
otEnvData: // 客户端工作环境空间
{ 不在此释放 } ;
otTaskInf: // 发送数据描述
FreeMem(ANode^.Data);
otIOData: begin // 收发内存块
FreeMem(PPerIOData(ANode^.Data)^.Data.buf);
FreeMem(ANode^.Data);
end;
else // 对象 TBaseSocket
TBaseSocket(ANode^.Data).Free;
end;
ANode^.Data := Nil;
end;
function TObjectPool.GetFull: Boolean;
begin
// 检查对象池是否用完
FLock.Acquire;
try
Result := FUsedCount >= FInICount;
finally
FLock.Release;
end;
end;
procedure TObjectPool.Lock;
begin
FLock.Acquire;
end;
function TObjectPool.Pop: PLinkRec;
begin
// 弹出 空闲 链表的顶,加入到在用链表顶
FLock.Acquire;
try
if (FFreeNode = nil) then
Result := AddNode // 增加节点(同时建实例)
else
Result := FFreeNode;
// 下一空闲节点为顶
FFreeNode := FFreeNode^.Next; // 下一节点上移
if (FFreeNode <> Nil) then // 不为空,指向空
FFreeNode^.Prev := Nil;
// 加 Result 到 在用 链表顶
Result^.Prev := nil;
Result^.Next := FFirstNode;
Result^.InUsed := True;
if (FFirstNode <> Nil) then
FFirstNode^.Prev := Result;
FFirstNode := Result; // 为顶
Inc(FUsedCount);
finally
FLock.Release;
end;
end;
procedure TObjectPool.Push(const ANode: PLinkRec);
begin
// 把 在用/队列 链表的 ANode 加入到空闲链表
FLock.Acquire;
try
if ANode^.InUsed and (FUsedCount > 0) then
begin
// 从 在用 链表中断开 ANode
if (ANode^.Prev = Nil) then // 是顶
begin
FFirstNode := ANode^.Next; // 下一节点上移
if (FFirstNode <> Nil) then
FFirstNode^.Prev := nil;
end else
begin // 上节点连下节点
ANode^.Prev^.Next := ANode^.Next;
if (ANode^.Next <> Nil) then // 不是底
ANode^.Next^.Prev := ANode^.Prev;
end;
// 加入到 空闲 链表的顶
ANode^.Prev := Nil;
ANode^.Next := FFreeNode;
ANode^.InUsed := False;
if (FFreeNode <> Nil) then
FFreeNode^.Prev := ANode;
FFreeNode := ANode; // 变顶
Dec(FUsedCount); // 只在此处 -
end;
finally
FLock.Release;
end;
end;
procedure TObjectPool.OptimizeDetail(List: TInDataList);
var
i: Integer;
PNode, PTail: PLinkRec;
PFreeLink: PLinkRec;
UsedNodes: TInDataList;
begin
// 优化资源,恢复到初始化时的状态。
// (释放非自动增加的节点 Auto = False)
// 遍历空闲链表,建非自动建节点的链表 -> 释放
FLock.Acquire;
UsedNodes := TInDataList.Create;
try
PTail := nil; // 尾
PFreeLink := Nil; // 空链表
PNode := FFreeNode; // 当前节点
while (PNode <> nil) do // 遍历空闲链表
begin
if (PNode^.Auto = False) then
begin
// 从空闲表中脱开节点 PNode
if (PNode^.Prev = Nil) then // 是顶
begin
FFreeNode := PNode^.Next; // 下一节点上移
if (FFreeNode <> Nil) then
FFreeNode^.Prev := nil;
end else // 上节点连下节点
begin
PNode^.Prev^.Next := PNode^.Next;
if (PNode^.Next <> Nil) then // 不是底
PNode^.Next^.Prev := PNode^.Prev;
end;
// 建链表
if (PFreeLink = nil) then
PFreeLink := PNode
else
PTail^.Next := PNode;
// 当作尾
PTail := PNode;
PTail^.InUsed := False;
// 取下一节点
PNode := PNode^.Next;
// 在后
PTail^.Next := nil;
Dec(FNodeCount);
end else
PNode := PNode^.Next;
end;
if Assigned(List) then
begin
// 优化管理列表
// 把新增、使用中的节点移到 FIniCount 位置之前
for i := FIniCount to List.Count - 1 do
begin
PNode := List.Items[i];
if Assigned(PNode) and PNode^.InUsed then
UsedNodes.Add(PNode);
end;
// UsedNodes 的节点前移
for i := 0 to UsedNodes.Count - 1 do
List.Items[FIniCount + i] := UsedNodes.Items[i];
// 调整节点数
List.Count := FNodeCount;
end;
finally
UsedNodes.Free;
FLock.Release;
end;
// 释放链表 PFreeLink 的节点资源
while (PFreeLink <> Nil) do
begin
PNode := PFreeLink;
PFreeLink := PFreeLink^.Next;
if (PNode^.Data <> Nil) then
FreeNodeObject(PNode);
Dispose(PNode);
end;
end;
procedure TObjectPool.Optimize;
begin
OptimizeDetail(nil); // 优化资源,恢复到初始化时的状态。
end;
procedure TObjectPool.Scan(var FromObject: Pointer; Callback: TScanListEvent);
var
CancelScan: Boolean;
PNode: PLinkRec;
begin
// 遍历 在用 链表对象(调用前要加锁)
// FromObject: 一个对象或内存开始位置
CancelScan := False;
PNode := FFirstNode;
while (PNode <> Nil) and (CancelScan = False) do
begin
Callback(FObjectType, FromObject, PNode^.Data, CancelScan);
PNode := PNode^.Next;
end;
end;
procedure TObjectPool.UnLock;
begin
FLock.Release;
end;
{ TDataListPool }
constructor TDataListPool.Create(AObjectType: TObjectType; ASize: Integer);
begin
// 增加一个资源节点列表,释放时加快速度
FNodeList := TInDataList.Create;
inherited;
end;
procedure TDataListPool.CreateObjData(const ALinkNode: PLinkRec);
begin
FNodeList.Add(ALinkNode); // 登记到列表
end;
destructor TDataListPool.Destroy;
begin
FreeListObjects(FNodeList); // 用列表法删除资源
FNodeList.Free;
inherited;
end;
procedure TDataListPool.Optimize;
begin
OptimizeDetail(FNodeList);
end;
{ TIOCPSocketPool }
function TIOCPSocketPool.Clone(Source: TObject): TObject;
var
Socket: TBaseSocketRef;
begin
// 复制一个 TBaseSocket
FLock.Acquire;
try
Socket := Pop^.Data;
Socket.Clone(TBaseSocket(Source));
Result := Socket;
finally
FLock.Release;
end;
end;
constructor TIOCPSocketPool.Create(AObjectType: TObjectType; ASize: Integer);
begin
case AObjectType of
otIOCPSocket: // TIOCPSocket
FSocketClass := TIOCPSocket;
otHttpSocket: // THttpSocket
FSocketClass := THttpSocket;
otStreamSocket: // TStreamSocket
FSocketClass := TStreamSocket;
otWebSocket: // TWebSocket
FSocketClass := TWebSocket;
otIOCPBroker: // 代理
FSocketClass := TSocketBroker;
else
raise Exception.Create('TBaseSocket 类型错误.');
end;
inherited;
end;
procedure TIOCPSocketPool.CreateObjData(const ALinkNode: PLinkRec);
begin
inherited;
// 链表节点的 LinkNode.Data 存放一个 Socket 对象,
// Socket.LinkNode 记录链表节点(双向记录,方便回收空间)
ALinkNode^.Data := TBaseSocketClass(FSocketClass).Create(Self, ALinkNode);
end;
procedure TIOCPSocketPool.GetSockets(List: TInList; IngoreSocket: TObject;
AdminType: Boolean; Group: string);
var
PNode: PLinkRec;
begin
// 推送时,取接收过数据的全部节点
FLock.Acquire;
try
PNode := FFirstNode;
while (PNode <> Nil) do // 遍历在用表
begin
if (PNode^.Data <> IngoreSocket) and // 不是要忽略的对象
TBaseSocketRef(PNode^.Data).GetObjectState(Group, AdminType) then // 可接受推送
List.Add(PNode^.Data);
PNode := PNode^.Next;
end;
finally
FLock.Release;
end;
end;
{ TIODataPool }
constructor TIODataPool.Create(ASize: Integer);
begin
inherited Create(otIOData, ASize * 5); // 5 倍缓存
end;
procedure TIODataPool.CreateObjData(const ALinkNode: PLinkRec);
var
IOData: PPerIOData;
begin
inherited;
// 链表节点的 LinkNode.Data 指向 TPerIOData 内存块
GetMem(ALinkNode^.Data, SizeOf(TPerIOData));
IOData := PPerIOData(ALinkNode^.Data);
IOData^.Node := ALinkNode;
IOData^.Data.len := IO_BUFFER_SIZE;
// 内存、虚拟内存要充裕,否则会 out of memory!
GetMem(IOData^.Data.buf, IO_BUFFER_SIZE);
end;
destructor TIODataPool.Destroy;
begin
inherited;
end;
{ TStringHash }
procedure TStringHash.Add(const Key: AnsiString; Value: Pointer);
var
Hash: Integer;
Bucket: PHashItem;
begin
FLock.Acquire;
try
Hash := HashOf(Key) mod Cardinal(Length(FBuckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.Value := Value;
Bucket^.Next := FBuckets[Hash];
FBuckets[Hash] := Bucket;
Inc(FCount);
finally
FLock.Release;
end;
end;
procedure TStringHash.Clear;
var
i: Integer;
Prev, Next: PHashItem;
begin
FLock.Acquire;
try
if (FCount > 0) then
for i := 0 to Length(FBuckets) - 1 do
begin
Prev := FBuckets[i];
FBuckets[i] := nil;
while Assigned(Prev) do
begin
Next := Prev^.Next;
FreeItemData(Prev); // 增加
Dispose(Prev);
Prev := Next;
Dec(FCount);
end;
end;
finally
FLock.Release;
end;
end;
constructor TStringHash.Create(Size: Cardinal);
begin
SetLength(FBuckets, Size);
FLock := TThreadLock.Create;
end;
destructor TStringHash.Destroy;
begin
Clear;
FLock.Free;
SetLength(FBuckets, 0);
inherited Destroy;
end;
function TStringHash.Find(const Key: AnsiString): PPHashItem;
var
Hash: Integer;
begin
// Key 用 AnsiString
Hash := HashOf(Key) mod Cardinal(Length(FBuckets));
Result := @FBuckets[Hash];
while Result^ <> nil do
begin
if Result^.Key = Key then
Exit
else
Result := @Result^.Next;
end;
end;
procedure TStringHash.FreeItemData(Item: PHashItem);
begin
// 释放节点关联的数据
end;
function TStringHash.HashOf(const Key: AnsiString): Cardinal;
var
i: Integer;
begin
// Key 用 AnsiString
Result := 0;
for i := 1 to Length(Key) do
Result := ((Result shl 2) or (Result shr (SizeOf(Result) * 8 - 2))) xor Ord(Key[i]);
end;
procedure TStringHash.Lock;
begin
FLock.Acquire;
end;
function TStringHash.Modify(const Key: AnsiString; Value: Pointer): Boolean;
var
P: PHashItem;
begin
FLock.Acquire;
try
P := Find(Key)^;
if Assigned(P) then
begin
Result := True;
P^.Value := Value;
end else
Result := False;
finally
FLock.Release;
end;
end;
procedure TStringHash.Remove(const Key: AnsiString);
var
P: PHashItem;
Prev: PPHashItem;
begin
FLock.Acquire;
try
Prev := Find(Key);
P := Prev^;
if Assigned(P) then
begin
Prev^ := P^.Next; // 断开 p
FreeItemData(P); // 增加
Dispose(P); // 删除 p
Dec(FCount);
end;
finally
FLock.Release;
end;
end;
procedure TStringHash.Remove2(Item: PPHashItem);
var
P: PHashItem;
begin
P := Item^;
if Assigned(p) then
begin
Item^ := P^.Next; // 断开 p
FreeItemData(P); // 增加
Dispose(P); // 删除 p
Dec(FCount);
end;
end;
procedure TStringHash.Scan(var Dest: Pointer; CallEvent: TScanListEvent);
var
i: Integer;
P: PHashItem;
CancelScan: Boolean;
begin
// 遍历节点(要在外部加锁)
// 见:TInClientManager.GetLoginedClients
if (FCount > 0) then
begin
CancelScan := False;
for i := 0 to Length(FBuckets) - 1 do
begin
P := FBuckets[i];
while Assigned(P) do
begin
CallEvent(otEnvData, Dest, TObject(P^.Value), CancelScan);
if CancelScan then
Exit;
P := P^.Next;
end;
end;
end;
end;
procedure TStringHash.Scan(CallEvent: TScanHashEvent);
var
i: Integer;
Prev: PPHashItem;
P: PHashItem;
begin
// 遍历节点(要在外部加锁)
if (FCount > 0) then
for i := 0 to Length(FBuckets) - 1 do
begin
Prev := @FBuckets[i];
P := Prev^;
while Assigned(P) do
begin
if Assigned(CallEvent) then
CallEvent(P^.Value); // 引用对象被释放 -> P^.Value = Nil
if (P^.Value = Nil) then // P^.Value = Nil 对象被释放
begin
Dec(FCount);
Prev^ := P^.Next;
Dispose(P); // 释放节点空间
P := Prev^;
end else
begin
Prev := @P;
P := P^.Next;
end;
end;
end;
end;
procedure TStringHash.UnLock;
begin
FLock.Release;
end;
function TStringHash.ValueOf(const Key: AnsiString): Pointer;
var
P: PHashItem;
begin
FLock.Acquire;
try
P := Find(Key)^;
if Assigned(P) then
Result := P^.Value
else
Result := Nil;
finally
FLock.Release;
end;
end;
function TStringHash.ValueOf2(const Key: AnsiString): Pointer;
var
P: PHashItem;
begin
P := Find(Key)^;
if Assigned(P) then
Result := P^.Value
else
Result := Nil;
end;
function TStringHash.ValueOf3(const Key: AnsiString; var Item: PPHashItem): Pointer;
var
P: PHashItem;
begin
Item := Find(Key);
P := Item^;
if Assigned(P) then
Result := P^.Value
else
Result := Nil;
end;
{ TPreventAttack }
function TPreventAttack.CheckAttack(const PeerIP: String; MSecond, InterCount: Integer): Boolean;
var
Item: PAttackInfo;
TickCount: Int64;
begin
// 检查恶意攻击
// 正常的客户端连接数不多,也不频繁
TickCount := GetUTCTickCount;
Lock;
try
Item := Self.ValueOf2(PeerIP);
if Assigned(Item) then
begin
// MSecond 毫秒内出现 InterCount 个客户端连接,
// 当作攻击, 15 分钟内禁止连接
if (Item^.TickCount > TickCount) then // 攻击过,未解禁
Result := True
else begin
Result := (Item^.Count >= InterCount) and
(TickCount - Item^.TickCount <= MSecond);
if Result then // 是攻击
Item^.TickCount := TickCount + 900000 // 900 秒
else
Item^.TickCount := TickCount;
Inc(Item^.Count);
end;
end else
begin
// 未重复连接过,登记
Item := New(PAttackInfo);
Item^.PeerIP := PeerIP;
Item^.TickCount := TickCount;
Item^.Count := 1;
// 加入 Hash 表
Self.Add(PeerIP, Item);
Result := False;
end;
finally
UnLock;
end;
end;
procedure TPreventAttack.DecRef(const PeerIP: String);
var
Item: PAttackInfo;
begin
// 减少 IP 引用次数
if (PeerIP <> '') then
begin
Lock;
try
Item := Self.ValueOf2(PeerIP);
if Assigned(Item) and (Item^.Count > 0) then
Dec(Item^.Count);
finally
UnLock;
end;
end;
end;
procedure TPreventAttack.FreeItemData(Item: PHashItem);
begin
// 释放节点空间
Dispose(PAttackInfo(Item^.Value));
end;
end.
|
unit MobileForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Media,
IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile,
FMX.ListBox, FMX.StdCtrls, FMX.Layouts, FMX.Edit, System.Actions, FMX.ActnList;
type
TForm1 = class(TForm)
TetheringManager1: TTetheringManager;
TetheringAppProfile1: TTetheringAppProfile;
Label1: TLabel;
Layout1: TLayout;
ListBox1: TListBox;
Layout2: TLayout;
Edit1: TEdit;
Label2: TLabel;
Layout3: TLayout;
Button1: TButton;
ComboBox1: TComboBox;
Label3: TLabel;
Button2: TButton;
ActionList1: TActionList;
SendID: TAction;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure TetheringManager1EndManagersDiscovery(const Sender: TObject;
const RemoteManagers: TTetheringManagerInfoList);
procedure Button1Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure TetheringManager1PairedToRemote(const Sender: TObject;
const AManagerInfo: TTetheringManagerInfo);
procedure Edit1Change(Sender: TObject);
procedure TetheringAppProfile1AcceptResource(const Sender: TObject;
const AProfileId: string; const AResource: TCustomRemoteItem;
var AcceptResource: Boolean);
procedure TetheringAppProfile1ActionUpdated(const Sender: TObject;
const AResource: TRemoteAction);
procedure TetheringAppProfile1RemoteProfileUpdate(const Sender: TObject;
const AProfileId: string);
procedure TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
procedure TetheringAppProfile1ResourceUpdated(const Sender: TObject;
const AResource: TRemoteResource);
procedure ListBox1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Label1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses System.Generics.Collections;
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
begin
ComboBox1.Clear;
TetheringManager1.DiscoverManagers;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
with TetheringManager1, TetheringAppProfile1 do
if RemoteProfiles.Count > 0 then begin
Connect(RemoteProfiles[0]);
SubscribeToRemoteItem(RemoteProfiles[0],'NewDish');
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
action: TRemoteAction;
begin
with TetheringManager1 do
if RemoteProfiles.Count > 0 then begin
TetheringAppProfile1.Connect(RemoteProfiles[0]);
for action in TetheringAppProfile1.GetRemoteProfileActions(RemoteProfiles[0]) do
if action.Name = 'SendID' then
TetheringAppProfile1.RunRemoteAction(action);
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
TetheringManager1.PairManager(
TetheringManager1.RemoteManagers[Integer(ComboBox1.Items.Objects[ComboBox1.ItemIndex])]);
end;
procedure TForm1.Edit1Change(Sender: TObject);
begin
TetheringManager1.Text := Edit1.Text;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Label1.Text := TetheringManager1.Identifier;
TetheringManager1.DiscoverManagers;
end;
procedure TForm1.Label1Click(Sender: TObject);
begin
SendID.Execute;
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var
newDish: TRemoteResource;
// resources: TList<TRemoteResource>;
// profiles: TList<TTetheringProfileInfo>;
begin
with TetheringManager1 do
if RemoteProfiles.Count > 0 then begin
TetheringAppProfile1.Connect(RemoteProfiles[0]);
// profiles := TetheringAppProfile1.ConnectedProfiles;
// resources:=TetheringAppProfile1.GetRemoteProfileResources(RemoteProfiles[0]);
newDish := TetheringAppProfile1.GetRemoteResourceValue(RemoteProfiles[0], 'NewDish');
if Assigned(newDish) then
ListBox1.Items.Add(newDish.Value.AsString + ' is available');
end;
end;
procedure TForm1.TetheringAppProfile1AcceptResource(const Sender: TObject;
const AProfileId: string; const AResource: TCustomRemoteItem;
var AcceptResource: Boolean);
begin
ListBox1.Items.Add('OnAcceptResource');
end;
procedure TForm1.TetheringAppProfile1ActionUpdated(const Sender: TObject;
const AResource: TRemoteAction);
begin
ListBox1.Items.Add('OnActionUpdated');
end;
procedure TForm1.TetheringAppProfile1RemoteProfileUpdate(const Sender: TObject;
const AProfileId: string);
begin
ListBox1.Items.Add('OnRemoteProfileUpdate');
end;
procedure TForm1.TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
begin
ListBox1.Items.Add('OnResourceReceived');
end;
procedure TForm1.TetheringAppProfile1ResourceUpdated(const Sender: TObject;
const AResource: TRemoteResource);
begin
ListBox1.Items.Add(AResource.Value.AsString + ' is available');
end;
procedure TForm1.TetheringManager1EndManagersDiscovery(const Sender: TObject;
const RemoteManagers: TTetheringManagerInfoList);
var
idx: Integer;
begin
for idx := 0 to RemoteManagers.count-1 do
if RemoteManagers[idx].ManagerName = 'CookService' then
ComboBox1.Items.AddObject(RemoteManagers[idx].ManagerText, TObject(idx));
end;
procedure TForm1.TetheringManager1PairedToRemote(const Sender: TObject;
const AManagerInfo: TTetheringManagerInfo);
begin
ListBox1.Items.Add('Connected to ' + AManagerInfo.ManagerText);
end;
end.
|
unit evStyles_SH;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Модуль: "w:/common/components/gui/Garant/Everest/evStyles_SH.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SettingsHolder::Class>> Shared Delphi::Everest::StyleTable::evStyles
//
// Стили
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
afwInterfaces,
l3ProtoObject,
evInterface
;
type
SHevStyles = class(TevInterface)
{* Стили }
public
// public methods
class function PrintAndExportFontSize: Integer;
{* Эффективный размер шрифта для печати и экспорта }
class function PrintAndExportDefaultSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" }
class function PrintAndExportCustomSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" }
class function PrintAndExportFontSizeSetting: Integer;
{* Метод для получения значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
class procedure WritePrintAndExportFontSizeSetting(aValue: Integer);
{* Метод для записи значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
end;//SHevStyles
implementation
uses
Classes
{$If not defined(DesignTimeLibrary)}
,
evStyleTableSpy
{$IfEnd} //not DesignTimeLibrary
,
evStylesPrintAndExportSettingRes,
afwFacade,
evStylesPrintAndExportFontSizeSettingRes,
l3Base {a},
SysUtils,
afwSettingsChangePublisher
;
type
_afwSettingChanged_Parent_ = Tl3ProtoObject;
{$Include w:\common\components\gui\Garant\AFW\implementation\afwSettingChanged.imp.pas}
TevStylesSettingsListener = class(_afwSettingChanged_)
{* Экземпляр evStyles, который подписывается к настройкам }
private
// private methods
function IsSettingAffectsUs(const aSettingId: TafwSettingId): Boolean;
{* Метод для проверки того факта, что TevStylesSettingsListener касается изменение указанной настройки }
protected
// overridden protected methods
function DoSettingChanged(const aSettingId: TafwSettingId): Boolean; override;
{* Обработчик изменения указанной настройки }
public
// public methods
class procedure CheckSubscribe;
{* Метод для проверки того факта, что TevStylesSettingsListener подписан на изменения необходимых настроек }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
// singleton factory method
class function Instance: TevStylesSettingsListener;
{- возвращает экземпляр синглетона. }
end;//TevStylesSettingsListener
// start class TevStylesSettingsListener
var g_TevStylesSettingsListener : TevStylesSettingsListener = nil;
procedure TevStylesSettingsListenerFree;
begin
l3Free(g_TevStylesSettingsListener);
end;
class function TevStylesSettingsListener.Instance: TevStylesSettingsListener;
begin
if (g_TevStylesSettingsListener = nil) then
begin
l3System.AddExitProc(TevStylesSettingsListenerFree);
g_TevStylesSettingsListener := Create;
end;
Result := g_TevStylesSettingsListener;
end;
{$Include w:\common\components\gui\Garant\AFW\implementation\afwSettingChanged.imp.pas}
// start class TevStylesSettingsListener
class procedure TevStylesSettingsListener.CheckSubscribe;
{-}
begin
if (g_TevStylesSettingsListener = nil) then
if (afw.Application <> nil) then
if (afw.Application.Settings <> nil) then
TevStylesSettingsListener.Instance;
end;//TevStylesSettingsListener.CheckSubscribe
function TevStylesSettingsListener.IsSettingAffectsUs(const aSettingId: TafwSettingId): Boolean;
{-}
begin
Result := ANSISameText(aSettingId, pi_evStyles_PrintAndExport_Default) OR
ANSISameText(aSettingId, pi_evStyles_PrintAndExport_Custom) OR
ANSISameText(aSettingId, pi_evStyles_PrintAndExportFontSize);
end;//TevStylesSettingsListener.IsSettingAffectsUs
class function TevStylesSettingsListener.Exists: Boolean;
{-}
begin
Result := g_TevStylesSettingsListener <> nil;
end;//TevStylesSettingsListener.Exists
function TevStylesSettingsListener.DoSettingChanged(const aSettingId: TafwSettingId): Boolean;
//#UC START# *47EA863A035C_5EDF2B8ACE76_var*
//#UC END# *47EA863A035C_5EDF2B8ACE76_var*
begin
Result := inherited DoSettingChanged(aSettingId);
if IsSettingAffectsUs(aSettingId) then
begin
Result := true;
//#UC START# *522ED9B4018BSettingChanged*
{$IfNDef DesignTimeLibrary}
EvNotifyStyleTableChanging;
EvNotifyStyleTableChanged;
{$EndIf DesignTimeLibrary}
//#UC END# *522ED9B4018BSettingChanged*
end;//IsSettingAffectsUs(aSettingId)
end;//TevStylesSettingsListener.DoSettingChanged
class function SHevStyles.PrintAndExportFontSize: Integer;
//#UC START# *52387143039D_522ED9B4018B_var*
const
cSizes : array [PrintAndExportFontSizeEnum] of Integer = (8, 9, 10, 11, 12, 14, 16);
var
l_Size : Integer;
//#UC END# *52387143039D_522ED9B4018B_var*
begin
//#UC START# *52387143039D_522ED9B4018B_impl*
TevStylesSettingsListener.CheckSubscribe;
if PrintAndExportDefaultSetting then
Result := 0
else
begin
l_Size := PrintAndExportFontSizeSetting;
if (l_Size >= Ord(Low(PrintAndExportFontSizeEnum))) AND
(l_Size <= Ord(High(PrintAndExportFontSizeEnum))) then
Result := cSizes[PrintAndExportFontSizeEnum(l_Size)]
else
Result := 12;
end;//PrintAndExportDefaultSetting
//#UC END# *52387143039D_522ED9B4018B_impl*
end;//SHevStyles.PrintAndExportFontSize
class function SHevStyles.PrintAndExportDefaultSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := true
else
Result := afw.Settings.LoadBoolean(pi_evStyles_PrintAndExport_Default, true);
end;//SHevStyles.PrintAndExportDefaultSetting
class function SHevStyles.PrintAndExportCustomSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := false
else
Result := afw.Settings.LoadBoolean(pi_evStyles_PrintAndExport_Custom, false);
end;//SHevStyles.PrintAndExportCustomSetting
class function SHevStyles.PrintAndExportFontSizeSetting: Integer;
{-}
begin
if (afw.Settings = nil) then
Result := dv_evStyles_PrintAndExportFontSize
else
Result := afw.Settings.LoadInteger(pi_evStyles_PrintAndExportFontSize, dv_evStyles_PrintAndExportFontSize);
end;//SHevStyles.PrintAndExportFontSizeSetting
class procedure SHevStyles.WritePrintAndExportFontSizeSetting(aValue: Integer);
{-}
begin
if (afw.Settings <> nil) then
afw.Settings.SaveInteger(pi_evStyles_PrintAndExportFontSize, aValue);
end;//SHevStyles.WritePrintAndExportFontSizeSetting
end. |
unit TERRA_CustomPropertyEditor;
interface
uses SysUtils, Classes, Messages, ExtCtrls, Controls, StdCtrls,
Dialogs, Graphics, Buttons,
TERRA_String, TERRA_Object, TERRA_Utils, TERRA_OS, TERRA_Color, TERRA_VCLApplication;
Const
MarginTop = 10;
MarginSide = 10;
ExpandSize = 15;
CellHeight = 25;
MarginColor = TColor($DDDDDD);
type
TCustomPropertyEditor = Class;
TPropertyCell = Class(TERRAObject)
Protected
_Owner:TCustomPropertyEditor;
_Index:Integer;
_Parent:TERRAObject;
_Prop:TERRAObject;
_Visible:Boolean;
_Label:TLabel;
_Editor:TControl;
_Expand:TSpeedButton;
Function CreateEditor():TControl; Virtual; Abstract;
Procedure Update(); Virtual; Abstract;
Procedure Resize();
Procedure ExpandProps(Sender: TObject; Button: TMouseButton; Shift:TShiftState; X, Y: Integer);
Public
Constructor Create(Owner:TCustomPropertyEditor; Parent, Prop:TERRAObject);
Procedure Release(); Override;
Procedure SetVisible(Value:Boolean);
End;
TPropertyCellType = Class Of TPropertyCell;
TTextCell = Class(TPropertyCell)
Protected
_Edit:TEdit;
Function CreateEditor():TControl; Override;
Procedure Update(); Override;
Procedure OnKeyDown(Sender:TObject; var Key: Word; Shift: TShiftState);
Procedure OnChange(Sender:TObject);
End;
TColorCell = Class(TPropertyCell)
Protected
_Shape:TShape;
_Dialog:TColorDialog;
Function CreateEditor():TControl; Override;
Procedure Update(); Override;
Procedure OnMouseDown(Sender: TObject; Button: TMouseButton; Shift:TShiftState; X, Y: Integer);
End;
TBooleanCell = Class(TPropertyCell)
Protected
_Check:TCheckbox;
Function CreateEditor():TControl; Override;
Procedure Update(); Override;
Procedure OnClick(Sender: TObject);
End;
TCustomPropertyEditor = class(TPanel)
private
_Bevel:TBevel;
_Target: TERRAObject;
_Cells:Array Of TPropertyCell;
_CellCount:Integer;
procedure SetTarget(Target: TERRAObject);
protected
Procedure InsertRow(Parent, Prop:TERRAObject);
Procedure Clear();
Function GetMiddle():Integer;
Function FindCell(Prop:TERRAObject):TPropertyCell;
procedure Paint; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent);
Procedure AddPropertiesFromObject(Parent, Source:TERRAObject);
Procedure RequestUpdate();
Property Target:TERRAObject Read _Target Write SetTarget;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BevelInner;
property BevelOuter Default bvLowered;
property BevelWidth;
property BiDiMode;
property BorderWidth;
property BorderStyle;
property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
property Locked;
property ParentBiDiMode;
property ParentBackground;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
// property OnValidate: TOnValidateEvent read FOnValidate write FOnValidate;
end;
procedure Register;
implementation
uses Forms, TypInfo, Variants, Consts;
procedure Register;
begin
RegisterComponents('Samples', [TCustomPropertyEditor]);
end;
{ TCustomPropertyEditor }
constructor TCustomPropertyEditor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 306;
Height := 300;
_Bevel := TBevel.Create(Self);
_Bevel.Parent := Self;
_Bevel.Width := 20;
_Bevel.Height := Height;
_Bevel.Top := 10;
_Bevel.Left := Width Div 2;
// _Bevel.Shape := bsLeftLine;
end;
Procedure TCustomPropertyEditor.AddPropertiesFromObject(Parent, Source:TERRAObject);
Var
Index, Row:Integer;
Prop:TERRAObject;
S:TERRAString;
Begin
Index := 0;
Repeat
Prop := Source.GetPropertyByIndex(Index);
If Prop = Nil Then
Break;
S := Prop.GetBlob();
If S<>'' Then
Begin
Self.InsertRow(Parent, Prop);
End;
If Not Prop.IsValueObject() Then
Begin
AddPropertiesFromObject(Prop, Prop);
End;
Inc(Index);
Until False;
End;
Procedure TCustomPropertyEditor.SetTarget(Target: TERRAObject);
Begin
If Target <> _Target Then
Self.Clear();
_Target := Target;
If Target = Nil Then
Exit;
AddPropertiesFromObject(Nil, Target);
End;
Procedure TCustomPropertyEditor.InsertRow(Parent, Prop: TERRAObject);
Var
CellType:TPropertyCellType;
Cell:TPropertyCell;
S:TERRAString;
Begin
S := Prop.GetObjectType();
If StringEquals(S, 'color') Then
CellType := TColorCell
Else
If StringEquals(S, 'bool') Then
CellType := TBooleanCell
Else
CellType := TTextCell;
Cell := CellType.Create(Self, Parent, Prop);
Inc(_CellCount);
SetLength(_Cells, _CellCount);
_Cells[Pred(_CellCount)] := Cell;
End;
procedure TCustomPropertyEditor.Clear;
Var
I:Integer;
begin
For I:=0 To Pred(_CellCount) Do
ReleaseObject(_Cells[I]);
_CellCount := 0;
Self.Repaint();
end;
procedure TCustomPropertyEditor.Paint;
Var
I, N, MidW, H:Integer;
begin
inherited;
If _CellCount<=0 Then
Exit;
MidW := GetMiddle();
Canvas.Pen.Style := psDash;
Canvas.Pen.Color := MarginColor;
Canvas.Pen.Width := 2;
Canvas.MoveTo(MidW, 0);
Canvas.LineTo(MidW, Self.Height);
//Canvas.Pen.Style := psDot;
Canvas.Pen.Width := 1;
N := 0;
For I:=0 To Pred(_CellCount) Do
Begin
If Not _Cells[I]._Visible Then
Continue;
H := (MarginTop Shr 1) + Succ(N) * CellHeight;
Canvas.MoveTo(0, H);
Canvas.LineTo(Self.Width, H);
Inc(N);
End;
end;
function TCustomPropertyEditor.GetMiddle: Integer;
begin
Result := Trunc(Self.Width * 0.4);
end;
procedure TCustomPropertyEditor.Resize;
Var
I, N:Integer;
begin
N := 0;
For I:=0 To Pred(_CellCount) Do
If _Cells[I]._Visible Then
Begin
_Cells[I]._Index := N;
_Cells[I].Resize();
Inc(N);
End;
end;
procedure TCustomPropertyEditor.RequestUpdate;
Var
I:Integer;
begin
For I:=0 To Pred(_CellCount) Do
_Cells[I].Update();
end;
function TCustomPropertyEditor.FindCell(Prop: TERRAObject): TPropertyCell;
Var
I:Integer;
begin
For I:=0 To Pred(_CellCount) Do
If _Cells[I]._Prop = Prop Then
Begin
Result := _Cells[I];
Exit;
End;
Result := Nil;
end;
{ TPropertyCell }
Constructor TPropertyCell.Create(Owner:TCustomPropertyEditor; Parent, Prop: TERRAObject);
Var
I:Integer;
S:TERRAString;
Begin
_Owner := Owner;
_Parent := Parent;
_Prop := Prop;
_Index := 0;
For I:=0 To Pred(_Owner._CellCount) Do
If (_Owner._Cells[I]._Visible) Then
Inc(_Index);
_Label := TLabel.Create(Owner);
_Label.Parent := Owner;
_Label.Caption := Prop.ObjectName;
_Editor := Self.CreateEditor();
_Editor.Parent := _Owner;
// Chk.Anchors := [akLeft, akTop, akRight, akBottom];
If (Not _Prop.IsValueObject()) Then
Begin
_Expand := TSpeedButton.Create(_Owner);
_Expand.Parent := _Owner;
_Expand.Width := ExpandSize;
_Expand.Height := _Expand.Width;
_Expand.Caption := '+';
_Expand.OnMouseDown := ExpandProps;
End Else
_Expand := Nil;
SetVisible(_Owner.FindCell(_Parent) = Nil);
Self.Update();
Self.Resize();
end;
procedure TPropertyCell.ExpandProps(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
I:Integer;
Value:Boolean;
Begin
Value := _Expand.Caption = '+';
If Value Then
_Expand.Caption := '-'
Else
_Expand.Caption := '+';
For I:=0 To Pred(_Owner._CellCount) Do
If (_Owner._Cells[I]._Parent = Self._Prop) Then
Begin
_Owner._Cells[I].SetVisible(Value);
End;
_Owner.RequestUpdate();
_Owner.Resize();
End;
Procedure TPropertyCell.Release;
Begin
FreeAndNil(_Label);
FreeAndNil(_Editor);
FreeAndNil(_Expand);
End;
procedure TPropertyCell.Resize;
begin
_Label.Left := 10;
_Label.Top := MarginTop + _Index * CellHeight;
_Editor.Top := _Label.Top;
_Editor.Left := _Owner.GetMiddle() + MarginSide;
_Editor.Width := _Owner.Width - (_Editor.Left + MarginSide);
If Assigned(_Expand) Then
Begin
_Expand.Top := _Label.Top;
_Expand.Left := _Owner.GetMiddle() - ((MarginSide Shr 1) + _Expand.Width);
End;
end;
procedure TPropertyCell.SetVisible(Value: Boolean);
begin
_Visible := Value;
If Assigned(_Label) Then
_Label.Visible := Value;
If Assigned(_Editor) Then
_Editor.Visible := Value;
If Assigned(_Expand) Then
_Expand.Visible := Value;
end;
{ TTextCell }
Function TTextCell.CreateEditor: TControl;
Begin
_Edit := TEdit.Create(_Owner);
//_Edit.OnKeyDown := Self.OnKeyDown;
_Edit.OnChange := Self.OnChange;
Result := _Edit;
End;
procedure TTextCell.OnChange(Sender: TObject);
begin
_Prop.SetBlob(_Edit.Text);
end;
procedure TTextCell.OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
If Key<>keyEnter Then
Exit;
_Prop.SetBlob(_Edit.Text);
end;
Procedure TTextCell.Update;
Begin
_Edit.Text := _Prop.GetBlob();
End;
{ TColorCell }
Function TColorCell.CreateEditor: TControl;
Begin
_Shape := TShape.Create(_Owner);
_Shape.Shape := stRoundRect;
_Shape.Width := CellHeight - 10;
_Shape.Height := _Shape.Width;
_Shape.OnMouseDown := Self.OnMouseDown;
Result := _Shape;
End;
procedure TColorCell.OnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
C:Color;
begin
If _Dialog = Nil Then
Begin
_Dialog := TColorDialog.Create(_Owner);
End;
//_Dialog.Color :=
If _Dialog.Execute Then
Begin
C := TERRAColorPack(_Dialog.Color);
_Prop.SetBlob(TERRA_Color.ColorToString(C));
_Owner.RequestUpdate();
End;
end;
procedure TColorCell.Update;
Var
S:TERRAString;
begin
S := _Prop.GetBlob();
_Shape.Brush.Color := TERRAColorUnpack(ColorCreateFromString(S));
end;
{ TBooleanCell }
Function TBooleanCell.CreateEditor: TControl;
Begin
_Check := TCheckbox.Create(_Owner);
_Check.OnClick := OnClick;
Result := _Check;
End;
procedure TBooleanCell.Update;
begin
_Check.Checked := StringToBool(_Prop.GetBlob());
end;
Procedure TBooleanCell.OnClick(Sender: TObject);
begin
_Prop.SetBlob(BoolToString(_Check.Checked));
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: Classes to handle session for THttpAppSrv and MidWare.
Creation: Dec 20, 2003
Version: 1.01
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list midware@elists.org or twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1998-2010 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software and or any
derived or altered versions for any purpose, excluding commercial
applications. You can use this software for personal use only.
You may distribute it freely untouched.
The following restrictions applies:
1. The origin of this software must not be misrepresented, you
must not claim that you wrote the original software.
2. If you use this software in a product, an acknowledgment in
the product documentation and displayed on screen is required.
The text must be: "This product is based on MidWare. Freeware
source code is available at http://www.overbyte.be."
3. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
4. This notice may not be removed or altered from any source
distribution and must be added to the product documentation.
Updates:
Apr 19, 2010 V1.01 Angus, stop MaxAge (SessionTimeout) being restored with saved
session data since it can never then be changed
Added SessionDataCount so client can use it, only set by AssignName
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *_*}
unit OverbyteIcsWebSession;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$I OVERBYTEICSDEFS.INC}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
interface
uses
Windows, Messages, SysUtils, Classes, SyncObjs,
OverbyteIcsTimeList,
OverbyteIcsUtils;
type
TWebSessions = class;
TWebSessionData = class(TComponent)
private
FSessionDataCount: integer; // V1.01 Angus 17 Apr 2010 keep counter so client can use it
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure AssignName; virtual;
published
property SessionDataCount: integer read FSessionDataCount write FSessionDataCount;
end;
PWebSession = ^TWebSession;
TWebSession = class(TComponent)
protected
FVarName : array of String;
FVarValue : array of String;
FTimeRec : PTimeRec;
FTimeMark : TDateTime;
FSession : Integer;
FRefCount : Integer;
FCritSec : TCriticalSection;
FSessionData : TWebSessionData;
FSessions : TWebSessions;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetVarNames(nIndex: Integer): String;
function GetVarValues(nIndex: Integer): String;
function GetCount: Integer;
function GetTimeMark: TDateTime;
procedure SetTimeMark(const Value: TDateTime);
function GetValues(VName: String): String;
procedure SetValues(VName: String; const Value: String);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Refresh;
function SetValue(const VarName : String;
const VarValue : String) : Integer;
function GetValue(const VarName : String;
var VarValue : String) : Integer;
function DecRefCount : Integer;
function IncRefCount : Integer;
function GetRefCount : Integer;
procedure DefineProperties(Filer : TFiler); override;
procedure ReadSessionDataProperty(Reader: TReader);
procedure WriteSessionDataProperty(Writer: TWriter);
procedure ReadVarNamesValuesProperty(Reader : TReader);
procedure WriteVarNamesValuesProperty(Writer : TWriter);
property RefCount : Integer read GetRefCount;
property Count : Integer read GetCount;
property Values[VName : String] : String read GetValues
write SetValues;
property VarNames[nIndex : Integer] : String read GetVarNames;
property VarValues[nIndex : Integer] : String read GetVarValues;
property SessionData : TWebSessionData read FSessionData
write FSessionData;
property Sessions : TWebSessions read FSessions
write FSessions;
property TimeRec : PTimeRec read FTimeRec;
published
property TimeMark : TDateTime read GetTimeMark
write SetTimeMark;
property Session : Integer read FSession
write FSession;
end;
TDeleteSessionEvent = procedure (Sender : TObject;
Session : TWebSession) of Object;
TWebSessions = class(TComponent)
protected
FTimeList : TTimeList;
FCritSec : TCriticalSection;
FOnCreateSession : TDeleteSessionEvent;
FOnDeleteSession : TDeleteSessionEvent;
procedure TimeListDeleteHandler(Sender: TObject; PItem: PTimeRec);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function AddSession(const Value : String) : TWebSession; virtual;
function CreateSession(const Param : String;
var SessionID : String) : TWebSession; virtual;
function CreateSessionEx(const Param : String;
var SessionID : String;
SessionData : TWebSessionData) : TWebSession; virtual;
procedure ValidateSession(const SessionID : String;
SessionRef : PWebSession); virtual;
procedure ReleaseSession(SessionRef : PWebSession); virtual;
procedure RemoveAged; virtual;
function FindSession(const Value : String): TWebSession;
function FindSessionEx(const Value : String;
Refresh : Boolean): TWebSession;
function FindSessionValue(nIndex : Integer): String;
function DeleteSession(const Value : String): Boolean;
function RefreshSession(const Value : String): TWebSession;
function GetMaxAge: Integer;
procedure SetMaxAge(const Value: Integer);
function GetCount: Integer;
function GetSessions(nIndex: Integer): TWebSession;
procedure Clear;
procedure Lock;
procedure Unlock;
procedure SaveToFile(const FileName: String);
procedure SaveToStream(Dest: TStream);
procedure LoadFromFile(const FileName: String);
procedure LoadFromStream(Src: TStream);
procedure DefineProperties(Filer : TFiler); override;
procedure ReadSessionsProperty(Reader : TReader);
procedure WriteSessionsProperty(Writer : TWriter);
property Count : Integer read GetCount;
property Sessions[nIndex : Integer] : TWebSession read GetSessions;
published
property MaxAge : Integer read GetMaxAge // Seconds
write SetMaxAge;
property OnDeleteSession : TDeleteSessionEvent read FOnDeleteSession
write FOnDeleteSession;
property OnCreateSession : TDeleteSessionEvent read FOnCreateSession
write FOnCreateSession;
end;
procedure GWebSessionsCreate(MaxAge : Integer); // Seconds
procedure GWebSessionsDestroy;
var
GWebSessions : TWebSessions;
implementation
var
GSessionID : Integer = 0;
GSessionDataCount : Integer = 0;
GSignature : AnsiString = 'WebSessions V1.01' + #13#10#26;
threadvar
LockCount : Integer;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure GWebSessionsCreate(MaxAge : Integer);
begin
if not Assigned(GWebSessions) then
GWebSessions := TWebSessions.Create(nil);
GWebSessions.MaxAge := MaxAge;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure GWebSessionsDestroy;
begin
if Assigned(GWebSessions) then
FreeAndNil(GWebSessions);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Base64Encode(Input : String) : String;
var
Final : String;
Count : Integer;
Len : Integer;
const
Base64Out: array [0..64] of Char =
('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '=');
begin
Final := '';
Count := 1;
Len := Length(Input);
while Count <= Len do begin
Final := Final + Base64Out[(Byte(Input[Count]) and $FC) shr 2];
if (Count + 1) <= Len then begin
Final := Final + Base64Out[((Byte(Input[Count]) and $03) shl 4) +
((Byte(Input[Count+1]) and $F0) shr 4)];
if (Count+2) <= Len then begin
Final := Final + Base64Out[((Byte(Input[Count+1]) and $0F) shl 2) +
((Byte(Input[Count+2]) and $C0) shr 6)];
Final := Final + Base64Out[(Byte(Input[Count+2]) and $3F)];
end
else begin
Final := Final + Base64Out[(Byte(Input[Count+1]) and $0F) shl 2];
Final := Final + '=';
end
end
else begin
Final := Final + Base64Out[(Byte(Input[Count]) and $03) shl 4];
Final := Final + '==';
end;
Count := Count + 3;
end;
Result := Final;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Base64Decode(Input : String) : String;
var
Final : String;
Count : Integer;
Len : Integer;
DataIn0 : Byte;
DataIn1 : Byte;
DataIn2 : Byte;
DataIn3 : Byte;
const
Base64In: array[0..127] of Byte =
(255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 255, 255, 255, 64, 255, 255, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255);
begin
Final := '';
Count := 1;
Len := Length(Input);
while Count <= Len do begin
DataIn0 := Base64In[Byte(Input[Count])];
DataIn1 := Base64In[Byte(Input[Count+1])];
DataIn2 := Base64In[Byte(Input[Count+2])];
DataIn3 := Base64In[Byte(Input[Count+3])];
Final := Final + Char(((DataIn0 and $3F) shl 2) +
((DataIn1 and $30) shr 4));
if DataIn2 <> $40 then begin
Final := Final + Char(((DataIn1 and $0F) shl 4) +
((DataIn2 and $3C) shr 2));
if DataIn3 <> $40 then
Final := Final + Char(((DataIn2 and $03) shl 6) +
(DataIn3 and $3F));
end;
Count := Count + 4;
end;
Result := Final;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ }
{ TWebSession }
{ }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TWebSession.Create(AOwner: TComponent);
begin
inherited;
FCritSec := TCriticalSection.Create;
//WriteLn('TWebSession.Create');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TWebSession.Destroy;
begin
//WriteLn('TWebSession.Destroy. RefCount = ', FRefCount);
if Assigned(FSessionData) then
FreeAndNil(FSessionData);
if Assigned(FCritSec) then
FreeAndNil(FCritSec);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.Refresh;
begin
FTimeRec.TimeMark := Now;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.GetRefCount: Integer;
begin
FCritSec.Enter;
try
Result := FRefCount;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.DecRefCount: Integer;
begin
FCritSec.Enter;
try
Dec(FRefCount);
Result := FRefCount;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.IncRefCount: Integer;
begin
FCritSec.Enter;
try
Inc(FRefCount);
Result := FRefCount;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Used for property Values[]
function TWebSession.GetValues(VName: String): String;
begin
GetValue(VName, Result);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Return -1 if VarName not found, VarValue set to empty string
// Return index if found, VarValue set to data value
function TWebSession.GetValue(
const VarName : String;
var VarValue : String): Integer;
begin
FCritSec.Enter;
try
Result := 0;
while Result < Length(FVarName) do begin
if CompareText(FVarName[Result], VarName) = 0 then begin
VarValue := FVarValue[Result];
Exit;
end;
Inc(Result);
end;
// not found
Result := -1;
VarValue := '';
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Used for property Values[]
procedure TWebSession.SetValues(VName: String; const Value: String);
begin
SetValue(VName, Value);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Set or create a new VarValue. Returns the index into the arrays
function TWebSession.SetValue(const VarName, VarValue: String) : Integer;
var
OldValue : String;
begin
FCritSec.Enter;
try
Result := GetValue(VarName, OldValue);
if Result >= 0 then begin
// VarName already exists, replace VarValue
FVarValue[Result] := VarValue;
end
else begin
// VarName doesn't exist, add new item
Result := Length(FVarName) + 1;
SetLength(FVarName, Result);
SetLength(FVarValue, Result);
FVarName[Result - 1] := VarName;
FVarValue[Result - 1] := VarValue;
end;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.GetCount: Integer;
begin
FCritSec.Enter;
try
Result := Length(FVarName);
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.GetVarNames(nIndex: Integer): String;
begin
FCritSec.Enter;
try
Result := FVarName[nIndex];
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.GetVarValues(nIndex: Integer): String;
begin
FCritSec.Enter;
try
Result := FVarValue[nIndex];
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSession.GetTimeMark: TDateTime;
begin
FCritSec.Enter;
try
Result := FTimeMark;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.SetTimeMark(const Value: TDateTime);
begin
FCritSec.Enter;
try
FTimeMark := Value;
if Assigned(FTimeRec) then
FTimeRec^.TimeMark := FTimeMark;
finally
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('VarNamesValues',
ReadVarNamesValuesProperty,
WriteVarNamesValuesProperty, TRUE);
Filer.DefineProperty('SessionData',
ReadSessionDataProperty,
WriteSessionDataProperty, TRUE);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.ReadSessionDataProperty(Reader : TReader);
begin
if Reader.ReadBoolean then
SessionData := Reader.ReadComponent(SessionData) as TWebSessionData;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.WriteSessionDataProperty(Writer : TWriter);
begin
Writer.WriteBoolean(SessionData <> nil);
if SessionData <> nil then
Writer.WriteComponent(SessionData);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.ReadVarNamesValuesProperty(Reader: TReader);
var
N, V : String;
begin
SetLength(FVarName, 0);
SetLength(FVarValue, 0);
Reader.ReadListBegin;
while not Reader.EndOfList do begin
N := Reader.ReadString;
V := Reader.ReadString;
SetValue(N, V);
end;
Reader.ReadListEnd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.WriteVarNamesValuesProperty(Writer: TWriter);
var
I : Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do begin
Writer.WriteString(FVarName[I]);
Writer.WriteString(FVarValue[I]);
end;
Writer.WriteListEnd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSession.Notification(
AComponent : TComponent;
Operation : TOperation);
begin
//WriteLn('TWebSession.Notification op=' + IntToStr(Ord(operation)) + ' AComponent=$' + IntToHex(Integer(AComponent), 8) + ' ' + AComponent.ClassName);
inherited Notification(AComponent, operation);
if Operation = opRemove then begin
if AComponent = FSessionData then
FSessionData := nil
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ }
{ TWebSessions }
{ }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TWebSessions.Create(AOwner: TComponent);
begin
inherited;
FTimeList := TTimeList.Create(Self);
FTimeList.OnDelete := TimeListDeleteHandler;
FCritSec := TCriticalSection.Create;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TWebSessions.Destroy;
begin
Lock;
try
if Assigned(FTimeList) then begin
Clear;
FreeAndNil(FTimeList);
end;
finally
Unlock;
end;
if Assigned(FCritSec) then
FreeAndNil(FCritSec);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.AddSession(const Value : String) : TWebSession;
begin
Lock;
try
Result := nil;
if not Assigned(FTimeList) then
Exit;
Result := TWebSession.Create(Self);
InterlockedIncrement(GSessionID);
Result.Session := GSessionID;
Result.Name := 'WebSession' + IntToStr(GSessionID);
Result.FTimeRec := FTimeList.AddWithData(Value, Result, nil);
Result.FTimeMark := Result.FTimeRec^.TimeMark;
Result.FSessions := Self;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.FindSession(const Value: String): TWebSession;
begin
Result := FindSessionEx(Value, FALSE);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.FindSessionEx(
const Value : String;
Refresh : Boolean): TWebSession;
var
Item : Integer;
begin
Lock;
try
if not Assigned(FTimeList) then begin
Result := nil;
Exit;
end;
Item := FTimeList.IndexOf(Value);
if Item < 0 then begin
Result := nil;
end
else if FTimeList.RemoveItemIfAged(Item) then begin
Result := nil;
end
else begin
Result := TWebSession(FTimeList.Items[Item].Data);
Result.Refresh;
//FTimeList.Items[Item].TimeMark := Now;
end;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Set TimeMark to Now for the given session
function TWebSessions.RefreshSession(const Value: String): TWebSession;
begin
Result := FindSessionEx(Value, TRUE);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.FindSessionValue(nIndex : Integer): String;
begin
Lock;
try
if not Assigned(FTimeList) then begin
Result := '';
Exit;
end;
Result := FTimeList.Items[nIndex].Value;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.DeleteSession(const Value: String) : Boolean;
var
TheSession : TWebSession;
begin
Result := FALSE;
Lock;
try
if not Assigned(FTimeList) then
Exit;
TheSession := FindSession(Value);
if not Assigned(TheSession) then begin
Exit;
end;
//WriteLn('DeleteSession. RefCount = ', TheSession.RefCount);
// Delete will call TimeListDeleteHandler which will free the session
FTimeList.Delete(Value);
// if TheSession.DecRefCount < 0 then
// TheSession.Destroy;
Result := TRUE;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.TimeListDeleteHandler(
Sender : TObject;
PItem : PTimeRec);
var
TheSession : TWebSession;
begin
if PItem.Data <> nil then begin
TheSession := TWebSession(PItem.Data);
if Assigned(FOnDeleteSession) then
FOnDeleteSession(Self, TheSession);
// Do not free WebSessions that has a positive RefCount
if TheSession.DecRefCount < 0 then
TheSession.Free;
PItem.Data := nil;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.Clear;
begin
Lock;
try
if Assigned(FTimeList) then begin
while FTimeList.Count > 0 do
DeleteSession(PTimeRec(FTimeList.Items[0]).Value);
end;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.GetMaxAge: Integer;
begin
Lock;
try
if Assigned(FTimeList) then
Result := FTimeList.MaxAge
else
Result := 0;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.RemoveAged;
begin
Lock;
try
if Assigned(FTimeList) then
FTimeList.RemoveAged;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.SetMaxAge(const Value: Integer);
begin
Lock;
try
if Assigned(FTimeList) then
FTimeList.MaxAge := Value;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// CreateSession _must_ be matched with a ReleaseSession
function TWebSessions.CreateSession(
const Param : String;
var SessionID : String): TWebSession;
begin
Result := CreateSessionEx(Param, SessionID, nil);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// CreateSession _must_ be matched with a ReleaseSession
function TWebSessions.CreateSessionEx(
const Param : String;
var SessionID : String;
SessionData : TWebSessionData): TWebSession;
var
TheSessionID : String;
Year, Month, Day : Word;
Hour, Min, Sec, MSec : Word;
Today : TDateTime;
begin
Today := Now;
DecodeDate(Today, Year, Month, Day);
DecodeTime(Today, Hour, Min, Sec, MSec);
TheSessionID := Format('^%s^%s^%04d%02d%02d %02d%02d%02d.%03d^',
[UpperCase(Trim(Param)),
IntToHex(GSessionID, 8),
Year, Month, Day,
Hour, Min, Sec, MSec]);
SessionID := Base64Encode(TheSessionID);
Lock;
try
Result := AddSession(SessionID);
if Assigned(Result) then begin
Result.IncRefCount;
Result.SessionData := SessionData;
end;
//WriteLn('CreateSession. RefCount = ', Result.RefCount);
finally
Unlock;
end;
if Assigned(FOnCreateSession) then
FOnCreateSession(Self, Result);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Works with ReleaseSession.
// Each call to ValidateSession _must_ be balanced by a call to ReleaseSession
procedure TWebSessions.ValidateSession(
const SessionID : String;
SessionRef : PWebSession);
begin
Lock;
try
RemoveAged;
SessionRef^ := FindSession(SessionID);
if Assigned(SessionRef^) then begin
SessionRef^.FTimeRec := FTimeList.AddWithData(SessionID, SessionRef^, nil);
SessionRef^.IncRefCount;
//WriteLn('ValidateSession. RefCount = ', SessionRef^.RefCount);
end
else begin
end;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.GetCount: Integer;
begin
Lock;
try
if not Assigned(FTimeList) then
Result := 0
else
Result := FTimeList.Count;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWebSessions.GetSessions(nIndex: Integer): TWebSession;
var
PItem : PTimeRec;
begin
Lock;
try
if not Assigned(FTimeList) then
Result := nil
else begin
PItem := FTimeList.Items[nIndex];
if PItem = nil then
Result := nil
else
Result := TWebSession(PItem.Data);
end;
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.Lock;
begin
Inc(LockCount); // LockCount is a threadvar !
if (LockCount = 1) and Assigned(FCritSec) then
FCritSec.Enter;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.Unlock;
begin
if LockCount <= 0 then // Should never occur ! Unlock called
LockCount := 0 // without first calling Lock.
else begin
Dec(LockCount); // LockCount is a threadvar !
if (LockCount = 0)and Assigned(FCritSec) then
FCritSec.Leave;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Works with ValidateSession.
// Each call to ReleaseSession _must_ be balanced by a preceding call
// to ValidateSession
procedure TWebSessions.ReleaseSession(SessionRef: PWebSession);
begin
if not Assigned(SessionRef^) then
Exit;
//WriteLn('ReleaseSession. RefCount = ', SessionRef^.RefCount);
SessionRef^.DecRefCount;
if SessionRef^.RefCount < 0 then
SessionRef^.Destroy;
SessionRef^ := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.SaveToStream(Dest : TStream);
begin
Lock;
try
Dest.Write(GSignature[1], Length(GSignature));
Dest.WriteComponent(Self);
finally
Unlock;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.SaveToFile(const FileName : String);
var
Stream : TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('Sessions',
ReadSessionsProperty,
WriteSessionsProperty, Count > 0);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.ReadSessionsProperty(Reader: TReader);
var
WebSession : TWebSession;
Value : String;
begin
Reader.ReadListBegin;
FTimeList.Clear;
while not Reader.EndOfList do begin
Value := Reader.ReadString;
WebSession := Reader.ReadComponent(nil) as TWebSession;
WebSession.FTimeRec := FTimeList.AddWithData(Value, WebSession, nil);
WebSession.FTimeRec^.TimeMark := WebSession.FTimeMark;
WebSession.FSessions := Self;
end;
Reader.ReadListEnd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.WriteSessionsProperty(Writer: TWriter);
var
I:Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do begin
Writer.WriteString(PTimeRec(FTimeList.Items[I]).Value);
Writer.WriteComponent(Sessions[I]);
end;
Writer.WriteListEnd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.LoadFromFile(const FileName: String);
var
Stream : TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessions.LoadFromStream(Src: TStream);
var
Buf : AnsiString;
I, J : Integer;
CName : String;
OldDeleteSession : TDeleteSessionEvent;
OldMaxAge : Integer;
begin
if Src.Size = 0 then
Exit;
// First, check the signature
SetLength(Buf, Length(GSignature));
I := Src.Read(Buf[1], Length(GSignature));
if (I <> Length(GSignature)) or (Buf <> GSignature) then
raise Exception.Create('TWebSessions.LoadFromStream: ' +
'invalid data format');
// Disable OnDeleteSession event because most of the time deleteing or
// adding a session will result in a SaveToFile which would fails
// when we are in the load process (the file is opened).
OldDeleteSession := OnDeleteSession;
OnDeleteSession := nil;
OldMaxAge := MaxAge ; // V1.01 Angus 17 Apr 2010 keep MaxAge since it about to read from file
try
// Delete all existing data
Clear;
// Load data from stream (we use Delphi serialization to save)
Src.ReadComponent(Self);
// Remove old sessions we just loaded
RemoveAged;
finally
OnDeleteSession := OldDeleteSession;
end;
MaxAge := OldMaxAge ; // V1.01 Angus 17 Apr 2010 restore MaxAge
// Update the global counters according to what was loaded
for I := Count - 1 downto 0 do begin
if Sessions[I].Session > GSessionID then
GSessionID := Sessions[I].Session;
if Assigned(Sessions[I].SessionData) then begin
if Sessions[I].SessionData.SessionDataCount > 0 then // V1.01 Angus 17 Apr 2010 might be available as integer
J := Sessions[I].SessionData.SessionDataCount
else begin
CName := Sessions[I].SessionData.Name;
J := Length(CName);
// while (J > 0) and (CName[J] in ['0'..'9']) do
while (J > 0) and IsCharInSysCharSet(CName[J], ['0'..'9']) do
Dec(J);
J := StrToInt(Copy(CName, J + 1, 10));
end;
if J > GSessionDataCount then
GSessionDataCount := J;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CompName(const ClassName : String; Count : Integer) : String;
begin
Result := Copy(ClassName, 2, Length(ClassName)) + IntToStr(Count);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TWebSessionData.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
InterlockedIncrement(GSessionDataCount);
// Name has to be set by the caller. For example calling AssignName method
// Name := CompName(ClassName, GSessionDataCount);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TWebSessionData.Destroy;
begin
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWebSessionData.AssignName;
begin
Name := CompName(ClassName, GSessionDataCount);
SessionDataCount := GSessionDataCount; // V1.01 Angus 17 Apr 2010 keep counter
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
initialization
RegisterClass(TWebSession);
RegisterClass(TWebSessions);
RegisterClass(TWebSessionData);
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
// ***************************************************************************
//
// Delphi MVC Framework
//
// Copyright (c) 2010-2018 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// Collaborators with this file: Ezequiel Juliano Müller (ezequieljuliano@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.
//
// ***************************************************************************
unit CustomTypesSerializersU;
interface
uses
MVCFramework.Serializer.Intf,
System.Rtti;
type
// Custom serializer for TUserRoles type
TUserRolesSerializer = class(TInterfacedObject, IMVCTypeSerializer)
public
procedure Serialize(
const AElementValue: TValue;
var ASerializerObject: TObject;
const AAttributes: TArray<TCustomAttribute>
);
procedure Deserialize(
const ASerializedObject: TObject;
var AElementValue: TValue;
const AAttributes: TArray<TCustomAttribute>
);
end;
// Custom serializer for TNullableAliasSerializer type
TNullableAliasSerializer = class(TInterfacedObject, IMVCTypeSerializer)
public
procedure Serialize(
const AElementValue: TValue;
var ASerializerObject: TObject;
const AAttributes: TArray<TCustomAttribute>
);
procedure Deserialize(
const ASerializedObject: TObject;
var AElementValue: TValue;
const AAttributes: TArray<TCustomAttribute>
);
end;
implementation
uses
JsonDataObjects, CustomTypesU, MVCFramework.Serializer.JsonDataObjects;
{ TUserPasswordSerializer }
procedure TUserRolesSerializer.Deserialize(const ASerializedObject: TObject;
var AElementValue: TValue; const AAttributes: TArray<TCustomAttribute>);
begin
// todo: if you need, implement the deserialize method
end;
procedure TUserRolesSerializer.Serialize(const AElementValue: TValue;
var ASerializerObject: TObject; const AAttributes: TArray<TCustomAttribute>);
var
lJSONArr: TJDOJsonArray;
lRole: string;
I: Integer;
begin
{ Here I want to serialize the userroles array as json array }
// I know that the selected serializer uses JsonDataObject as serialization engine.
// You have to check the serializer documentation to find out what are the
// correct objects to create here!
lJSONArr := TJDOJsonArray.Create;
// Assign to the var parameter the correct object
ASerializerObject := lJSONArr;
// Then fill the returned object with the correct values
// reading from the AElementValue
lJSONArr.Add('--begin--'); { just to prove that the custom serializaion happends }
for I := 0 to AElementValue.GetArrayLength - 1 do
begin
lRole := AElementValue.GetArrayElement(i).AsString;
lJSONArr.Add(lRole);
end;
lJSONArr.Add('--end--'); { just to prove that the custom serializaion happends }
end;
{ TNullableAliasSerializer }
procedure TNullableAliasSerializer.Deserialize(const ASerializedObject: TObject;
var AElementValue: TValue; const AAttributes: TArray<TCustomAttribute>);
begin
end;
procedure TNullableAliasSerializer.Serialize(const AElementValue: TValue;
var ASerializerObject: TObject; const AAttributes: TArray<TCustomAttribute>);
begin
ASerializerObject := TJsonValue.Create;
TJsonValue(ASerializerObject).Value := AElementValue.AsType<TNullableRecordAlias>.Value;
end;
end.
|
unit CounterImpl;
interface
uses orb_int, orbtypes, CosTransactions, CosTransactions_int, Counter, Counter_int,
osthread, poa_int;
type
TCounterImpl = class;
// The counter resource implementation. Note that this resource does
// not implement the semantics of a recoverable resource. Most
// notably:
//
// - The resource is not a persistent object-reference.
//
// - The resource does not log the prepare VoteCommit decision to
// stable store.
//
// - The resource does not implement recovery.
TCounterResourceImpl = class(TResource_serv, ICounter)
private
// The associated counter implementation
FCounter: TCounterImpl;
// The original count
FOrigCount: Integer;
// The transactional count
FCount: Integer;
protected
function prepare: TVote; override;
procedure rollback; override;
procedure commit; override;
procedure commit_one_phase; override;
procedure forget; override;
{ ICounter }
procedure increment;
procedure decrement;
procedure shutdown;
function _get_count: long;
public
constructor Create(ACounter: TCounterImpl; ACount: Integer);
end;
TCounterImpl = class(TCounter_serv)
private
FCurrent: ICurrent;
FCoordinator: ICoordinator;
FResource: IResource;
FCount: Integer;
FMonitor: TThreadMonitor;
procedure Join;
procedure EndTransaction;
procedure Commit(count: Integer);
protected
procedure increment; override;
procedure decrement; override;
procedure shutdown; override;
function _get_count: long; override;
public
constructor Create(const ACurrent: ICurrent);
destructor Destroy; override;
end;
implementation
uses orb, throw, exceptions, internalexceptions;
{ TCounterResourceImpl }
procedure TCounterResourceImpl.commit;
begin
FCounter.Commit(FCount);
end;
procedure TCounterResourceImpl.commit_one_phase;
begin
FCounter.Commit(FCount);
end;
procedure TCounterResourceImpl.decrement;
begin
Dec(FCount);
end;
procedure TCounterResourceImpl.forget;
begin
FCounter.EndTransaction;
end;
procedure TCounterResourceImpl.increment;
begin
Inc(FCount);
end;
function TCounterResourceImpl.prepare: TVote;
begin
if FCount = FOrigCount then begin
FCounter.EndTransaction;
result := VoteReadOnly
end
else
result := VoteCommit;
end;
procedure TCounterResourceImpl.rollback;
begin
FCounter.EndTransaction;
end;
function TCounterResourceImpl._get_count: long;
begin
result := FCount;
end;
procedure TCounterResourceImpl.shutdown;
begin
end;
constructor TCounterResourceImpl.Create(ACounter: TCounterImpl;
ACount: Integer);
begin
inherited Create;
FCounter := ACounter;
FOrigCount := ACount;
FCount := ACount;
end;
{ TCounterImpl }
function TCounterImpl._get_count: long;
var
sync: ISynchronized;
begin
sync := TSynchronized.Create(FMonitor);
Join;
result := (FResource as ICounter).count;
end;
procedure TCounterImpl.decrement;
var
sync: ISynchronized;
begin
sync := TSynchronized.Create(FMonitor);
Join;
(FResource as ICounter).decrement;
end;
procedure TCounterImpl.increment;
var
sync: ISynchronized;
begin
sync := TSynchronized.Create(FMonitor);
Join;
(FResource as ICounter).increment;
end;
procedure TCounterImpl.shutdown;
begin
ORB_Instance.shutdown(false);
end;
procedure TCounterImpl.Join;
var
control: IControl;
coordinator: ICoordinator;
res: TCounterResourceImpl;
begin
try
control := FCurrent.get_control();
if control = nil then
dorb_throw(st_TRANSACTION_REQUIRED);
try
coordinator := control.get_coordinator();
except
on E: SystemException do
if E.extype = st_OBJECT_NOT_EXIST then
dorb_throw(st_TRANSACTION_REQUIRED)
else
raise;
end;
try
// Is this resource is already part of a transaction?
while FCoordinator <> nil do begin
// If the transaction isn't the same as the transaction
// that the resource is already involved with then wait
// for that transaction to terminate.
if(coordinator.is_same_transaction(FCoordinator)) then
Break;
try
FMonitor.wait();
except
on E: EInterruptedException do ;
end;
end;
except
// If the coordinator goes away then the transaction aborted.
on E: SystemException do
if E.extype = st_OBJECT_NOT_EXIST then
EndTransaction()
else
raise;
end;
// Is this resource joining the transaction for the first time?
if FCoordinator = nil then begin
FCoordinator := coordinator;
// Allocate a new resource
res := TCounterResourceImpl.Create(Self, FCount);
FResource := res;
FCoordinator.register_resource(res._this);
end;
except
on E: TInactive do
// The transaction is not active, marked for rollback,
// already preparing.
dorb_throw(st_INVALID_TRANSACTION);
end;
end;
procedure TCounterImpl.EndTransaction;
var
sync: ISynchronized;
oid: ObjectId;
begin
sync := TSynchronized.Create(FMonitor);
// Destroy the resource
oid := FPOA.servant_to_id(FResource as IServant);
FPOA.deactivate_object(oid);
FResource := nil;
// Reset the coordinator to allow the Counter to join a new
// transaction
FCoordinator := nil;
FMonitor.notify();
end;
procedure TCounterImpl.Commit(count: Integer);
var
sync: ISynchronized;
begin
sync := TSynchronized.Create(FMonitor);
FCount := count;
EndTransaction;
end;
constructor TCounterImpl.Create(const ACurrent: ICurrent);
begin
inherited Create;
FCurrent := ACurrent;
FMonitor := TThreadMonitor.Create;
end;
destructor TCounterImpl.Destroy;
begin
FMonitor.Free;
inherited;
end;
end.
|
unit Aircraft;
interface
uses
Windows, Classes, GameTypes, MapSprites, LanderTypes, MapTypes, SoundTypes;
const
cPlaneFramesPerSec = 16;
cPlaneFrameDelay = 1000 div cPlaneFramesPerSec;
type
IAircraft =
interface(IMapSprite)
function GetSoundTarget : ISoundTarget;
procedure SetSoundTarget(const SoundTarget : ISoundTarget);
property SoundTarget : ISoundTarget read GetSoundTarget write SetSoundTarget;
end;
IAircraftManager =
interface(IMapSpriteManager)
procedure RegionUpdated(imin, jmin, imax, jmax : integer);
end;
TAircraft =
class(TInterfacedObject, IAircraft)
public
constructor Create(Id : integer; const IniMapPos : TPoint; IniAngle : TAngle; BlocksToMove : integer; const Manager : IAircraftManager; PlaneClass : PPlaneClass);
destructor Destroy; override;
private
fId : integer;
fFrame : integer;
fAngle : TAngle;
fMapPos : TPoint;
fOldMapPos : TPoint;
fBlockX : integer;
fBlockY : integer;
fOldBlockX : integer;
fOldBlockY : integer;
fManager : IAircraftManager;
fSoundTarget : ISoundTarget;
fLastFrameUpdate : integer;
fBlocksToMove : integer;
fFramesPerBlock : integer;
fLastMoveTicks : dword;
fAnimTicks : integer;
fDeltaX : integer;
fDeltaY : integer;
fDeltaXRest : integer;
fDeltaYRest : integer;
fSlope : single;
fZoom : TZoomRes; // last zoom seen
fRotation : TRotation; // last rotation seen
fImages : array[TZoomRes, TRotation] of TSpriteImages;
private
procedure ReprogramPlane;
function MoveInMap(var FreePlane : boolean) : boolean;
procedure UpdateFrame;
private
function RotateBlockX(blockx, blocky : integer; rotation : TRotation) : integer;
function RotateBlockY(blockx, blocky : integer; rotation : TRotation) : integer;
private // IMapSprite
function GetId : integer;
function GetFrame : integer;
function GetAngle : TAngle;
function GetMapX : integer;
function GetMapY : integer;
function GetOldMapX : integer;
function GetOldMapY : integer;
procedure AnimationTick;
procedure NewView(const View : IGameView);
function GetBlockX(const View : IGameView) : integer;
function GetBlockY(const View : IGameView) : integer;
function GetOldBlockX(const View : IGameView) : integer;
function GetOldBlockY(const View : IGameView) : integer;
function GetWidth(const View : IGameView) : integer;
function GetHeight(const View : IGameView) : integer;
private // IAircraft
function GetSoundTarget : ISoundTarget;
procedure SetSoundTarget(const SoundTarget : ISoundTarget);
end;
type
PPlaneClasses = ^TPlaneClasses;
TPlaneClasses = array [0..0] of TPlaneClass;
type
TAircraftManager =
class(TMapSpriteManager, IAircraftManager)
public
constructor Create(const Map : IWorldMap; const Converter : ICoordinateConverter; const Manager : ILocalCacheManager; MinAnimInterval : integer; OwnsSprites : boolean);
destructor Destroy; override;
private // IMapSpriteManager
function GetSpriteCount : integer; override;
function GetSprite(i : integer) : IMapSprite; override;
procedure SpriteMapPosChanged(const Sprite : IMapSprite); override;
function RegisterSprite(const Sprite : IMapSprite) : integer; override;
procedure UnregisterSprite(const Sprite : IMapSprite); override;
procedure RecacheSoundTargets(soundsenabled : boolean); override;
procedure Disable; override;
private // IPlanesManager
procedure RegionUpdated(imin, jmin, imax, jmax : integer);
private
fPlaneInstances : TList;
fTicks : integer;
private // valid classes cache
fClassCount : integer;
fClasses : PPlaneClasses;
private
fSoundsEnabled : boolean;
protected
procedure AnimationTick; override;
function GetFullSpriteId(const Sprite : IMapSprite) : integer; override;
procedure RegulatePlaneFlow(imin, jmin, imax, jmax : integer);
end;
const
cPlanesTimerInterval = cPlaneFrameDelay;
implementation
const
cAirTrafficRegInterval = 20000 div cPlanesTimerInterval;
const
u = 16; // >>>
const
cStoppedPlaneDeathDelay = 300;
procedure FreeObject(var which);
var
aux : TObject;
begin
aux := TObject(which);
TObject(which) := nil;
aux.Free;
end;
procedure boundvalue(min, max : single; var value : single);
begin
if value < min
then value := min;
if value > max
then value := max;
end;
// TAircraft
constructor TAircraft.Create(Id : integer; const IniMapPos : TPoint; IniAngle : TAngle; BlocksToMove : integer; const Manager : IAircraftManager; PlaneClass : PPlaneClass);
begin
inherited Create;
fId := Id;
fMapPos := IniMapPos;
fAngle := IniAngle;
fBlocksToMove := BlocksToMove;
fOldMapPos := fMapPos;
fManager := Manager;
fFramesPerBlock := round(cPlaneFramesPerSec/PlaneClass.Speed);
fManager.RegisterSprite(IAircraft(Self));
fManager.UpdateSpriteRect(IAircraft(Self));
fManager._Release; // >> cross referenced
end;
destructor TAircraft.Destroy;
begin
if fManager <> nil
then fManager.UnregisterSprite(IAircraft(Self));
pointer(fManager) := nil; // >> cross referenced
inherited;
end;
procedure TAircraft.ReprogramPlane;
const
cBlocksInc = 32;
begin
if fBlocksToMove = 0
then inc(fBlocksToMove, cBlocksInc);
end;
function TAircraft.MoveInMap(var FreePlane : boolean) : boolean;
var
DeltaX, DeltaY : integer;
begin
DeltaX := 0;
DeltaY := 0;
if fBlocksToMove > 0
then
begin
dec(fBlocksToMove);
case fAngle of
agN:
DeltaY := 1;
agNE:
begin
DeltaX := 1;
DeltaY := 1;
end;
agE:
DeltaX := 1;
agSE:
begin
DeltaX := 1;
DeltaY := -1;
end;
agS:
DeltaY := -1;
agSW:
begin
DeltaX := -1;
DeltaY := -1;
end;
agW:
DeltaX := -1;
agNW:
begin
DeltaX := -1;
DeltaY := 1;
end;
end;
end;
if (DeltaX <> 0) or (DeltaY <> 0)
then
begin
fBlockX := 0;
fBlockY := 0;
case DeltaX of
-1:
case DeltaY of
-1:
begin
fDeltaX := 0;
fDeltaXRest := 0;
fDeltaY := 2*u div pred(fFramesPerBlock);
fDeltaYRest := 2*u mod pred(fFramesPerBlock);
fSlope := 0;
end;
0:
begin
fDeltaX := -(2*u div pred(fFramesPerBlock));
fDeltaXRest := -(2*u mod pred(fFramesPerBlock));
fDeltaY := u div pred(fFramesPerBlock);
fDeltaYRest := u mod pred(fFramesPerBlock);
fSlope := -0.5;
end;
1:
begin
fDeltaX := -(4*u div pred(fFramesPerBlock));
fDeltaXRest := -(4*u mod pred(fFramesPerBlock));
fDeltaY := 0;
fDeltaYRest := 0;
fSlope := 0;
end;
end;
0:
case DeltaY of
-1:
begin
fDeltaX := 2*u div pred(fFramesPerBlock);
fDeltaXRest := 2*u mod pred(fFramesPerBlock);
fDeltaY := u div pred(fFramesPerBlock);
fDeltaYRest := u mod pred(fFramesPerBlock);
fSlope := 0.5;
end;
1:
begin
fDeltaX := -(2*u div pred(fFramesPerBlock));
fDeltaXRest := -(2*u mod pred(fFramesPerBlock));
fDeltaY := -(u div pred(fFramesPerBlock));
fDeltaYRest := -(u mod pred(fFramesPerBlock));
fSlope := 0.5;
end;
end;
1:
case DeltaY of
-1:
begin
fDeltaX := 4*u div pred(fFramesPerBlock);
fDeltaXRest := 4*u mod pred(fFramesPerBlock);
fDeltaY := 0;
fDeltaYRest := 0;
fSlope := 0;
end;
0:
begin
fDeltaX := 2*u div pred(fFramesPerBlock);
fDeltaXRest := 2*u mod pred(fFramesPerBlock);
fDeltaY := -(u div pred(fFramesPerBlock));
fDeltaYRest := -(u mod pred(fFramesPerBlock));
fSlope := -0.5;
end;
1:
begin
fDeltaX := 0;
fDeltaXRest := 0;
fDeltaY := -(2*u div pred(fFramesPerBlock));
fDeltaYRest := -(2*u mod pred(fFramesPerBlock));
fSlope := 0;
end;
end;
end;
inc(fMapPos.X, DeltaX);
inc(fMapPos.Y, DeltaY);
fManager.SpriteMapPosChanged(IAircraft(Self));
fLastMoveTicks := GetTickCount;
Result := true;
end
else
begin
if (GetTickCount - fLastMoveTicks > cStoppedPlaneDeathDelay) and not fManager.IsSpriteVisible(IAircraft(Self))
then FreePlane := true
else
if fManager.IsSpriteVisible(IAircraft(Self))
then ReprogramPlane;
Result := false;
end;
end;
procedure TAircraft.UpdateFrame;
var
ElapsedTicks : integer;
CurrentTick : integer;
Img : TGameImage;
begin
Img := fImages[fZoom, fRotation][fAngle];
if (Img <> nil) and (Img.FrameCount > 1)
then
begin
CurrentTick := GetTickCount;
if fFrame >= Img.FrameCount
then
begin
fFrame := 0;
fLastFrameUpdate := CurrentTick;
end;
ElapsedTicks := CurrentTick - fLastFrameUpdate;
if ElapsedTicks >= Img.FrameDelay[fFrame]
then
begin
if fFrame < pred(Img.FrameCount)
then inc(fFrame)
else fFrame := 0;
fLastFrameUpdate := CurrentTick;
end;
end;
end;
function TAircraft.RotateBlockX(blockx, blocky : integer; rotation : TRotation) : integer;
begin
case rotation of
drNorth:
Result := blockx;
drEast:
Result := 2*blocky;
drSouth:
Result := -blockx;
else // drWest
Result := -2*blocky;
end;
end;
function TAircraft.RotateBlockY(blockx, blocky : integer; rotation : TRotation) : integer;
begin
case rotation of
drNorth:
Result := blocky;
drEast:
Result := round(-blockx/2);
drSouth:
Result := -blocky;
else // drWest
Result := round(blockx/2);
end;
end;
function TAircraft.GetId : integer;
begin
Result := fId;
end;
function TAircraft.GetFrame : integer;
begin
Result := fFrame;
end;
function TAircraft.GetAngle : TAngle;
begin
Result := fAngle;
end;
function TAircraft.GetMapX : integer;
begin
Result := fMapPos.X;
end;
function TAircraft.GetMapY : integer;
begin
Result := fMapPos.Y;
end;
function TAircraft.GetOldMapX : integer;
begin
Result := fOldMapPos.x;
end;
function TAircraft.GetOldMapY : integer;
begin
Result := fOldMapPos.y;
end;
procedure TAircraft.AnimationTick;
var
OldFrame : integer;
FreePlane : boolean;
begin
fOldBlockX := fBlockX;
fOldBlockY := fBlockY;
fOldMapPos := fMapPos;
FreePlane := false;
if fAnimTicks < pred(pred(fFramesPerBlock))
then
begin
inc(fAnimTicks);
if fSlope <> 0
then
begin
inc(fBlockX, fDeltaX);
if fDeltaXRest > 0
then
begin
inc(fBlockX);
dec(fDeltaXRest);
end
else
if fDeltaXRest < 0
then
begin
dec(fBlockX);
inc(fDeltaXRest);
end;
fBlockY := round(fSlope*fBlockX);
end
else
if fDeltaX <> 0
then
begin
if fDeltaXRest > 0
then
begin
inc(fBlockX);
dec(fDeltaXRest);
end
else
if fDeltaXRest < 0
then
begin
dec(fBlockX);
inc(fDeltaXRest);
end;
inc(fBlockX, fDeltaX);
end
else
if fDeltaY <> 0
then
begin
inc(fBlockY, fDeltaY);
if fDeltaYRest > 0
then
begin
inc(fBlockY);
dec(fDeltaYRest);
end
else
if fDeltaYRest < 0
then
begin
dec(fBlockY);
inc(fDeltaYRest);
end;
end;
end
else
if MoveInMap(FreePlane) and not FreePlane
then fAnimTicks := 0;
OldFrame := fFrame;
UpdateFrame;
if ((fMapPos.x <> fOldMapPos.x) or (fMapPos.y <> fOldMapPos.y) or (fBlockX <> fOldBlockX) or (fBlockY <> fOldBlockY) or (OldFrame <> fFrame) or FreePlane) and (fManager <> nil)
then fManager.UpdateSpriteRect(IAircraft(Self));
if FreePlane
then _Release;
end;
procedure TAircraft.NewView(const View : IGameView);
begin
fFrame := 0;
fillchar(fImages[fZoom, fRotation], sizeof(fImages[fZoom, fRotation]), 0);
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(IAircraft(Self), View, fImages[fZoom, fRotation]);
end;
function TAircraft.GetBlockX(const View : IGameView) : integer;
begin
Result := RotateBlockX(fBlockX, fBlockY, View.Rotation)*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n - GetWidth(View) div 2;
end;
function TAircraft.GetBlockY(const View : IGameView) : integer;
begin
Result := RotateBlockY(fBlockX, fBlockY, View.Rotation)*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n - GetHeight(View) div 2;
end;
function TAircraft.GetOldBlockX(const View : IGameView) : integer;
begin
Result := RotateBlockX(fOldBlockX, fOldBlockY, View.Rotation)*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n - GetWidth(View) div 2;
end;
function TAircraft.GetOldBlockY(const View : IGameView) : integer;
begin
Result := RotateBlockY(fOldBlockX, fOldBlockY, View.Rotation)*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n - GetHeight(View) div 2;
end;
function TAircraft.GetWidth(const View : IGameView) : integer;
begin
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(IAircraft(Self), View, fImages[fZoom, fRotation]);
if fImages[fZoom, fRotation][fAngle] <> nil
then Result := fImages[fZoom, fRotation][fAngle].Width
else Result := 0;
end;
function TAircraft.GetHeight(const View : IGameView) : integer;
begin
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(IAircraft(Self), View, fImages[fZoom, fRotation]);
if fImages[fZoom, fRotation][fAngle] <> nil
then Result := fImages[fZoom, fRotation][fAngle].Height
else Result := 0;
end;
function TAircraft.GetSoundTarget : ISoundTarget;
begin
Result := fSoundTarget;
end;
procedure TAircraft.SetSoundTarget(const SoundTarget : ISoundTarget);
begin
fSoundTarget := SoundTarget;
end;
// TAircraftSoundTarget
type
TAircraftSoundTarget =
class(TInterfacedObject, ISoundTarget)
public
constructor Create(Owner : IGameFocus; const Aircraft : IAircraft; PlaneClass : PPlaneClass; const Converter : ICoordinateConverter);
destructor Destroy; override;
private
fOwner : IGameFocus;
fAircraft : IAircraft;
fConverter : ICoordinateConverter;
fSoundData : TSoundData;
fPan : single;
fVolume : single;
fLastPlayed : dword;
private // ISoundTarget
function GetSoundName : string;
function GetSoundKind : integer;
function GetPriority : integer;
function IsLooped : boolean;
function GetVolume : single;
function GetPan : single;
function ShouldPlayNow : boolean;
function IsCacheable : boolean;
function IsEqualTo(const SoundTarget : ISoundTarget) : boolean;
function GetObject : TObject;
procedure UpdateSoundParameters;
end;
constructor TAircraftSoundTarget.Create(Owner : IGameFocus; const Aircraft : IAircraft; PlaneClass : PPlaneClass; const Converter : ICoordinateConverter);
begin
inherited Create;
fOwner := Owner;
fOwner._Release; // >> cross referenced
fAircraft := Aircraft;
fAircraft._Release; // >> cross referenced
fSoundData := PlaneClass.SoundData;
fConverter := Converter;
fConverter._Release; // >> cross referenced
UpdateSoundParameters;
end;
destructor TAircraftSoundTarget.Destroy;
begin
pointer(fConverter) := nil; // >> cross referenced
pointer(fAircraft) := nil; // >> cross referenced
pointer(fOwner) := nil; // >> cross referenced
inherited;
end;
function TAircraftSoundTarget.GetSoundName : string;
begin
Result := fSoundData.wavefile;
end;
function TAircraftSoundTarget.GetSoundKind : integer;
begin
Result := integer(Self);
end;
function TAircraftSoundTarget.GetPriority : integer;
begin
Result := fSoundData.priority;
end;
function TAircraftSoundTarget.IsLooped : boolean;
begin
Result := fSoundData.looped;
end;
function TAircraftSoundTarget.GetVolume : single;
begin
Result := fVolume*fSoundData.atenuation;
end;
function TAircraftSoundTarget.GetPan : single;
begin
Result := fPan;
end;
function TAircraftSoundTarget.ShouldPlayNow : boolean;
var
ElapsedTicks : integer;
begin
with fSoundData do
if (not looped and (period <> 0)) or (fLastPlayed = 0)
then
begin
ElapsedTicks := GetTickCount - fLastPlayed;
if ElapsedTicks >= period
then
begin
if random < probability
then Result := true
else Result := false;
fLastPlayed := GetTickCount;
end
else Result := false;
end
else Result := false;
end;
function TAircraftSoundTarget.IsCacheable : boolean;
begin
Result := false;
end;
function TAircraftSoundTarget.IsEqualTo(const SoundTarget : ISoundTarget) : boolean;
var
SndTargetObj : TObject;
begin
SndTargetObj := SoundTarget.GetObject;
if SndTargetObj is TAircraftSoundTarget
then Result := fAircraft = TAircraftSoundTarget(SndTargetObj).fAircraft
else Result := false;
end;
function TAircraftSoundTarget.GetObject : TObject;
begin
Result := Self;
end;
procedure TAircraftSoundTarget.UpdateSoundParameters;
var
screensize : TPoint;
tmppt : TPoint;
x, y : integer;
u : integer;
ci, cj : integer;
Dist : single;
view : IGameView;
begin
with fOwner do
begin
view := GetView;
fConverter.MapToScreen(view, fAircraft.MapY, fAircraft.MapX, x, y);
tmppt := view.ViewPtToScPt(Point(x, y));
x := tmppt.x;
y := tmppt.y;
u := 2 shl view.ZoomLevel;
x := x + 2*u;
screensize := Point(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
if abs(x - screensize.x/2) > cPanDeadZone
then fPan := cLeftPan + (cRightPan - cLeftPan)*x/screensize.x
else fPan := cCenterPan;
boundvalue(cLeftPan, cRightPan, fPan);
tmppt := view.ScPtToViewPt(Point(screensize.x div 2, screensize.y div 2));
fConverter.ScreenToMap(view, tmppt.x, tmppt.y, ci, cj);
Dist := sqrt(sqr(ci - fAircraft.MapY) + sqr(cj - fAircraft.MapX));
if Dist < cMaxHearDist
then fVolume := cMinVol + (1 - Dist/cMaxHearDist)*(cMaxVol - cMinVol)*(1 - abs(view.ZoomLevel - ord(cBasicZoomRes))*cZoomVolStep)
else fVolume := cMinVol;
boundvalue(cMinVol, cMaxVol, fVolume);
end;
end;
// TAircraftManager
constructor TAircraftManager.Create(const Map : IWorldMap; const Converter : ICoordinateConverter; const Manager : ILocalCacheManager; MinAnimInterval : integer; OwnsSprites : boolean);
var
i : integer;
id : idCar;
PlaneClass : PPlaneClass;
begin
inherited Create(Map, Converter, Manager, MinAnimInterval, OwnsSprites);
fPlaneInstances := TList.Create;
fInterval := cPlanesTimerInterval;
with fMap do
begin
fClassCount := fManager.GetPlaneClassCount;
getmem(fClasses, fClassCount*sizeof(fClasses[0]));
zeromemory( fClasses, fClassCount*sizeof(fClasses[0]));
i := 0;
for id := low(id) to high(id) do
begin
PlaneClass := fManager.GetPlaneClass(id);
if (PlaneClass <> nil) and PlaneClass.valid
then
try
fClasses[i] := PlaneClass^;
inc(i);
except
end;
end;
end;
fSoundsEnabled := true;
end;
destructor TAircraftManager.Destroy;
begin
FreeObject(fPlaneInstances);
freemem(fClasses);
inherited;
end;
function TAircraftManager.GetSpriteCount : integer;
begin
Result := fPlaneInstances.Count;
end;
function TAircraftManager.GetSprite(i : integer) : IMapSprite;
begin
Result := IMapSprite(fPlaneInstances[i]);
end;
procedure TAircraftManager.SpriteMapPosChanged(const Sprite : IMapSprite);
var
SoundTarget : ISoundTarget;
Focus : IGameFocus;
i : integer;
begin
for i := 0 to pred(fFocuses.Count) do
begin
Focus := IGameFocus(fFocuses[i]);
SoundTarget := IAircraft(Sprite).SoundTarget; // >> must ask for focus SoundTarget
if SoundTarget <> nil
then
begin
SoundTarget.UpdateSoundParameters;
Focus.GetSoundManager.UpdateTarget(SoundTarget);
end;
end;
end;
function TAircraftManager.RegisterSprite(const Sprite : IMapSprite) : integer;
var
SoundTarget : ISoundTarget;
Focus : IGameFocus;
i : integer;
PlaneClass : PPlaneClass;
begin
Result := fPlaneInstances.Add(pointer(Sprite));
Sprite._AddRef;
if fSoundsEnabled
then
begin
PlaneClass := fManager.GetPlaneClass(Sprite.Id);
for i := 0 to pred(fFocuses.Count) do
begin
Focus := IGameFocus(fFocuses[i]);
if PlaneClass.SoundData.wavefile <> ''
then
begin
SoundTarget := TAircraftSoundTarget.Create(Focus, IAircraft(Sprite), PlaneClass, fConverter);
IAircraft(Sprite).SoundTarget := SoundTarget; // >> must keep a sound target for each focus
Focus.GetSoundManager.AddTargets(SoundTarget);
end;
end;
end;
end;
procedure TAircraftManager.UnregisterSprite(const Sprite : IMapSprite);
var
SoundTarget : ISoundTarget;
Focus : IGameFocus;
i : integer;
begin
fPlaneInstances[fPlaneInstances.IndexOf(pointer(Sprite))] := nil;
SoundTarget := IAircraft(Sprite).SoundTarget; // >>
if SoundTarget <> nil
then
for i := 0 to pred(fFocuses.Count) do
begin
Focus := IGameFocus(fFocuses[i]);
Focus.GetSoundManager.RemoveTarget(SoundTarget);
end;
end;
procedure TAircraftManager.RecacheSoundTargets(soundsenabled : boolean);
var
i : integer;
j : integer;
Focus : IGameFocus;
Aircraft : IAircraft;
PlaneClass : PPlaneClass;
SoundTarget : ISoundTarget;
begin
fSoundsEnabled := soundsenabled;
for i := 0 to pred(fPlaneInstances.Count) do
begin
Aircraft := IAircraft(fPlaneInstances[i]);
if Aircraft <> nil
then
begin
PlaneClass := fManager.GetPlaneClass(Aircraft.Id);
for j := 0 to pred(fFocuses.Count) do
begin
Focus := IGameFocus(fFocuses[j]);
if PlaneClass.SoundData.wavefile <> ''
then
begin
Aircraft.SoundTarget := nil;
if fSoundsEnabled
then
begin
SoundTarget := TAircraftSoundTarget.Create(Focus, Aircraft, PlaneClass, fConverter);
Aircraft.SoundTarget := SoundTarget; // >> must keep a sound target for each focus
Focus.GetSoundManager.AddTargets(SoundTarget);
end;
end;
end;
end;
end;
end;
procedure TAircraftManager.Disable;
begin
inherited;
fPlaneInstances.Pack;
end;
procedure TAircraftManager.RegionUpdated(imin, jmin, imax, jmax : integer);
begin
if not fExternallyDisabled
then RegulatePlaneFlow(imin, jmin, imax, jmax);
end;
procedure TAircraftManager.AnimationTick;
var
i : integer;
imin : integer;
jmin : integer;
imax : integer;
jmax : integer;
begin
inherited;
fPlaneInstances.Pack;
if fTicks = pred(cAirTrafficRegInterval)
then
begin
for i := 0 to pred(fFocuses.Count) do
begin
fConverter.GetViewRegion(IGameFocus(fFocuses[i]).GetView, imin, jmin, imax, jmax);
RegulatePlaneFlow(imin, jmin, imax, jmax);
end;
fTicks := 0;
end
else inc(fTicks);
end;
function TAircraftManager.GetFullSpriteId(const Sprite : IMapSprite) : integer;
begin
Result := idPlaneMask or Sprite.Id;
end;
procedure TAircraftManager.RegulatePlaneFlow(imin, jmin, imax, jmax: integer);
function GetNorthAngle : TAngle;
var
randnum : integer;
begin
randnum := random(3);
case randnum of
0:
Result := agNW;
1:
Result := agN;
2:
Result := agNE
else
Result := agN;
end;
end;
function GetSouthAngle : TAngle;
var
randnum : integer;
begin
randnum := random(3);
case randnum of
0:
Result := agSW;
1:
Result := agS;
2:
Result := agSE
else
Result := agS;
end;
end;
function GetEastAngle : TAngle;
var
randnum : integer;
begin
randnum := random(3);
case randnum of
0:
Result := agNE;
1:
Result := agE;
2:
Result := agSE
else
Result := agE;
end;
end;
function GetWestAngle : TAngle;
var
randnum : integer;
begin
randnum := random(3);
case randnum of
0:
Result := agNW;
1:
Result := agW;
2:
Result := agSW
else
Result := agW;
end;
end;
function GeneratePlaneId(out planeid : idPlane) : boolean;
var
selectedids : array [idPlane] of idPlane;
selectedidscnt : word;
threshold : single;
maxprob : single;
i : integer;
planeclass : TPlaneClass;
begin
threshold := random;
selectedidscnt := 0;
maxprob := 0;
for i := 0 to pred(fClassCount) do
begin
planeclass := fClasses[i];
if planeclass.Prob > threshold
then
begin
selectedids[selectedidscnt] := planeclass.id;
inc(selectedidscnt);
end
else
if planeclass.Prob > maxprob
then maxprob := planeclass.Prob;
end;
if selectedidscnt = 0
then
for i := 0 to pred(fClassCount) do
begin
planeclass := fClasses[i];
if planeclass.Prob = maxprob
then
begin
selectedids[selectedidscnt] := planeclass.id;
inc(selectedidscnt);
end;
end;
if selectedidscnt > 0
then
begin
planeid := selectedids[random(selectedidscnt)];
Result := true;
end
else Result := false;
end; // >> check this id selection method, bug here!!!
const
cMaxPlanes = 5;
cBlocksToMove = 32;
var
zone : byte;
planeid : idPlane;
planeclass : PPlaneClass;
begin
zone := random(4);
if (fFocuses.Count > 0) and (fPlaneInstances.Count < cMaxPlanes)
then
if GeneratePlaneId(planeid)
then
begin
planeclass := fManager.GetPlaneClass(planeid);
case Zone of
0:
TAircraft.Create(planeid, Point(jmin + random(jmax - jmin), imin - 8), GetNorthAngle, cBlocksToMove, Self, planeclass);
1:
TAircraft.Create(planeid, Point(jmin + random(jmax - jmin), imax + 8), GetSouthAngle, cBlocksToMove, Self, planeclass);
2:
TAircraft.Create(planeid, Point(jmin - 8, imin + random(imax - imin)), GetEastAngle, cBlocksToMove, Self, planeclass);
3:
TAircraft.Create(planeid, Point(jmax + 8, imin + random(imax - imin)), GetWestAngle, cBlocksToMove, Self, planeclass);
end;
end;
end;
end.
|
unit xibfile;
{$mode objfpc}
interface
uses
Classes, SysUtils, XMLRead, DOM;
type
{ TXibObject }
TXibObject = class(TObject)
private
fXibNode : TDOMNode;
fNextObject : TXibObject;
fChildObject : TXibObject;
protected
function GetBoolProp(const PropName: String):Boolean;
function GetIntProp(const PropName: String):Integer;
function GetStrProp(const PropName: String):String;
function FindProperty(const PropName: String): TDOMNode;
function GetName: String;
function GetXibClass: String;
public
constructor Create(AXibNode: TDOMNode);
destructor Destroy; override;
procedure GetUnnamedStrProps(list: TStrings);
property NextObject: TXibObject read fNextObject;
property ChildObject: TXibObject read fChildObject;
property BoolProp[const PropName: String]: Boolean read GetBoolProp;
property StrProp[const PropName: String]: String read GetStrProp;
property IntProp[const PropName: String]: Integer read GetIntProp;
property Name: String read GetName;
property XibClass: String read GetXibClass;
end;
{ TXibFile }
TXibFile = class(TObject)
private
fDoc : TXMLDocument;
fFirstObject : TXibObject;
public
destructor Destroy; override;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: AnsiString);
property FirstObject: TXibObject read fFirstObject;
end;
procedure DoReadXibDoc(ADoc: TXMLDocument; var Obj: TXibObject);
function FindXibObject(root: TXibObject; const ObjName: String; Recursive: Boolean=False): TXibObject;
type
TXibKeyValue = record
Key : AnsiString;
Value : AnsiString;
end;
{ TXibClassDescr }
TXibClassDescr = class(TObject)
Name : AnsiString;
Actions : array of TXibKeyValue;
Outlets : array of TXibKeyValue;
constructor Create(const AName: AnsiString);
end;
procedure ListClassesDescr(root: TXibObject; DstList : TList); overload;
procedure ListClassesDescr(const FileName: AnsiString; DstList : TList); overload;
implementation
function Min(a,b: integer): Integer;
begin
if a<b then Result:=a
else Result:=b;
end;
procedure SetActions(names, types: TStrings; descr: TXibClassDescr);
var
i : integer;
begin
if not Assigned(names) or not Assigned(types) then Exit;
SetLength(descr.Actions, Min(names.Count, types.Count));
for i:=0 to length(descr.Actions)- 1 do begin
descr.Actions[i].Key:=names[i];
descr.Actions[i].Value:=types[i];
end;
end;
procedure SetOutlets(names, types: TStrings; descr: TXibClassDescr);
var
i : integer;
begin
if not Assigned(names) or not Assigned(types) then Exit;
SetLength(descr.Outlets, Min(names.Count, types.Count));
for i:=0 to length(descr.Outlets)- 1 do begin
descr.Outlets[i].Key:=names[i];
descr.Outlets[i].Value:=types[i];
end;
end;
procedure ListDictionary(dict: TXibObject; keys, values: TStrings);
var
xibkeys : TXibObject;
xibvals : TXibObject;
begin
if Assigned(dict) then begin
xibkeys:=FindXibObject(dict, 'dict.sortedKeys');
xibvals:=FindXibObject(dict, 'dict.values');
if Assigned(xibkeys) and Assigned(xibvals) then begin
xibkeys.GetUnnamedStrProps(keys);
xibvals.GetUnnamedStrProps(values);
end;
end;
end;
procedure ListClassesDescr(root: TXibObject; DstList : TList);
var
obj : TXibObject;
act : TXibObject;
outs : TXibObject;
cls : TXibClassDescr;
names : TStringList;
types : TStringList;
begin
if not Assigned(DstList) then Exit;
obj:=FindXibObject(root, 'IBDocument.Classes', true);
if not Assigned(obj) then Exit;
names := TStringList.Create;
types := TStringList.Create;
obj:=FindXibObject(obj, 'referencedPartialClassDescriptions', true);
obj:=obj.ChildObject;
while Assigned(obj) do begin
if obj.XibClass<>'IBPartialClassDescription' then begin
obj:=obj.NextObject;
Continue;
end;
cls:=TXibClassDescr.Create(obj.StrProp['className']);
act:=FindXibObject(obj, 'actions');
if Assigned(act) then begin
names.Clear; types.Clear;
ListDictionary(act, names, types);
SetActions(names, types, cls);
end;
outs:=FindXibObject(obj, 'outlets');
if Assigned(outs) then begin
names.Clear; types.Clear;
ListDictionary(outs, names, types);
SetOutlets(names, types, cls);
end;
DstList.Add(cls);
obj:=obj.NextObject;
end;
names.Free;
types.Free;
end;
function FindXibObject(root: TXibObject; const ObjName: String; Recursive: Boolean): TXibObject;
var
obj : TXibObject;
begin
obj:=root.ChildObject;
while Assigned(obj) and (obj.Name<>ObjName) do begin
if Recursive then begin
Result:=FindXibObject(obj, ObjName, Recursive);
if Assigned(Result) then Exit;
end;
obj:=obj.NextObject;
end;
Result:=obj;
end;
procedure DoReadXibDoc(ADoc: TXMLDocument; var Obj: TXibObject);
const
DataNode = 'data';
XibObject = 'object';
var
node : TDOMNode;
n : TDOMNode;
xib : TXibObject;
pending : TList;
begin
Obj:=nil;
writeln('ADoc = ', Integer(ADoc));
// node:=ADoc.FindNode(DataNode);
node:=ADoc.FindNode('archive');
node:=node.FindNode('data');
writeln('no data? ', Integer(node));
if not Assigned(node) then Exit;
xib:=TXibObject.Create(node);
pending:=TList.Create;
Obj:=xib;
try
while Assigned(xib) do begin
node:=xib.fXibNode;
n:=node.NextSibling;
while Assigned(n) and (n.NodeName<>XibObject) do
n:=n.NextSibling;
if Assigned(n) then begin
xib.fNextObject:=TXibObject.Create(n);
pending.add(xib.NextObject);
end;
n:=node.FirstChild;
while Assigned(n) and (n.NodeName<>XibObject) do
n:=n.NextSibling;
if Assigned(n) then begin
xib.fChildObject:=TXibObject.Create(n);
pending.add(xib.ChildObject);
end;
if pending.Count>0 then begin
xib:=TXibObject(pending[0]);
pending.Delete(0);
end else
xib:=nil;
end;
except
end;
pending.Free;
end;
{ TXibFile }
destructor TXibFile.Destroy;
begin
fDoc.Free;
fFirstObject.Free;
inherited Destroy;
end;
procedure TXibFile.LoadFromStream(Stream:TStream);
begin
fDoc.Free;
fDoc:=nil;
try
ReadXMLFile(fDoc, Stream);
DoReadXibDoc(fDoc, fFirstObject);
except
end;
end;
procedure TXibFile.LoadFromFile(const FileName:AnsiString);
var
fs : TFileStream;
begin
fs:=TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(fs);
finally
fs.Free;
end;
end;
{ TXibObject }
constructor TXibObject.Create(AXibNode:TDOMNode);
begin
inherited Create;
fXibNode:=AXibNode;
end;
destructor TXibObject.Destroy;
begin
fNextObject.Free;
fChildObject.Free;
inherited Destroy;
end;
procedure TXibObject.GetUnnamedStrProps(list:TStrings);
var
n : TDOMNode;
begin
if not Assigned(list) then Exit;
n:=fXibNode.FirstChild;
while Assigned(n) do begin
if (n.NodeName='string') and (TDOMElement(n).AttribStrings['key']='') then
list.Add(n.TextContent);
n:=n.NextSibling;
end;
end;
function TXibObject.GetBoolProp(const PropName: String):Boolean;
var
n : TDOMNode;
begin
n:=FindProperty(PropName);
Result:=Assigned(n) and (n.NodeName='bool') and (n.TextContent='YES');
end;
function TXibObject.GetIntProp(const PropName: String):Integer;
var
n : TDOMNode;
err : Integer;
begin
n:=FindProperty(PropName);
if Assigned(n) and (n.NodeName='int') then begin
Val(n.TextContent, Result, err);
if err<>0 then Result:=0;
end else
Result:=0;
end;
function TXibObject.GetStrProp(const PropName: String):String;
var
n : TDOMNode;
begin
n:=FindProperty(PropName);
if Assigned(n) and (n.NodeName='string') then Result:=n.TextContent
else Result:='';
end;
function isKeyAttr(n: TDomNode; const KeyAttrVal: String): Boolean;
begin
Result:=Assigned(n) and (n is TDOMElement) and (TDOMElement(n).AttribStrings['key']=KeyAttrVal)
end;
function TXibObject.FindProperty(const PropName:String):TDOMNode;
var
n : TDOMNode;
begin
n:=fXibNode.FirstChild;
while Assigned(n) and (n.NodeName='object') and (not isKeyAttr(n, PropName)) do
n:=n.NextSibling;
Result:=n;
end;
function TXibObject.GetName:String;
begin
if not (fXibNode is TDOMElement) then begin
Result:='';
Exit;
end;
Result:=TDOMElement(fXibNode).AttribStrings['key'];
end;
function TXibObject.GetXibClass:String;
begin
if not (fXibNode is TDOMElement) then begin
Result:='';
Exit;
end;
Result:=TDOMElement(fXibNode).AttribStrings['class'];
end;
procedure ListClassesDescr(const FileName: AnsiString; DstList : TList); overload;
var
xib : TXibFile;
begin
xib := TXibFile.Create;
try
xib.LoadFromFile(FileName);
ListClassesDescr(xib.FirstObject, DstList);
finally
xib.Free;
end;
end;
{ TXibClassDescr }
constructor TXibClassDescr.Create(const AName:AnsiString);
begin
inherited Create;
Name:=AName;
end;
end.
|
namespace Nancy.Bootstrappers.Autofac;
uses
Autofac,
Autofac.Core.Lifetime,
Nancy,
Nancy.Bootstrapper,
Nancy.Configuration,
Nancy.Diagnostics, System.Collections.Generic;
type
AutofacNancyBootstrapper = public abstract class(NancyBootstrapperWithRequestContainerBase<ILifetimeScope>)
protected
method GetDiagnostics:IDiagnostics;override;
begin
exit self.ApplicationContainer.Resolve<IDiagnostics>;
end;
/// <summary>
/// Gets all registered application startup tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns>
method GetApplicationStartupTasks:IEnumerable<IApplicationStartup>;override;
begin
exit self.ApplicationContainer.Resolve<IEnumerable<IApplicationStartup>>;
end;
/// <summary>
/// Gets all registered request startup tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns>
method RegisterAndGetRequestStartupTasks(container:ILifetimeScope; requestStartupTypes: array of &Type):IEnumerable<IRequestStartup> ;override;
begin
container.Update(builder ->
begin
for each requestStartupType in requestStartupTypes do
begin
builder.RegisterType(requestStartupType).As<IRequestStartup>().PreserveExistingDefaults().InstancePerDependency();
end;
end);
exit container.Resolve<IEnumerable<IRequestStartup>>();
end;
/// <summary>
/// Gets all registered application registration tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns>
method GetRegistrationTasks:IEnumerable<IRegistrations> ;override;
begin
exit self.ApplicationContainer.Resolve<IEnumerable<IRegistrations>>();
end;
/// <summary>
/// Get INancyEngine
/// </summary>
/// <returns>INancyEngine implementation</returns>
method GetEngineInternal:INancyEngine;override;
begin
exit self.ApplicationContainer.Resolve<INancyEngine>();
end;
/// <summary>
/// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th.
/// </summary>
/// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns>
method GetEnvironmentConfigurator:INancyEnvironmentConfigurator;override;
begin
exit self.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();
end;
/// <summary>
/// Registers an <see cref="INancyEnvironment"/> instance in the container.
/// </summary>
/// <param name="container">The container to register into.</param>
/// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param>
method RegisterNancyEnvironment(container:ILifetimeScope; environment:INancyEnvironment);override;
begin
container.Update(builder -> builder.RegisterInstance(environment));
end;
/// <summary>
/// Create a default, unconfigured, container
/// </summary>
/// <returns>Container instance</returns>
method GetApplicationContainer():ILifetimeScope;override;
begin
exit new ContainerBuilder().Build();
end;
/// <summary>
/// Bind the bootstrapper's implemented types into the container.
/// This is necessary so a user can pass in a populated container but not have
/// to take the responsibility of registering things like INancyModuleCatalog manually.
/// </summary>
/// <param name="applicationContainer">Application container to register into</param>
method RegisterBootstrapperTypes(applicationContainer:ILifetimeScope);override;
begin
applicationContainer.Update(builder -> builder.RegisterInstance(self).As<INancyModuleCatalog>());
end;
/// <summary>
/// Bind the default implementations of internally used types into the container as singletons
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="typeRegistrations">Type registrations to register</param>
method RegisterTypes(container:ILifetimeScope; typeRegistrations:IEnumerable<TypeRegistration>);override;
begin
container.Update(builder ->
begin
for each typeRegistration in typeRegistrations do
begin
case typeRegistration.Lifetime of
Lifetime.Transient: builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).InstancePerDependency();
Lifetime.Singleton: builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).SingleInstance();
Lifetime.PerRequest: raise new InvalidOperationException("Unable to directly register a per request lifetime.");
else
raise new ArgumentOutOfRangeException();
end;
end;
end);
end;
/// <summary>
/// Bind the various collections into the container as singletons to later be resolved
/// by IEnumerable{Type} constructor dependencies.
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="collectionTypeRegistrations">Collection type registrations to register</param>
method RegisterCollectionTypes(container:ILifetimeScope; collectionTypeRegistrations:IEnumerable<CollectionTypeRegistration>);override;
begin
container.Update(builder ->
begin
for each collectionTypeRegistration in collectionTypeRegistrations do
begin
for each implementationType in collectionTypeRegistration.ImplementationTypes do
begin
case collectionTypeRegistration.Lifetime of
Lifetime.Transient: builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().InstancePerDependency();
Lifetime.Singleton: builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().SingleInstance();
Lifetime.PerRequest: raise new InvalidOperationException("Unable to directly register a per request lifetime.");
else
raise new ArgumentOutOfRangeException();
end;
end;
end;
end);
end;
/// <summary>
/// Bind the given instances into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="instanceRegistrations">Instance registration types</param>
method RegisterInstances(container:ILifetimeScope; instanceRegistrations:IEnumerable<InstanceRegistration>);override;
begin
container.Update(builder ->
begin
for each instanceRegistration in instanceRegistrations do
begin
builder.RegisterInstance(instanceRegistration.Implementation).As(instanceRegistration.RegistrationType);
end;
end);
end;
/// <summary>
/// Creates a per request child/nested container
/// </summary>
/// <param name="context">Current context</param>
/// <returns>Request container instance</returns>
method CreateRequestContainer(context:NancyContext):ILifetimeScope;override;
begin
exit ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
end;
/// <summary>
/// Bind the given module types into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="moduleRegistrationTypes"><see cref="INancyModule"/> types</param>
method RegisterRequestContainerModules(container:ILifetimeScope; moduleRegistrationTypes:IEnumerable<ModuleRegistration>);override;
begin
container.Update(builder ->
begin
for each moduleRegistrationType in moduleRegistrationTypes do
begin
builder.RegisterType(moduleRegistrationType.ModuleType).As<INancyModule>();
end;
end);
end;
/// <summary>
/// Retrieve all module instances from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <returns>Collection of <see cref="INancyModule"/> instances</returns>
method GetAllModules(container:ILifetimeScope):IEnumerable<INancyModule> ;override;
begin
exit container.Resolve<IEnumerable<INancyModule>>();
end;
/// <summary>
/// Retreive a specific module instance from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <param name="moduleType">Type of the module</param>
/// <returns>An <see cref="INancyModule"/> instance</returns>
method GetModule(container:ILifetimeScope; moduleType:&Type):INancyModule;override;
begin
exit container.Update(builder -> builder.RegisterType(moduleType).As<INancyModule>()).Resolve<INancyModule>();
end;
public
/// <summary>
/// Get the <see cref="INancyEnvironment" /> instance.
/// </summary>
/// <returns>An configured <see cref="INancyEnvironment" /> instance.</returns>
/// <remarks>The boostrapper must be initialised (<see cref="INancyBootstrapper.Initialise" />) prior to calling this.</remarks>
method GetEnvironment():INancyEnvironment; override;
begin
exit self.ApplicationContainer.Resolve<INancyEnvironment>();
end;
end;
end. |
unit SpriteToSurface;
interface
uses
Windows, DDraw, SpriteImages, ColorTables;
procedure RenderSpriteToSurface(Sprite : TFrameImage; x, y : integer; aFrame, Alpha : cardinal; const ClipArea : TRect; const surfacedesc : TDDSurfaceDesc2; aPaletteInfo : TPaletteInfo);
implementation
uses
SysUtils, Rects, BitBlt;
function BitCountFromDDPixFormat(const DDPixFormat : TDDPixelFormat) : integer;
begin
if DDPixFormat.dwRGBBitCount = 16
then
if DDPixFormat.dwGBitMask = $7e0
then Result := 16
else Result := 15
else Result := DDPixFormat.dwRGBBitCount;
end;
procedure RenderSpriteToSurface(Sprite : TFrameImage; x, y : integer; aFrame, Alpha : cardinal; const ClipArea : TRect; const surfacedesc : TDDSurfaceDesc2; aPaletteInfo : TPaletteInfo);
var
ImageArea : TRect;
ClipSize : TPoint;
dx, dy : integer;
dstPitch : integer;
srcAddr : pointer;
dstAddr : pointer;
PaletteInfo : TPaletteInfo;
begin
if aFrame > Sprite.FrameCount
then raise Exception.Create( 'Bad frame specified in TFrameImage.DrawGlassed!!' );
with ImageArea do
begin
Left := x;
Right := x + Sprite.Size.X;
Top := y;
Bottom := y + Sprite.Size.Y;
end;
IntersectRect(ImageArea, ImageArea, ClipArea);
ClipSize := RectSize(ImageArea);
if x < ClipArea.Left
then
begin
dx := ClipArea.Left - x;
x := ClipArea.Left;
end
else dx := 0;
if y < ClipArea.Top
then
begin
dy := ClipArea.Top - y;
y := ClipArea.Top;
end
else dy := 0;
dstPitch := surfacedesc.lPitch;
srcAddr := Sprite.PixelAddr[dx, dy, aFrame];
dstAddr := pchar(surfacedesc.lpSurface) + surfacedesc.lPitch*y + x*(surfacedesc.ddpfPixelFormat.dwRGBBitCount div 8);
PaletteInfo := aPaletteInfo;
if PaletteInfo = nil
then PaletteInfo := Sprite.Tables.MainTable;
case BitCountFromDDPixFormat(surfacedesc.ddpfPixelFormat) of
8 :
if Alpha = 0
then BltCopyTrans(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx,
Sprite.FramePitch[ aFrame ], dstPitch)
else
begin
if not (tsMixMatrixValid in PaletteInfo.ValidTables)
then
begin
OutputDebugString(pchar('Unassigned MixMatrix!!'));
PaletteInfo.RequiredTable(tsMixMatrixValid);
end;
// In this case we ignore the value of alpha since in 8 bits 50/50 is the only alpha we support (Alpha=4)
BltCopyBlend(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx,
Sprite.FramePitch[ aFrame ], dstPitch, PaletteInfo.MixMatrix);
end;
15 :
begin
if not (tsHiColor555TableValid in PaletteInfo.ValidTables)
then
begin
OutputDebugString(pchar('Unassigned HiColor555Table!!'));
PaletteInfo.RequiredTable(tsHiColor555TableValid);
end;
BltCopySourceCTT16(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx, Alpha,
Sprite.FramePitch[ aFrame ], dstPitch, PaletteInfo.ColorTable);
end;
16 :
begin
if not (tsHiColor565TableValid in PaletteInfo.ValidTables)
then
begin
OutputDebugString(pchar('Unassigned HiColor565Table!!'));
PaletteInfo.RequiredTable(tsHiColor565TableValid);
end;
BltCopySourceCTT16(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx, Alpha,
Sprite.FramePitch[ aFrame ], dstPitch, PaletteInfo.ColorTable);
end;
24 :
begin
if not (tsTrueColorTableValid in PaletteInfo.ValidTables)
then
begin
OutputDebugString(pchar('Unassigned TrueColorTable!!'));
PaletteInfo.RequiredTable(tsTrueColorTableValid);
end;
BltCopySourceCTT24(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx, Alpha,
Sprite.FramePitch[ aFrame ], dstPitch, PaletteInfo.ColorTable);
end;
32 :
begin
if not (tsTrueColorTableValid in PaletteInfo.ValidTables)
then
begin
OutputDebugString(pchar('Unassigned TrueColorTable!!'));
PaletteInfo.RequiredTable(tsTrueColorTableValid);
end;
BltCopySourceCTT32(srcAddr, dstAddr,
ClipSize.x, ClipSize.y, Sprite.TransparentIndx, Alpha,
Sprite.FramePitch[ aFrame ], dstPitch, PaletteInfo.ColorTable);
end;
end;
end;
end.
|
unit InfoPULLTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoPULLRecord = record
PLender: String[4];
PSIStatus: String[2];
PRunDate: String[8];
PLoanNumber: String[18];
PModCount: SmallInt;
PName: String[30];
POfficer: String[6];
PPolicy: String[10];
End;
TInfoPULLClass2 = class
public
PLender: String[4];
PSIStatus: String[2];
PRunDate: String[8];
PLoanNumber: String[18];
PModCount: SmallInt;
PName: String[30];
POfficer: String[6];
PPolicy: String[10];
End;
// function CtoRInfoPULL(AClass:TInfoPULLClass):TInfoPULLRecord;
// procedure RtoCInfoPULL(ARecord:TInfoPULLRecord;AClass:TInfoPULLClass);
TInfoPULLBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoPULLRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoPULL = (InfoPULLPrimaryKey, InfoPULLName, InfoPULLOfficer, InfoPULLPolicy);
TInfoPULLTable = class( TDBISAMTableAU )
private
FDFLender: TStringField;
FDFSIStatus: TStringField;
FDFRunDate: TStringField;
FDFLoanNumber: TStringField;
FDFModCount: TSmallIntField;
FDFName: TStringField;
FDFOfficer: TStringField;
FDFPolicy: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPSIStatus(const Value: String);
function GetPSIStatus:String;
procedure SetPRunDate(const Value: String);
function GetPRunDate:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPOfficer(const Value: String);
function GetPOfficer:String;
procedure SetPPolicy(const Value: String);
function GetPPolicy:String;
procedure SetEnumIndex(Value: TEIInfoPULL);
function GetEnumIndex: TEIInfoPULL;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoPULLRecord;
procedure StoreDataBuffer(ABuffer:TInfoPULLRecord);
property DFLender: TStringField read FDFLender;
property DFSIStatus: TStringField read FDFSIStatus;
property DFRunDate: TStringField read FDFRunDate;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFModCount: TSmallIntField read FDFModCount;
property DFName: TStringField read FDFName;
property DFOfficer: TStringField read FDFOfficer;
property DFPolicy: TStringField read FDFPolicy;
property PLender: String read GetPLender write SetPLender;
property PSIStatus: String read GetPSIStatus write SetPSIStatus;
property PRunDate: String read GetPRunDate write SetPRunDate;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PModCount: SmallInt read GetPModCount write SetPModCount;
property PName: String read GetPName write SetPName;
property POfficer: String read GetPOfficer write SetPOfficer;
property PPolicy: String read GetPPolicy write SetPPolicy;
published
property Active write SetActive;
property EnumIndex: TEIInfoPULL read GetEnumIndex write SetEnumIndex;
end; { TInfoPULLTable }
TInfoPULLQuery = class( TDBISAMQueryAU )
private
FDFLender: TStringField;
FDFSIStatus: TStringField;
FDFRunDate: TStringField;
FDFLoanNumber: TStringField;
FDFModCount: TSmallIntField;
FDFName: TStringField;
FDFOfficer: TStringField;
FDFPolicy: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPSIStatus(const Value: String);
function GetPSIStatus:String;
procedure SetPRunDate(const Value: String);
function GetPRunDate:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPOfficer(const Value: String);
function GetPOfficer:String;
procedure SetPPolicy(const Value: String);
function GetPPolicy:String;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoPULLRecord;
procedure StoreDataBuffer(ABuffer:TInfoPULLRecord);
property DFLender: TStringField read FDFLender;
property DFSIStatus: TStringField read FDFSIStatus;
property DFRunDate: TStringField read FDFRunDate;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFModCount: TSmallIntField read FDFModCount;
property DFName: TStringField read FDFName;
property DFOfficer: TStringField read FDFOfficer;
property DFPolicy: TStringField read FDFPolicy;
property PLender: String read GetPLender write SetPLender;
property PSIStatus: String read GetPSIStatus write SetPSIStatus;
property PRunDate: String read GetPRunDate write SetPRunDate;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PModCount: SmallInt read GetPModCount write SetPModCount;
property PName: String read GetPName write SetPName;
property POfficer: String read GetPOfficer write SetPOfficer;
property PPolicy: String read GetPPolicy write SetPPolicy;
published
property Active write SetActive;
end; { TInfoPULLTable }
procedure Register;
implementation
procedure TInfoPULLTable.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFSIStatus := CreateField( 'SIStatus' ) as TStringField;
FDFRunDate := CreateField( 'RunDate' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFOfficer := CreateField( 'Officer' ) as TStringField;
FDFPolicy := CreateField( 'Policy' ) as TStringField;
end; { TInfoPULLTable.CreateFields }
procedure TInfoPULLTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoPULLTable.SetActive }
procedure TInfoPULLTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoPULLTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoPULLTable.SetPSIStatus(const Value: String);
begin
DFSIStatus.Value := Value;
end;
function TInfoPULLTable.GetPSIStatus:String;
begin
result := DFSIStatus.Value;
end;
procedure TInfoPULLTable.SetPRunDate(const Value: String);
begin
DFRunDate.Value := Value;
end;
function TInfoPULLTable.GetPRunDate:String;
begin
result := DFRunDate.Value;
end;
procedure TInfoPULLTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoPULLTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoPULLTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoPULLTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoPULLTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoPULLTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoPULLTable.SetPOfficer(const Value: String);
begin
DFOfficer.Value := Value;
end;
function TInfoPULLTable.GetPOfficer:String;
begin
result := DFOfficer.Value;
end;
procedure TInfoPULLTable.SetPPolicy(const Value: String);
begin
DFPolicy.Value := Value;
end;
function TInfoPULLTable.GetPPolicy:String;
begin
result := DFPolicy.Value;
end;
procedure TInfoPULLTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Lender, String, 4, N');
Add('SIStatus, String, 2, N');
Add('RunDate, String, 8, N');
Add('LoanNumber, String, 18, N');
Add('ModCount, SmallInt, 0, N');
Add('Name, String, 30, N');
Add('Officer, String, 6, N');
Add('Policy, String, 10, N');
end;
end;
procedure TInfoPULLTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Lender;SIStatus;RunDate;LoanNumber, Y, Y, N, N');
Add('Name, Lender;SIStatus;Name, N, N, N, N');
Add('Officer, Lender;SIStatus;Officer, N, N, N, N');
Add('Policy, Lender;SIStatus;Policy, N, N, N, N');
end;
end;
procedure TInfoPULLTable.SetEnumIndex(Value: TEIInfoPULL);
begin
case Value of
InfoPULLPrimaryKey : IndexName := '';
InfoPULLName : IndexName := 'Name';
InfoPULLOfficer : IndexName := 'Officer';
InfoPULLPolicy : IndexName := 'Policy';
end;
end;
function TInfoPULLTable.GetDataBuffer:TInfoPULLRecord;
var buf: TInfoPULLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PSIStatus := DFSIStatus.Value;
buf.PRunDate := DFRunDate.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PModCount := DFModCount.Value;
buf.PName := DFName.Value;
buf.POfficer := DFOfficer.Value;
buf.PPolicy := DFPolicy.Value;
result := buf;
end;
procedure TInfoPULLTable.StoreDataBuffer(ABuffer:TInfoPULLRecord);
begin
DFLender.Value := ABuffer.PLender;
DFSIStatus.Value := ABuffer.PSIStatus;
DFRunDate.Value := ABuffer.PRunDate;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFModCount.Value := ABuffer.PModCount;
DFName.Value := ABuffer.PName;
DFOfficer.Value := ABuffer.POfficer;
DFPolicy.Value := ABuffer.PPolicy;
end;
function TInfoPULLTable.GetEnumIndex: TEIInfoPULL;
var iname : string;
begin
result := InfoPULLPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoPULLPrimaryKey;
if iname = 'NAME' then result := InfoPULLName;
if iname = 'OFFICER' then result := InfoPULLOfficer;
if iname = 'POLICY' then result := InfoPULLPolicy;
end;
procedure TInfoPULLQuery.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFSIStatus := CreateField( 'SIStatus' ) as TStringField;
FDFRunDate := CreateField( 'RunDate' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFOfficer := CreateField( 'Officer' ) as TStringField;
FDFPolicy := CreateField( 'Policy' ) as TStringField;
end; { TInfoPULLQuery.CreateFields }
procedure TInfoPULLQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoPULLQuery.SetActive }
procedure TInfoPULLQuery.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoPULLQuery.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoPULLQuery.SetPSIStatus(const Value: String);
begin
DFSIStatus.Value := Value;
end;
function TInfoPULLQuery.GetPSIStatus:String;
begin
result := DFSIStatus.Value;
end;
procedure TInfoPULLQuery.SetPRunDate(const Value: String);
begin
DFRunDate.Value := Value;
end;
function TInfoPULLQuery.GetPRunDate:String;
begin
result := DFRunDate.Value;
end;
procedure TInfoPULLQuery.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoPULLQuery.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoPULLQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoPULLQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoPULLQuery.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoPULLQuery.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoPULLQuery.SetPOfficer(const Value: String);
begin
DFOfficer.Value := Value;
end;
function TInfoPULLQuery.GetPOfficer:String;
begin
result := DFOfficer.Value;
end;
procedure TInfoPULLQuery.SetPPolicy(const Value: String);
begin
DFPolicy.Value := Value;
end;
function TInfoPULLQuery.GetPPolicy:String;
begin
result := DFPolicy.Value;
end;
function TInfoPULLQuery.GetDataBuffer:TInfoPULLRecord;
var buf: TInfoPULLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PSIStatus := DFSIStatus.Value;
buf.PRunDate := DFRunDate.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PModCount := DFModCount.Value;
buf.PName := DFName.Value;
buf.POfficer := DFOfficer.Value;
buf.PPolicy := DFPolicy.Value;
result := buf;
end;
procedure TInfoPULLQuery.StoreDataBuffer(ABuffer:TInfoPULLRecord);
begin
DFLender.Value := ABuffer.PLender;
DFSIStatus.Value := ABuffer.PSIStatus;
DFRunDate.Value := ABuffer.PRunDate;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFModCount.Value := ABuffer.PModCount;
DFName.Value := ABuffer.PName;
DFOfficer.Value := ABuffer.POfficer;
DFPolicy.Value := ABuffer.PPolicy;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoPULLTable, TInfoPULLQuery, TInfoPULLBuffer ] );
end; { Register }
function TInfoPULLBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..8] of string = ('LENDER','SISTATUS','RUNDATE','LOANNUMBER','MODCOUNT','NAME'
,'OFFICER','POLICY' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 8) and (flist[x] <> s) do inc(x);
if x <= 8 then result := x else result := 0;
end;
function TInfoPULLBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftSmallInt;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
end;
end;
function TInfoPULLBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLender;
2 : result := @Data.PSIStatus;
3 : result := @Data.PRunDate;
4 : result := @Data.PLoanNumber;
5 : result := @Data.PModCount;
6 : result := @Data.PName;
7 : result := @Data.POfficer;
8 : result := @Data.PPolicy;
end;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 25/11/2019 10:50:57
//
unit UDaoCliente;
interface
uses Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy,
System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXJSONReflect,
UConstante;
type
TdaoClienteClient = class(TDSAdminClient)
private
FDsClienteCommand: TDBXCommand;
FIncluirClienteCommand: TDBXCommand;
FAlteraClienteCommand: TDBXCommand;
FDeletarClienteCommand: TDBXCommand;
FIncImgCliCommand: TDBXCommand;
FAltImgCliCommand: TDBXCommand;
FDelImgCliCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function DsCliente: OleVariant;
function IncluirCliente(O: TJSONValue): Boolean;
function AlteraCliente(O: TJSONValue): Boolean;
function DeletarCliente(O: TJSONValue): Boolean;
function IncImgCli(O: TJSONValue): Boolean;
function AltImgCli(O: TJSONValue): Boolean;
function DelImgCli(O: TJSONValue): Boolean;
end;
implementation
{ TdaoClienteClient }
function TdaoClienteClient.DsCliente: OleVariant;
begin
if FDsClienteCommand = nil then
begin
FDsClienteCommand := FDBXConnection.CreateCommand;
FDsClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDsClienteCommand.Text := _srv00023;
FDsClienteCommand.Prepare;
end;
FDsClienteCommand.ExecuteUpdate;
Result := FDsClienteCommand.Parameters[0].Value.AsVariant;
end;
function TdaoClienteClient.IncImgCli(O: TJSONValue): Boolean;
begin
if FIncluirClienteCommand = nil then
begin
FIncluirClienteCommand := FDBXConnection.CreateCommand;
FIncluirClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FIncluirClienteCommand.Text := _srv00024;
FIncluirClienteCommand.Prepare;
end;
FIncluirClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FIncluirClienteCommand.ExecuteUpdate;
Result := FIncluirClienteCommand.Parameters[1].Value.GetBoolean;
end;
function TdaoClienteClient.IncluirCliente(O: TJSONValue): Boolean;
begin
if FIncluirClienteCommand = nil then
begin
FIncluirClienteCommand := FDBXConnection.CreateCommand;
FIncluirClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FIncluirClienteCommand.Text := _srv00025;
FIncluirClienteCommand.Prepare;
end;
FIncluirClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FIncluirClienteCommand.ExecuteUpdate;
Result := FIncluirClienteCommand.Parameters[1].Value.GetBoolean;
end;
function TdaoClienteClient.AlteraCliente(O: TJSONValue): Boolean;
begin
if FAlteraClienteCommand = nil then
begin
FAlteraClienteCommand := FDBXConnection.CreateCommand;
FAlteraClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FAlteraClienteCommand.Text := _srv00026;
FAlteraClienteCommand.Prepare;
end;
FAlteraClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FAlteraClienteCommand.ExecuteUpdate;
Result := FAlteraClienteCommand.Parameters[1].Value.GetBoolean;
end;
function TdaoClienteClient.DeletarCliente(O: TJSONValue): Boolean;
begin
if FDeletarClienteCommand = nil then
begin
FDeletarClienteCommand := FDBXConnection.CreateCommand;
FDeletarClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeletarClienteCommand.Text := _srv00027;
FDeletarClienteCommand.Prepare;
end;
FDeletarClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FDeletarClienteCommand.ExecuteUpdate;
Result := FDeletarClienteCommand.Parameters[1].Value.GetBoolean;
end;
function TdaoClienteClient.DelImgCli(O: TJSONValue): Boolean;
begin
if FDeletarClienteCommand = nil then
begin
FDeletarClienteCommand := FDBXConnection.CreateCommand;
FDeletarClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeletarClienteCommand.Text := _srv00028;
FDeletarClienteCommand.Prepare;
end;
FDeletarClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FDeletarClienteCommand.ExecuteUpdate;
Result := FDeletarClienteCommand.Parameters[1].Value.GetBoolean;
end;
constructor TdaoClienteClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
function TdaoClienteClient.AltImgCli(O: TJSONValue): Boolean;
begin
if FAlteraClienteCommand = nil then
begin
FAlteraClienteCommand := FDBXConnection.CreateCommand;
FAlteraClienteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FAlteraClienteCommand.Text := _srv00029;
FAlteraClienteCommand.Prepare;
end;
FAlteraClienteCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FAlteraClienteCommand.ExecuteUpdate;
Result := FAlteraClienteCommand.Parameters[1].Value.GetBoolean;
end;
constructor TdaoClienteClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TdaoClienteClient.Destroy;
begin
FreeAndNil(FDsClienteCommand);
FreeAndNil(FIncluirClienteCommand);
FreeAndNil(FAlteraClienteCommand);
FreeAndNil(FDeletarClienteCommand);
FreeAndNil(FIncImgCliCommand);
FreeAndNil(FAltImgCliCommand);
FreeAndNil(FDelImgCliCommand);
inherited;
end;
end.
|
unit GeocodingUnit;
interface
uses
REST.Json.Types, System.Generics.Collections, SysUtils,
Generics.Defaults,
JSONNullableAttributeUnit,
NullableBasicTypesUnit, EnumsUnit;
type
/// <summary>
/// Geocoding
/// </summary>
TGeocoding = class
private
[JSONName('destination')]
[Nullable]
FDestination: NullableString;
[JSONName('lat')]
[Nullable]
FLatitude: NullableDouble;
[JSONName('lng')]
[Nullable]
FLongitude: NullableDouble;
[JSONName('confidence')]
[Nullable]
FConfidence: NullableString;
[JSONName('type')]
[Nullable]
FType: NullableString;
[JSONName('original')]
[Nullable]
FOriginal: NullableString;
function GetConfidence: TConfidenceType;
procedure SetConfidence(const Value: TConfidenceType);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// Specific description of the geocoding result
/// </summary>
property Destination: NullableString read FDestination write FDestination;
/// <summary>
/// Latitude
/// </summary>
property Latitude: NullableDouble read FLatitude write FLatitude;
/// <summary>
/// Longitude
/// </summary>
property Longitude: NullableDouble read FLongitude write FLongitude;
/// <summary>
/// Confidence ("high", "medium", "low")
/// </summary>
property Confidence: TConfidenceType read GetConfidence write SetConfidence;
procedure SetConfidenceAsString(Value: NullableString);
/// <summary>
/// Non-standardized. Is used for tooltip ("Street", "City" etc)
/// </summary>
property Type_: NullableString read FType write FType;
/// <summary>
/// </summary>
property Original: NullableString read FOriginal write FOriginal;
end;
TGeocodingArray = TArray<TGeocoding>;
TGeocodingList = TObjectList<TGeocoding>;
implementation
{ TGeocoding }
constructor TGeocoding.Create;
begin
Inherited;
FDestination := NullableString.Null;
FLatitude := NullableDouble.Null;
FLongitude := NullableDouble.Null;
FConfidence := NullableString.Null;
FType := NullableString.Null;
FOriginal := NullableString.Null;
end;
destructor TGeocoding.Destroy;
begin
inherited;
end;
function TGeocoding.GetConfidence: TConfidenceType;
var
ConfidenceType: TConfidenceType;
begin
Result := TConfidenceType.ctUnknown;
if FConfidence.IsNotNull then
for ConfidenceType := Low(TConfidenceType) to High(TConfidenceType) do
if (FConfidence = TConfidenceTypeDescription[ConfidenceType]) then
Exit(ConfidenceType);
end;
procedure TGeocoding.SetConfidence(const Value: TConfidenceType);
begin
FConfidence := TConfidenceTypeDescription[Value];
end;
procedure TGeocoding.SetConfidenceAsString(Value: NullableString);
begin
FConfidence := Value;
end;
end.
|
unit evCellsIterator;
// ћодуль: "w:\common\components\gui\Garant\Everest\evCellsIterator.pas"
// —тереотип: "SimpleClass"
// Ёлемент модели: "TevCellsIterator" MUID: (4FC48D1B02AC)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
{$If Defined(k2ForEditor) AND Defined(evNeedEditableCursors)}
uses
l3IntfUses
, evCustomParaListUtils
, evEditorInterfaces
, nevTools
, l3Variant
, nevBase
;
type
TevCellsIterator = class(TevRowChild, IedBackCellsIterator, IedCellsIterator)
private
f_NeedNeighbours: Boolean;
f_StartCell: Integer;
f_First: Integer;
protected
function Last(aNeedNeighbours: Boolean): IedCell;
{* возвращает последнюю €чейку и начинает перебор }
function Prev: IedCell;
{* возвращает предыдущую €чейку или nil, если перебор закончен }
function pm_GetBackIterator: IedBackCellsIterator;
function First(aNeedNeighbours: Boolean): IedCell;
{* возвращает первую €чейку и начинает перебор }
function Next: IedCell;
{* возвращает следующую €чейку или nil, если перебор закончен }
function CellsCount: Integer;
{* оличество €чеек }
public
class function Make(const aView: InevView;
const aRow: IedRow;
aTagWrap: Tl3Variant;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil): IedCellsIterator;
end;//TevCellsIterator
{$IfEnd} // Defined(k2ForEditor) AND Defined(evNeedEditableCursors)
implementation
{$If Defined(k2ForEditor) AND Defined(evNeedEditableCursors)}
uses
l3ImplUses
, l3Base
, SysUtils
, nevFacade
//#UC START# *4FC48D1B02ACimpl_uses*
//#UC END# *4FC48D1B02ACimpl_uses*
;
class function TevCellsIterator.Make(const aView: InevView;
const aRow: IedRow;
aTagWrap: Tl3Variant;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil): IedCellsIterator;
//#UC START# *4FC48DC101EB_4FC48D1B02AC_var*
var
l_CellsIterator : TevCellsIterator;
//#UC END# *4FC48DC101EB_4FC48D1B02AC_var*
begin
//#UC START# *4FC48DC101EB_4FC48D1B02AC_impl*
l_CellsIterator := Create(aView, aRow, aTagWrap, aProcessor, aLocation);
try
Result := l_CellsIterator;
finally
l3Free(l_CellsIterator);
end;//try..finally
//#UC END# *4FC48DC101EB_4FC48D1B02AC_impl*
end;//TevCellsIterator.Make
function TevCellsIterator.Last(aNeedNeighbours: Boolean): IedCell;
{* возвращает последнюю €чейку и начинает перебор }
//#UC START# *4BBC922302CA_4FC48D1B02AC_var*
//#UC END# *4BBC922302CA_4FC48D1B02AC_var*
begin
//#UC START# *4BBC922302CA_4FC48D1B02AC_impl*
f_First := TagInst.ChildrenCount - 1;
f_NeedNeighbours := aNeedNeighbours;
Result := Prev;
//#UC END# *4BBC922302CA_4FC48D1B02AC_impl*
end;//TevCellsIterator.Last
function TevCellsIterator.Prev: IedCell;
{* возвращает предыдущую €чейку или nil, если перебор закончен }
//#UC START# *4BBC92390009_4FC48D1B02AC_var*
var
l_Result : IedCell absolute Result;
function _DoCell(const aCellBlock: InevRange; anIndex: Integer): Boolean;
var
l_Para : InevPara;
begin//_DoCell
Result := false;
l_Para := aCellBlock.Obj.AsPara;
l_Result := GetRow.Table.GetTagCell(TagInst, l_Para, anIndex, aCellBlock, f_NeedNeighbours);
Dec(f_First);
// - —ледующий раз начинаем с предыдущей €чейки
end;//_DoCell
var
l_Sel : InevRange;
//#UC END# *4BBC92390009_4FC48D1B02AC_var*
begin
//#UC START# *4BBC92390009_4FC48D1B02AC_impl*
Result := nil;
if f_First < 0 then Exit;
if Supports(f_Location, InevRange, l_Sel) then
l_Sel.IterateF(evL2TSA(@_DoCell), f_First)
//#UC END# *4BBC92390009_4FC48D1B02AC_impl*
end;//TevCellsIterator.Prev
function TevCellsIterator.pm_GetBackIterator: IedBackCellsIterator;
//#UC START# *4BBC9430038B_4FC48D1B02ACget_var*
//#UC END# *4BBC9430038B_4FC48D1B02ACget_var*
begin
//#UC START# *4BBC9430038B_4FC48D1B02ACget_impl*
Result := Self;
//#UC END# *4BBC9430038B_4FC48D1B02ACget_impl*
end;//TevCellsIterator.pm_GetBackIterator
function TevCellsIterator.First(aNeedNeighbours: Boolean): IedCell;
{* возвращает первую €чейку и начинает перебор }
//#UC START# *4BBC944C0195_4FC48D1B02AC_var*
//#UC END# *4BBC944C0195_4FC48D1B02AC_var*
begin
//#UC START# *4BBC944C0195_4FC48D1B02AC_impl*
f_First := f_StartCell;
f_NeedNeighbours := aNeedNeighbours;
Result := Next;
//#UC END# *4BBC944C0195_4FC48D1B02AC_impl*
end;//TevCellsIterator.First
function TevCellsIterator.Next: IedCell;
{* возвращает следующую €чейку или nil, если перебор закончен }
//#UC START# *4BBC94640082_4FC48D1B02AC_var*
var
l_Result : IedCell absolute Result;
function _DoCell(const aCellBlock: InevRange; anIndex: Integer): Boolean;
var
l_Para : InevPara;
begin//_DoCell
Result := false;
l_Para := aCellBlock.Obj.AsPara;
l_Result := GetRow.Table.GetTagCell(TagInst, l_Para, anIndex, aCellBlock, f_NeedNeighbours);
f_First := anIndex + 1;
// - —ледующий раз начинаем со следующей €чейки
end;//_DoCell
var
l_Sel : InevRange;
//#UC END# *4BBC94640082_4FC48D1B02AC_var*
begin
//#UC START# *4BBC94640082_4FC48D1B02AC_impl*
Result := nil;
if Supports(f_Location, InevRange, l_Sel) then
l_Sel.IterateF(evL2TSA(@_DoCell), f_First)
//#UC END# *4BBC94640082_4FC48D1B02AC_impl*
end;//TevCellsIterator.Next
function TevCellsIterator.CellsCount: Integer;
{* оличество €чеек }
//#UC START# *4BBC947B0399_4FC48D1B02AC_var*
//#UC END# *4BBC947B0399_4FC48D1B02AC_var*
begin
//#UC START# *4BBC947B0399_4FC48D1B02AC_impl*
Result := TagInst.ChildrenCount;
//#UC END# *4BBC947B0399_4FC48D1B02AC_impl*
end;//TevCellsIterator.CellsCount
{$IfEnd} // Defined(k2ForEditor) AND Defined(evNeedEditableCursors)
end.
|
unit DragData;
// Модуль: "w:\common\components\gui\Garant\VT\DragData.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "DragData" MUID: (4F0C0B6801C7)
{$Include w:\common\components\gui\Garant\VT\vtDefine.inc}
interface
uses
l3IntfUses
, Messages
, vtDragDataTypes
, Windows
, l3Except
, l3Base
, l3Interfaces
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
, Classes
;
const
{* Алиасы для значений vtDragDataTypes.TDragDataState }
dsPassive = vtDragDataTypes.dsPassive;
dsActive = vtDragDataTypes.dsActive;
dsPaused = vtDragDataTypes.dsPaused;
wm_DropAccept = Messages.WM_USER + $100;
wm_DropAccepted = Messages.WM_USER + $101;
cnActiveState = [dsActive, dsPaused];
type
TDragDataState = vtDragDataTypes.TDragDataState;
TGetCursorByType = function(DDType: Integer): HCURSOR;
EDragInProcess = class(El3NoLoggedException)
public
constructor Create; reintroduce;
end;//EDragInProcess
TDragDataSupport = class(Tl3Base, Il3WndProcListener, Il3WndProcRetListener, Il3MouseListener)
private
f_PrevMRecurse: Boolean;
f_PrevWRecurse: Boolean;
f_NeedStop: Boolean;
f_DCursor: HCURSOR;
f_DragDataType: Integer;
f_DragData: Pointer;
f_AnswerData: Pointer;
f_SourceControl: TControl;
f_DragState: TDragDataState;
f_DragSuccess: Boolean;
f_OnDragStop: TNotifyEvent;
f_OnGetCursorByType: TGetCursorByType;
private
procedure InitListeners;
procedure RemoveListeners;
protected
procedure pm_SetDragDataType(aValue: Integer);
procedure pm_SetDragData(aValue: Pointer);
procedure MouseListenerNotify(aMouseMessage: WPARAM;
aHookStruct: PMouseHookStruct;
var theResult: Tl3HookProcResult);
procedure WndProcListenerNotify(Msg: PCWPStruct;
var theResult: Tl3HookProcResult);
procedure WndProcRetListenerNotify(Msg: PCWPRetStruct;
var theResult: Tl3HookProcResult);
public
function DoDrop(aDestControl: TControl = nil): Boolean;
function Execute(SrcControl: TControl): Boolean;
procedure RunDragData(SrcControl: TControl);
procedure Stop(aSuccess: Boolean);
procedure Pause;
procedure Restore;
procedure CheckInProgress;
class function Instance: TDragDataSupport;
{* Метод получения экземпляра синглетона TDragDataSupport }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property DCursor: HCURSOR
read f_DCursor
write f_DCursor;
property DragDataType: Integer
read f_DragDataType
write pm_SetDragDataType;
property DragData: Pointer
read f_DragData
write pm_SetDragData;
property AnswerData: Pointer
read f_AnswerData
write f_AnswerData;
property SourceControl: TControl
read f_SourceControl;
property DragState: TDragDataState
read f_DragState;
property DragSuccess: Boolean
read f_DragSuccess;
property OnDragStop: TNotifyEvent
read f_OnDragStop
write f_OnDragStop;
property OnGetCursorByType: TGetCursorByType
read f_OnGetCursorByType
write f_OnGetCursorByType;
end;//TDragDataSupport
implementation
uses
l3ImplUses
, afwFacade
, l3ListenersManager
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoScripts)}
, TtfwClassRef_Proxy
{$IfEnd} // NOT Defined(NoScripts)
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
, kwVTControlsPack
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
, SysUtils
//#UC START# *4F0C0B6801C7impl_uses*
//#UC END# *4F0C0B6801C7impl_uses*
;
var g_TDragDataSupport: TDragDataSupport = nil;
{* Экземпляр синглетона TDragDataSupport }
procedure TDragDataSupportFree;
{* Метод освобождения экземпляра синглетона TDragDataSupport }
begin
l3Free(g_TDragDataSupport);
end;//TDragDataSupportFree
constructor EDragInProcess.Create;
//#UC START# *5530C7180149_552FCE4601AC_var*
//#UC END# *5530C7180149_552FCE4601AC_var*
begin
//#UC START# *5530C7180149_552FCE4601AC_impl*
inherited Create('Предыдущая операция переноса не завершена!');
//#UC END# *5530C7180149_552FCE4601AC_impl*
end;//EDragInProcess.Create
procedure TDragDataSupport.pm_SetDragDataType(aValue: Integer);
//#UC START# *552FD2B903C5_4F0C0B870141set_var*
var
lCursor: HCURSOR;
//#UC END# *552FD2B903C5_4F0C0B870141set_var*
begin
//#UC START# *552FD2B903C5_4F0C0B870141set_impl*
f_DragDataType := aValue;
lCursor := 0;
if Assigned(f_OnGetCursorByType) then
begin
lCursor := f_OnGetCursorByType(f_DragDataType);
if lCursor > 0 then
f_DCursor := lCursor;
end;
if lCursor = 0 then
f_DCursor := Screen.Cursors[crDefault];
//#UC END# *552FD2B903C5_4F0C0B870141set_impl*
end;//TDragDataSupport.pm_SetDragDataType
procedure TDragDataSupport.pm_SetDragData(aValue: Pointer);
//#UC START# *552FD48A0290_4F0C0B870141set_var*
//#UC END# *552FD48A0290_4F0C0B870141set_var*
begin
//#UC START# *552FD48A0290_4F0C0B870141set_impl*
CheckInProgress;
Stop(False);
f_DragData := aValue;
//#UC END# *552FD48A0290_4F0C0B870141set_impl*
end;//TDragDataSupport.pm_SetDragData
procedure TDragDataSupport.InitListeners;
//#UC START# *552FDEE30376_4F0C0B870141_var*
//#UC END# *552FDEE30376_4F0C0B870141_var*
begin
//#UC START# *552FDEE30376_4F0C0B870141_impl*
if Win32Platform = VER_PLATFORM_WIN32_NT
then Tl3ListenersManager.AddWndProcRetListener(Self)
else Tl3ListenersManager.AddWndProcListener(Self);
Tl3ListenersManager.AddMouseListener(Self);
//#UC END# *552FDEE30376_4F0C0B870141_impl*
end;//TDragDataSupport.InitListeners
procedure TDragDataSupport.RemoveListeners;
//#UC START# *552FDEFB010E_4F0C0B870141_var*
//#UC END# *552FDEFB010E_4F0C0B870141_var*
begin
//#UC START# *552FDEFB010E_4F0C0B870141_impl*
Tl3ListenersManager.RemoveWndProcRetListener(Self);
Tl3ListenersManager.RemoveWndProcListener(Self);
Tl3ListenersManager.RemoveMouseListener(Self);
//#UC END# *552FDEFB010E_4F0C0B870141_impl*
end;//TDragDataSupport.RemoveListeners
function TDragDataSupport.DoDrop(aDestControl: TControl = nil): Boolean;
//#UC START# *552FDF3003B5_4F0C0B870141_var*
var
lParentForm: TCustomForm;
lShiftMode: Boolean;
//#UC END# *552FDF3003B5_4F0C0B870141_var*
begin
//#UC START# *552FDF3003B5_4F0C0B870141_impl*
Result := False;
lShiftMode := GetKeyState(VK_SHIFT) < 0;
if f_DragState = dsActive then
try
Windows.SetCursor(Screen.Cursors[crHourGlass]);
if aDestControl <> nil then
begin
try
Result := aDestControl.Perform(wm_DropAccept, DragDataType, Integer(Self)) <> 0;
except
Result := False;
end;
if not Result then
begin
lParentForm := GetParentForm(aDestControl);
if lParentForm <> nil then
try
Result := lParentForm.Perform(wm_DropAccept, DragDataType, Integer(aDestControl)) > 0;
except
Result := False;
end;
end;
end
else
Result := True;
if Result and (f_SourceControl <> nil) then
begin
Pause;
Result := f_SourceControl.Perform(wm_DropAccepted, DragDataType, Integer(Self)) >= 0;
end;
if Result and not lShiftMode then
Stop(True);
finally
Restore; // if was paused
Windows.SetCursor(DCursor);
end;
//#UC END# *552FDF3003B5_4F0C0B870141_impl*
end;//TDragDataSupport.DoDrop
function TDragDataSupport.Execute(SrcControl: TControl): Boolean;
//#UC START# *552FDF5D03B3_4F0C0B870141_var*
//#UC END# *552FDF5D03B3_4F0C0B870141_var*
begin
//#UC START# *552FDF5D03B3_4F0C0B870141_impl*
RunDragData(SrcControl);
while f_DragState in cnActiveState do
afw.ProcessMessages;
Result := f_DragSuccess;
//#UC END# *552FDF5D03B3_4F0C0B870141_impl*
end;//TDragDataSupport.Execute
procedure TDragDataSupport.RunDragData(SrcControl: TControl);
//#UC START# *552FDF8E01C9_4F0C0B870141_var*
//#UC END# *552FDF8E01C9_4F0C0B870141_var*
begin
//#UC START# *552FDF8E01C9_4F0C0B870141_impl*
f_PrevMRecurse := False;
f_PrevWRecurse := False;
f_NeedStop := False;
CheckInProgress;
f_SourceControl := SrcControl;
InitListeners;
Windows.SetCursor(DCursor);
f_DragSuccess := False;
f_DragState := dsActive;
//#UC END# *552FDF8E01C9_4F0C0B870141_impl*
end;//TDragDataSupport.RunDragData
procedure TDragDataSupport.Stop(aSuccess: Boolean);
//#UC START# *552FDFF10077_4F0C0B870141_var*
//#UC END# *552FDFF10077_4F0C0B870141_var*
begin
//#UC START# *552FDFF10077_4F0C0B870141_impl*
if f_DragState in cnActiveState then
begin
f_DragState := dsPassive;
f_DragSuccess := aSuccess;
RemoveListeners;
//SetCaptureControl(nil); //fix problem with csCaptureMouse
DragDataType := 0;
//Windows.SetCursor(Screen.Cursors[crDefault]);
if Assigned(f_OnDragStop) then
f_OnDragStop(Self);
end;
//#UC END# *552FDFF10077_4F0C0B870141_impl*
end;//TDragDataSupport.Stop
procedure TDragDataSupport.Pause;
//#UC START# *552FE00B02AA_4F0C0B870141_var*
//#UC END# *552FE00B02AA_4F0C0B870141_var*
begin
//#UC START# *552FE00B02AA_4F0C0B870141_impl*
if f_DragState = dsActive then
begin
f_DragState := dsPaused;
RemoveListeners;
end;
//#UC END# *552FE00B02AA_4F0C0B870141_impl*
end;//TDragDataSupport.Pause
procedure TDragDataSupport.Restore;
//#UC START# *552FE0130188_4F0C0B870141_var*
//#UC END# *552FE0130188_4F0C0B870141_var*
begin
//#UC START# *552FE0130188_4F0C0B870141_impl*
if f_DragState = dsPaused then
begin
f_DragState := dsActive;
InitListeners;
end;
//#UC END# *552FE0130188_4F0C0B870141_impl*
end;//TDragDataSupport.Restore
procedure TDragDataSupport.CheckInProgress;
//#UC START# *552FE01A0138_4F0C0B870141_var*
//#UC END# *552FE01A0138_4F0C0B870141_var*
begin
//#UC START# *552FE01A0138_4F0C0B870141_impl*
if f_DragState in cnActiveState then
raise EDragInProcess.Create;
//#UC END# *552FE01A0138_4F0C0B870141_impl*
end;//TDragDataSupport.CheckInProgress
procedure TDragDataSupport.MouseListenerNotify(aMouseMessage: WPARAM;
aHookStruct: PMouseHookStruct;
var theResult: Tl3HookProcResult);
//#UC START# *4F79CEDF005A_4F0C0B870141_var*
var
DestCtrl: TControl;
//#UC END# *4F79CEDF005A_4F0C0B870141_var*
begin
//#UC START# *4F79CEDF005A_4F0C0B870141_impl*
if ((aMouseMessage = WM_LBUTTONDOWN) or (aMouseMessage = WM_NCLBUTTONDOWN) or
(aMouseMessage = WM_RBUTTONDOWN) or (aMouseMessage = WM_NCRBUTTONDOWN) or
(aMouseMessage = WM_RBUTTONUP) or (aMouseMessage = WM_NCRBUTTONUP)) and
f_PrevMRecurse then
Exit;
try
f_PrevMRecurse := True;
try
if (aMouseMessage = WM_LBUTTONDOWN) or (aMouseMessage = WM_NCLBUTTONDOWN) then
if GetKeyState(VK_MENU) < 0 then
begin
DestCtrl := FindDragTarget(aHookStruct.Pt, False);
try
If (DestCtrl <> nil) then Self.DoDrop(DestCtrl);
except
theResult.Result := 0;
end;
Exit;
end;
if (aMouseMessage = WM_RBUTTONDOWN) or (aMouseMessage = WM_NCRBUTTONDOWN) then
if GetKeyState(VK_MENU) < 0 then
begin
f_NeedStop := True;
theResult.Result := 1;
theResult.Handled := True;
Exit;
end;
if (aMouseMessage = WM_RBUTTONUP) or (aMouseMessage = WM_NCRBUTTONUP) then
begin
if f_NeedStop then
begin
f_NeedStop := False;
if GetKeyState(VK_MENU) < 0 then
begin
Self.Stop(False);
//PMouseHookStruct(LParam)^.hwnd := 0;
theResult.Result := 1;
theResult.Handled := True;
Exit;
end;
end;
end;
finally
f_PrevMRecurse := False;
end;
except
on E: Exception do
l3System.Exception2Log(E);
end;
//#UC END# *4F79CEDF005A_4F0C0B870141_impl*
end;//TDragDataSupport.MouseListenerNotify
procedure TDragDataSupport.WndProcListenerNotify(Msg: PCWPStruct;
var theResult: Tl3HookProcResult);
//#UC START# *4F79CF3400BB_4F0C0B870141_var*
//#UC END# *4F79CF3400BB_4F0C0B870141_var*
begin
//#UC START# *4F79CF3400BB_4F0C0B870141_impl*
if (Msg.message = WM_SETCURSOR) and (SmallInt(Msg.lParam) = HTCLIENT) then
try
Windows.SetCursor(DCursor);
Msg.message := WM_NULL;
theResult.Result := 1;
theResult.Handled := True;
except
on E: Exception do
l3System.Exception2Log(E);
end;
//#UC END# *4F79CF3400BB_4F0C0B870141_impl*
end;//TDragDataSupport.WndProcListenerNotify
procedure TDragDataSupport.WndProcRetListenerNotify(Msg: PCWPRetStruct;
var theResult: Tl3HookProcResult);
//#UC START# *4F79CF9200A0_4F0C0B870141_var*
//#UC END# *4F79CF9200A0_4F0C0B870141_var*
begin
//#UC START# *4F79CF9200A0_4F0C0B870141_impl*
if (Msg.message = WM_SETCURSOR) and (SmallInt(Msg.lParam) = HTCLIENT) then
try
Windows.SetCursor(DCursor);
except
on E: Exception do
l3System.Exception2Log(E);
end;
//#UC END# *4F79CF9200A0_4F0C0B870141_impl*
end;//TDragDataSupport.WndProcRetListenerNotify
class function TDragDataSupport.Instance: TDragDataSupport;
{* Метод получения экземпляра синглетона TDragDataSupport }
begin
if (g_TDragDataSupport = nil) then
begin
l3System.AddExitProc(TDragDataSupportFree);
g_TDragDataSupport := Create;
end;
Result := g_TDragDataSupport;
end;//TDragDataSupport.Instance
class function TDragDataSupport.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TDragDataSupport <> nil;
end;//TDragDataSupport.Exists
initialization
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(EDragInProcess);
{* Регистрация EDragInProcess }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit InfoWORKMAILTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoWORKMAILRecord = record
PLender: String[4];
PImageID: String[9];
PStatus: String[10];
End;
TInfoWORKMAILBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoWORKMAILRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoWORKMAIL = (InfoWORKMAILPrimaryKey, InfoWORKMAILByStatus);
TInfoWORKMAILTable = class( TDBISAMTableAU )
private
FDFLender: TStringField;
FDFImageID: TStringField;
FDFStatus: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPImageID(const Value: String);
function GetPImageID:String;
procedure SetPStatus(const Value: String);
function GetPStatus:String;
procedure SetEnumIndex(Value: TEIInfoWORKMAIL);
function GetEnumIndex: TEIInfoWORKMAIL;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoWORKMAILRecord;
procedure StoreDataBuffer(ABuffer:TInfoWORKMAILRecord);
property DFLender: TStringField read FDFLender;
property DFImageID: TStringField read FDFImageID;
property DFStatus: TStringField read FDFStatus;
property PLender: String read GetPLender write SetPLender;
property PImageID: String read GetPImageID write SetPImageID;
property PStatus: String read GetPStatus write SetPStatus;
published
property Active write SetActive;
property EnumIndex: TEIInfoWORKMAIL read GetEnumIndex write SetEnumIndex;
end; { TInfoWORKMAILTable }
procedure Register;
implementation
procedure TInfoWORKMAILTable.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFImageID := CreateField( 'ImageID' ) as TStringField;
FDFStatus := CreateField( 'Status' ) as TStringField;
end; { TInfoWORKMAILTable.CreateFields }
procedure TInfoWORKMAILTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoWORKMAILTable.SetActive }
procedure TInfoWORKMAILTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoWORKMAILTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoWORKMAILTable.SetPImageID(const Value: String);
begin
DFImageID.Value := Value;
end;
function TInfoWORKMAILTable.GetPImageID:String;
begin
result := DFImageID.Value;
end;
procedure TInfoWORKMAILTable.SetPStatus(const Value: String);
begin
DFStatus.Value := Value;
end;
function TInfoWORKMAILTable.GetPStatus:String;
begin
result := DFStatus.Value;
end;
procedure TInfoWORKMAILTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Lender, String, 4, N');
Add('ImageID, String, 9, N');
Add('Status, String, 10, N');
end;
end;
procedure TInfoWORKMAILTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Lender;ImageID, Y, Y, N, N');
Add('ByStatus, Lender;Status;ImageID, N, N, N, N');
end;
end;
procedure TInfoWORKMAILTable.SetEnumIndex(Value: TEIInfoWORKMAIL);
begin
case Value of
InfoWORKMAILPrimaryKey : IndexName := '';
InfoWORKMAILByStatus : IndexName := 'ByStatus';
end;
end;
function TInfoWORKMAILTable.GetDataBuffer:TInfoWORKMAILRecord;
var buf: TInfoWORKMAILRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PImageID := DFImageID.Value;
buf.PStatus := DFStatus.Value;
result := buf;
end;
procedure TInfoWORKMAILTable.StoreDataBuffer(ABuffer:TInfoWORKMAILRecord);
begin
DFLender.Value := ABuffer.PLender;
DFImageID.Value := ABuffer.PImageID;
DFStatus.Value := ABuffer.PStatus;
end;
function TInfoWORKMAILTable.GetEnumIndex: TEIInfoWORKMAIL;
var iname : string;
begin
result := InfoWORKMAILPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoWORKMAILPrimaryKey;
if iname = 'BYSTATUS' then result := InfoWORKMAILByStatus;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoWORKMAILTable, TInfoWORKMAILBuffer ] );
end; { Register }
function TInfoWORKMAILBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..3] of string = ('LENDER','IMAGEID','STATUS' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 3) and (flist[x] <> s) do inc(x);
if x <= 3 then result := x else result := 0;
end;
function TInfoWORKMAILBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
end;
end;
function TInfoWORKMAILBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLender;
2 : result := @Data.PImageID;
3 : result := @Data.PStatus;
end;
end;
end.
|
unit HGM.Tools.Hint;
interface
uses
Vcl.Controls, System.Classes, Winapi.Messages, Winapi.Windows,
System.SysUtils, Vcl.Graphics, Vcl.ExtCtrls, Vcl.Themes, Vcl.Forms,
Vcl.ImgList, Vcl.ActnList, System.SyncObjs, System.Types, System.UITypes,
HGM.Controls.PanelExt, HGM.Common;
type
TlkHint = class(TComponent)
private
FText:string;
FTimerHide:TTimer;
FTimerRepaint:TTimer;
FRect:TRect;
FHeight, FWidth:Integer;
FPanel:TPanelExt;
FAutoHide: Cardinal;
FColor: TColor;
FFont: TFont;
FMaxWidth: Integer;
procedure FHide;
procedure FShow;
procedure SetHintSize;
procedure OnTimerHideTimer(Sender:TObject);
procedure OnTimerRepaintTime(Sender:TObject);
procedure OnPanelPaint(Sender:TObject);
procedure SetColor(const Value: TColor);
procedure SetFont(const Value: TFont);
procedure SetMaxWidth(const Value: Integer);
public
procedure Show(Control:TControl); overload;
procedure Show(PosPoint:TPoint); overload;
procedure Hide;
constructor Create(AOwner: TComponent); override;
published
property Text:string read FText write FText;
property AutoHide:Cardinal read FAutoHide write FAutoHide default 5000;
property Color:TColor read FColor write SetColor default clWhite;
property Font:TFont read FFont write SetFont;
property MaxWidth:Integer read FMaxWidth write SetMaxWidth default 200;
end;
procedure Register;
implementation
uses Math;
procedure Register;
begin
RegisterComponents(PackageName, [TlkHint]);
end;
{ TlkHint }
constructor TlkHint.Create(AOwner: TComponent);
begin
inherited;
FFont := TFont.Create;
FFont.Color := clBlack;
FFont.Size := 10;
FFont.Name := 'Segoe UI';
FText := '';
FColor := clWhite;
FTimerHide:=TTimer.Create(Self);
FTimerHide.Enabled:=False;
FTimerHide.OnTimer:=OnTimerHideTimer;
FTimerRepaint:=TTimer.Create(Self);
FTimerRepaint.Enabled:=False;
FTimerRepaint.Interval := 50;
FTimerRepaint.OnTimer:=OnTimerRepaintTime;
FAutoHide := 5000;
FMaxWidth := 200;
end;
procedure TlkHint.FHide;
begin
if Assigned(FPanel) then FreeAndNil(FPanel);
FTimerHide.Enabled:=False;
FTimerRepaint.Enabled := False;
end;
procedure TlkHint.FShow;
var RGN:HRGN;
begin
if not Assigned(FPanel) then
begin
FPanel:=TPanelExt.Create(nil);
FPanel.DoubleBuffered:=True;
FPanel.Visible:=False;
FPanel.OnPaint:=OnPanelPaint;
FPanel.ParentWindow:=GetDesktopWindow;
end;
FPanel.Left:=FRect.Left;
FPanel.Top:=FRect.Top;
FPanel.Width := FWidth;
FPanel.Height := FHeight;
FTimerRepaint.Enabled:=True;
FTimerHide.Enabled:=True;
FTimerHide.Interval:=FAutoHide;
RGN:=CreateRoundRectRgn(0, 0, FWidth, FHeight, FHeight, FHeight);
SetWindowRgn(FPanel.Handle, RGN, True);
DeleteObject(RGN);
FPanel.Repaint;
FPanel.Show;
FPanel.BringToFront;
end;
procedure TlkHint.SetColor(const Value: TColor);
begin
FColor := Value;
if Assigned(FPanel) then FPanel.Repaint;
end;
procedure TlkHint.SetFont(const Value: TFont);
begin
FFont := Value;
if Assigned(FPanel) then FPanel.Canvas.Font.Assign(Value);
end;
procedure TlkHint.SetHintSize;
begin
if not Assigned(FPanel) then Exit;
FHeight:=Max(FPanel.Canvas.TextHeight(FText), 10);
FWidth:=Min(Max(FPanel.Canvas.TextWidth(FText), 10), FMaxWidth)+10;
end;
procedure TlkHint.SetMaxWidth(const Value: Integer);
begin
FMaxWidth := Value;
end;
procedure TlkHint.Show(Control: TControl);
begin
SetHintSize;
FRect.Left:=(Control.Left+Control.Width div 2) - (FWidth div 2);
FRect.Top:=Control.Top-FHeight;
FRect.Right:=FRect.Left+FWidth;
FRect.Bottom:=FRect.Top+FHeight;
FShow;
end;
procedure TlkHint.Show(PosPoint: TPoint);
begin
SetHintSize;
FRect.Left:=Min(Max(PosPoint.X - (FWidth div 2), 0), Screen.DesktopWidth - FWidth);
FRect.Top:=PosPoint.Y - FHeight;
FRect.Right:=FRect.Left+FWidth;
FRect.Bottom:=FRect.Top+FHeight;
FShow;
end;
procedure TlkHint.Hide;
begin
FHide;
end;
procedure TlkHint.OnPanelPaint(Sender: TObject);
var R:TRect;
S:String;
begin
if not Assigned(FPanel) then Exit;
with FPanel.Canvas do
begin
Brush.Color := FColor;
Brush.Style := bsSolid;
FillRect(FPanel.ClientRect);
R := FPanel.ClientRect;
R.Offset(-1, -1);
S := FText;
Font.Assign(FFont);
TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfCenter]);
end;
end;
procedure TlkHint.OnTimerHideTimer(Sender: TObject);
begin
FHide;
end;
procedure TlkHint.OnTimerRepaintTime(Sender: TObject);
begin
if Assigned(FPanel) then FPanel.Repaint;
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: Registration unit for TWSocket. If you build a runtime
package, you shouldn't include this unit.
Creation: Feb 24, 2002
Version: 5.00
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2002-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
Feb 24, 2002 V1.00 Wilfried Mestdagh <wilfried@mestdagh.biz> created a
property editor for LineEnd property. I moved his code ti this
new unit so that it is compatible with Delphi 6.
Jan 19, 2003 V5.00 First pre-release for ICS-SSL. New major version number.
Skipped version numbers to mach wsocket.pas major version number.
May 31, 2004 V5.01 Used ICSDEFS.INC the same way as in other units
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverByteIcsWSocketE;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFNDEF VER80} { Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
interface
uses
{$IFDEF USEWINDOWS}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Classes,
{$IFDEF COMPILER6_UP}
{ Delphi 6/7: Add $(DELPHI)\Source\ToolsAPI to your library path }
{ and add designide.dcp to ICS package. }
{ BCB6 6: Add $(BCB)\Source\ToolsAPI to your library path }
{ and add designide.bpi to ICS package. }
DesignIntf, DesignEditors;
{$ELSE}
DsgnIntf;
{$ENDIF}
const
WSocketEVersion = 501;
CopyRight : String = ' WSocketE (c) 2002-2006 F. Piette V5.01 ';
type
TWSocketLineEndProperty = class(TStringProperty)
public
function GetLineEnd(const Value: String): String;
function SetLineEnd(const Value: String): String;
function GetValue: String; override;
procedure SetValue(const Value: String); override;
end;
procedure Register;
implementation
uses
OverByteIcsWSocket;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Register;
begin
RegisterComponents('FPiette',
[TWSocket
{ You must define USE_SSL so that SSL code is included in the component. }
{ To be able to compile the component, you must have the SSL related files }
{ which are _NOT_ freeware. See http://www.overbyte.be for details. }
{$IFDEF USE_SSL}
, TSslWSocket
, TSslContext
{$ENDIF}
]);
RegisterPropertyEditor(TypeInfo(string), TWSocket, 'LineEnd',
TWSocketLineEndProperty);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ LineEnd Property Editor }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketLineEndProperty.SetLineEnd(const Value: String): String;
var
Offset : Integer;
C : Char;
begin
if Pos('#', Value) = 0 then
raise Exception.Create('Invalid value');
Offset := 1;
Result := '';
repeat
if Value[Offset] <> '#' then
break;
Inc(Offset);
C := #0;
while (Offset <= Length(Value)) and
(Value[Offset] in ['0'..'9']) do begin
C := Char(Ord(C) * 10 + Ord(Value[Offset]) - Ord('0'));
Inc(Offset);
end;
Result := Result + C;
until Offset > Length(Value);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketLineEndProperty.GetLineEnd(const Value: String): String;
var
N: integer;
begin
Result := '';
for N := 1 to Length(Value) do
Result := Result + '#' + IntToStr(Ord(Value[N]));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketLineEndProperty.GetValue: String;
begin
Result := GetLineEnd(inherited GetValue);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketLineEndProperty.SetValue(const Value: String);
begin
inherited SetValue(SetLineEnd(Value));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit afwCaretPair;
{* Пара кареток (для вставки и замены). }
// Модуль: "w:\common\components\gui\Garant\AFW\implementation\Visual\afwCaretPair.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TafwCaretPair" MUID: (480DD9F600F6)
{$Include w:\common\components\gui\Garant\AFW\afwDefine.inc}
interface
uses
l3IntfUses
, afwSingleCaret
, afwInsCaretType
, afwOvrCaretType
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
;
const
DefInsMode = True;
type
TafwCaretPair = class(TafwSingleCaret)
{* Пара кареток (для вставки и замены). }
private
f_InsertMode: Boolean;
{* режим вставки? }
f_InsCaretType: TafwInsCaretType;
{* тип каретки для режима вставки. }
f_OvrCaretType: TafwOvrCaretType;
{* тип каретки для режима замены. }
protected
procedure pm_SetInsertMode(aValue: Boolean);
procedure pm_SetInsCaretType(aValue: TafwInsCaretType);
procedure pm_SetOvrCaretType(aValue: TafwOvrCaretType);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(anOwner: TWinControl); override;
public
property InsertMode: Boolean
read f_InsertMode
write pm_SetInsertMode;
{* режим вставки? }
property InsCaretType: TafwInsCaretType
read f_InsCaretType
write pm_SetInsCaretType;
{* тип каретки для режима вставки. }
property OvrCaretType: TafwOvrCaretType
read f_OvrCaretType
write pm_SetOvrCaretType;
{* тип каретки для режима замены. }
end;//TafwCaretPair
implementation
uses
l3ImplUses
, l3Base
//#UC START# *480DD9F600F6impl_uses*
//#UC END# *480DD9F600F6impl_uses*
;
procedure TafwCaretPair.pm_SetInsertMode(aValue: Boolean);
//#UC START# *480DDA5902F7_480DD9F600F6set_var*
//#UC END# *480DDA5902F7_480DD9F600F6set_var*
begin
//#UC START# *480DDA5902F7_480DD9F600F6set_impl*
if (aValue <> f_InsertMode) then
begin
f_InsertMode := aValue;
if f_InsertMode then
CaretType := f_InsCaretType
else
CaretType := f_OvrCaretType;
end;//aValue <> f_InsertMode
//#UC END# *480DDA5902F7_480DD9F600F6set_impl*
end;//TafwCaretPair.pm_SetInsertMode
procedure TafwCaretPair.pm_SetInsCaretType(aValue: TafwInsCaretType);
//#UC START# *480DDA71036A_480DD9F600F6set_var*
//#UC END# *480DDA71036A_480DD9F600F6set_var*
begin
//#UC START# *480DDA71036A_480DD9F600F6set_impl*
if l3Set(f_InsCaretType, aValue) AND InsertMode then
CaretType := f_InsCaretType;
//#UC END# *480DDA71036A_480DD9F600F6set_impl*
end;//TafwCaretPair.pm_SetInsCaretType
procedure TafwCaretPair.pm_SetOvrCaretType(aValue: TafwOvrCaretType);
//#UC START# *480DDAA60276_480DD9F600F6set_var*
//#UC END# *480DDAA60276_480DD9F600F6set_var*
begin
//#UC START# *480DDAA60276_480DD9F600F6set_impl*
if l3Set(f_OvrCaretType, aValue) AND not InsertMode then
CaretType := f_OvrCaretType;
//#UC END# *480DDAA60276_480DD9F600F6set_impl*
end;//TafwCaretPair.pm_SetOvrCaretType
procedure TafwCaretPair.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_480DD9F600F6_var*
//#UC END# *479731C50290_480DD9F600F6_var*
begin
//#UC START# *479731C50290_480DD9F600F6_impl*
l3Free(f_InsCaretType);
l3Free(f_OvrCaretType);
inherited;
//#UC END# *479731C50290_480DD9F600F6_impl*
end;//TafwCaretPair.Cleanup
constructor TafwCaretPair.Create(anOwner: TWinControl);
//#UC START# *52FCEEE902D1_480DD9F600F6_var*
//#UC END# *52FCEEE902D1_480DD9F600F6_var*
begin
//#UC START# *52FCEEE902D1_480DD9F600F6_impl*
inherited Create(anOwner);
f_InsCaretType := TafwInsCaretType.Create;
f_OvrCaretType := TafwOvrCaretType.Create;
f_InsertMode := DefInsMode;
if f_InsertMode then
CaretType := f_InsCaretType
else
CaretType := f_OvrCaretType;
//#UC END# *52FCEEE902D1_480DD9F600F6_impl*
end;//TafwCaretPair.Create
end.
|
unit ReqWorkForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OkCancel_frame, StdCtrls, FIBDatabase, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet, Mask, DBCtrls, DBCtrlsEh, DBLookupEh,
FIBQuery, pFIBQuery, DBGridEh;
type
TReqWorkForm = class(TForm)
okcnclfrm1: TOkCancelFrame;
srcWork: TDataSource;
dsWork: TpFIBDataSet;
trWrite: TpFIBTransaction;
trRead: TpFIBTransaction;
Label2: TLabel;
Label3: TLabel;
dbmmoSolution: TDBMemoEh;
dbeName: TDBEditEh;
edtHours: TDBNumberEditEh;
lbl1: TLabel;
grpAfterAdd: TGroupBox;
lbl3: TLabel;
cbATRAction: TDBComboBoxEh;
dsAttributes: TpFIBDataSet;
srcAttributes: TDataSource;
cbbAttribute: TDBLookupComboboxEh;
lbl4: TLabel;
cbService: TDBLookupComboboxEh;
dsService: TpFIBDataSet;
srcService: TDataSource;
dbckDefault: TDBCheckBoxEh;
lbl5: TLabel;
ed1: TDBNumberEditEh;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure okcnclfrm1bbOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function ReguestWorkModify (const aW_ID:Integer; const aRT_ID : Integer): Integer;
implementation
uses
DM;
{$R *.dfm}
function ReguestWorkModify (const aW_ID:Integer; const aRT_ID : Integer): Integer;
begin
result := aW_ID;
with TReqWorkForm.Create(Application) do
try
dsWork.ParamByName('W_ID').AsInteger := aW_ID;
dsWork.Open;
dsService.Open;
dsAttributes.Open;
if aW_ID = -1 then dsWork.Insert;
if ShowModal = mrOk
then begin
if aW_ID = -1
then begin
result := dmMain.dbTV.Gen_Id('GEN_OPERATIONS_UID',1);
dsWork.ParamByName('W_ID').AsInteger := Result;
dsWork['RQ_TYPE'] := aRT_ID;
end;
if dsWork.State in [dsEdit, dsInsert] then dsWork.Post;
end
else begin
if dsWork.State in [dsEdit, dsInsert] then dsWork.Cancel;
result := -1;
end;
dsWork.Close;
dsService.Close;
dsAttributes.Close;
finally
free
end;
end;
procedure TReqWorkForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN)
then okcnclfrm1bbOkClick(sender);
end;
procedure TReqWorkForm.okcnclfrm1bbOkClick(Sender: TObject);
begin
okcnclfrm1.actExitExecute(Sender);
end;
end.
|
unit BinarySearch;
(*
* org. Author : Michael Puff - http://www.michael-puff.de
* Redesign by : sx2008
* Date : 2008-06-03
* License : PUBLIC DOMAIN
*)
interface
uses Classes;
type
TBSFound = (bsFound {gefunden},
bsNotFound {nicht gefunden},
bsLower,
bsHigher);
// abstrakte Basisklasse für binäre Suche und Sortieren
// muss immer für einen konkreten Datentyp abgeleitet werden
TBSearch = class(TObject)
private
FSorted : Boolean;
procedure QuickSort(L, R: Integer);
protected
FLeft : Integer; // untere Grenze der Daten (meist 0)
FRight : Integer; // obere Grenze der Daten
// Rückgabewert von KeyCompare()
// Key < daten[index] => -1 (negative Zahl)
// Key = daten[index] => 0
// Key > daten[index] => +1 (positive Zahl)
function KeyCompare(index:integer):integer;virtual;abstract;
function Compare(a, b: integer):integer;virtual;abstract;
procedure Exchange(a, b: integer);virtual;abstract;
public
procedure Sort;
function Search: Integer; overload;
function Search(out found:TBSFound): Integer; overload;
property Sorted : Boolean read FSorted write FSorted;
end;
//==============================================================================
TIntArray = array of Integer;
TBSearchInteger = class(TBSearch)
private
FData : TIntArray;
procedure SetData(const value:TIntArray);
protected
function KeyCompare(index:integer):integer;override;
function Compare(a, b: integer):integer;override;
procedure Exchange(a, b: integer);override;
public
Key : Integer; // der Wert nach dem gesucht werden soll
property Data : TIntArray read FData write SetData;
end;
TBSearchTStrings = class(TBSearch)
private
FData : TStrings;
protected
function KeyCompare(index:integer):integer;override;
function Compare(a, b: integer):integer;override;
procedure Exchange(a, b: integer);override;
public
Key : String; // der Wert nach dem gesucht werden soll
property Data : TStrings read FData write FData;
end;
implementation
uses SysUtils;
{ TBSearch }
procedure TBSearch.QuickSort(L, R: Integer);
var
I, J, P: Integer;
begin
repeat
I := L;
J := R;
P := (L + R) shr 1;
repeat
while Compare(I, P) < 0 do
Inc(I);
while Compare(J, P) > 0 do
Dec(J);
if (I <= J) then
begin
Exchange(I, J);
Inc(I);
Dec(J);
end;
until (I > J);
if (L < J) then
QuickSort(L, J);
L := I;
until (I >= R);
end;
function TBSearch.Search: Integer;
var
found : TBSFound;
begin
result := Search(found);
if found <> bsFound then Result := -1;
end;
function TBSearch.Search(out found: TBSFound): Integer;
var
left, right, middle, cv : integer;
begin
if not Sorted then Sort; // sortieren, falls nötig
if KeyCompare(FLeft) < 0 then
begin
found := bsLower;
Result := Fleft - 1;
exit;
end;
if KeyCompare(FRight) > 0 then
begin
found := bsHigher;
Result := FRight - 1;
exit;
end;
left := FLeft;
right := FRight;
found := bsNotFound;
Result := -1;
// Algorithmus Binärsuche
while (left <= right) do
begin
middle := (left + right) div 2;
cv := KeyCompare(middle);
if cv < 0 then
right := middle - 1
else if cv > 0 then
left := middle + 1
else
begin
Result := middle;
Found := bsFound;
break;
end;
end;
end;
procedure TBSearch.Sort;
begin
QuickSort(FLeft, FRight);
FSorted := True;
end;
//==============================================================================
procedure TBSearchInteger.SetData(const value:TIntArray);
begin
FLeft := Low(value); // untere
FRight:= High(value); // und obere Grenze merken
FData := value;
Sorted := False; // die Daten sind unsortiert
end;
function TBSearchInteger.Compare(a, b: integer): integer;
begin
if FData[a] < FData[b] then Result := -1
else if FData[a] > FData[b] then Result := 1
else Result := 0;
end;
procedure TBSearchInteger.Exchange(a, b: integer);
var t: integer;
begin
t := FData[a];
FData[a] := FData[b];
FData[b] := t;
end;
function TBSearchInteger.KeyCompare(index:integer):integer;
begin
if Key < FData[index] then Result := -1
else if Key > FData[index] then Result := 1
else Result := 0;
// möglich wäre auch: Result := Key - FData[index]
end;
{ TBSearchTStrings }
function TBSearchTStrings.Compare(a, b: integer): integer;
begin
result := CompareStr(FData[a],FData[b]);
end;
procedure TBSearchTStrings.Exchange(a, b: integer);
begin
FData.Exchange(a,b);
end;
function TBSearchTStrings.KeyCompare(index: integer): integer;
begin
result := CompareStr(Key, FData[index]);
end;
end.
|
program Ch1;
{$mode objfpc}
uses
SysUtils;
var
A1:array[0..3] of Char = ('e','m','u','g');
A2:array[0..3] of Char = ('d','c','e','f');
A3:array[0..2] of Char = ('j','a','r');
A4:array[0..3] of Char = ('d','c','a','f');
A5:array[0..3] of Char = ('t','g','a','l');
procedure QuickSort(var A:array of Char;Left,Right:Integer);
var
I,J:Integer;
Pivot,Temp:Char;
begin
I := Left;
J := Right;
Pivot := A[(Left + Right) div 2];
repeat
while Ord(Pivot) > Ord(A[I]) do Inc(I);
while Ord(Pivot) < Ord(A[J]) do Dec(J);
if I <= J then
begin
Temp := A[I];
A[I] := A[J];
A[J] := Temp;
Inc(I);
Dec(J);
end;
until I > J;
if Left < J then QuickSort(A, Left, J);
if I < Right then QuickSort(A, I, Right);
end;
function GreaterCharacter(var A:array of Char;Target:Char):Char;
var
I:Integer;
begin
QuickSort(A, Low(A), High(A));
for I := Low(A) to High(A) do
if A[I] > Target then Exit(A[I]);
Result := Target;
end;
begin
WriteLn(GreaterCharacter(A1,'b'));
WriteLn(GreaterCharacter(A2,'a'));
WriteLn(GreaterCharacter(A3,'o'));
WriteLn(GreaterCharacter(A4,'a'));
WriteLn(GreaterCharacter(A5,'v'));
end.
|
unit Log;
interface
uses
SysUtils;
type
TLog = class
class procedure Append(const aLine: string);
end;
implementation
{$IFDEF DEBUG}
var vLog: text;
{$ENDIF}
class procedure TLog.Append(const aLine: string);
begin
{$IFDEF DEBUG}
WriteLn(vLog, DateTimeToStr(Now()) + ' ' + aLine);
Flush(vLog);
{$ENDIF}
end;
var
VFileName: string;
initialization
vFileName := ChangeFileExt(ParamStr(0), '.log');
{$IFDEF DEBUG}
Assign(vLog, vFileName);
if FileExists(vFileName) then
Append(vLog)
else
Rewrite(vLog);
finalization
Close(vLog);
{$ENDIF}
end.
|
program alumnosUNLP;
const
dimF = 400;
type
alumno = record
inscripcion :integer;
dni :integer;
apellido :string;
nombre :string;
anio :integer;
end;
maximos = record
primero :alumno;
segundo :alumno;
end;
alumnos = array [1..dimF] of alumno;
procedure leerAlumno(var a:alumno);
begin
write('Ingrese el nro de inscripción del alumno: ');
readln(a.inscripcion);
write('Ingrese el apellido del alumno: ');
readln(a.apellido);
write('Ingrese el nombre del alumno: ');
readln(a.nombre);
write('Ingrese el año de nacimiento del alumno: ');
readln(a.anio);
end;
function comprobarDigPar(dni:integer):boolean;
var
digito :integer;
cumple :boolean;
begin
cumple := true;
repeat
digito := dni MOD 10;
dni := dni DIV 10;
if (digito MOD 2 <> 0) then
cumple := false;
until (dni = 0);
comprobarDigPar := cumple;
end;
procedure actualizarMaximo(var m:alumno; mNuevo:alumno);
begin
m.nombre := mNuevo.nombre;
m.apellido := mNuevo.apellido;
m.anio := mNuevo.anio;
end;
var
i, dimL, cantidadAlumnosPar :integer;
porcentajeAlumnosPar :real;
a :alumnos;
aActual :alumno;
m :maximos;
begin
m.primero.anio := 2021;
m.segundo.anio := 2021;
cantidadAlumnosPar := 0;
dimL := 0;
i := 1;
// Cargar alumnos
leerAlumno(aActual);
a[i] := aActual;
while((a[i].dni <> -1) and (i<dimF)) do
begin
dimL := dimL + 1;
leerAlumno(aActual);
a[i] := aActual;
end;
// Procesar alumnos
for i:=1 to dimL do
begin
// Digitos pares
if (comprobarDigPar(a[i].dni)) then
cantidadAlumnosPar := cantidadAlumnosPar + 1;
// Maximos edades
if (a[i].anio < m.primero.anio) then
begin
actualizarMaximo(m.segundo, m.primero); // Guardo el primer maximo en el segundo
actualizarMaximo(m.primero, a[i]); // Actualizo el primer máximo
end
else
if (a[i].anio < m.segundo.anio) then
actualizarMaximo(m.segundo, a[i]); // Actualizo el segundo máximo
end;
porcentajeAlumnosPar := cantidadAlumnosPar / dimL;
writeln(
'El porcentaje de alumnos con DNI compuesto solo por dígitos pares es: ',
porcentajeAlumnosPar
);
writeln(
'Los dos alumnos de mayor edad son: ',
m.primero.nombre, ' ', m.primero.apellido, ' y ',
m.segundo.nombre, ' ', m.segundo.apellido, '.'
);
end. |
(*
* Project: lab6
* User: alexander_sumaneev
* Date: 05.04.2017
*)
unit cmdline;
interface
type cmd_line = object
private
cmdstr: string; //строка на экране
cmd:string; //команда после разбиения строки
cmd_number:string; //аргумент команды
symbols: set Of char; //доступные символы для печати
cmd_list: array[0..4] of string; //список доступных команд
prev_cmd:string; //предыдущая команда
procedure arrow_up; //действия при нажатии стрелки вверх
procedure enter; // при нажатии enter
procedure tab; //автодополнение команды при нажатии tab
procedure key_press; //обработка нажатия клавиш
procedure del_spaces; //удаление лишних пробелов
procedure help; //вывод справки
Procedure backspace(); //стираем символ
procedure split; //разделение команды на слово и число
//----------------------------------------------------------------------------------
public
constructor create;
procedure init; //запуск меню
//----------------------------------------------------------------------------------
end;
implementation
uses regexpr,crt,bintree;
var
my_tree:bin_tree; //дерево
procedure cmd_line.help();
var
f:Text;
s:string;
begin //выводит файл со справкой на экран
Assign(f,'help.txt');
Reset(f);
while not Eof(f) do
begin
ReadLn(f,s);
WriteLn(s);
end;
Close(f);
end;
procedure cmd_line.split();
var
space_pos:Integer;
begin
WriteLn();
space_pos:=pos(' ',cmdstr);
if space_pos <> 0 then //если нашли пробел разбиваем команду на 2 части
begin
cmd:=Copy(cmdstr,1,space_pos-1); //сама команда
cmd_number:=Copy(cmdstr,space_pos+1,Length(cmdstr)); //cmd_number содержит число
if cmd='insert' then
my_tree.insert_tree(cmd_number);
if cmd='find' then
my_tree.find_tree(cmd_number,my_tree.root_tree());
end
else
begin
cmd:=cmdstr;
if cmd='help' then
help();
if cmd='print' then
my_tree.print_tree(my_tree.root_tree());
if cmd='delete' then
my_tree.delete_tree(my_tree.root_tree());
end;
end;
procedure cmd_line.del_spaces();
Var
RegexObj: TRegExpr;
begin
RegexObj := TRegExpr.Create;
RegexObj.Expression:='(^\s*)|(\s*$)/(\s\s)'; //пробелы в начале и в конце
cmdstr:=RegexObj.Replace(cmdstr,'',false);
RegexObj.Expression:='\s+'; //лишние пробелы между словами
cmdstr:=RegexObj.Replace(cmdstr,' ',false);
RegexObj.Expression:='\s$'; //пробел в конце
cmdstr:=RegexObj.Replace(cmdstr,'',false);
RegexObj.Destroy();
end;
procedure cmd_line.tab();
var
i:Integer;
begin
del_spaces();
for i:=0 to 4 do
begin
if pos(cmdstr,cmd_list[i]) = 1 then //если нашли команду в списке команд
begin
cmdstr:=cmd_list[i]+' ';
delline;
gotoxy(1,wherey);
Write(cmdstr);
break;
end;
end;
end;
procedure cmd_line.enter();
var
expr:string;
RegexObj: TRegExpr;
begin
prev_cmd:=cmdstr;
del_spaces();
expr:='^(((help)|(print)|(delete))$)|((insert|find)\s(0|(-(1|2|3|4|5|6|7|8|9)\d*)|(1|2|3|4|5|6|7|8|9)\d*))$';
RegexObj := TRegExpr.Create;
RegexObj.Expression := expr;
If not RegexObj.Exec(cmdstr) Then
begin //если команда не соответствует регулярному выражению expr
writeln(#10#13,'Incorrect command *',cmdstr,'*');
cmdstr:='';
end
Else
begin
split();
cmdstr:='';
WriteLn();
end;
RegexObj.Destroy();
end;
procedure cmd_line.arrow_up(); //выводит предыдущую команду
begin
cmdstr:=prev_cmd;
gotoxy(1,wherey);
clreol;
write(cmdstr);
end;
Procedure cmd_line.backspace();
Begin
delete(cmdstr,length(cmdstr),1);
gotoxy(wherex-1,wherey);
clreol;
End;
procedure cmd_line.key_press();
var
key:char;
begin
if Length(cmdstr) > 80 then //если слишком много вбили в консоль
begin
WriteLn(#10#13,'The length of string is 80 characters');
cmdstr:='';
end
else
begin
key := readkey();
If (key In symbols) Then
Begin
write(key);
cmdstr := cmdstr+key;
End;
If (key=#27) Then //Esc
Halt();
If (key=#13) Then
enter();
If (key=#9) Then
tab();
If (key=#8) Then
backspace();
If (key=#0) Then
Case readkey() Of
#72: arrow_up();
End;
end;
end;
constructor cmd_line.create ;
begin
cmd_list[0]:='help';
cmd_list[1]:='insert';
cmd_list[2]:='print';
cmd_list[3]:='find';
cmd_list[4]:='delete';
symbols:=['a'..'z','0' .. '9',' ','-'];
end;
procedure cmd_line.init();
begin
help();
my_tree.create();
while(true) do
begin
key_press();
end;
end;
end. |
unit uHighlighterReg;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
SynHighlighterADSP21xx, SynHighlighterFortran, SynHighlighterFoxpro, SynHighlighterGalaxy, SynHighlighterBaan,
SynHighlighterHaskell, SynHighlighterCache, SynHighlighterCS, SynHighlighterDml, SynHighlighterCAC,
SynHighlighterModelica, SynHighlighterCobol, SynHighlighterTclTk, SynHighlighterHP48, SynHighlighterAWK,
SynHighlighterProgress, SynHighlighterEiffel, SynHighlighterGWS, SynHighlighterDOT, SynHighlighterLDraw,
SynHighlighterVBScript, SynHighlighterUnreal, SynHighlighterVrml97, SynHighlighterSml, SynHighlighterIDL,
SynHighlighterRuby, SynHighlighterInno, SynHighlighterAsm, SynHighlighter8051, SynHighlighterLua,
SynHighlighterKix, SynHighlighterSDD, SynHighlighterProlog, SynHighlighterRC, SynHighlighterM3;
{.$R ImagesPNG.Res}
{.$R ImagesPNG.Res}
{.$R ImagesPNG.Res}
{.$R *.rc}
{.$R Images.rc}
//failed miserably to use rc files they are not linked in lazarus for some reason although if I delete the res file
//from the disk the compiler complains about the missing file.
procedure Register;
implementation
uses LResources;
procedure Register;
begin
RegisterComponents('SynEdit Highlighters',[TSynADSP21xxSyn, TSynTclTkSyn, TSynRubySyn, TSynDOTSyn, TSynCSSyn,
TSynHaskellSyn, TSynFoxproSyn, TSynInnoSyn, TSynDmlSyn, TSynCACSyn,
TSynModelicaSyn, TSynVrml97Syn, TSynHP48Syn, TSynKixSyn, TSynAWKSyn,
TSynProgressSyn, TSynEiffelSyn, TSynBaanSyn, TSynM3Syn, TSynLDRSyn,
TSynVBScriptSyn, TSynUnrealSyn, TSynSMLSyn, TSynIdlSyn, TSynCobolSyn,
TSynGWScriptSyn, TSynGalaxySyn, TSyn8051Syn, TSynAsmSyn, TSynLuaSyn,
TSynFortranSyn, TSynPrologSyn, TSynSDDSyn, TSynRCSyn, TSynCacheSyn]);
end;
initialization
{$I Images.lrs}
end.
|
(*
JCore WebServices, JSON Streaming Classes
Copyright (C) 2015 Joao Morais
See the file LICENSE.txt, included in this distribution,
for details about the copyright.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*)
unit JCoreWSJSON;
{$I jcore.inc}
interface
uses
typinfo,
contnrs,
fpjson,
fpjsonrtti;
type
{ TJCoreWSJSONSerializer }
TJCoreWSJSONSerializer = class(TJSONStreamer)
protected
function StreamClassProperty(const AObject: TObject): TJSONData; override;
function StreamObjectList(const AObjectList: TObjectList): TJSONArray;
end;
{ TJCoreWSJSONUnserializer }
TJCoreWSJSONUnserializer = class(TJSONDeStreamer)
protected
procedure DoRestoreProperty(AObject: TObject; PropInfo: PPropInfo; PropData: TJSONData); override;
procedure RestoreObjectList(const AObject: TObject; const APropInfo: PPropInfo; const APropData: TJSONData);
end;
implementation
uses
sysutils;
{ TJCoreWSJSONSerializer }
function TJCoreWSJSONSerializer.StreamClassProperty(const AObject: TObject): TJSONData;
begin
if AObject is TObjectList then
Result := StreamObjectList(TObjectList(AObject))
else
Result := inherited StreamClassProperty(AObject);
end;
function TJCoreWSJSONSerializer.StreamObjectList(const AObjectList: TObjectList): TJSONArray;
var
I: Integer;
begin
Result := TJSONArray.Create;
try
for I := 0 to Pred(AObjectList.Count) do
Result.Add(ObjectToJSON(AObjectList.Items[I]));
except
FreeAndNil(Result);
raise;
end;
end;
{ TJCoreWSJSONUnserializer }
procedure TJCoreWSJSONUnserializer.DoRestoreProperty(AObject: TObject; PropInfo: PPropInfo;
PropData: TJSONData);
begin
if (PropData is TJSONArray) and GetTypeData(PropInfo^.PropType)^.ClassType.InheritsFrom(TObjectList) then
RestoreObjectList(AObject, PropInfo, PropData)
else
inherited DoRestoreProperty(AObject, PropInfo, PropData);
end;
procedure TJCoreWSJSONUnserializer.RestoreObjectList(const AObject: TObject; const APropInfo: PPropInfo;
const APropData: TJSONData);
var
VList: TObjectList;
VArray: TJSONArray;
VItem: TObject;
I: Integer;
begin
VList := TObjectList.Create(True);
SetObjectProp(AObject, APropInfo, VList);
VArray := TJSONArray(APropData);
for I := 0 to Pred(VArray.Count) do
begin
{ TODO : Take the item classes of the list from the model }
VItem := TObject.Create;
VList.Add(VItem);
JSONToObject(VArray[I] as TJSONObject, VItem);
end;
end;
initialization
{$ifdef VER3}
TJSONObject.CompressedJSON := True;
{$endif}
end.
|
unit LS.Config;
interface
type
TLocationConfig = class(TObject)
private
class function GetFileName: string;
class function GetJSON: string;
private
FIsPaused: Boolean;
public
class function GetConfig: TLocationConfig;
public
procedure Save;
property IsPaused: Boolean read FIsPaused write FIsPaused;
end;
implementation
uses
System.IOUtils, System.SysUtils,
REST.Json;
{ TLocationConfig }
class function TLocationConfig.GetConfig: TLocationConfig;
var
LJSON: string;
begin
Result := nil;
LJSON := GetJSON;
if not LJSON.IsEmpty then
Result := TJson.JsonToObject<TLocationConfig>(LJSON);
if Result = nil then
Result := TLocationConfig.Create;
end;
class function TLocationConfig.GetFileName: string;
begin
Result := TPath.Combine(TPath.GetDocumentsPath, 'LocationConfig.json');
end;
class function TLocationConfig.GetJSON: string;
begin
if TFile.Exists(GetFileName) then
Result := TFile.ReadAllText(GetFileName)
else
Result := '';
end;
procedure TLocationConfig.Save;
begin
TFile.WriteAllText(GetFileName, TJson.ObjectToJsonString(Self));
end;
end.
|
unit Should;
interface
uses
// Variants,
SysUtils, System.Rtti, System.TypInfo;
type
TActualValue = class;
TActualCall = class;
IConstraint<T> = interface;
TValueConstraintOp = record
private
FConstraint: IConstraint<TActualValue>;
public
class operator LogicalNot(c: TValueConstraintOp): TValueConstraintOp;
class operator LogicalOr(c1, c2: TValueConstraintOp): TValueConstraintOp;
class operator LogicalAnd(c1, c2: TValueConstraintOp): TValueConstraintOp;
constructor Create(c: IConstraint<TActualValue>);
procedure Evaluate(actual: TActualValue; negate: boolean);
end;
TCallConstraintOp = record
private
FConstraint: IConstraint<TActualCall>;
public
class operator LogicalNot(c: TCallConstraintOp): TCallConstraintOp;
class operator LogicalOr(c1, c2: TCallConstraintOp): TCallConstraintOp;
class operator LogicalAnd(c1, c2: TCallConstraintOp): TCallConstraintOp;
constructor Create(c: IConstraint<TActualCall>);
procedure Evaluate(actual: TActualCall; negate: boolean);
end;
TActualValue = class(TObject)
type
TEvaluator = record
private
FActual: TActualValue;
public
procedure Should(constraint: TValueConstraintOp);
end;
private
FFieldName: string;
FData: TValue;
end;
TActualCall = class
type
TEvaluator = record
private
FActual: TActualCall;
public
procedure Should(constraint: TCallConstraintOp);
end;
private
FFieldName: string;
FCall: TProc;
end;
TActualValueProvider = record
private
FFieldName: string;
public
function Val<T>(value: T): TActualValue.TEvaluator; overload;
function Val(value: TValue): TActualValue.TEvaluator; overload;
function Call(supplier: TProc): TActualCall.TEvaluator;
end;
TEvalResult = record
type
TEvalStatus = (Pass, Falure, Fatal);
public
Status: TEvalStatus;
Message: string;
end;
IConstraint<T> = interface
function Evaluate(actual: T; negate: boolean): TEvalResult;
end;
TValueConstraint = class(TInterfacedObject, IConstraint<TActualValue>)
public
function Evaluate(actual: TActualValue; negate: boolean): TEvalResult; virtual; abstract;
end;
TCallConstraint = class(TInterfacedObject, IConstraint<TActualCall>)
public
function Evaluate(actual: TActualCall; negate: boolean): TEvalResult; virtual; abstract;
end;
TBaseValueConstraint = class(TValueConstraint)
protected
FExpected: TValue;
protected
procedure EvaluateInternal(actual: TValue; negate: boolean; fieldName: string; out EvalResult: TEvalResult); virtual; abstract;
public
constructor Create(expected: TValue);
destructor Destroy; override;
function Evaluate(actual: TActualValue; negate: boolean): TEvalResult; override;
end;
TDelegateValueConstraint = class(TBaseValueConstraint)
type
TDelegate = reference to procedure (actual, expected: TValue; negate: boolean; fieldName: string; var outEvalResult: TEvalResult);
private
FDelegate: TDelegate;
protected
procedure EvaluateInternal(actual: TValue; negate: boolean; fieldName: string; out EvalResult: TEvalResult); override;
public
constructor Create(expected: TValue; callback: TDelegate);
end;
TDelegateCallConstraint = class(TCallConstraint)
type
TDelegate = reference to procedure (actual: TProc; negate: boolean; fieldName: string; var outEvalResult: TEvalResult);
private
FDelegate: TDelegate;
public
constructor Create(callback: TDelegate);
function Evaluate(actual: TActualCall; negate: boolean): TEvalResult; override;
end;
TNotConstraint<T> = class(TInterfacedObject, IConstraint<T>)
private
FConstraint: IConstraint<T>;
public
constructor Create(constraint: IConstraint<T>);
destructor Destroy; override;
function Evaluate(actual: T; negate: boolean): TEvalResult;
end;
TAndOrConstraint<T> = class(TInterfacedObject, IConstraint<T>)
private
FConstraints: TArray<IConstraint<T>>;
FIsAnd: boolean;
function EvaluateAsAnd(actual: T; negate: boolean): TEvalResult;
function EvaluateAsOr(actual: T; negate: boolean): TEvalResult;
public
constructor Create(c1, c2: IConstraint<T>; isAnd: boolean);
destructor Destroy; override;
function Evaluate(actual: T; negate: boolean): TEvalResult;
end;
{ Eval Result Helper }
TMaybeEvalResult = record
type
TMaybeSelector = reference to function: TEvalResult;
public
Result: TEvalResult;
constructor Create(EvalResult: TEvalResult); overload;
constructor Create(fn: TMaybeSelector); overload;
function Next(fn: TMaybeSelector): TMaybeEvalResult;
end;
{ Test Exception Handler }
type TestExceptionHandlerproc = reference to procedure (evalResult: TEvalResult);
procedure RegisterExceptionHandler(handler: TestExceptionHandlerproc);
procedure RaiseTestError(evalResult: TEvalResult);
{ Assertion Entry Point }
function Its(comment: string): TActualValueProvider; overload;
function Its(comment: string; args: array of const): TActualValueProvider; overload;
implementation
var
gExceptionHandler: TestExceptionHandlerproc;
procedure RegisterExceptionHandler(handler: TestExceptionHandlerproc);
begin
gExceptionHandler := handler;
end;
procedure RaiseTestError(evalResult: TEvalResult);
begin
System.Assert(Assigned(gExceptionHandler), 'テスト例外ハンドラが設定されていない');
gExceptionHandler(evalResult);
end;
function Its(comment: string): TActualValueProvider;
begin
Result.FFieldName := comment;
end;
function Its(comment: string; args: array of const): TActualValueProvider;
begin
Result := Its(Format(comment, args));
end;
function TBaseValueConstraint.Evaluate(actual: TActualValue; negate: boolean): TEvalResult;
begin
Result.Status := TEvalResult.TEvalStatus.Pass;
Result.Message := '';
Self.EvaluateInternal(actual.FData, negate, actual.FFieldName, Result);
end;
constructor TBaseValueConstraint.Create(expected: TValue);
begin
FExpected := expected;
end;
destructor TBaseValueConstraint.Destroy;
begin
inherited;
end;
{ TDelegateConstraint }
constructor TDelegateValueConstraint.Create(expected: TValue; callback: TDelegate);
begin
inherited Create(expected);
System.Assert(Assigned(callback));
FDelegate := callback;
end;
procedure TDelegateValueConstraint.EvaluateInternal(actual: TValue; negate: boolean; fieldName: string; out EvalResult: TEvalResult);
begin
FDelegate(actual, FExpected, negate, fieldName, EvalResult);
end;
{ TDelegateCallConstraint }
constructor TDelegateCallConstraint.Create(callback: TDelegate);
begin
System.Assert(Assigned(callback));
FDelegate := callback;
end;
function TDelegateCallConstraint.Evaluate(actual: TActualCall; negate: boolean): TEvalResult;
begin
FDelegate(actual.FCall, negate, actual.FFieldName, Result);
end;
constructor TNotConstraint<T>.Create(constraint: IConstraint<T>);
begin
System.Assert(Assigned(constraint));
FConstraint := constraint;
end;
destructor TNotConstraint<T>.Destroy;
begin
FConstraint := nil;
end;
function TNotConstraint<T>.Evaluate(actual: T; negate: boolean): TEvalResult;
begin
Result := FConstraint.Evaluate(actual, not negate);
end;
constructor TAndOrConstraint<T>.Create(c1, c2: IConstraint<T>; isAnd: boolean);
begin
FConstraints := TArray<IConstraint<T>>.Create(c1, c2);
FIsAnd := isAnd;
end;
destructor TAndOrConstraint<T>.Destroy;
var
c: IConstraint<T>;
begin
// for c in FConstraints do begin
// c := nil;
// end;
end;
function TAndOrConstraint<T>.Evaluate(actual: T; negate: boolean): TEvalResult;
var
isAnd: boolean;
begin
if negate then isAnd := not FIsAnd else isAnd := FIsAnd;
if isAnd then begin
Result := Self.EvaluateAsAnd(actual, negate);
end
else begin
Result := Self.EvaluateAsOr(actual, negate);
end;
end;
function TAndOrConstraint<T>.EvaluateAsAnd(actual: T; negate: boolean): TEvalResult;
var
c: IConstraint<T>;
evalResult : TEvalResult;
begin
for c in FConstraints do begin
evalResult := c.Evaluate(actual, negate);
if evalResult.Status <> TEvalResult.TEvalStatus.Pass then begin
Result := evalResult;
Exit;
end;
end;
end;
function TAndOrConstraint<T>.EvaluateAsOr(actual: T; negate: boolean): TEvalResult;
var
c: IConstraint<T>;
evalResult : TEvalResult;
begin
for c in FConstraints do begin
evalResult := c.Evaluate(actual, negate);
if evalResult.Status = TEvalResult.TEvalStatus.Pass then begin
Exit;
end;
end;
Result := evalResult;
end;
{ TConstraint }
constructor TValueConstraintOp.Create(c: IConstraint<TActualValue>);
begin
FConstraint := c;
end;
procedure TValueConstraintOp.Evaluate(actual: TActualValue; negate: boolean);
begin
RaiseTestError(FConstraint.Evaluate(actual, negate));
end;
class operator TValueConstraintOp.LogicalNot(c: TValueConstraintOp): TValueConstraintOp;
begin
Result.FConstraint := TNotConstraint<TActualValue>.Create(c.FConstraint);
end;
class operator TValueConstraintOp.LogicalOr(c1, c2: TValueConstraintOp): TValueConstraintOp;
begin
Result.FConstraint := TAndOrConstraint<TActualValue>.Create(c1.FConstraint, c2.FConstraint, false);
end;
class operator TValueConstraintOp.LogicalAnd(c1, c2: TValueConstraintOp): TValueConstraintOp;
begin
Result.FConstraint := TAndOrConstraint<TActualValue>.Create(c1.FConstraint, c2.FConstraint, true);
end;
{ TCallConstraintOp }
constructor TCallConstraintOp.Create(c: IConstraint<TActualCall>);
begin
FConstraint := c;
end;
procedure TCallConstraintOp.Evaluate(actual: TActualCall; negate: boolean);
begin
RaiseTestError(FConstraint.Evaluate(actual, negate));
end;
class operator TCallConstraintOp.LogicalNot(c: TCallConstraintOp): TCallConstraintOp;
begin
Result.FConstraint := TNotConstraint<TActualCall>.Create(c.FConstraint);
end;
class operator TCallConstraintOp.LogicalOr(c1, c2: TCallConstraintOp): TCallConstraintOp;
begin
Result.FConstraint := TAndOrConstraint<TActualCall>.Create(c1.FConstraint, c2.FConstraint, false);
end;
class operator TCallConstraintOp.LogicalAnd(c1,c2: TCallConstraintOp): TCallConstraintOp;
begin
Result.FConstraint := TAndOrConstraint<TActualCall>.Create(c1.FConstraint, c2.FConstraint, true);
end;
{ TMaybeEvalResult }
constructor TMaybeEvalResult.Create(EvalResult: TEvalResult);
begin
Self.Result := EvalResult;
end;
constructor TMaybeEvalResult.Create(fn: TMaybeSelector);
begin
System.Assert(Assigned(fn));
Self.Result := fn;
end;
function TMaybeEvalResult.Next(fn: TMaybeSelector): TMaybeEvalResult;
begin
if Self.Result.Status = TEvalResult.TEvalStatus.Pass then begin
Result.Result := fn;
end
else begin
Result := Self;
end;
end;
{ TActualValueProvider }
function TActualValueProvider.Call(supplier: TProc): TActualCall.TEvaluator;
begin
Result.FActual := TActualCall.Create;
Result.FActual.FFieldName := FFieldName;
Result.FActual.FCall := supplier;
end;
function TActualValueProvider.Val(value: TValue): TActualValue.TEvaluator;
begin
Result.FActual := TActualValue.Create;
Result.FActual.FFieldName := FFieldName;
Result.FActual.FData := value;
end;
function TActualValueProvider.Val<T>(value: T): TActualValue.TEvaluator;
var
valueType, refType: PTypeInfo;
begin
Result.FActual := TActualValue.Create;
Result.FActual.FFieldName := FFieldName;
valueType := System.TypeInfo(T);
refType := TypeInfo(TValue);
if valueType <> refType then begin
Result := Val(TValue.From(value));
end
else begin
Result := Val<T>(value);
end;
end;
procedure TActualValue.TEvaluator.Should(constraint: TValueConstraintOp);
begin
try
constraint.Evaluate(FActual, false);
finally
constraint.FConstraint := nil;
FActual.Free;
end;
end;
{ TActualCall.TEvaluator }
procedure TActualCall.TEvaluator.Should(constraint: TCallConstraintOp);
begin
try
constraint.Evaluate(FActual, false);
finally
constraint.FConstraint := nil;
FActual.Free;
end;
end;
end.
|
(*
* http 服务各种对象类
*)
unit http_objects;
interface
{$I in_iocp.inc}
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes,
System.SysUtils, System.StrUtils, Data.DB, {$ELSE}
Windows, Classes, SysUtils, StrUtils, DB, {$ENDIF}
iocp_Winsock2, iocp_base, iocp_senders, iocp_lists,
iocp_objPools, iocp_msgPacks, http_base, http_utils,
iocp_SHA1;
type
// ================ Http Session 类 ================
// Set-Cookie: InIOCP_SID=Value
THttpSession = class(TObject)
private
FExpires: Int64; // 生成 UTC 时间(读取速度快)
FTimeOut: Integer; // 超时时间(秒)
FCount: Integer; // 累计请求次数
public
function CheckAttack(const SessionId: AnsiString): Boolean;
function CreateSessionId: AnsiString;
function ValidateSession: Boolean;
procedure UpdateExpires;
public
class function Extract(const SetCookie: AnsiString; var SessionId: AnsiString): Boolean;
end;
// ================ Http Session 管理 类 ================
THttpSessionManager = class(TStringHash)
private
procedure CheckSessionEvent(var Data: Pointer);
protected
procedure FreeItemData(Item: PHashItem); override;
public
function CheckAttack(const SessionId: AnsiString): Boolean;
procedure DecRef(const SessionId: AnsiString);
procedure InvalidateSessions;
end;
// ================== Http 数据提供 组件类 ======================
THttpBase = class; // 基类
THttpRequest = class; // 请求
THttpResponse = class; // 响应
TOnAcceptEvent = procedure(Sender: TObject; Request: THttpRequest;
var Accept: Boolean) of object;
TOnInvalidSession = procedure(Sender: TObject; Request: THttpRequest;
Response: THttpResponse) of object;
TOnReceiveFile = procedure(Sender: TObject; Request: THttpRequest;
const FileName: String; Data: PAnsiChar;
DataLength: Integer; State: THttpPostState) of object;
// 请求事件(Sender 是 Worker)
THttpRequestEvent = procedure(Sender: TObject;
Request: THttpRequest;
Response: THttpResponse) of object;
// 升级为 WebSocket 的事件
TOnUpgradeEvent = procedure(Sender: TObject; const Origin: String;
var Accept: Boolean) of object;
THttpDataProvider = class(TComponent)
private
FSessionMgr: THttpSessionManager; // 全部 Session 管理
FMaxContentLength: Integer; // 请求实体的最大长度
FKeepAlive: Boolean; // 保存连接
FPeerIPList: TPreventAttack; // 客户端 IP 列表
FPreventAttack: Boolean; // IP列表(防攻击)
procedure CheckSessionState(Request: THttpRequest; Response: THttpResponse);
procedure SetMaxContentLength(const Value: Integer);
procedure SetPreventAttack(const Value: Boolean);
protected
FServer: TObject; // TInIOCPServer 服务器
FOnAccept: TOnAcceptEvent; // 是否接受请求
FOnDelete: THttpRequestEvent; // 请求:Delete
FOnGet: THttpRequestEvent; // 请求:Get
FOnPost: THttpRequestEvent; // 请求:Post
FOnPut: THttpRequestEvent; // 请求:Put
FOnOptions: THttpRequestEvent; // 请求:Options
FOnReceiveFile: TOnReceiveFile; // 接收文件事件
FOnTrace: THttpRequestEvent; // 请求:Trace
FOnUpgrade: TOnUpgradeEvent; // 升级为 WebSocket 事件
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClearIPList;
public
property SessionMgr: THttpSessionManager read FSessionMgr;
published
property KeepAlive: Boolean read FKeepAlive write FKeepAlive default True;
property MaxContentLength: Integer read FMaxContentLength write SetMaxContentLength default MAX_CONTENT_LENGTH;
property PreventAttack: Boolean read FPreventAttack write SetPreventAttack default False;
published
property OnAccept: TOnAcceptEvent read FOnAccept write FOnAccept;
property OnDelete: THttpRequestEvent read FOnDelete write FOnDelete;
property OnGet: THttpRequestEvent read FOnGet write FOnGet;
property OnPost: THttpRequestEvent read FOnPost write FOnPost;
property OnPut: THttpRequestEvent read FOnPut write FOnPut;
property OnOptions: THttpRequestEvent read FOnOptions write FOnOptions;
property OnReceiveFile: TOnReceiveFile read FOnReceiveFile write FOnReceiveFile;
property OnTrace: THttpRequestEvent read FOnTrace write FOnTrace;
end;
// ================ 客户端表单字段/参数 类 ================
THttpFormParams = class(TBasePack)
public // 公开常用属性(只读)
property AsBoolean[const Index: String]: Boolean read GetAsBoolean;
property AsDateTime[const Index: String]: TDateTime read GetAsDateTime;
property AsFloat[const Index: String]: Double read GetAsFloat;
property AsInteger[const Index: String]: Integer read GetAsInteger;
property AsString[const Index: String]: String read GetAsString;
end;
// ================ 请求报头的额外信息/参数 类 ================
THttpHeaderParams = class(THttpFormParams)
private
FOwner: THttpBase;
function GetBoundary: AnsiString;
function GetContentLength: Integer;
function GetContentType: THttpContentType;
function GetUTF8Encode: Boolean;
function GetKeepAlive: Boolean;
function GetMultiPart: Boolean;
function GetRange: AnsiString;
function GetIfMath: AnsiString;
function GetLastModified: AnsiString;
public
constructor Create(AOwner: THttpBase);
public
// 属性:报头常用
property Boundary: AnsiString read GetBoundary; // Content-Type: multipart/form-data; Boundary=
property ContentLength: Integer read GetContentLength; // Content-Length 的值
property ContentType: THttpContentType read GetContentType; // Content-Type 的值
property UTF8Encode: Boolean read GetUTF8Encode; // UTF-8...
property IfMath: AnsiString read GetIfMath; // if-math...
property LastModified: AnsiString read GetLastModified; // Last-Modified
property KeepAlive: Boolean read GetKeepAlive; // Keep-Alive...
property MultiPart: Boolean read GetMultiPart; // Content-Type:multipart/form-data
property Range: AnsiString read GetRange; // range
end;
// ================ Http 基类 ================
THttpBase = class(TObject)
private
FDataProvider: THttpDataProvider; // HTTP 支持
FOwner: TObject; // THttpSocket 对象
FContentSize: Int64; // 实体长度
FFileName: AnsiString; // 收到、发送到的文件名
FKeepAlive: Boolean; // 保持连接
FSessionId: AnsiString; // 对话期 ID
function GetSocketState: Boolean;
function GetHasSession: Boolean;
protected
FExtParams: THttpHeaderParams; // 请求 Headers 的额外参数/变量表
FStatusCode: Integer; // 状态代码
public
constructor Create(ADataProvider: THttpDataProvider; AOwner: TObject);
procedure Clear; virtual;
public
property HasSession: Boolean read GetHasSession;
property KeepAlive: Boolean read FKeepAlive;
property SessionId: AnsiString read FSessionId;
property SocketState: Boolean read GetSocketState;
property Owner: TObject read FOwner;
end;
// ================ Http 请求 ================
// 报头数组
PHeadersArray = ^THeadersArray;
THeadersArray = array[TRequestHeaderType] of AnsiString;
THttpRequest = class(THttpBase)
private
FAccepted: Boolean; // 接受请求
FAttacked: Boolean; // 被攻击
FByteCount: Integer; // 数据包长度
FHeadersAry: THeadersArray; // 报头数组(原始数据)
FParams: THttpFormParams; // 客户端表单的字段/参数/变量表
FStream: TInMemStream; // 变量/参数原始流
FContentType: THttpContentType; // 实体类型
FContentLength: Integer; // 实体长度
FMethod: THttpMethod; // 请求命令
FRequestURI: AnsiString; // 请求资源
FUpgradeState: Integer; // 升级为 WebSocket 的状态
FVersion: AnsiString; // 版本 http/1.1
function GetCompleted: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF}
function GetHeaderIndex(const Header: AnsiString): TRequestHeaderType; {$IFDEF USE_INLINE} inline; {$ENDIF}
function GetHeaders(Index: TRequestHeaderType): AnsiString;
procedure ExtractElements(Data: PAnsiChar; Len: Integer; RecvFileEvent: TOnReceiveFile);
procedure ExtractHeaders(Data: PAnsiChar; DataLength: Integer);
procedure ExtractMethod(var Data: PAnsiChar);
procedure ExtractParams(Data: PAnsiChar; Len: Integer; Decode: Boolean);
procedure InitializeInStream;
procedure URLDecodeRequestURI;
procedure WriteHeader(Index: TRequestHeaderType; const Content: AnsiString);
protected
procedure Decode(Sender: TBaseTaskSender; Response: THttpResponse; Data: PPerIOData);
public
constructor Create(ADataProvider: THttpDataProvider; AOwner: TObject);
destructor Destroy; override;
procedure Clear; override;
public
property Accepted: Boolean read FAccepted;
property Attacked: Boolean read FAttacked;
property Completed: Boolean read GetCompleted;
property Entity: TInMemStream read FStream; // 实体内容
property Headers[Index: TRequestHeaderType]: AnsiString read GetHeaders;
property Method: THttpMethod read FMethod;
property Params: THttpFormParams read FParams;
property URI: AnsiString read FRequestURI;
property UpgradeState: Integer read FUpgradeState;
property StatusCode: Integer read FStatusCode;
end;
// ================ 响应报头 类 ================
// 一般来说,响应报头内容不会很大(小于 IO_BUFFER_SIZE),
// 为加快速度,响应报头的内存直接引用发送器的 TPerIOData.Data,
// 用 Add 方法加入报头,用 Append 方法加入小页面的实体(总长 <= IO_BUFFER_SIZE)
THeaderArray = array[TResponseHeaderType] of Boolean;
THttpResponseHeaders = class(TObject)
private
FHeaders: THeaderArray; // 已加入的报头
FData: PWsaBuf; // 引用发送器缓存
FBuffer: PAnsiChar; // 发送缓存当前位置
FOwner: TServerTaskSender; // 数据发送器
function GetSize: Integer; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure InterAdd(const Content: AnsiString; SetCRLF: Boolean = True);
procedure SetOwner(const Value: TServerTaskSender);
public
procedure Clear;
procedure Add(Code: TResponseHeaderType; const Content: AnsiString = '');
procedure Append(const Content: AnsiString; SetCRLF: Boolean = True); overload;
procedure Append(var AHandle: THandle; ASize: Cardinal); overload;
procedure Append(var AStream: TStream; ASize: Cardinal); overload;
procedure Append(AList: TInStringList; ASize: Cardinal); overload;
procedure AddCRLF;
procedure ChunkDone;
procedure ChunkSize(ASize: Cardinal);
procedure SetStatus(Code: Integer);
public
property Size: Integer read GetSize;
property Owner: TServerTaskSender read FOwner write SetOwner;
end;
// ================ Http 响应 ================
THttpResponse = class(THttpBase)
private
FRequest: THttpRequest; // 引用请求
FHeaders: THttpResponseHeaders; // 服务器状态、报头
FContent: TInStringList; // 列表式实体内容
FHandle: THandle; // 要发送的文件
FStream: TStream; // 要发送的数据流
FSender: TBaseTaskSender; // 任务发送器
FContentType: AnsiString; // 内容类型
FGZipStream: Boolean; // 是否压缩流
FLastWriteTime: Int64; // 文件最后修改时间
FWorkDone: Boolean; // 发送结果完毕
function GetFileETag: AnsiString;
function GZipCompress(Stream: TStream): TStream;
procedure AddHeaderList(SendNow: Boolean);
procedure AddDataPackets;
procedure FreeResources;
procedure SendChunkHeaders(const ACharSet: AnsiString = '');
protected
// 正式发送数据
procedure SendWork;
procedure Upgrade;
public
constructor Create(ADataProvider: THttpDataProvider; AOwner: TObject);
destructor Destroy; override;
// 清空资源
procedure Clear; override;
// Session:新建、删除
procedure CreateSession;
procedure RemoveSession;
// 设置状态、报头
procedure SetStatus(Code: Integer);
procedure AddHeader(Code: TResponseHeaderType; const Content: AnsiString = '');
// 设置实体
procedure SetContent(const Content: AnsiString);
procedure AddContent(const Content: AnsiString);
// 立刻分块发送(优化,自动发送结束标志)
procedure SendChunk(Stream: TStream);
// 设置发送源:数据流、文件
procedure SendStream(Stream: TStream; Compress: Boolean = False);
procedure TransmitFile(const FileName: String; AutoView: Boolean = True);
// 发送 JSON
procedure SendJSON(DataSet: TDataSet; CharSet: THttpCharSet = hcsDefault); overload;
procedure SendJSON(const JSON: AnsiString); overload;
// 设置 Head 信息
procedure SetHead;
// 重定位
procedure Redirect(const URL: AnsiString);
public
property ContentType: AnsiString read FContentType;
property StatusCode: Integer read FStatusCode write FStatusCode;
end;
implementation
uses
iocp_log, iocp_varis, iocp_utils,
iocp_server, iocp_managers, iocp_sockets, iocp_zlib;
type
TBaseSocketRef = class(TBaseSocket);
{ THttpSession }
function THttpSession.CheckAttack(const SessionId: AnsiString): Boolean;
var
TickCount: Int64;
begin
// 10 秒内出现 10 个请求,当作攻击, 15 分钟内禁止连接
// 用 httptest.exe 测试成功。
TickCount := GetUTCTickCount;
if (FExpires > TickCount) then // 攻击过,未解禁
Result := True
else begin
Result := (FCount >= 10) and (TickCount - FExpires <= 10000);
if Result then // 是攻击
begin
FExpires := TickCount + 900000; // 900 秒
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('THttpSession.CheckAttack->拒绝服务,攻击对话期:' + SessionId);
{$ENDIF}
end else
FExpires := TickCount;
Inc(FCount);
end;
end;
function THttpSession.CreateSessionId: AnsiString;
const
// BASE_CHARS 长 62
BASE_CHARS = AnsiString('0123456789aAbBcCdDeEfFgGhHiIjJ' +
'kKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ');
var
i: Integer;
begin
Randomize;
Result := Copy(BASE_CHARS, 1, 32); // 32 字节
for i := 1 to 32 do // 总长 32
Result[i] := BASE_CHARS[Random(62) + 1]; // 1 <= Random < 62
FExpires := GetUTCTickCount; // 当前时间
FTimeOut := 300; // 300 秒超时
end;
class function THttpSession.Extract(const SetCookie: AnsiString; var SessionId: AnsiString): Boolean;
var
pa, p2: PAnsiChar;
begin
// 提取 SetCookie 的 SessionId
pa := PAnsiChar(SetCookie);
p2 := pa;
if SearchInBuffer(p2, Length(SetCookie), HTTP_SESSION_ID) then
begin
SessionId := Copy(SetCookie, Integer(p2 - pa) + 2, 32); // 32 字节
Result := (SessionId <> '');
end else
begin
SessionId := '';
Result := False;
end;
end;
procedure THttpSession.UpdateExpires;
begin
// 延迟生命期
FExpires := GetUTCTickCount; // 当前时间
end;
function THttpSession.ValidateSession: Boolean;
begin
// 检查是否有效
Result := (GetUTCTickCount - FExpires) <= FTimeOut * 1000;
end;
{ THttpSessionManager }
procedure THttpSessionManager.CheckSessionEvent(var Data: Pointer);
var
Session: THttpSession;
begin
// 回调:检查 Session 是否有效
Session := THttpSession(Data);
if (Session.ValidateSession = False) then
try
Session.Free;
finally
Data := Nil;
end;
end;
procedure THttpSessionManager.DecRef(const SessionId: AnsiString);
var
Session: THttpSession;
begin
// 减少 SessionId 引用
if (SessionId <> '') and (SessionId <> HTTP_INVALID_SESSION) then
begin
Lock;
try
Session := ValueOf2(SessionId);
if Assigned(Session) and (Session.FCount > 0) then
Dec(Session.FCount);
finally
UnLock;
end;
end;
end;
function THttpSessionManager.CheckAttack(const SessionId: AnsiString): Boolean;
var
Session: THttpSession;
begin
// 检查是否为 SessionId 攻击(短时间大量使用)
Lock;
try
Session := ValueOf2(SessionId);
Result := Assigned(Session) and Session.CheckAttack(SessionId);
finally
UnLock;
end;
end;
procedure THttpSessionManager.FreeItemData(Item: PHashItem);
begin
// 释放 Session 对象
try
THttpSession(Item^.Value).Free;
finally
Item^.Value := Nil;
end;
end;
procedure THttpSessionManager.InvalidateSessions;
begin
// 检查全部 Session 的状态
// 删除过期的 Session
Lock;
try
Scan(CheckSessionEvent);
finally
Unlock;
end;
end;
{ THttpDataProvider }
procedure THttpDataProvider.CheckSessionState(Request: THttpRequest; Response: THttpResponse);
var
Session: THttpSession;
Item: PPHashItem;
begin
// 检查客户端 Session 在服务端的状态
// 从 FSessionMgr 中查找客户端 SessionId 对应的 THttpSession
FSessionMgr.Lock;
try
Session := FSessionMgr.ValueOf3(Request.FSessionId, Item);
if (Assigned(Session) = False) then // 没有
Request.FSessionId := ''
else
if Session.ValidateSession then // 有效
begin
Response.FSessionId := Request.FSessionId; // 方便操作界面判断
Session.UpdateExpires; // 生命期延后
end else
begin
Request.FSessionId := '';
FSessionMgr.Remove2(Item);
end;
finally
FSessionMgr.UnLock;
end;
end;
procedure THttpDataProvider.ClearIPList;
begin
// 清除 IP 列表内容
if Assigned(FPeerIPList) then
TPreventAttack(FPeerIPList).Clear;
end;
constructor THttpDataProvider.Create(AOwner: TComponent);
begin
inherited;
FKeepAlive := True; // 默认值
FMaxContentLength := MAX_CONTENT_LENGTH;
FPreventAttack := False;
FSessionMgr := THttpSessionManager.Create(512);
end;
destructor THttpDataProvider.Destroy;
begin
if Assigned(FPeerIPList) then
FPeerIPList.Free;
FSessionMgr.Free;
inherited;
end;
procedure THttpDataProvider.SetMaxContentLength(const Value: Integer);
begin
if (Value <= 0) then
FMaxContentLength := MAX_CONTENT_LENGTH
else
FMaxContentLength := Value;
end;
procedure THttpDataProvider.SetPreventAttack(const Value: Boolean);
begin
FPreventAttack := Value;
if not (csDesigning in ComponentState) then
if FPreventAttack then
FPeerIPList := TPreventAttack.Create
else
if Assigned(FPeerIPList) then
FPeerIPList.Free;
end;
{ THttpHeaderParams }
constructor THttpHeaderParams.Create(AOwner: THttpBase);
begin
inherited Create;
FOwner := AOwner;
end;
function THttpHeaderParams.GetBoundary: AnsiString;
begin
Result := inherited AsString['BOUNDARY'];
end;
function THttpHeaderParams.GetContentLength: Integer;
begin
Result := inherited AsInteger['CONTENT-LENGTH'];
end;
function THttpHeaderParams.GetContentType: THttpContentType;
begin
Result := THttpContentType(inherited AsInteger['CONTENT-TYPE']);
end;
function THttpHeaderParams.GetUTF8Encode: Boolean;
begin
Result := inherited AsBoolean['UTF8-ENCODE'];
end;
function THttpHeaderParams.GetIfMath: AnsiString;
begin
Result := inherited AsString['IF-MATH'];
end;
function THttpHeaderParams.GetKeepAlive: Boolean;
begin
Result := inherited AsBoolean['KEEP-ALIVE'];
end;
function THttpHeaderParams.GetLastModified: AnsiString;
begin
Result := inherited AsString['LAST-MODIFIED'];
end;
function THttpHeaderParams.GetMultiPart: Boolean;
begin
Result := inherited AsBoolean['MULTIPART'];
end;
function THttpHeaderParams.GetRange: AnsiString;
begin
Result := inherited AsString['RANGE'];
end;
{ THttpBase }
procedure THttpBase.Clear;
begin
// 清空资源:变量,数值
FContentSize := 0;
FFileName := '';
FSessionId := '';
FStatusCode := 200; // 默认
end;
constructor THttpBase.Create(ADataProvider: THttpDataProvider; AOwner: TObject);
begin
inherited Create;
FDataProvider := ADataProvider; // HTTP 支持
FOwner := AOwner; // THttpSocket 对象
end;
function THttpBase.GetSocketState: Boolean;
begin
Result := THttpSocket(FOwner).SocketState;
end;
function THttpBase.GetHasSession: Boolean;
begin
Result := (FSessionId <> ''); // 合法时才不为空
end;
{ THttpRequest }
procedure THttpRequest.Clear;
var
i: TRequestHeaderType;
begin
inherited;
FAttacked := False;
FContentLength := 0; // 下次要比较
FContentType := hctUnknown;
for i := rqhHost to High(FHeadersAry) do
Delete(FHeadersAry[i], 1, Length(FHeadersAry[i]));
Delete(FRequestURI, 1, Length(FRequestURI)); // 无
Delete(FVersion, 1, Length(FVersion)); // 版本
FParams.Clear;
FExtParams.Clear;
FStream.Clear;
end;
constructor THttpRequest.Create(ADataProvider: THttpDataProvider; AOwner: TObject);
begin
inherited;
FExtParams := THttpHeaderParams.Create(Self);
FParams := THttpFormParams.Create;
FStream := TInMemStream.Create;
end;
procedure THttpRequest.Decode(Sender: TBaseTaskSender; Response: THttpResponse; Data: PPerIOData);
var
Buf: PAnsiChar;
begin
// 解码:分析、提取请求信息
// 1. 任务完成 -> 开始新任务
// 2. 任务未接收完成,继续接收
Response.FRequest := Self; // 引用
Response.FExtParams := FExtParams; // 引用参数表
Response.FSender := Sender; // 引用数据发送器
// 设置报头缓存,把报头对象和发送器关联起来
Response.FHeaders.Owner := TServerTaskSender(Sender);
Buf := Data^.Data.buf; // 开始地址
FByteCount := Data^.Overlapped.InternalHigh; // 数据包长度
if Completed then // 新的请求
begin
// 提取命令行信息(可能带参数)
ExtractMethod(Buf);
if (FMethod > hmUnknown) and (FRequestURI <> '') and (FStatusCode = 200) then
begin
// 分析报头 Headers( Buf 已移到第 2 行的首位置)
ExtractHeaders(Buf, Integer(Data^.Overlapped.InternalHigh) -
Integer(Buf - Data^.Data.buf));
// 复制 FKeepAlive
Response.FKeepAlive := FKeepAlive;
// URI 解码, 提取 GET 请求的参数表
if (FMethod = hmGet) then
URLDecodeRequestURI;
if (FSessionId <> '') then // 检查 FSessionId 是否有效
FDataProvider.CheckSessionState(Self, Response);
// 调用事件:是否允许请求
if Assigned(FDataProvider.FOnAccept) then
FDataProvider.FOnAccept(THttpSocket(FOwner).Worker,
Self, FAccepted);
if (FAccepted = False) then // 禁止请求
begin
FStatusCode := 403; // 403: Forbidden
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog(THttpSocket(FOwner).PeerIPPort +
'->拒绝请求 ' + METHOD_LIST[FMethod] + ' ' +
FRequestURI + ', 状态=' + IntToStr(FStatusCode));
{$ENDIF}
end else
if (FUpgradeState = 15) then // 检查是否要升级为 WebSocket, 15=8+4+2+1
begin
if Assigned(FDataProvider.FOnUpgrade) then // 是否允许升级
FDataProvider.FOnUpgrade(Self, FHeadersAry[rqhOrigin], FAccepted);
if (FAccepted = False) then
begin
FStatusCode := 406; // 406 Not Acceptable
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog(THttpSocket(FOwner).PeerIPPort + '->拒绝请求升级为 WebSocket.');
{$ENDIF}
end;
Exit;
end;
end else
begin
FAccepted := False;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog(THttpSocket(FOwner).PeerIPPort +
'->错误的请求 ' + METHOD_LIST[FMethod] + ' ' +
FRequestURI + ', 状态=' + IntToStr(FStatusCode));
{$ENDIF}
end;
end else
if FAccepted then // 上传数据包,接收
begin
Inc(FContentSize, FByteCount); // 接收总数 +
FStream.Write(Buf^, FByteCount); // 写入流
end;
if (FStatusCode > 200) then
begin
FExtParams.Clear;
FStream.Clear;
end else // 接收数据完毕
if FAccepted and Completed and (FStream.Size > 0) then
if (FMethod = hmPost) and (FContentType <> hctUnknown) then
try
if FExtParams.MultiPart then // 提取表单字段
ExtractElements(FStream.Memory, FStream.Size, FDataProvider.FOnReceiveFile)
else // 提取普通变量/参数
ExtractParams(FStream.Memory, FStream.Size, True);
finally
FStream.Clear;
end;
end;
destructor THttpRequest.Destroy;
begin
FParams.Free;
FExtParams.Free;
FStream.Free;
inherited;
end;
procedure THttpRequest.ExtractElements(Data: PAnsiChar; Len: Integer;
RecvFileEvent: TOnReceiveFile);
var
IgnoreSearch: Boolean;
EleBuf, EleBuf2, TailBuf: PAnsiChar;
FldType, FldType2: TFormElementType;
Boundary, EleValue, EleValue2: AnsiString;
begin
// 提取实体类型为 multipart/form-data 的字段/参数,加入 FParams
// ---------------------Boundary
// Content-Disposition: form-data; name="textline2"; filename="测试.txt"
// <Empty Line>
// Value Text
// ---------------------Boundary--
// multipart/form-data类型 Form:
// 不对字符编码。在使用包含文件上传控件的表单时,必须使用该类型。
// 字段描述:1、普通内容,无 Content-Type
// 2、文件内容:Content-Type: text/plain
try
EleBuf := Nil; // 字段内容开始
TailBuf := PAnsiChar(Data + Len);
// 传输实际内容时要在前面加 '--', 全部字段内容结束时再在末尾加 '--'
Boundary := '--' + FExtParams.Boundary;
FldType := fdtUnknown;
FldType2 := fdtUnknown;
IgnoreSearch := False;
while IgnoreSearch or
SearchInBuffer(Data, TailBuf - Data, Boundary) do
if (Data^ in [#13, '-']) then // 分隔标志或末尾
begin
if (EleBuf = Nil) then // 字段开始,分析描述,定位内容位置
begin
// 跳过回车换行
Inc(Data, 2);
// 下次要查询 Boundary
IgnoreSearch := False;
// 关键的描述缺少时继续循环
if (SearchInBuffer2(Data, 40, 'FORM-DATA') = False) then
begin
FStatusCode := 417; // 不符预期:Expectation Failed
Break;
end;
// 定位内容位置:描述之后第一个连续出现的两空行(STR_CRLF2)
EleBuf2 := Data;
if SearchInBuffer(Data, TailBuf - Data, STR_CRLF2) then
begin
EleBuf := Data;
Data := EleBuf2;
end else
begin
FStatusCode := 417; // 不符预期:Expectation Failed
Break;
end;
// 已经定位到 FORM-DATA 后一字节,确定字段类型是否为文件
FldType := ExtractFieldInf(Data, Integer(EleBuf - Data), EleValue); // name="xxx",xxx 不能太长
FldType2 := ExtractFieldInf(Data, Integer(EleBuf - Data), EleValue2);
Data := EleBuf; // 到内容位置
if (FldType = fdtUnknown) and (FldType2 = fdtUnknown) then
begin
FStatusCode := 417; // 不符预期:Expectation Failed
Break;
end;
if (FldType2 = fdtFileName) then // 文件
begin
FFileName := EleValue2;
FldType := fdtName;
end else
if (FldType = fdtFileName) then // 文件,变量值互换
begin
FFileName := EleValue;
EleValue := EleValue2;
FldType2 := fdtFileName; // 修改!
end;
end else
begin
// 当前字段内容结束、新字段内容开始,回退到前字段的结束位置
EleBuf2 := PAnsiChar(Data - Length(Boundary));
if (FldType2 = fdtFileName) then
begin
// 文件类型字段:如果名称不为空(可能内容为空),则调用外部事件
try
FParams.SetAsString(EleValue, FFileName);
if (FFileName <> '') then
if Assigned(RecvFileEvent) then
begin
// 执行一次请求
RecvFileEvent(THttpSocket(FOwner).Worker, THttpRequest(Self),
FFileName, Nil, 0, hpsRequest);
RecvFileEvent(THttpSocket(FOwner).Worker, THttpRequest(Self),
FFileName, EleBuf, LongWord(EleBuf2 - EleBuf) - 2,
hpsRecvData);
end;
finally
Delete(FFileName, 1, Length(FFileName));
end;
end else
if (FldType = fdtName) then
begin
// 数值类型字段:加入变量表
if (EleBuf^ in [#13, #10]) then // 空值
FParams.SetAsString(EleValue, '')
else begin
// 复制数据内容(没编码,回退2字节)
SetString(EleValue2, EleBuf, Longword(EleBuf2 - EleBuf) - 2);
FParams.SetAsString(EleValue, EleValue2);
end;
end else
begin
FStatusCode := 417; // 异常
Break;
end;
// 遇到结束标志:Boundary--
if ((Data^ = '-') and ((Data + 1)^ = '-')) then
Break;
// 准备下一字段
EleBuf := nil;
IgnoreSearch := True;
end;
end;
except
on E: Exception do
begin
FStatusCode := 500;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('THttpBase.ExtractElements->' + E.Message);
{$ENDIF}
end;
end;
end;
procedure THttpRequest.ExtractHeaders(Data: PAnsiChar; DataLength: Integer);
var
i, k, iPos: Integer;
p: PAnsiChar;
Header, HeaderValue: AnsiString;
begin
// 格式:
// Accept: image/gif.image/jpeg,*/*
// Accept-Language: zh-cn
// Referer: <a href="http://www.google.cn/">http://www.google.cn/</a>
// Connection: Keep-Alive
// Host: localhost
// User-Agent: Mozila/4.0(compatible;MSIE5.01;Window NT5.0)
// Accept-Encoding: gzip,deflate
// Content-Type: text/plain
// application/x-www-form-urlencoded
// multipart/form-data; boundary=---------------------------7e119f8908f8
// Content-Length: 21698
// Cookie: ...
//
// Body...
// 1、application/x-www-form-urlencoded:
// 在发送前编码所有字符(默认),空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值。
// 正文:
// textline=&textline2=%D2%BB%B8%F6%CE%C4%B1%BE%A1%A3++a&onefile=&morefiles='
// 2、text/plain: 每字段一行,不对特殊字符编码。
// 正文(IE、Chrome):
// textline=#13#10textline2=一个文本。 a#13#10onefile=#13#10morefiles=#13#10
FAttacked := False; // 非攻击
FAccepted := True; // 默认接受请求
FContentLength := 0; // 实体长度
FContentType := hctUnknown; // 实体类型
FKeepAlive := False; // 默认不保持连接
FUpgradeState := 0; // 清0, 不升级为 WebSocket
i := 0; // 开始位置
k := 0; // 行首位置
iPos := 0; // 分号位置
p := Data; // 指针位置
while i < DataLength do
begin
case p^ of
CHAR_SC:
if (iPos = 0) then // 第一个分号 :
iPos := i;
CHAR_CR,
CHAR_LF: // 行结束
if (iPos > 0) then
begin
// 取参数、值
SetString(Header, Data + k, iPos - k);
SetString(HeaderValue, Data + iPos + 1, i - iPos - 1);
// 保存 Header 到数组:AnsiString -> String
WriteHeader(GetHeaderIndex(UpperCase(Header)), Trim(HeaderValue));
// 出现异常
if (FStatusCode > 200) then
Exit;
k := i + 1; // 下行首位置
iPos := 0;
if ((p + 1)^ = CHAR_LF) then // 前进 1 字节,到行尾
begin
Inc(k); // 下行首位置
Inc(i);
Inc(p);
if ((p + 1)^ = CHAR_CR) then // 进入实体 Body
begin
Dec(DataLength, i + 3); // 减 3
if (DataLength > 0) then // 有实体内容
begin
if (FContentLength > 0) then
InitializeInStream;
if (DataLength <= FContentLength) then
FContentSize := DataLength
else
FContentSize := FContentLength;
FStream.Write((p + 3)^, FContentSize);
end;
Break;
end;
end;
end;
end;
Inc(i);
Inc(p);
end;
// 未收到实体内容,预设空间
if (FContentLength > 0) and (FStream.Size = 0) then // 预设空间
InitializeInStream;
end;
procedure THttpRequest.ExtractMethod(var Data: PAnsiChar);
function CheckMethod(const S: AnsiString): THttpMethod;
var
i: THttpMethod;
begin
// 检查命令是否合法
for i := hmGet to High(METHOD_LIST) do
if (S = METHOD_LIST[i]) then
begin
Result := i;
Exit;
end;
Result := hmUnknown;
end;
var
i, iPos: Integer;
Method: AnsiString;
p: PAnsiChar;
begin
// 分析请求方法、URI和版本号
// 格式:GET /sn/index.php?user=aaa&password=ppp HTTP/1.1
FMethod := hmUnknown; // 未知
FRequestURI := ''; // 无
FStatusCode := 200; // 状态
iPos := 0; // 空格(内容开始)位置
p := Data; // 指针位置
for i := 0 to FByteCount - 1 do // 遍历内容
begin
case p^ of
CHAR_CR, CHAR_LF: begin // 回车换行,首行结束
SetString(FVersion, Data + iPos + 1, i - iPos - 1);
Break; // 第一行分析完毕
end;
CHAR_SP, CHAR_TAB: // 空格,TAB
if (iPos = 0) then // 请求命令结束,取请求 GET, POST...
begin
if (i < 8) then // = Length('CONNECT') + 1
begin
SetString(Method, Data, i);
FMethod := CheckMethod(UpperCase(Method));
end;
if (FMethod = hmUnknown) then
begin
FStatusCode := 400; // 错误的请求
Break;
end else
iPos := i; // 下一内容的开始位置
end else
if (FRequestURI = '') then // URI 结束,取 URI
begin
SetString(FRequestURI, Data + iPos + 1, i - iPos - 1);
iPos := i; // 下一内容的开始位置
end;
end;
Inc(p); // 下一字符
end;
// 支持版本: 1.0, 1.1
if (FVersion <> HTTP_VER1) and (FVersion <> HTTP_VER) then
FStatusCode := 505
else begin
if (p^ = CHAR_CR) then // 前进,到下一行首
Inc(p, 2);
Data := p; // Data 指向下行首
end;
end;
procedure THttpRequest.ExtractParams(Data: PAnsiChar; Len: Integer; Decode: Boolean);
var
i: Integer;
Buf: PAnsiChar;
Param, Value: AnsiString;
begin
// 分析参数或表单字段(要知道编码)
// 不编码:1、user=aaa&password=ppp&No=123
// 2、textline=#13#10textline2=一个文本。 a#13#10onefile=#13#10morefiles=#13#10
// 默认编码:textline=&textline2=%D2%BB%B8%F6%CE%C4%B1%BE%A1%A3++a&onefile=&morefiles='
Buf := Data;
for i := 1 to Len do // 末尾已经预设为"&"
begin
case Data^ of
'=': begin // 参数名称
SetString(Param, Buf, Data - Buf);
Buf := Data + 1; // 到下一字节
end;
'&', #13: // 参数值,加入参数
if (Param <> '') then
begin
if (Buf = Data) then // 值为空
FParams.SetAsString(Param, '')
else begin
// 非空值(hctMultiPart 类型时不在此处理)
SetString(Value, Buf, Data - Buf);
// 字符集转换
if Decode then
if FExtParams.UTF8Encode then // TNetHttpClient:UTF-8 编码
Value := System.UTF8Decode(Value)
else
if (FContentType = hctUrlEncoded) then // hctUrlEncoded 表单不是 UTF-8 编码
Value := DecodeHexText(Value);
// 加入参数
FParams.SetAsString(Param, Value);
end;
// 推进
if (Data^ = #13) then // 回车
begin
Buf := Data + 2;
Inc(Data, 2);
end else
begin
Buf := Data + 1;
Inc(Data);
end;
// 清 Param
Delete(Param, 1, Length(Param));
end;
end;
// 推进
Inc(Data);
end;
end;
function THttpRequest.GetCompleted: Boolean;
begin
// 判断是否接收完毕
Result := (FContentLength = 0) or (FContentSize >= FContentLength);
end;
function THttpRequest.GetHeaderIndex(const Header: AnsiString): TRequestHeaderType;
var
i: TRequestHeaderType;
begin
// 查找 Header 在数组 REQUEST_HEADERS 的位置
for i := rqhHost to High(TRequestHeaderType) do
if (REQUEST_HEADERS[i] = Header) then
begin
Result := i;
Exit;
end;
Result := rqhUnknown;
end;
function THttpRequest.GetHeaders(Index: TRequestHeaderType): AnsiString;
begin
Result := FHeadersAry[Index];
end;
procedure THttpRequest.InitializeInStream;
begin
// 初始化 FStream 空间
if (FContentType = hctUnknown) then // hctUnknown 时末尾不加 &
FStream.Initialize(FContentLength)
else begin // 末尾 + &
FStream.Initialize(FContentLength + 1);
PAnsiChar(PAnsiChar(FStream.Memory) + FContentLength)^ := AnsiChar('&');
end;
end;
procedure THttpRequest.URLDecodeRequestURI;
var
i, k: Integer;
ParamList: AnsiString;
begin
// URL 解码,提取参数
// 分离出 GET 请求的参数表:/aaa/ddd.jsp?code=111&name=WWW
// 可能为 UFT-8,UFT-16
if (Pos(AnsiChar('%'), FRequestURI) > 0) then
begin
ParamList := DecodeHexText(FRequestURI);
if CheckUTFEncode(ParamList, k) then // ParamList 可能是 UTF,中文“一”特殊,歧义?
begin
FRequestURI := System.UTF8Decode(ParamList);
if (Length(FRequestURI) <> k) then // 有特殊字符
FRequestURI := ParamList;
end else
FRequestURI := ParamList;
end;
i := Pos(AnsiChar('?'), FRequestURI);
if (i > 0) then
begin
k := Length(FRequestURI) - i + 1;
SetLength(ParamList, k); // 多一个字节
System.Move(FRequestURI[i + 1], ParamList[1], k - 1);
ParamList[k] := AnsiChar('&'); // 末尾设为 &
ExtractParams(PAnsiChar(ParamList), k, False); // 提取参数表
Delete(FRequestURI, i, Length(FRequestURI));
end;
end;
procedure THttpRequest.WriteHeader(Index: TRequestHeaderType; const Content: AnsiString);
var
i: Int64;
ItemValue: AnsiString;
begin
// 保存 Content 到报头数组
FHeadersAry[Index] := Content;
// 根据情况增加额外的变量/参数
case Index of
rqhAcceptCharset: // TNetHttpClient
FExtParams.SetAsBoolean('UTF8-ENCODE', Pos('UTF-8', UpperCase(Content)) > 0);
rqhContentLength:
// Content-Length: 增设长度变量, 文件太大时,IE < 0, Chrome 正常
if (TryStrToInt64(Content, i) = False) then
FStatusCode := 417 // 417 Expectation Failed
else
if (i < 0) or (i > FDataProvider.FMaxContentLength) then
begin
FStatusCode := 413; // 内容太长:413 Request Entity Too Large
FExtParams.SetAsInteger('CONTENT-LENGTH', 0);
end else
begin
// 10 秒内同一 IP 出现 3 个 >= 10M 的请求,当作恶意
if (i >= 10240000) and Assigned(FDataProvider.FPeerIPList) then
FAttacked := FDataProvider.FPeerIPList.CheckAttack(THttpSocket(FOwner).PeerIP, 10000, 3)
else
FAttacked := False;
if FAttacked then // 恶意的
FStatusCode := 403 // 403 Forbidden
else begin
FContentLength := i; // 返回长度 i
FExtParams.SetAsInt64('CONTENT-LENGTH', i);
end;
end;
rqhConnection: // Connection: Upgrade、Keep-Alive
if (UpperCase(Content) = 'UPGRADE') then // 支持 WebSocket
begin
FUpgradeState := FUpgradeState xor 1;
FKeepAlive := True;
end else
if (UpperCase(Content) = 'KEEP-ALIVE') then
begin
FKeepAlive := FDataProvider.FKeepAlive;
FExtParams.SetAsBoolean('KEEP-ALIVE', FKeepAlive);
end else
FExtParams.SetAsBoolean('KEEP-ALIVE', False);
rqhContentType: begin
// Content-Type: text/plain
// application/x-www-form-urlencoded
// multipart/form-data; boundary=...
// 增设三个变量:CONTENT-TYPE、MULTIPART、BOUNDARY
ItemValue := LowerCase(Content);
if (FMethod = hmGet) then
begin
if (Pos('%', FRequestURI) > 0) then
begin
FContentType := hctUrlEncoded;
FExtParams.SetAsInteger('CONTENT-TYPE', Integer(hctUrlEncoded));
end;
if (Pos('utf-8', ItemValue) > 1) then
FExtParams.SetAsBoolean('UTF8-ENCODE', True);
end else
if (ItemValue = 'text/plain') then
begin
FContentType := hctTextPlain;
FExtParams.SetAsString('BOUNDARY', '');
FExtParams.SetAsInteger('CONTENT-TYPE', Integer(hctTextPlain));
FExtParams.SetAsBoolean('MULTIPART', False);
end else
if (Pos('application/x-www-form-urlencoded', ItemValue) = 1) then
begin
FContentType := hctUrlEncoded;
FExtParams.SetAsString('BOUNDARY', '');
FExtParams.SetAsInteger('CONTENT-TYPE', Integer(hctUrlEncoded));
FExtParams.SetAsBoolean('MULTIPART', False);
end else
if (Pos('multipart/form-data', ItemValue) = 1) then
begin
FStatusCode := 417; // 不符预期
i := PosEx('=', Content, 28);
if (i >= 29) then // multipart/form-data; boundary=...
begin
ItemValue := Copy(Content, i + 1, 999);
if (ItemValue <> '') then
begin
FContentType := hctMultiPart;
FExtParams.SetAsString('BOUNDARY', ItemValue);
FExtParams.SetAsInteger('CONTENT-TYPE', Integer(hctMultiPart));
FExtParams.SetAsBoolean('MULTIPART', True);
FStatusCode := 200;
end;
end;
end else
begin
// 当作普通数据流,无参数
FContentType := hctUnknown;
FExtParams.SetAsInteger('CONTENT-TYPE', Integer(hctUnknown));
end;
end;
rqhCookie: // 提取 Cookie 信息
if THttpSession.Extract(Content, ItemValue) then
begin
FAttacked := FDataProvider.FSessionMgr.CheckAttack(ItemValue);
if FAttacked then // 被用 SessionId 攻击
FAccepted := False
else // SessionId 有效
if (ItemValue <> HTTP_INVALID_SESSION) then
FSessionId := ItemValue;
end;
rqhIfMatch,
rqhIfNoneMatch:
FExtParams.SetAsString('IF_MATCH', Copy(Content, 2, Length(Content) - 2));
rqhIfRange: begin // 断点下载
ItemValue := Copy(Content, 2, Length(Content) - 2);
FExtParams.SetAsString('IF_MATCH', ItemValue);
FExtParams.SetAsString('IF_RANGE', ItemValue);
end;
rqhRange: // 断点下载
FExtParams.SetAsString('RANGE', Content);
rqhIfModifiedSince,
rqhIfUnmodifiedSince:
FExtParams.SetAsString('LAST_MODIFIED', Content);
rqhUserAgent: // 'Mozilla/4.0 (compatible; MSIE 8.0; ...
if Pos('MSIE ', Content) > 0 then
FExtParams.SetAsBoolean('MSIE', True);
// 支持 WebSocket
// Connection: Upgrade
// Upgrade: websocket
// Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
// Sec-WebSocket-Protocol: chat, superchat
// Sec-WebSocket-Version: 13
// Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
// Origin: http://example.com
rqhUpgrade: // 升级到 WebSocket
if (UpperCase(Content) = 'WEBSOCKET') then
FUpgradeState := FUpgradeState xor 2;
rqhWebSocketKey:
if (Length(Content) > 0) then
FUpgradeState := FUpgradeState xor 4;
rqhWebSocketVersion:
if (Content = '13') then
FUpgradeState := FUpgradeState xor 8;
end;
end;
{ THttpResponseHeaders }
procedure THttpResponseHeaders.Add(Code: TResponseHeaderType; const Content: AnsiString);
begin
// 增加报头信息
if (Code = rshUnknown) then // 自定义
begin
if (Content <> '') then // 空时忽略
InterAdd(Content);
end else
if (FHeaders[Code] = False) then
begin
FHeaders[Code] := True;
case Code of
rshDate:
InterAdd(RESPONSE_HEADERS[Code] + CHAR_SC2 + GetHttpGMTDateTime);
rshServer:
InterAdd(RESPONSE_HEADERS[Code] + CHAR_SC2 + HTTP_SERVER_NAME);
else
InterAdd(RESPONSE_HEADERS[Code] + CHAR_SC2 + Content);
end;
end;
end;
procedure THttpResponseHeaders.AddCRLF;
begin
// 加回车换行
PStrCRLF(FBuffer)^ := STR_CRLF;
Inc(FBuffer, 2);
Inc(FData^.len, 2);
end;
procedure THttpResponseHeaders.Append(var AHandle: THandle; ASize: Cardinal);
begin
// 追加文件内容(实体)
try
ReadFile(AHandle, FBuffer^, ASize, ASize, Nil);
Inc(FBuffer, ASize);
Inc(FData^.len, ASize);
finally
CloseHandle(AHandle);
AHandle := 0; // 必须,否则清资源时异常
end;
end;
procedure THttpResponseHeaders.Append(var AStream: TStream; ASize: Cardinal);
begin
// 追加数据流(实体)
try
AStream.Read(FBuffer^, ASize);
Inc(FBuffer, ASize);
Inc(FData^.len, ASize);
finally
AStream.Free;
AStream := nil; // 必须,否则清资源时异常
end;
end;
procedure THttpResponseHeaders.Append(AList: TInStringList; ASize: Cardinal);
var
i: Integer;
S: AnsiString;
begin
// 追加列表内容(实体)
try
for i := 0 to AList.Count - 1 do
begin
S := AList.Strings[i];
System.Move(S[1], FBuffer^, Length(S));
Inc(FBuffer, Length(S));
end;
Inc(FData^.len, ASize);
finally
AList.Clear;
end;
end;
procedure THttpResponseHeaders.Append(const Content: AnsiString; SetCRLF: Boolean);
begin
// 加入字符串(一行内容)
InterAdd(Content, SetCRLF);
end;
procedure THttpResponseHeaders.ChunkDone;
begin
PAnsiChar(FData^.buf)^ := AnsiChar('0'); // 0
PStrCRLF2(FData^.buf + 1)^ := STR_CRLF2; // 回车换行, 两个
FData^.len := 5;
end;
procedure THttpResponseHeaders.ChunkSize(ASize: Cardinal);
begin
if (ASize > 0) then
begin
// 修改 Chunk 长度,在当前位置加 STR_CRLF,设置填充长度
PChunkSize(FData.buf)^ := PChunkSize(AnsiString(IntToHex(ASize, 4)) + STR_CRLF)^;
PStrCRLF(FBuffer)^ := STR_CRLF;
Inc(FData^.len, 8);
end else
begin // 清空,前移 6 字节
FBuffer := FData^.buf;
FData^.len := 0;
Inc(FBuffer, 6); // 只留出长度描述空间
end;
end;
procedure THttpResponseHeaders.Clear;
begin
// 写入地址恢复到开始位置
FillChar(FHeaders, SizeOf(THeaderArray), 0);
if Assigned(FBuffer) and (FData^.len > 0) then
begin
FBuffer := FData^.buf;
FData^.len := 0;
end;
end;
function THttpResponseHeaders.GetSize: Integer;
begin
// 取发送内容长度
Result := FData^.len;
end;
procedure THttpResponseHeaders.InterAdd(const Content: AnsiString; SetCRLF: Boolean);
begin
// 增加报头项目
// 如:Server: InIOCP/2.0
// 加入内容
System.Move(Content[1], FBuffer^, Length(Content));
Inc(FData^.len, Length(Content));
Inc(FBuffer, Length(Content));
// 加回车换行
if SetCRLF then
begin
PStrCRLF(FBuffer)^ := STR_CRLF;
Inc(FData^.len, 2);
Inc(FBuffer, 2);
end;
end;
procedure THttpResponseHeaders.SetOwner(const Value: TServerTaskSender);
begin
// 初始化
FOwner := Value;
FData := FOwner.Data;
FData^.len := 0;
FBuffer := FData^.buf;
end;
procedure THttpResponseHeaders.SetStatus(Code: Integer);
begin
// 设置响应状态
Clear;
case Code div 100 of
1:
InterAdd(HTTP_VER + HTTP_STATES_100[Code - 100]);
2:
InterAdd(HTTP_VER + HTTP_STATES_200[Code - 200]);
3:
InterAdd(HTTP_VER + HTTP_STATES_300[Code - 300]);
4:
InterAdd(HTTP_VER + HTTP_STATES_400[Code - 400]);
else
InterAdd(HTTP_VER + HTTP_STATES_500[Code - 500]);
end;
end;
{ THttpResponse }
procedure THttpResponse.AddContent(const Content: AnsiString);
begin
// 增加实体内容
FContent.Add(Content);
FContentSize := FContent.Size; // 调
end;
procedure THttpResponse.AddDataPackets;
var
ETag, LastModified: AnsiString;
procedure AddPacket(Range: AnsiString);
var
StartPos, EndPos: Integer;
begin
// 分析范围
EndPos := 0;
if (Range[1] = '-') then // -235
begin
StartPos := StrToInt(Copy(Range, 2, 99));
if (FContentSize >= StartPos) then
begin
StartPos := FContentSize - StartPos;
EndPos := FContentSize - 1;
end else
FStatusCode := 416; // 416 Requested range not satisfiable
end else
if (Range[Length(Range)] = '-') then // 235-
begin
Delete(Range, Length(Range), 1);
StartPos := StrToInt(Range);
if (FContentSize >= StartPos) then
EndPos := FContentSize - 1
else
FStatusCode := 416; // 416 Requested range not satisfiable
end else // 235-2289
begin
EndPos := Pos('-', Range);
StartPos := StrToInt(Copy(Range, 1, EndPos - 1));
EndPos := StrToInt(Copy(Range, EndPos + 1, 99));
if (StartPos > EndPos) or (EndPos >= FContentSize) then
FStatusCode := 416; // 416 Requested range not satisfiable
end;
if (FStatusCode <> 416) then
begin
SetStatus(206);
FHeaders.Add(rshServer);
FHeaders.Add(rshDate);
FHeaders.Add(rshAcceptRanges, 'bytes');
FHeaders.Add(rshContentType, FContentType);
if (FSessionId <> '') then // 加入 Cookie
FHeaders.Add(rshSetCookie, HTTP_SESSION_ID + '=' + FSessionId);
// 数据块长度
FHeaders.Add(rshContentLength, IntToStr(EndPos - StartPos + 1));
// 范围:起始-截止/总长
FHeaders.Add(rshContentRange, 'bytes ' + IntToStr(StartPos) + '-' +
IntToStr(EndPos) + '/' + IntToStr(FContentSize));
FHeaders.Add(rshETag, ETag);
FHeaders.Add(rshLastModified, LastModified);
if FKeepAlive then
FHeaders.Add(rshConnection, 'keep-alive')
else
FHeaders.Add(rshConnection, 'close');
// 先发送报头
FHeaders.AddCRLF;
FSender.SendBuffers;
// 后发送文件实体
if (FSender.ErrorCode = 0) then
FSender.Send(FHandle, FContentSize, StartPos, EndPos);
end;
end;
var
i: Integer;
RangeList: AnsiString;
begin
// 断点下载
// 设置要发送的数据块范围
// 可能同时请求多个范围,不支持 TransmitFile 发送
ETag := '"' + GetFileETag + '"';
LastModified := GetHttpGMTDateTime(TFileTime(FLastWriteTime));
RangeList := FExtParams.Range + ','; // 'bytes=123-145,1-1,-23,900-,';
i := Pos('=', RangeList);
Delete(RangeList, 1, i);
i := Pos(',', RangeList);
repeat
AddPacket(Copy(RangeList, 1, i - 1)); // 增加一个数据块发送任务
// 请求范围错误、发送异常 -> 退出
if (FStatusCode = 416) or (FSender.ErrorCode <> 0) then
Break
else begin
Delete(RangeList, 1, i);
i := Pos(',', RangeList);
end;
until i = 0;
end;
procedure THttpResponse.AddHeader(Code: TResponseHeaderType; const Content: AnsiString);
begin
// 增加报头信息
if (FStatusCode = 0) then
FStatusCode := 200;
if (FHeaders.Size = 0) then
begin
SetStatus(FStatusCode);
FHeaders.Add(rshServer);
FHeaders.Add(rshDate);
end;
FHeaders.Add(Code, Content);
end;
procedure THttpResponse.AddHeaderList(SendNow: Boolean);
begin
// 准备状态、报头
if (FStatusCode = 0) then
FStatusCode := 200;
if (FHeaders.Size = 0) then
begin
SetStatus(FStatusCode);
FHeaders.Add(rshServer);
FHeaders.Add(rshDate);
end;
if (FStatusCode < 400) and (FStatusCode <> 204) then
begin
// 统一使用 gb2312
// 用 text/html: IE 8 可能乱码, Chrome 正常
if (FContentType <> '') then
FHeaders.Add(rshContentType, FContentType + '; CharSet=gb2312')
else
if (FContent.Count > 0) or (FContentSize = 0) then
FHeaders.Add(rshContentType, 'text/html; CharSet=gb2312')
else
FHeaders.Add(rshContentType, 'text/plain; CharSet=gb2312');
// 发送源
if (FContent.Count > 0) then
begin
// html 脚本
FHeaders.Add(rshContentLength, IntToStr(FContentSize));
end else
if Assigned(FStream) then
begin
// 内存/文件流
if FGZipStream then
FHeaders.Add(rshContentEncoding, 'gzip');
FHeaders.Add(rshContentLength, IntToStr(FContentSize));
end else
if (FContentSize > 0) and (FLastWriteTime > 0) then
begin
// 文件句柄,返回文件标记和文件的 UTC 修改时间(64位,精确到千万分之一秒)
FHeaders.Add(rshContentLength, IntToStr(FContentSize));
FHeaders.Add(rshAcceptRanges, 'bytes');
FHeaders.Add(rshETag, '"' + GetFileETag + '"');
FHeaders.Add(rshLastModified, GetHttpGMTDateTime(TFileTime(FLastWriteTime)));
// Content-Disposition,让浏览器下载,不是直接打开。
if (FFileName <> '') then
FHeaders.Add(rshUnknown, 'Content-Disposition: attachment; filename=' + FFileName);
end;
FHeaders.Add(rshCacheControl, 'No-Cache');
if FKeepAlive then
FHeaders.Add(rshConnection, 'keep-alive')
else
FHeaders.Add(rshConnection, 'close');
end else
begin
// 异常,返回 FContent 的内容
FHeaders.Add(rshContentLength, IntToStr(FContent.Size));
if (FContent.Size > 0) then
begin
FHeaders.AddCRLF;
FHeaders.Append(FContent, FContent.Size);
end;
end;
if (FSessionId <> '') then // 加入 Cookie
FHeaders.Add(rshSetCookie, HTTP_SESSION_ID + '=' + FSessionId);
// 报头结束,发送
FHeaders.AddCRLF;
if SendNow then
FSender.SendBuffers;
end;
procedure THttpResponse.Clear;
begin
inherited;
FreeResources;
FContentType := '';
FGZipStream := False;
FLastWriteTime := 0;
FWorkDone := False;
end;
constructor THttpResponse.Create(ADataProvider: THttpDataProvider; AOwner: TObject);
begin
inherited;
FContent := TInStringList.Create; // 消息内容
FHeaders := THttpResponseHeaders.Create; // 服务器状态、报头
end;
procedure THttpResponse.CreateSession;
var
Session: THttpSession;
begin
// 新建 SessionId
Session := THttpSession.Create;
FSessionId := Session.CreateSessionId;
FDataProvider.FSessionMgr.Add(FSessionId, Session); // 加入 Hash 表的值
end;
destructor THttpResponse.Destroy;
begin
FreeResources;
FHeaders.Free;
FContent.Free;
inherited;
end;
procedure THttpResponse.FreeResources;
begin
if Assigned(FStream) then
begin
FStream.Free;
FStream := nil;
end;
if (FHandle > 0) then
begin
CloseHandle(FHandle);
FHandle := 0;
end;
if (FContent.Count > 0) then
FContent.Clear;
end;
function THttpResponse.GetFileETag: AnsiString;
begin
// 取文件标识(原理上是唯一的)
Result := IntToHex(FLastWriteTime, 2) + '-' + IntToHex(FContentSize, 4);
end;
function THttpResponse.GZipCompress(Stream: TStream): TStream;
begin
// GZip 压缩流、返回文件流
Result := TFileStream.Create(iocp_varis.gTempPath + '_' +
IntToStr(NativeUInt(Self)) + '.tmp', fmCreate);
try
Stream.Position := 0; // 必须
iocp_zlib.GZCompressStream(Stream, Result, '');
finally
Stream.Free;
end;
end;
procedure THttpResponse.Redirect(const URL: AnsiString);
begin
// 定位到指定的 URL
SetStatus(302); // 302 Found, 303 See Other
FHeaders.Add(rshServer);
FHeaders.Add(rshLocation, URL);
FHeaders.AddCRLF;
end;
procedure THttpResponse.RemoveSession;
begin
// 设置无效的 SessionId,反馈给客户端
if (FSessionId <> '') and (FSessionId <> HTTP_INVALID_SESSION) then
FDataProvider.FSessionMgr.Remove(FSessionId);
FSessionId := HTTP_INVALID_SESSION; // 无效的
end;
procedure THttpResponse.SendWork;
procedure AppendEntityData;
begin
// 把小实体内容加入到 FHeaders 之后
if (FHandle > 0) then // 可能是 Handle 流
FHeaders.Append(FHandle, FContentSize)
else
if (Assigned(FStream)) then // 发送流
FHeaders.Append(FStream, FContentSize)
else
if (FContent.Count > 0) then // 发送实体列表
FHeaders.Append(FContent, FContentSize);
end;
procedure SendEntityData;
begin
// 发送实体内容
{$IFDEF TRANSMIT_FILE}
// 1. 用 TransmitFile 发送
// 发送完成或异常都在 THttpSocket.ClearResources 中
// 释放资源 FHandle 和 FStream
with TBaseSocketRef(FOwner) do
if (FHandle > 0) then // 文件句柄 Handle
FTask.SetTask(FHandle, FContentSize)
else
if Assigned(FStream) then // 流
FTask.SetTask(FStream, FContentSize)
else
if (FContent.Count > 0) then // 发送实体列表
begin
FTask.SetTask(FContent.HttpString[False]);
FContent.Clear;
end;
{$ELSE}
// 2. 用 WSASend 发送, 自动释放 FHandle、FStream
if (FHandle > 0) then // 文件句柄 Handle
FSender.Send(FHandle, FContentSize)
else
if Assigned(FStream) then // 流
FSender.Send(FStream, FContentSize, True)
else
if (FContent.Count > 0) then // 发送实体列表
begin
FSender.Send(FContent.HttpString[False]);
FContent.Clear;
end;
{$ENDIF}
end;
begin
// 正式发送数据
if (FStatusCode = 206) then // 1. 断点下载
begin
AddDataPackets;
if (FStatusCode = 416) then // 请求范围错误
begin
Clear; // 释放资源
AddHeaderList(True);
end;
end else
if (FWorkDone = False) then // 2. 普通发送
if (FStatusCode >= 400) or (FSender.ErrorCode > 0) then // 2.1 异常
AddHeaderList(True) // 立即发送
else begin
AddHeaderList(False); // 先不发送
if (FContentSize + FHeaders.Size <= IO_BUFFER_SIZE) then
begin
// 2.2 发送缓存还装得下实体
if (FContentSize > 0) then
AppendEntityData; // 加入实体内容
FSender.SendBuffers; // 正式发送
end else
begin
// 2.3 实体太长, 先发报头,再实体
FSender.SendBuffers; // 正式发送
SendEntityData; // 发实体
end;
end;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog(TBaseSocket(FOwner).PeerIPPort +
'->执行请求 ' + METHOD_LIST[FRequest.FMethod] + ' ' +
FRequest.FRequestURI + ', 状态=' + IntToStr(FStatusCode));
{$ENDIF}
{$IFDEF TRANSMIT_FILE}
TBaseSocketRef(FOwner).InterTransmit;
{$ELSE}
FHandle := 0; // 已经发出
FStream := nil; // 已经发出
{$ENDIF}
end;
procedure THttpResponse.SendChunk(Stream: TStream);
begin
// 立即分块发送(在外部释放 Stream)
// HTTP 协议不能对单块进行压缩(整体传输时可以)
// 不支持 TransmitFile 模式发送数据!
FreeResources;
if (Assigned(Stream) = False) then
FStatusCode := 204
else
try
// 发送的数据结构:
// 1. 报头;
// 2. 长度 + 回车换行 + 内容 + 回车换行;
// 3. "0" + 回车换行 + 回车换行
// 1. 发送报头
SendChunkHeaders;
// 2. 发送调制的实体
TServerTaskSender(FSender).Chunked := True; // 分块发送!
FSender.Send(Stream, Stream.Size, False); // 不释放流!
finally
FWorkDone := True;
if (Stream is TMemoryStream) then
Stream.Size := 0;
end;
end;
procedure THttpResponse.SendChunkHeaders(const ACharSet: AnsiString);
begin
// 发送分块描述
SetStatus(200);
FHeaders.Add(rshServer);
FHeaders.Add(rshDate);
FHeaders.Add(rshContentType, CONTENT_TYPES[0].ContentType + ACharSet);
if (FSessionId <> '') then // 加入 Cookie: InIOCP_SID=...
FHeaders.Add(rshSetCookie, HTTP_SESSION_ID + '=' + FSessionId);
FHeaders.Add(rshTransferEncoding, 'chunked');
FHeaders.Add(rshCacheControl, 'no-cache, no-store');
FHeaders.Add(rshPragma, 'no-cache');
FHeaders.Add(rshExpires, '-1');
// 报头结束,发送
FHeaders.AddCRLF;
FSender.SendBuffers;
end;
procedure THttpResponse.SendJSON(DataSet: TDataSet; CharSet: THttpCharSet);
begin
// 把大数据集转为 JSON 分块发送(立即发送)
// CharSet:把记录转换为相应的字符集
SendChunkHeaders(HTTP_CHAR_SETS[CharSet]); // 发送报头
try
LargeDataSetToJSON(DataSet, FHeaders, CharSet); // 建 JSON,发送
finally
FWorkDone := True; // 改进,在发送器自动发送结束标志
end;
end;
procedure THttpResponse.SendJSON(const JSON: AnsiString);
begin
// 设置要发送的 JSON(不立即发送)
SetContent(JSON);
end;
procedure THttpResponse.SendStream(Stream: TStream; Compress: Boolean);
begin
// 准备要发送的数据流
FreeResources;
if Assigned(Stream) then
begin
FContentSize := Stream.Size;
if (FContentSize > MAX_TRANSMIT_LENGTH div 200) then // 太大
begin
FContentSize := 0;
FStatusCode := 413;
end else
begin
if Compress then // 压缩
begin
FStream := GZipCompress(Stream); // 压缩成文件流,释放 Stream
FContentSize := FStream.Size; // 改变
end else
FStream := Stream; // 不压缩
FGZipStream := Compress;
FContentType := CONTENT_TYPES[0].ContentType;
end;
end else
FStatusCode := 204;
end;
procedure THttpResponse.SetContent(const Content: AnsiString);
begin
// 第一次加入实体内容
if (FContent.Count > 0) then
FContent.Clear;
FContent.Add(Content);
FContentSize := FContent.Size; // 调
end;
procedure THttpResponse.SetHead;
begin
// 返回 Head 请求的信息
SetStatus(200);
FHeaders.Add(rshServer);
FHeaders.Add(rshDate);
FHeaders.Add(rshAllow, 'GET, POST, HEAD'); // CONNECT, DELETE, PUT, OPTIONS, TRACE');
FHeaders.Add(rshContentType, 'text/html; CharSet=gb2312');
FHeaders.Add(rshContentLang, 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3');
FHeaders.Add(rshContentEncoding, 'gzip, deflate');
FHeaders.Add(rshContentLength, IntToStr(FDataProvider.FMaxContentLength));
FHeaders.Add(rshCacheControl, 'no-cache');
FHeaders.Add(rshTransferEncoding, 'chunked');
if FKeepAlive then
FHeaders.Add(rshConnection, 'keep-alive')
else
FHeaders.Add(rshConnection, 'close');
// 报头结束
FHeaders.AddCRLF;
end;
procedure THttpResponse.SetStatus(Code: Integer);
begin
// 设置响应状态
FStatusCode := Code;
FHeaders.SetStatus(Code);
end;
procedure THttpResponse.TransmitFile(const FileName: String; AutoView: Boolean);
var
ETag: AnsiString;
TempFileName: String;
lpCreationTime, lpLastAccessTime: _FILETIME;
begin
// 打开文件资源
// http://blog.csdn.net/xiaofei0859/article/details/52883500
FreeResources;
TempFileName := AdjustFileName(FileName);
if (FileExists(TempFileName) = False) then
begin
FStatusCode := 404;
SetContent('<html><body>InIOCP/2.0: 页面不存在!</body></html>');
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('THttpResponse.TransmitFile->文件不存在:' + FileName);
{$ENDIF}
Exit;
end;
// InternalOpenFile 把 INVALID_HANDLE_VALUE 转为 0
FHandle := InternalOpenFile(TempFileName);
if (FHandle > 0) then
begin
// 用 文件大小 + 修改时间 计算 ETag
FContentSize := GetFileSize64(FHandle);
// 返回 FFileName,chrome 浏览器以后断点下载
if not AutoView or (FContentSize > 4096000) then
FFileName := ExtractFileName(FileName);
GetFileTime(FHandle, @lpCreationTime, @lpLastAccessTime, @FLastWriteTime);
ETag := GetFileETag;
if (ETag = FExtParams.IfMath) and
(GetHttpGMTDateTime(TFileTime(FLastWriteTime)) = FExtParams.LastModified) then
begin
if (FExtParams.Range <> '') then // 请求断点下载
begin
FStatusCode := 206; // 可能请求多个数据块,大小未定
FContentType := CONTENT_TYPES[0].ContentType;
end else
begin
FStatusCode := 304; // 304 Not Modified,文件没修改过
FContentSize := 0;
FLastWriteTime := 0;
CloseHandle(FHandle);
FHandle := 0;
end;
end else
begin
if (FExtParams.Range <> '') then // 请求断点下载
begin
FStatusCode := 206; // 可能请求多个数据块,大小未定
FContentType := CONTENT_TYPES[0].ContentType;
end else
FContentType := GetContentType(FileName);
end;
end else
begin
FStatusCode := 500;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('THttpResponse.TransmitFile->打开文件异常:' + FileName);
{$ENDIF}
end;
end;
procedure THttpResponse.Upgrade;
begin
// 升级为 WebSocket,反馈
FHeaders.SetStatus(101);
FHeaders.Add(rshServer); // 可选
FHeaders.Add(rshDate); // 可选
FHeaders.Add(rshConnection, 'Upgrade');
FHeaders.Add(rshUpgrade, 'WebSocket');
FHeaders.Add(rshWebSocketAccept, iocp_SHA1.EncodeBase64(
iocp_SHA1.SHA1StringA(FRequest.GetHeaders(rqhWebSocketKey) +
WSOCKET_MAGIC_GUID)));
FHeaders.Add(rshContentType, 'text/html; charSet=utf-8'); // 可选
FHeaders.Add(rshContentLength, '0'); // 可选
FHeaders.AddCRLF;
FSender.SendBuffers;
end;
end.
|
unit GetTerritoriesUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TGetTerritories = class(TBaseExample)
public
procedure Execute;
end;
implementation
uses TerritoryUnit;
procedure TGetTerritories.Execute;
var
ErrorString: String;
Territories: TTerritoryList;
begin
Territories := Route4MeManager.Territory.GetList(ErrorString);
try
WriteLn('');
if (Territories.Count > 0) then
WriteLn(Format('GetTerritories executed successfully, %d zones returned',
[Territories.Count]))
else
WriteLn(Format('GetTerritories error: "%s"', [ErrorString]));
finally
FreeAndNil(Territories);
end;
end;
end.
|
unit NppMacro;
//{$I Notpad_Plugin.inc}
interface
uses
Windows, NppPluginInc, Scintilla, System.SysUtils;
function Npp_AddToolBarIcon(hWd: HWND; CmdID: UINT; icon: TToolbarIcons): Integer;
function Npp_MsgToPlugin(hWd: HWND; destModuleName: PTCHAR; var info: TCommunicationInfo): Boolean;
function Npp_GetPluginsConfigDir(hWd: HWND): string;
function Npp_SetMenuItemCheck(hWd: HWND; CmdId: ULONG; Checked: Boolean): Integer;
// Language
function Npp_GetCurrentLangType(hWd: HWND): TLangType;
function Npp_SetCurrentLangType(hWd: HWND; Lang: TLangType): Integer;
// File
function Npp_GetCurrentFileOf(hWd: HWND; MSG: ULONG):string;
function Npp_GetCurrentFileName(hWd: HWND): string;
function Npp_GetCurrentShortFileName(hWd: HWND): string;
function Npp_GetCurrentFileDir(hWd: HWND): string;
// Scintilla Editor
function Npp_GetCurrentScintilla(hWd: HWND): Integer;
function Npp_GetCurrentScintillaHandle(NppData: TNppData): HWND;
function Npp_SciReplaceSel(ScinthWd: HWND; Text: string): Integer;
function Npp_SciAppedText(ScinthWd: HWND; AText: TBytes): Integer;
function Npp_SciSetText(ScinthWd: HWND; AText: TBytes): Integer;
function Npp_SciGetText(ScinthWd: HWND): TBytes;
function Npp_SciGoToPos(ScinthWd: HWND; Posi: Integer): Integer;
function Npp_SciGetLength(ScinthWd: HWND): Integer;
function Npp_SciSetZoomLevel(ScinthWd: HWND; Level: Integer): Integer;
function Npp_SciGetZoomLevel(ScinthWd: HWND): Integer;
function Npp_SciEnSureVisible(ScinthWd: HWND; Line: Integer): Integer;
function Npp_SciGetLine(Scinthnd: HWND): Integer;
function Npp_SciGoToLine(ScinthWd: HWND; Line: Integer): Integer;
function Npp_SciGetSelText(ScinthWd: HWND): TBytes;
// Codeing
function Npp_GetCurrentCodePage(ScinthWd: HWND): Integer;
// MenuCmd
// File
function Npp_MenuCmdOf(hWd: HWND; Cmd: Integer): Integer;
function Npp_FileNew(hWd: HWND): Integer;
function Npp_FileOpen(hWd: HWND): Integer;
function Npp_FileClose(hWd: HWND): Integer;
function Npp_FileCloseAll(hWd: HWND): Integer;
function Npp_FileCloseAllNotCurrent(hWd: HWND): Integer;
function Npp_FileSave(hWd: HWND): Integer;
function Npp_FileSaveAll(hWd: HWND): Integer;
function Npp_FileSaveAs(hWd: HWND): Integer;
function Npp_FileAsianLang(hWd: HWND): Integer;
function Npp_FilePrint(hWd: HWND): Integer;
function Npp_FilePrintNow(hWd: HWND): Integer;
function Npp_FileExit(hWd: HWND): Integer;
function Npp_FileLoadSession(hWd: HWND): Integer;
function Npp_FileSaveSession(hWd: HWND): Integer;
function Npp_FileReLoad(hWd: HWND): Integer;
function Npp_FileSaveCopyAs(hWd: HWND): Integer;
function Npp_FileDelete(hWd: HWND): Integer;
function Npp_FileReName(hWd: HWND): Integer;
// Edit
function Npp_EditCut(hWd: HWND): Integer;
function Npp_EditCopy(hWd: HWND): Integer;
function Npp_EditUndo(hWd: HWND): Integer;
function Npp_EditRedo(hWd: HWND): Integer;
function Npp_EditPaste(hWd: HWND): Integer;
function Npp_EditDelete(hWd: HWND): Integer;
function Npp_EditSeleteAll(hWd: HWND): Integer;
// Dock Dialog
function Npp_DockDialogAdd(hWd, SubhWd: HWND): Integer;
function Npp_DockDialogRemove(hWd, SubhWd: HWND): Integer;
function Npp_DockDialogRegister(hWd: HWND; Data: TtTbData):Integer;
function Npp_DockDialogUpdateDisplay(hWd, SubhWd: HWND): Integer;
function Npp_DockDialogShow(hWd, SubhWd: HWND): Integer;
function Npp_DockDialogHide(hWd, SubhWd: HWND): Integer;
implementation
function Npp_AddToolBarIcon(hWd: HWND; CmdID: UINT; icon: TToolbarIcons): Integer;
begin
Result := SendMessage(hWd, NPPM_ADDTOOLBARICON, CmdID, LPARAM(@icon));
end;
function Npp_MsgToPlugin(hWd: HWND; destModuleName: PTCHAR; var info: TCommunicationInfo): Boolean;
begin
Result := SendMessage(hWd, NPPM_MSGTOPLUGIN, WPARAM(destModuleName), LPARAM(@info)) <> 0;
end;
function Npp_GetPluginsConfigDir(hWd: HWND): string;
var
LDir: array[0..MAX_PATH-1] of UCHAR;
begin
FillChar(LDir, SizeOf(LDir), 0);
SendMessage(hWd, NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, LParam(@LDir[0]));
Result := LDir;
end;
function Npp_SetMenuItemCheck(hWd: HWND; CmdId: ULONG; Checked: Boolean): Integer;
begin
Result := SendMessage(hWd, NPPM_SETMENUITEMCHECK, CmdId, Integer(Checked));
end;
// Language
function Npp_GetCurrentLangType(hWd: HWND): TLangType;
var
Value: Integer;
begin
Value := 1;
SendMessage(hWd, NPPM_GETCURRENTLANGTYPE, 0, LPARAM(@Value));
if Value = -1 then
Result := L_TXT
else
Result := TLangType(Value);
end;
function Npp_SetCurrentLangType(hWd: HWND; Lang: TLangType): Integer;
var
Value: Integer;
begin
Value := Integer(Lang);
Result := SendMessage(hWd, NPPM_SETCURRENTLANGTYPE, 0, Value);
end;
// File
function Npp_GetCurrentFileOf(hWd: HWND; MSG: ULONG):string;
var
Path: array[0..MAX_PATH-1] of UCHAR;
begin
SendMessage(hWd, MSG, 0, LPARAM(@path[0]));
Result := Path;
end;
function Npp_GetCurrentFileName(hWd: HWND): string;
begin
Result := Npp_GetCurrentFileOf(hWd, NPPM_GETFULLCURRENTPATH);
end;
function Npp_GetCurrentShortFileName(hWd: HWND): string;
begin
Result := Npp_GetCurrentFileOf(hWd, NPPM_GETFILENAME);
end;
function Npp_GetCurrentFileDir(hWd: HWND): string;
begin
Result := Npp_GetCurrentFileOf(hWd, NPPM_GETCURRENTDIRECTORY);
end;
// Editor
function Npp_GetCurrentScintilla(hWd: HWND): Integer;
begin
Result := -1;
SendMessage(hWd, NPPM_GETCURRENTSCINTILLA, 0, LParam(@Result));
end;
function Npp_GetCurrentScintillaHandle(NppData: TNppData): HWND;
begin
if Npp_GetCurrentScintilla(NppData._nppHandle) = 0 then
Result := NppData._scintillaMainHandle
else Result := NppData._scintillaSecondHandle;
end;
function Npp_SciReplaceSel(ScinthWd: HWND; Text: string): Integer;
begin
Result := SendMessage(ScinthWd, SCI_REPLACESEL, 0, LParam(PAnsiChar(Text)));
end;
function Npp_SciAppedText(ScinthWd: HWND; AText: TBytes): Integer;
begin
Result := SendMessage(ScinthWd, SCI_APPENDTEXT, 1, LParam(@AText[0]));
end;
function Npp_SciSetText(ScinthWd: HWND; AText: TBytes): Integer;
begin
Result := SendMessage(ScinthWd, SCI_SETTEXT, 0, LParam(@AText[0]));
end;
function Npp_SciGetText(ScinthWd: HWND): TBytes;
var
Len: Integer;
begin
Len := Npp_SciGetLength(ScinthWd);
SetLength(Result, Len);
if Len > 0 then
SendMessage(ScinthWd, SCI_GETTEXT, Len, LPARAM(@Result[0]));
end;
// SCI_GETCURRENTPOS
function Npp_SciGoToPos(ScinthWd: HWND; Posi: Integer): Integer;
begin
Result := SendMessage(ScinthWd, SCI_GOTOPOS, Posi, 0);
end;
function Npp_SciGetLength(ScinthWd: HWND): Integer;
begin
Result := SendMessage(ScinthWd, SCI_GETLENGTH, 0, 0);
end;
function Npp_SciSetZoomLevel(ScinthWd: HWND; Level: Integer): Integer;
begin
Result := SendMessage(ScinthWd, SCI_SETZOOM, Level, 0);
end;
function Npp_SciGetZoomLevel(ScinthWd: HWND): Integer;
begin
Result := SendMessage(ScinthWd, SCI_GETZOOM, 0, 0);
end;
function Npp_SciEnSureVisible(ScinthWd: HWND; Line: Integer): Integer;
begin
Result := SendMessage(ScinthWd, SCI_ENSUREVISIBLE, Line - 1, 0);
end;
function Npp_SciGetLine(Scinthnd: HWND): Integer;
begin
Result := SendMessage(Scinthnd, SCI_GETLINE, 0, 0) + 1;
end;
function Npp_SciGoToLine(ScinthWd: HWND; Line: Integer): Integer;
begin
Result := SendMessage(ScinthWd, SCI_GOTOLINE, Line - 1, 0);
end;
function Npp_SciGetSelText(ScinthWd: HWND): TBytes;
var
Len: Integer;
begin
Len := Npp_SciGetLength(ScinthWd);
SetLength(Result, Len);
if Len > 0 then
SendMessage(ScinthWd, SCI_GETSELTEXT, Len, LPARAM(@Result[0]));
end;
// Coding
function Npp_GetCurrentCodePage(ScinthWd: HWND): Integer;
begin
Result := SendMessage(ScinthWd, SCI_GETCODEPAGE, 0, 0);
end;
// MenuCmd
// File
function Npp_MenuCmdOf(hWd: HWND; Cmd: Integer): Integer;
begin
Result := SendMessage(hWd, NPPM_MENUCOMMAND, 0, Cmd);
end;
function Npp_FileNew(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_NEW);
end;
function Npp_FileOpen(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_OPEN);
end;
function Npp_FileClose(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_CLOSE)
end;
function Npp_FileCloseAll(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_CLOSEALL)
end;
function Npp_FileCloseAllNotCurrent(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_CLOSEALL_BUT_CURRENT);
end;
function Npp_FileSave(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_SAVE);
end;
function Npp_FileSaveAll(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_SAVEALL);
end;
function Npp_FileSaveAs(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_SAVEAS);
end;
function Npp_FileAsianLang(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_ASIAN_LANG);
end;
function Npp_FilePrint(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_PRINT);
end;
function Npp_FilePrintNow(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_PRINTNOW);
end;
function Npp_FileExit(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_EXIT);
end;
function Npp_FileLoadSession(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_LOADSESSION);
end;
function Npp_FileSaveSession(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_SAVESESSION);
end;
function Npp_FileReLoad(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_RELOAD);
end;
function Npp_FileSaveCopyAs(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_SAVECOPYAS);
end;
function Npp_FileDelete(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_DELETE);
end;
function Npp_FileReName(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_FILE_RENAME);
end;
// Edit
function Npp_EditCut(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_CUT);
end;
function Npp_EditCopy(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_COPY);
end;
function Npp_EditUndo(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_UNDO);
end;
function Npp_EditRedo(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_REDO);
end;
function Npp_EditPaste(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_PASTE);
end;
function Npp_EditDelete(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_DELETE);
end;
function Npp_EditSeleteAll(hWd: HWND): Integer;
begin
Result := Npp_MenuCmdOf(hWd, IDM_EDIT_SELECTALL);
end;
// Dock Dialog
function Npp_DockDialogAdd(hWd, SubhWd: HWND): Integer;
begin
Result := SendMessage(hWd, NPPM_MODELESSDIALOG, MODELESSDIALOGADD, SubhWd);
end;
function Npp_DockDialogRemove(hWd, SubhWd: HWND): Integer;
begin
Result := SendMessage(hWd, NPPM_MODELESSDIALOG, MODELESSDIALOGREMOVE, SubhWd);
end;
function Npp_DockDialogRegister(hWd: HWND; Data: TtTbData):Integer;
begin
Result := SendMessage(hWd, NPPM_DMMREGASDCKDLG, 0, LPARAM(@Data));
end;
function Npp_DockDialogUpdateDisplay(hWd, SubhWd: HWND): Integer;
begin
Result := SendMessage(hWd, NPPM_DMMUPDATEDISPINFO, 0, hWd);
end;
function Npp_DockDialogShow(hWd, SubhWd: HWND): Integer;
begin
Result := SendMessage(hWd, NPPM_DMMSHOW, 0, SubhWd);
end;
function Npp_DockDialogHide(hWd, SubhWd: HWND): Integer;
begin
Result := SendMessage(hWd, NPPM_DMMHIDE, 0, SubhWd);
end;
end.
|
///<summary>
/// This unit is based on the AutoTodoInserter wizard written by Peter Laman
/// and published on CodeCentral at
/// http://cc.embarcadero.com/codecentral/ccweb.exe/listing?id=22336
/// (Article on http://edn.embarcadero.com/article/32709)
///
/// The licence states "Commercial use requires permission", but I found no
/// way to contact him to get a permission. So for now I am assuming that he
/// has no objection.
/// @Peter: If you read this, please contact me through
/// http://blog.dummzeuch.de or https://plus.google.com/108684844040122144755 </summary>
unit GX_uAutoTodoHandler;
interface
uses
Windows,
SysUtils,
Classes;
type
TAutoTodoHandler = class
private
FTodoUser: string;
FTextToInsert: string;
function GenerateInsertText(const ProcName, BeginKey, EndKey, ProcType: string): string;
public
class function GetDefaultTextToInsert: string;
class procedure GetPlaceholders(_sl: TStrings);
constructor Create;
destructor Destroy; override;
///<summary>
/// Generates a list of string inserts for all empty
/// begin/end blocks. The objects part contains the original source positions
/// where to insert (0-based) </summary>
procedure Execute(const Source: string; List: TStrings);
///<summary>
/// Adds to-do items for all empty begin/end blocks in the given string. Calls Execute. </summary>
function Test(const Source: string): string;
property TodoUser: string read FTodoUser write FTodoUser;
property TextToInsert: string read FTextToInsert write FTextToInsert;
end;
implementation
uses
GX_GenericUtils;
const
// Unfortunately this is strictly no longer true, because e.g. Umlauts can also be used as
// identifiers, but most programmers will not do that.
IdChars = ['a'..'z', 'A'..'Z', '0'..'9', '_'];
SepChars = [#9, #32, #13, #10];
type
TRoutine = record
ProcType: string;
PrevPos: Integer;
NextPos: Integer;
PrevName: string;
NextName: string;
end;
TStringArray = array of string;
TKeywordPair = record
BeginKey: string;
EndKeys: TStringArray;
end;
TKeywordPairArray = array of TKeywordPair;
{ TAutoTodoHandler }
class function TAutoTodoHandler.GetDefaultTextToInsert: string;
const
DefaultTextToInsert = '//TODO 5 -o{UserName} -cEmpty Code Block: {ProcName} ({BeginKey}/{EndKey} in {ProcType})';
begin
Result := DefaultTextToInsert;
end;
class procedure TAutoTodoHandler.GetPlaceholders(_sl: TStrings);
begin
Assert(Assigned(_sl));
_sl.Add('Username');
_sl.Add('ProcName');
_sl.Add('BeginKey');
_sl.Add('EndKey');
_sl.Add('ProcType');
end;
constructor TAutoTodoHandler.Create;
begin
inherited;
FTodoUser := GetCurrentUser;
FTextToInsert := GetDefaultTextToInsert;
end;
destructor TAutoTodoHandler.Destroy;
begin
inherited;
end;
procedure UnCommentSourceCode(var SourceCode: string; const ClearStrings: Boolean);
var
i: Integer;
Ch: Char;
Prev: Char;
State: (sCode, sAccolade, sParentAsterisk, sDoubleSlash, sQuotedString);
begin
Prev := #0;
State := sCode;
for i := 1 to Length(SourceCode) do begin
Ch := SourceCode[i];
case State of
sCode:
case Ch of
'{': begin
State := sAccolade;
SourceCode[i] := #32;
end;
'''': begin
if ClearStrings then begin
State := sQuotedString;
SourceCode[i] := #32;
end;
end;
'*': if Prev = '(' then begin
State := sParentAsterisk;
SourceCode[i] := #32;
SourceCode[i - 1] := #32;
end;
'/': if Prev = '/' then begin
State := sDoubleSlash;
SourceCode[i] := #32;
SourceCode[i - 1] := #32;
end;
end;
sAccolade: begin
if not CharInSet(SourceCode[i], [#13, #10]) then
SourceCode[i] := #32;
if Ch = '}' then
State := sCode;
end;
sParentAsterisk: begin
if not CharInSet(SourceCode[i], [#13, #10]) then
SourceCode[i] := #32;
if (Prev = '*') and (Ch = ')') then
State := sCode;
end;
sDoubleSlash: begin
if Ch = #13 then
State := sCode
else
SourceCode[i] := #32;
end;
sQuotedString: begin
SourceCode[i] := #32;
if Ch = '''' then
State := sCode;
end;
end;
Prev := Ch;
end; // for i
end;
function IsSubstrHere(const SubStr, s: string; idx: Integer): Boolean;
var
Len: Integer;
SubL: Integer;
i: Integer;
begin
i := 1;
Len := Length(s);
SubL := Length(SubStr);
Result := True;
while idx <= Len do begin
if i > SubL then
Exit;
if SubStr[i] <> s[idx] then begin
Result := False;
Exit;
end;
Inc(idx);
Inc(i);
end;
Result := False;
end;
function FindKeyPairBegin(const KeyPairs: TKeywordPairArray;
const s: string; var StartPos: Integer; out PairIndex: Integer): Boolean;
var
Lo: Integer;
Hi: Integer;
KeyIdx: Integer;
Len: Integer;
begin
Lo := Low(KeyPairs);
Hi := High(KeyPairs);
Len := Length(s);
while StartPos <= Len do begin
for KeyIdx := Lo to Hi do
if IsSubstrHere(KeyPairs[KeyIdx].BeginKey, s, StartPos) then begin
Result := True;
PairIndex := KeyIdx;
Exit;
end;
Inc(StartPos);
end; // while StartPos <= L
Result := False;
end;
function FindId(const Id, s: string; StartPos: Integer): Integer;
var
Done: Boolean;
After: Integer;
begin
repeat
Result := Pos(Id, Copy(s, StartPos, MaxInt));
if Result > 0 then
Inc(Result, StartPos - 1);
After := Result + Length(Id);
Done := (Result = 0)
or ((Result = 1) or not CharInSet(s[Result - 1], IdChars))
and ((After > Length(s)) or not CharInSet(s[After], IdChars));
if not Done then
StartPos := Result + 1;
until Done;
end;
function FindKeyPairEnd(const KeyPairs: TKeywordPairArray;
const s: string; var StartPos: Integer; out EndKeywordIndex: Integer;
const PairIndex: Integer): Boolean;
var
i: Integer;
Len: Integer;
begin
Len := Length(s);
while StartPos <= Len do begin
for i := 0 to Length(KeyPairs[PairIndex].EndKeys) - 1 do begin
if IsSubstrHere(KeyPairs[PairIndex].EndKeys[i], s, StartPos) then begin
Result := True;
EndKeywordIndex := i;
Exit;
end;
end;
Inc(StartPos);
end; // while StartPos <= L
Result := False;
end;
function TAutoTodoHandler.GenerateInsertText(const ProcName, BeginKey, EndKey, ProcType: string): string;
begin
Result := FTextToInsert;
Result := StringReplace(Result, '{UserName}', FTodoUser, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '{ProcName}', ProcName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '{BeginKey}', BeginKey, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '{EndKey}', EndKey, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '{ProcType}', ProcType, [rfReplaceAll, rfIgnoreCase]);
end;
function TAutoTodoHandler.Test(const Source: string): string;
var
sl: TStringList;
i: Integer;
begin
sl := TStringList.Create;
try
Execute(Source, sl);
Result := Source;
for i := sl.Count - 1 downto 0 do
Insert(sl[i], Result, Integer(sl.Objects[i]) + 1);
finally
sl.Free;
end;
end;
procedure TAutoTodoHandler.Execute(const Source: string; List: TStrings);
var
LowSource: string;
BegPos: Integer;
Procs: array of TRoutine;
KeyPairs: TKeywordPairArray;
procedure CheckRoutine(var R: TRoutine);
var
i: Integer;
j: Integer;
Len: Integer;
begin
while R.NextPos < BegPos do begin
R.PrevPos := R.NextPos;
R.PrevName := R.NextName;
R.NextPos := FindId(R.ProcType, LowSource, BegPos + 1);
if R.NextPos = 0 then begin
R.NextPos := MaxInt; // No further searching
R.NextName := '';
Exit;
end;
// We found a routine, determine its name
Len := Length(LowSource);
i := R.NextPos + Length(R.ProcType);
while (i <= Len) and CharInSet(LowSource[i], SepChars) do
Inc(i);
j := i; // Start of routine name
while (i <= Len) and CharInSet(LowSource[i], IdChars + ['.']) do
Inc(i);
// Take the name from the mixed case original source string }
R.NextName := Copy(Source, j, i - j);
end; // while R.NextPos < BegPos
end; // CheckRoutine
function GetIndentOf(const Pos: Integer): string;
var
Len: Integer;
i: Integer;
begin
Len := Pos;
while (Len > 0) and (LowSource[Len] <> #10) do
Dec(Len);
Len := (Pos - Len - 1);
SetLength(Result, Len);
for i := 1 to Len do
Result[i] := #32;
end; // GetIndentOf
procedure AddToProcs(const ProcType: string);
var
idx: Integer;
begin
idx := Length(Procs);
SetLength(Procs, idx + 1);
Procs[idx].ProcType := ProcType;
Procs[idx].PrevPos := 0;
Procs[idx].NextPos := 0;
Procs[idx].PrevName := '';
Procs[idx].NextName := '';
end;
procedure AddToKeyPairs(const BeginKey, EndKey: string; const SecondEndKey: string = '');
var
idx: Integer;
begin
idx := Length(KeyPairs);
SetLength(KeyPairs, idx + 1);
KeyPairs[idx].BeginKey := BeginKey;
if SecondEndKey = '' then
SetLength(KeyPairs[idx].EndKeys, 1)
else begin
SetLength(KeyPairs[idx].EndKeys, 2);
KeyPairs[idx].EndKeys[1] := SecondEndKey;
end;
KeyPairs[idx].EndKeys[0] := EndKey;
end;
const
SInherited = 'inherited;';
var
EndPos: Integer;
CodePos: Integer;
FirstCR: Integer;
LastCR: Integer;
idx: Integer;
EmptyBlock: Boolean;
CurProc: Integer;
Pri: Integer;
KeyPairIndex: Integer;
EndKeywordIndex: Integer;
Todo: string;
begin // TAutoTodoHandler.Execute
List.BeginUpdate;
try
List.Clear;
LowSource := LowerCase(Source);
UnCommentSourceCode(LowSource, True);
BegPos := FindId('implementation', LowSource, 1);
if BegPos = 0 then
Exit; // There is no implementation part
SetLength(Procs, 0);
AddToProcs('class procedure');
AddToProcs('class function');
AddToProcs('procedure');
AddToProcs('function');
AddToProcs('constructor');
AddToProcs('destructor');
AddToProcs('class operator');
SetLength(KeyPairs, 0);
AddToKeyPairs('begin', 'end');
AddToKeyPairs('try', 'finally', 'except');
AddToKeyPairs('finally', 'end');
AddToKeyPairs('except', 'end');
AddToKeyPairs('repeat', 'until');
AddToKeyPairs('then', 'else');
AddToKeyPairs('of', 'end', 'else'); //Case of
AddToKeyPairs('else', 'end');
for Pri := Low(Procs) to High(Procs) do
CheckRoutine(Procs[Pri]);
Inc(BegPos);
repeat
if not FindKeyPairBegin(KeyPairs, LowSource, BegPos, KeyPairIndex) then
Exit;
if BegPos = 0 then
Exit;
// Determine the routine that owns the begin/end block
for Pri := Low(Procs) to High(Procs) do
CheckRoutine(Procs[Pri]);
CodePos := BegPos + Length(KeyPairs[KeyPairIndex].BeginKey);
EndPos := CodePos;
if not FindKeyPairEnd(KeyPairs, LowSource, EndPos, EndKeywordIndex, KeyPairIndex) then
Exit;
// Check if this begin/end block is empty
EmptyBlock := True;
FirstCR := 0;
LastCR := 0;
idx := CodePos;
while idx < EndPos do begin
if CharInSet(Source[idx], ['i', 'I']) and
SameText(Copy(Source, idx, Length(SInherited)), SInherited) then begin
Inc(idx, Length(SInherited) - 1);
if (idx < EndPos) and (Source[idx] = ';') then
Inc(idx);
CodePos := idx;
end else if not CharInSet(Source[idx], SepChars) then begin
EmptyBlock := False;
break;
end else if Source[idx] = #13 then begin
if FirstCR = 0 then
FirstCR := idx;
LastCR := idx;
end;
Inc(idx);
end; // while I < EndPos
// If this is an empty block, insert the TODO
if EmptyBlock then begin
// Determine current routine
CurProc := 0;
for Pri := Succ(Low(Procs)) to High(Procs) do
if Procs[Pri].PrevPos > Procs[CurProc].PrevPos then
CurProc := Pri;
Todo := GenerateInsertText(
Procs[CurProc].PrevName,
KeyPairs[KeyPairIndex].BeginKey,
KeyPairs[KeyPairIndex].EndKeys[EndKeywordIndex],
Procs[CurProc].ProcType);
if FirstCR = 0 then begin
// No line break between begin/end -> insert two
Todo := #13#10
+ GetIndentOf(BegPos) + #32#32 + Todo + '???'#13#10
+ GetIndentOf(BegPos);
idx := EndPos; // Insert position
end else begin
// There are line breaks between begin/end
idx := LastCR; // Insert position
Todo := GetIndentOf(BegPos) + #32#32 + Todo;
if FirstCR = LastCR then
Todo := #13#10 + Todo;
end;
List.AddObject(Todo, TObject(idx - 1));
end; // if EmptyBlock
BegPos := CodePos;
until False;
finally
List.EndUpdate;
end;
end; // TAutoTodoHandler.Execute
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Data.Win.ADODB,
System.StrUtils, Vcl.StdCtrls,
uDm, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
edtComName: TEdit;
edtGroupName: TEdit;
edtPhoneNum: TEdit;
edtQQ: TEdit;
btnAdd: TButton;
btnImport: TButton;
Label9: TLabel;
GroupBox3: TGroupBox;
Label1: TLabel;
Label2: TLabel;
btnTest: TButton;
edtIp: TEdit;
edtPwd: TEdit;
pnlHit: TPanel;
cmbBusiness: TComboBox;
Label10: TLabel;
procedure btnImportClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function OpenFile(): string;
procedure PostData(AData: string);
procedure ShowHint(AShow: Boolean = True);
procedure SaveConfig;
procedure LocaConfig;
function GetDataBaseName(AIndex: Integer): string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses ManSoy.Base64, ManSoy.Global, System.IniFiles;
{$R *.dfm}
procedure TForm1.btnAddClick(Sender: TObject);
var
sData: string;
begin
ShowHint();
try
if edtGroupName.Text = '' then
begin
ShowMessage('设备组名不能为空!');
edtGroupName.SetFocus;
Exit;
end;
if edtComName.Text = '' then
begin
ShowMessage('串口名不能为空!');
edtComName.SetFocus;
Exit;
end;
if edtPhoneNum.Text = '' then
begin
ShowMessage('手机号不能为空!');
edtPhoneNum.SetFocus;
Exit;
end;
if edtQQ.Text = '' then
begin
ShowMessage('QQ号不能为空!');
edtQQ.SetFocus;
Exit;
end;
if Application.MessageBox(
'友情提示: '#13' 之前同卡号下的数据将被清除,请谨慎操作!!! '#13''#13' 确定操作按【是】,取消操作按【否】',
'提示',
MB_ICONQUESTION or MB_YESNO
) = IDNO then Exit;
try
sData := Format('%s,%s,%s,[%s]', [Trim(edtGroupName.Text), Trim(edtComName.Text),Trim(edtPhoneNum.Text), Trim(edtQQ.Text)]);
PostData(sData);
ShowMessage('提交成功!');
except
ShowMessage('提交失败!');
end;
finally
ShowHint(False);
end;
end;
procedure TForm1.btnImportClick(Sender: TObject);
var
f: string;
t: TextFile;
s: string;
begin
ShowHint();
try
f := OpenFile;
if f = '' then Exit;
AssignFile(t,f);
Reset(t); //只读打开文件
while not Eof(t) do
begin
Readln(t,s);
PostData(Trim(s));
end;
ShowMessage('导入完成');
finally
ShowHint(False);
end;
end;
procedure TForm1.btnTestClick(Sender: TObject);
begin
if dm.ConnDB(edtIp.Text, edtPwd.Text, GetDataBaseName(cmbBusiness.ItemIndex)) then
begin
SaveConfig;
ShowMessage('连接成功!')
end else
ShowMessage('连接失败!');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ShowHint(False);
LocaConfig;
end;
function TForm1.GetDataBaseName(AIndex: Integer): string;
begin
Result := 'ModelPool';
case AIndex of
0: Result := 'ModelPool';
1: Result := 'ModelPool_1681';
end;
end;
procedure TForm1.LocaConfig;
var
sCfgFile: string;
iFile: TiniFile;
begin
sCfgFile := ExtractFilePath(ParamStr(0)) + 'Config\Cfg.ini';
iFile := TIniFile.Create(sCfgFile);
try
edtIp.Text := iFile.ReadString('DB', 'Host', '');
edtPwd.Text := ManSoy.Base64.Base64ToStr(iFile.ReadString('DB', 'Pwd', ''));
cmbBusiness.ItemIndex := iFile.ReadInteger('DB', 'Business', 0);
cmbBusiness.Enabled := False;
finally
FreeAndNil(iFile);
end;
end;
function TForm1.OpenFile: string;
begin
Result := '';
with TOpenDialog.Create(nil) do
try
Filter := 'Text Files|*.txt';
if Execute then
Result := FileName;
finally
Free;
end;
end;
procedure TForm1.PostData(AData: string);
var
s,sqlStr,groupName,comName,phone, qq: string;
sl: TStrings;
i: Integer;
begin
if not dm.ConnDB(edtIp.Text, edtPwd.Text, GetDataBaseName(cmbBusiness.ItemIndex)) then
begin
Application.MessageBox('连接失败!', '提示');
Exit;
end;
sl := TStringList.Create;
sl.CommaText := AData;
with dm do
try
conn.BeginTrans;
try
groupName := trim(sl.Strings[0]);
comName := trim(sl.Strings[1]);
phone := trim(sl.Strings[2]);
qq := trim(sl.Strings[3]);
qq := trim(Copy(qq,2, Length(qq)-2));
sl.Delimiter := '/';
sl.DelimitedText := qq;
//GROUPINFO-----------------------------------------------
qry.Close;
sqlStr := 'SELECT * FROM GROUPINFO WHERE GROUPNAME='+quotedstr(groupName);
qry.SQL.Text := sqlStr;
qry.Open;
if qry.RecordCount <= 0 then
begin
qry.Close;
sqlStr := Format('INSERT GROUPINFO (GROUPNAME) VALUES (%s);', [quotedstr(groupName)]);
qry.SQL.Text := sqlStr;
qry.ExecSQL;
end;
//COMPORTS---------------如果没有就insert,有的话就update-------
qry.Close;
qry.SQL.Text := 'DELETE COMPORTS ' +
'WHERE PhoneNum=' +quotedstr(phone);
//'WHERE GROUPNAME='+quotedstr(groupName)+
//' AND (COMNAME=' +quotedstr(comName) +
//' AND PhoneNum=' +quotedstr(phone);
qry.ExecSQL;
qry.Close;
sqlStr := Format('INSERT COMPORTS (GROUPNAME,COMNAME,PHONENUM) VALUES (%s,%s,%s);', [quotedstr(groupName), quotedstr(comName), quotedstr(phone)]);
qry.SQL.Text := sqlStr;
qry.ExecSQL;
//BIND----------------------------------------
i := 0;
for i := 0 to sl.Count - 1 do
begin
qq:= Trim(sl.Strings[i]);
qq:= Trim(sl.Strings[i]);
qry.Close;
qry.SQL.Text := 'DELETE BIND ' +
//'WHERE PHONENUM='+quotedstr(phone)+
//' AND QQ='+quotedstr(qq);
'WHERE QQ='+quotedstr(qq);
qry.ExecSQL;
qry.Close;
sqlStr := Format('INSERT BIND (PHONENUM,QQ) VALUES (%s,%s);', [quotedstr(phone), quotedstr(qq)]);
qry.SQL.Text := sqlStr;
qry.ExecSQL;
end;
conn.CommitTrans;
except on E: Exception do
begin
conn.RollbackTrans;
Application.MessageBox(PWideChar(Format('数据提交失败,错误原因'#13''#13'%s', [E.Message])), '提示', MB_ICONERROR)
end;
end;
finally
qry.Close;
sl.Free;
end;
end;
procedure TForm1.SaveConfig;
var
sCfgFile: string;
iFile: TiniFile;
begin
sCfgFile := ExtractFilePath(ParamStr(0)) + 'Config\Cfg.ini';
if not DirectoryExists(ExtractFileDir(sCfgFile)) then
ForceDirectories(ExtractFileDir(sCfgFile));
iFile := TIniFile.Create(sCfgFile);
try
iFile.WriteString('DB', 'Host', Trim(edtIp.Text));
iFile.WriteString('DB', 'Pwd', ManSoy.Base64.StrToBase64(Trim(edtPwd.Text)));
iFile.WriteInteger('DB', 'Business', cmbBusiness.ItemIndex);
finally
FreeAndNil(iFile);
end;
end;
procedure TForm1.ShowHint(AShow: Boolean);
begin
pnlHit.Visible := AShow;
Self.Enabled := not AShow;
if pnlHit.Visible then
begin
pnlHit.BringToFront
end else
pnlHit.SendToBack;
end;
end.
|
unit PrimPageSetup_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View$For F1 and Monitorings"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Search/Forms/PrimPageSetup_Form.pas"
// Начат: 15.09.2009 16:19
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMForm::Class>> F1 Common For Shell And Monitoring::Search::View$For F1 and Monitorings::Search$Presentation for F1 and Monitorings::PrimPageSetup
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin)}
uses
Classes
{$If not defined(NoVCM)}
,
vcmEntityForm
{$IfEnd} //not NoVCM
,
ConfigInterfaces
{$If not defined(NoVCM)}
,
vcmUserControls
{$IfEnd} //not NoVCM
,
vtGroupBox
{$If defined(Nemesis)}
,
nscPageControl
{$IfEnd} //Nemesis
,
l3StringIDEx
{$If not defined(NoScripts)}
,
tfwInteger
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
kwBynameControlPush
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
PrimPageSetup_pstNone_UserType,
vcmExternalInterfaces {a},
vcmInterfaces {a},
vcmBase {a}
;
{$IfEnd} //not Admin
{$If not defined(Admin)}
type
TPrimPageSetupForm = {form} class(TvcmEntityForm)
private
// private fields
f_PreviewGroupBox : TvtGroupBox;
{* Поле для свойства PreviewGroupBox}
f_SettingsPageControl : TnscPageControl;
{* Поле для свойства SettingsPageControl}
protected
procedure MakeControls; override;
protected
// property methods
function pm_GetPreviewGroupBox: TvtGroupBox;
function pm_GetSettingsPageControl: TnscPageControl;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
protected
// protected fields
f_CurrentColontitul : Integer;
f_PageSetup : InsPageSettingsInfo;
f_DisableControls : Boolean;
protected
// protected methods
procedure ReadPageFormats; virtual; abstract;
procedure SetColontitulComboBoxItemIndex(aIndex: Integer); virtual; abstract;
procedure ToGUIMargins; virtual; abstract;
public
// public methods
class function Make(const aData: InsPageSettingsInfo;
const aParams : IvcmMakeParams = nil;
aZoneType : TvcmZoneType = vcm_ztAny;
aUserType : TvcmEffectiveUserType = 0;
aDataSource : IvcmFormDataSource = nil): IvcmEntityForm; reintroduce;
public
// public properties
property PreviewGroupBox: TvtGroupBox
read pm_GetPreviewGroupBox;
property SettingsPageControl: TnscPageControl
read pm_GetSettingsPageControl;
end;//TPrimPageSetupForm
{$IfEnd} //not Admin
implementation
{$If not defined(Admin)}
uses
nsPageSetup
{$If not defined(NoScripts)}
,
tfwScriptingInterfaces
{$IfEnd} //not NoScripts
,
l3MessageID,
StdRes {a},
l3Base {a}
;
{$IfEnd} //not Admin
{$If not defined(Admin)}
var
{ Локализуемые строки pstNoneLocalConstants }
str_pstNoneCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'pstNoneCaption'; rValue : 'Настройка страницы');
{ Заголовок пользовательского типа "Настройка страницы" }
type
Tkw_PrimPageSetup_Control_PreviewGroupBox = class(TtfwControlString)
{* Слово словаря для идентификатора контрола PreviewGroupBox
----
*Пример использования*:
[code]
контрол::PreviewGroupBox TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimPageSetup_Control_PreviewGroupBox
// start class Tkw_PrimPageSetup_Control_PreviewGroupBox
{$If not defined(NoScripts)}
function Tkw_PrimPageSetup_Control_PreviewGroupBox.GetString: AnsiString;
{-}
begin
Result := 'PreviewGroupBox';
end;//Tkw_PrimPageSetup_Control_PreviewGroupBox.GetString
{$IfEnd} //not NoScripts
type
Tkw_PrimPageSetup_Control_PreviewGroupBox_Push = class(TkwBynameControlPush)
{* Слово словаря для контрола PreviewGroupBox
----
*Пример использования*:
[code]
контрол::PreviewGroupBox:push pop:control:SetFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimPageSetup_Control_PreviewGroupBox_Push
// start class Tkw_PrimPageSetup_Control_PreviewGroupBox_Push
{$If not defined(NoScripts)}
procedure Tkw_PrimPageSetup_Control_PreviewGroupBox_Push.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushString('PreviewGroupBox');
inherited;
end;//Tkw_PrimPageSetup_Control_PreviewGroupBox_Push.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_PrimPageSetup_Control_SettingsPageControl = class(TtfwControlString)
{* Слово словаря для идентификатора контрола SettingsPageControl
----
*Пример использования*:
[code]
контрол::SettingsPageControl TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimPageSetup_Control_SettingsPageControl
// start class Tkw_PrimPageSetup_Control_SettingsPageControl
{$If not defined(NoScripts)}
function Tkw_PrimPageSetup_Control_SettingsPageControl.GetString: AnsiString;
{-}
begin
Result := 'SettingsPageControl';
end;//Tkw_PrimPageSetup_Control_SettingsPageControl.GetString
{$IfEnd} //not NoScripts
type
Tkw_PrimPageSetup_Control_SettingsPageControl_Push = class(TkwBynameControlPush)
{* Слово словаря для контрола SettingsPageControl
----
*Пример использования*:
[code]
контрол::SettingsPageControl:push pop:control:SetFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimPageSetup_Control_SettingsPageControl_Push
// start class Tkw_PrimPageSetup_Control_SettingsPageControl_Push
{$If not defined(NoScripts)}
procedure Tkw_PrimPageSetup_Control_SettingsPageControl_Push.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushString('SettingsPageControl');
inherited;
end;//Tkw_PrimPageSetup_Control_SettingsPageControl_Push.DoDoIt
{$IfEnd} //not NoScripts
function TPrimPageSetupForm.pm_GetPreviewGroupBox: TvtGroupBox;
begin
if (f_PreviewGroupBox = nil) then
f_PreviewGroupBox := FindComponent('PreviewGroupBox') As TvtGroupBox;
Result := f_PreviewGroupBox;
end;
function TPrimPageSetupForm.pm_GetSettingsPageControl: TnscPageControl;
begin
if (f_SettingsPageControl = nil) then
f_SettingsPageControl := FindComponent('SettingsPageControl') As TnscPageControl;
Result := f_SettingsPageControl;
end;
class function TPrimPageSetupForm.Make(const aData: InsPageSettingsInfo;
const aParams : IvcmMakeParams = nil;
aZoneType : TvcmZoneType = vcm_ztAny;
aUserType : TvcmEffectiveUserType = 0;
aDataSource : IvcmFormDataSource = nil): IvcmEntityForm;
procedure AfterCreate(aForm : TPrimPageSetupForm);
begin
with aForm do
begin
//#UC START# *4AC607B7039E_4AAF8637036A_impl*
f_CurrentColontitul := -1;
// получим редактируемую конфигурацию
if (aData <> nil) then
f_PageSetup := aData
else
f_PageSetup := TnsPageSetup.Make;
// активная конфигурация не может отсутствовать
Assert(Assigned(f_PageSetup));
f_DisableControls := False;
ReadPageFormats;
PreviewGroupBox.Parent := SettingsPageControl.ActivePage;
SetColontitulComboBoxItemIndex(0);
ToGUIMargins;
//#UC END# *4AC607B7039E_4AAF8637036A_impl*
end;//with aForm
end;
var
l_AC : TvcmInitProc;
l_ACHack : Pointer absolute l_AC;
begin
l_AC := l3LocalStub(@AfterCreate);
try
Result := inherited Make(aParams, aZoneType, aUserType, nil, aDataSource, vcm_utAny, l_AC);
finally
l3FreeLocalStub(l_ACHack);
end;//try..finally
end;
procedure TPrimPageSetupForm.Cleanup;
//#UC START# *479731C50290_4AAF8637036A_var*
//#UC END# *479731C50290_4AAF8637036A_var*
begin
//#UC START# *479731C50290_4AAF8637036A_impl*
f_PageSetup := nil;
inherited;
//#UC END# *479731C50290_4AAF8637036A_impl*
end;//TPrimPageSetupForm.Cleanup
procedure TPrimPageSetupForm.MakeControls;
begin
inherited;
with AddUsertype(pstNoneName,
str_pstNoneCaption,
str_pstNoneCaption,
true,
-1,
-1,
'',
nil,
nil,
nil,
vcm_ccNone) do
begin
end;//with AddUsertype(pstNoneName
end;
{$IfEnd} //not Admin
initialization
{$If not defined(Admin)}
// Регистрация Tkw_PrimPageSetup_Control_PreviewGroupBox
Tkw_PrimPageSetup_Control_PreviewGroupBox.Register('контрол::PreviewGroupBox', TvtGroupBox);
{$IfEnd} //not Admin
{$If not defined(Admin)}
// Регистрация Tkw_PrimPageSetup_Control_PreviewGroupBox_Push
Tkw_PrimPageSetup_Control_PreviewGroupBox_Push.Register('контрол::PreviewGroupBox:push');
{$IfEnd} //not Admin
{$If not defined(Admin)}
// Регистрация Tkw_PrimPageSetup_Control_SettingsPageControl
Tkw_PrimPageSetup_Control_SettingsPageControl.Register('контрол::SettingsPageControl', TnscPageControl);
{$IfEnd} //not Admin
{$If not defined(Admin)}
// Регистрация Tkw_PrimPageSetup_Control_SettingsPageControl_Push
Tkw_PrimPageSetup_Control_SettingsPageControl_Push.Register('контрол::SettingsPageControl:push');
{$IfEnd} //not Admin
{$If not defined(Admin)}
// Инициализация str_pstNoneCaption
str_pstNoneCaption.Init;
{$IfEnd} //not Admin
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 ClpSecP521R1Field;
{$I ..\..\..\..\Include\CryptoLib.inc}
interface
uses
ClpNat,
ClpNat512,
ClpBigInteger,
ClpCryptoLibTypes;
type
// 2^521 - 1
TSecP521R1Field = class sealed(TObject)
strict private
const
P16 = UInt32($1FF);
class var
FP: TCryptoLibUInt32Array;
class function GetP: TCryptoLibUInt32Array; static; inline;
class procedure ImplMultiply(const x, y, zz: TCryptoLibUInt32Array);
static; inline;
class procedure ImplSquare(const x, zz: TCryptoLibUInt32Array);
static; inline;
class constructor SecP521R1Field();
public
class procedure Add(const x, y, z: TCryptoLibUInt32Array); static; inline;
class procedure AddOne(const x, z: TCryptoLibUInt32Array); static; inline;
class function FromBigInteger(const x: TBigInteger): TCryptoLibUInt32Array;
static; inline;
class procedure Half(const x, z: TCryptoLibUInt32Array); static; inline;
class procedure Multiply(const x, y, z: TCryptoLibUInt32Array);
static; inline;
class procedure Negate(const x, z: TCryptoLibUInt32Array); static; inline;
class procedure Reduce(const xx, z: TCryptoLibUInt32Array); static; inline;
class procedure Reduce23(const z: TCryptoLibUInt32Array); static; inline;
class procedure Square(const x, z: TCryptoLibUInt32Array); static; inline;
class procedure SquareN(const x: TCryptoLibUInt32Array; n: Int32;
const z: TCryptoLibUInt32Array); static; inline;
class procedure Subtract(const x, y, z: TCryptoLibUInt32Array);
static; inline;
class procedure Twice(const x, z: TCryptoLibUInt32Array); static; inline;
class property P: TCryptoLibUInt32Array read GetP;
end;
implementation
{ TSecP521R1Field }
class constructor TSecP521R1Field.SecP521R1Field;
begin
FP := TCryptoLibUInt32Array.Create($FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF,
$FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF,
$FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $1FF);
end;
class function TSecP521R1Field.GetP: TCryptoLibUInt32Array;
begin
result := FP;
end;
class procedure TSecP521R1Field.Add(const x, y, z: TCryptoLibUInt32Array);
var
c: UInt32;
begin
c := TNat.Add(16, x, y, z) + x[16] + y[16];
if ((c > P16) or ((c = P16) and (TNat.Eq(16, z, FP)))) then
begin
c := c + (TNat.Inc(16, z));
c := c and P16;
end;
z[16] := c;
end;
class procedure TSecP521R1Field.AddOne(const x, z: TCryptoLibUInt32Array);
var
c: UInt32;
begin
c := TNat.Inc(16, x, z) + x[16];
if ((c > P16) or ((c = P16) and (TNat.Eq(16, z, FP)))) then
begin
c := c + TNat.Inc(16, z);
c := c and P16;
end;
z[16] := c;
end;
class function TSecP521R1Field.FromBigInteger(const x: TBigInteger)
: TCryptoLibUInt32Array;
var
z: TCryptoLibUInt32Array;
begin
z := TNat.FromBigInteger(521, x);
if (TNat.Eq(17, z, FP)) then
begin
TNat.Zero(17, z);
end;
result := z;
end;
class procedure TSecP521R1Field.Half(const x, z: TCryptoLibUInt32Array);
var
x16, c: UInt32;
begin
x16 := x[16];
c := TNat.ShiftDownBit(16, x, x16, z);
z[16] := (x16 shr 1) or (c shr 23);
end;
class procedure TSecP521R1Field.ImplMultiply(const x, y,
zz: TCryptoLibUInt32Array);
var
x16, y16: UInt32;
begin
TNat512.Mul(x, y, zz);
x16 := x[16];
y16 := y[16];
zz[32] := TNat.Mul31BothAdd(16, x16, y, y16, x, zz, 16) + (x16 * y16);
end;
class procedure TSecP521R1Field.ImplSquare(const x, zz: TCryptoLibUInt32Array);
var
x16: UInt32;
begin
TNat512.Square(x, zz);
x16 := x[16];
zz[32] := TNat.MulWordAddTo(16, (x16 shl 1), x, 0, zz, 16) + (x16 * x16);
end;
class procedure TSecP521R1Field.Reduce23(const z: TCryptoLibUInt32Array);
var
z16, c: UInt32;
begin
z16 := z[16];
c := TNat.AddWordTo(16, (z16 shr 9), z) + (z16 and P16);
if ((c > P16) or ((c = P16) and (TNat.Eq(16, z, FP)))) then
begin
c := c + (TNat.Inc(16, z));
c := c and P16;
end;
z[16] := c;
end;
class procedure TSecP521R1Field.Reduce(const xx, z: TCryptoLibUInt32Array);
var
xx32, c: UInt32;
begin
{$IFDEF DEBUG}
System.Assert((xx[32] shr 18) = 0);
{$ENDIF DEBUG}
xx32 := xx[32];
c := TNat.ShiftDownBits(16, xx, 16, 9, xx32, z, 0) shr 23;
c := c + (xx32 shr 9);
c := c + (TNat.AddTo(16, xx, z));
if ((c > P16) or ((c = P16) and (TNat.Eq(16, z, FP)))) then
begin
c := c + (TNat.Inc(16, z));
c := c and P16;
end;
z[16] := c;
end;
class procedure TSecP521R1Field.Multiply(const x, y, z: TCryptoLibUInt32Array);
var
tt: TCryptoLibUInt32Array;
begin
tt := TNat.Create(33);
ImplMultiply(x, y, tt);
Reduce(tt, z);
end;
class procedure TSecP521R1Field.Negate(const x, z: TCryptoLibUInt32Array);
begin
if (TNat.IsZero(17, x)) then
begin
TNat.Zero(17, z);
end
else
begin
TNat.Sub(17, FP, x, z);
end;
end;
class procedure TSecP521R1Field.Square(const x, z: TCryptoLibUInt32Array);
var
tt: TCryptoLibUInt32Array;
begin
tt := TNat.Create(33);
ImplSquare(x, tt);
Reduce(tt, z);
end;
class procedure TSecP521R1Field.SquareN(const x: TCryptoLibUInt32Array;
n: Int32; const z: TCryptoLibUInt32Array);
var
tt: TCryptoLibUInt32Array;
begin
{$IFDEF DEBUG}
System.Assert(n > 0);
{$ENDIF DEBUG}
tt := TNat.Create(33);
ImplSquare(x, tt);
Reduce(tt, z);
System.Dec(n);
while (n > 0) do
begin
ImplSquare(z, tt);
Reduce(tt, z);
System.Dec(n);
end;
end;
class procedure TSecP521R1Field.Subtract(const x, y, z: TCryptoLibUInt32Array);
var
c: Int32;
begin
c := TNat.Sub(16, x, y, z) + Int32(x[16] - y[16]);
if (c < 0) then
begin
c := c + TNat.Dec(16, z);
c := c and P16;
end;
z[16] := UInt32(c);
end;
class procedure TSecP521R1Field.Twice(const x, z: TCryptoLibUInt32Array);
var
x16, c: UInt32;
begin
x16 := x[16];
c := TNat.ShiftUpBit(16, x, x16 shl 23, z) or (x16 shl 1);
z[16] := c and P16;
end;
end.
|
unit RequestWorksForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, FIBDataSet, pFIBDataSet, Grids, DBGridEh, ExtCtrls,
OkCancel_frame, GridsEh, StdCtrls, PropFilerEh,
PropStorageEh, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh,
DBGridEhGrouping, DynVarsEh, EhLibVCL;
type
TRequestWorksForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
dbGrid: TDBGridEh;
srcDataSource: TDataSource;
dsWorks: TpFIBDataSet;
OkCancelFrame1: TOkCancelFrame;
dbGridGroups: TDBGridEh;
cbAllMaterials: TCheckBox;
dsWorkGrps: TpFIBDataSet;
srcWorkGrps: TDataSource;
Splitter1: TSplitter;
PropStorage: TPropStorageEh;
procedure cbAllMaterialsClick(Sender: TObject);
procedure dbGridExit(Sender: TObject);
procedure dbGridGetCellParams(Sender: TObject; Column: TColumnEh;
AFont: TFont; var Background: TColor; State: TGridDrawState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure OkCancelFrame1bbOkClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
fEditMode : Byte;
public
{ Public declarations }
property EditMode : Byte read fEditMode write fEditMode;
end;
function ReqWorks(const aRequest:Integer; const aEditMode : Byte; const RQ_TYPE : Integer = -1): boolean;
var
RequestWorksForm: TRequestWorksForm;
implementation
uses DM, MAIN;
{$R *.dfm}
function ReqWorks(const aRequest:Integer; const aEditMode : Byte; const RQ_TYPE : Integer = -1): boolean;
begin
result := false;
with TRequestWorksForm.Create(Application) do
try
EditMode:=aEditMode;
dsWorkGrps.Open;
dsWorks.ParamByName('RQ_ID').AsInteger := aRequest;
dsWorks.Open;
if RQ_TYPE > -1 then dsWorkGrps.Locate('RT_ID', VarArrayOf([RQ_TYPE]),[]);
if ShowModal = mrOk
then result := true;
finally
free
end;
end;
procedure TRequestWorksForm.cbAllMaterialsClick(Sender: TObject);
var
s : string;
begin
dsWorks.Close;
s := dsWorks.SelectSQL.Text;
s := StringReplace(s,'and w.rq_type = :rt_id','',[rfReplaceAll, rfIgnoreCase]);
s := StringReplace(s,'ORDER BY 2','',[rfReplaceAll, rfIgnoreCase]);
dsWorks.SelectSQL.Text := Trim(s);
if not cbAllMaterials.Checked
then dsWorks.SelectSQL.Add(' and w.rq_type = :rt_id ');
dsWorks.SelectSQL.Add(' ORDER BY 2 ');
dsWorks.Open;
dbGridGroups.Visible := not cbAllMaterials.Checked;
end;
procedure TRequestWorksForm.dbGridExit(Sender: TObject);
begin
if (srcDataSource.DataSet.State in [dsInsert, dsEdit]) then srcDataSource.DataSet.Post;
end;
procedure TRequestWorksForm.dbGridGetCellParams(Sender: TObject;
Column: TColumnEh; AFont: TFont; var Background: TColor;
State: TGridDrawState);
begin
if gdFocused in State
then begin
if (Column.ReadOnly)
then begin
if not (dghPreferIncSearch in dbGrid.OptionsEh)
then dbGrid.OptionsEh := dbGrid.OptionsEh + [dghPreferIncSearch];
end
else begin
if dghPreferIncSearch in dbGrid.OptionsEh
then dbGrid.OptionsEh := dbGrid.OptionsEh - [dghPreferIncSearch];
end;
end
end;
procedure TRequestWorksForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dbGrid.SaveColumnsLayoutIni(A4MainForm.GetIniFileName, 'RecWorkGrid', true);
end;
procedure TRequestWorksForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN)
then OkCancelFrame1bbOkClick(sender);
end;
procedure TRequestWorksForm.FormShow(Sender: TObject);
begin
dbGrid.RestoreColumnsLayoutIni(A4MainForm.GetIniFileName, 'RecWorkGrid', [crpColIndexEh,crpColWidthsEh,crpColVisibleEh]);
end;
procedure TRequestWorksForm.OkCancelFrame1bbOkClick(Sender: TObject);
begin
OkCancelFrame1.actExitExecute(Sender);
ModalResult := mrOk;
end;
end.
|
unit uAsynchLoad;
interface
uses
System.Classes, System.SysUtils, System.SyncObjs,
REST.Client, REST.Types,
FMX.TMSBitmapContainer, FMX.Graphics;
type
TUpdateProc = procedure (bitmap : TBitmap; url : string) of object;
AsynchLoad = class(TThread)
protected
procedure Execute; override;
private
AURl : string;
RESTResponseImage: TRESTResponse;
RESTRequestImage: TRESTRequest;
RESTClientImage: TRESTClient;
FUpdateProc : TUpdateProc;
public
constructor Create(url : string; updateProc : TUpdateProc = nil);
end;
implementation
uses
formMain;
{ AsynchLoad }
{******************************************************************************}
constructor AsynchLoad.Create(url: string; updateProc: TUpdateProc);
begin
inherited Create(true);
if url.IsEmpty or (not Assigned(updateProc)) then
Terminate;
AURl := url;
FUpdateProc := updateProc;
RESTResponseImage := TRESTResponse.Create(nil);
RESTRequestImage := TRESTRequest.Create(nil);
RESTClientImage := TRESTClient.Create(nil);
RESTClientImage.BaseURL := AURl;
RESTRequestImage.Client := RESTClientImage;
RESTRequestImage.Response := RESTResponseImage;
end;
{******************************************************************************}
procedure AsynchLoad.Execute;
var
Image : TBitmap;
mStream : TMemoryStream;
begin
NameThreadForDebugging('AsynchLoad');
try
fRSS.Semafore.Acquire;
repeat
RESTRequestImage.Execute;
Image := TBitmap.Create;
mStream := TMemoryStream.Create;
try
mStream.WriteData(RESTResponseImage.RawBytes,
Length(RESTResponseImage.RawBytes));
mStream.Seek(0,0);
Image.LoadFromStream(mStream);
Synchronize
(
procedure
begin
FUpdateProc(Image, AURl);
end
);
finally
Terminate;
mStream.Free;
RESTResponseImage.FreeOnRelease;
RESTRequestImage.FreeOnRelease;
RESTClientImage.FreeOnRelease;
end;
until Terminated;
finally
fRSS.Semafore.Release;
end;
end;
{******************************************************************************}
end.
|
unit GX_XmlUtils;
interface
uses
OmniXML;
function CreateOrLoadFileToDom(const FileName, FileDescription: string;
const RootName: string = ''): IXMLDocument;
procedure AddXMLHeader(Doc: IXMLDocument);
function GetChildNodeOfType(Node: IXMLNode; NodeType: TNodeType): IXMLNode;
function GetCDataSectionTextOrNodeText(Node: IXMLNode): string;
function EscapeCDataText(const AText: string): string;
function UnEscapeCDataText(const AText: string): string;
implementation
uses
SysUtils;
function CreateOrLoadFileToDom(const FileName, FileDescription, RootName: string): IXMLDocument;
begin
Result := nil;
end;
(*
function CreateDom: TDomDocument;
begin
Result := TDomDocument.Create(TDomImplementation.Create(nil));
Result.AppendChild(Result.CreateXmlDeclaration('1.0', '', ''));
if RootName <> '' then
Result.AppendChild(Result.CreateElement(RootName));
end;
function LoadDom: TDomDocument;
const
Question = 'Your %s XML storage file appears corrupt:'+#13+#10+'%s'+#13+#10+'Would you like to delete and then recreate it?';
var
Parser: TXmlToDomParser;
begin
Result := nil;
Parser := TXmlToDomParser.Create(nil);
Parser.DOMImpl := TDomImplementation.Create(nil);
try
try
Result := Parser.fileToDom(FileName);
except on E: Exception do
begin
if MessageDlg(Format(Question, [FileDescription, E.Message]), mtConfirmation, [mbYes,mbNo], 0) = mrYes then
begin
DeleteFile(FileName);
Result := CreateDom;
end;
end;
end;
finally
FreeAndNil(Parser);
end;
end;
begin
if FileExists(FileName) then
begin
if GetFileSize(FileName) = 0 then
Result := CreateDom
else
Result := LoadDom;
end
else
Result := CreateDom;
end;
*)
procedure AddXMLHeader(Doc: IXMLDocument);
begin
Doc.AppendChild(Doc.CreateProcessingInstruction('xml', Format('version="1.0" encoding="%s"', ['UTF-8'])));
end;
function GetChildNodeOfType(Node: IXMLNode; NodeType: TNodeType): IXMLNode;
var
i: Integer;
begin
Assert(Assigned(Node));
Result := nil;
for i := 0 to Node.ChildNodes.Length - 1 do
begin
if Node.ChildNodes.Item[i].NodeType = NodeType then
begin
Result := Node.ChildNodes.Item[i];
Exit;
end;
end;
end;
function GetCDataSectionTextOrNodeText(Node: IXMLNode): string;
var
CDataNode: IXMLCDATASection;
begin
Assert(Assigned(Node));
Result := '';
if Node.ChildNodes.Length < 1 then
Exit;
CDataNode := (GetChildNodeOfType(Node, CDATA_SECTION_NODE) as IXMLCDataSection);
if Assigned(CDataNode) then
Result := UnEscapeCDataText(CDataNode.Data)
else
Result := Node.Text;
end;
const
CDataEndMarker = ']]>';
CDataEndMarkerEscape = '&GXCDataEndSectionEscape;';
function EscapeCDataText(const AText: string): string;
begin
Result := StringReplace(AText, CDataEndMarker, CDataEndMarkerEscape, [rfReplaceAll]);
end;
function UnEscapeCDataText(const AText: string): string;
begin
Result := StringReplace(AText, CDataEndMarkerEscape, CDataEndMarker, [rfReplaceAll]);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.