text stringlengths 14 6.51M |
|---|
{ Memory allocation and deallocation routines.
}
module ray_mem;
define ray_mem_alloc_perm;
%include 'ray2.ins.pas';
{
********************************************************************************
*
* Function RAY_MEM_ALLOC_PERM (SIZE)
*
* Allocate memory under the ray tracer context. This memory can not later be
* deallocated. It persists until the ray tracer memory context is deleted.
*
* The function returns a pointer to the start of the new memory. The program
* is bombed with error if the new memory is not available.
}
function ray_mem_alloc_perm ( {alloc un-releasable mem under ray tracer context}
in size: sys_int_adr_t) {amount of memory to allocate}
:univ_ptr; {pnt to new mem, bombs prog on no mem}
val_param;
var
p: univ_ptr; {pointer to the new memory}
begin
util_mem_grab ( {allocate dynamic memory}
size, {amount of memory to allocate}
ray_mem_p^, {memory context to allocate under}
false, {will not individually dealloc this memory}
p); {returned pointer to the new memory}
ray_mem_alloc_perm := p; {return pointer to the new memory}
end;
|
unit Model.ProSu.Subscriber;
interface
uses
Model.ProSu.Interfaces;
type
TProSuSubscriber = class(TInterfacedObject, ISubscriberInterface)
private
fUpdateMethod: TUpdateSubscriberMethod;
public
procedure updateSubscriber(const notifyClass: INotificationClass);
procedure setUpdateSubscriberMethod(newMethod: TUpdateSubscriberMethod);
end;
implementation
{ TProSuSubscriber }
procedure TProSuSubscriber.setUpdateSubscriberMethod(
newMethod: TUpdateSubscriberMethod);
begin
fUpdateMethod := newMethod;
end;
procedure TProSuSubscriber.updateSubscriber(
const notifyClass: INotificationClass);
begin
if Assigned(fUpdateMethod) then
fUpdateMethod(notifyClass);
end;
end.
|
unit JSONBr_Tests;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TTestJSONBr = class
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
// Sample Methods
// Simple single Test
[Test]
procedure TestAddPair_1;
end;
implementation
uses
jsonbr;
procedure TTestJSONBr.Setup;
begin
end;
procedure TTestJSONBr.TearDown;
begin
end;
procedure TTestJSONBr.TestAddPair_1;
var
LResult: String;
const
LJSON = '[{"ID":1,"Name":"Json"},[{"ID":2,"Name":"Json 2"},{"ID":3,"Name":"Json 3"}]]';
begin
LResult := TJSONBr
.BeginArray
.BeginObject
.AddPair('ID', 1)
.AddPair('Name', 'Json')
.EndObject
.BeginArray
.BeginObject
.AddPair('ID', 2)
.AddPair('Name', 'Json 2')
.EndObject
.BeginObject
.AddPair('ID', 3)
.AddPair('Name', 'Json 3')
.EndObject
.EndArray
.EndArray
.ToJSON;
Assert.AreEqual(LResult, LJSON, 'Não gerou conforme valor da constante!');
end;
initialization
TDUnitX.RegisterTestFixture(TTestJSONBr);
end.
|
unit Grijjy.LineNumberInfo;
{< Utilities for loading line number information from a .gol file.
Is used by the exception logger to retrieve line numbers from code addresses.
Currently only used for Intel 64-bit macOS.
Line number information files are generated by the Line Number Generator (LNG)
tool in the Tools directory.
The .gol file format is loosely modelled after the DWARF __debug_line section
format:
* 4 bytes: signature ('GOLN')
* 4 bytes: version in $MMMMmmmm format. M=Major version, m=minor version.
A change in minor version should not break the format.
A reader cannot read a file with a major version that is larger then the
one the reader is built for.
* 4 bytes: total size of the .gol file (use for sanity checking)
* 4 bytes: Number of line number entries in the file.
* 16 bytes: GUID of the mach-o executable and dSYM that was used to generate
the file.
* 8 bytes: starting VM address.
* 4 bytes: line number of starting VM address
What follows is a simple state machine program with instructions to build a
line number table. Each instruction starts with a single byte (Opcode) and can
optionally have arguments.
A simple compression algorithm is used that takes advantage of the facts that
VM addresses always increase, and the difference between consecutive VM
addresses is usually small. Similarly, it is efficient if the difference
between two consecutive line numbers is small. A lot of the time, line numbers
are increasing, but because of optimization and (compilation) unit changes,
line numbers may also decrease.
Opcodes 0-251 are used to update the address and line number, and add a new
entry all at once. It is used when the difference between the new address and
the previous address is at most 63, and the difference between the new line
number and previous line number is between 1 and 4 (inclusive). The Opcode is
than calculated as:
Opcode := (LineAdvance - 1) + (AddressAdvance - 1) * 4
So the mapping looks like:
Opcode LineAdvance AddressAdvance
0 1 1
1 2 1
2 3 1
3 4 1
4 1 2
5 2 2
...
247 4 62
248 1 63
249 2 63
250 3 63
251 4 63
Opcodes 252-255 have specific meaning. Only 252-254 are currently used:
252 OP_ADVANCE_ADDR: adds the value 63 to the current address. Is used when
the total address advance is between 63 and 126 and the line advance is
between 1 and 4. This opcode should be followed by a regular opcode in
the 0-247 range to set the final address and line.
253 OP_ADVANCE_REL: takes 2 VarInt arguments:
* the address advance. Increments the current address with this value +1
* the line advance. Increments the current line with this value +1
Adds an entry to the line number table with the new address and line.
254 OP_ADVANCE_ABS: takes 2 VarInt arguments:
* the address advance. Increments the current address with this value +1
* the line number. Sets the current line to this value (*not +1)
Adds an entry to the line number table with the new address and line.
The VarInt format is identical to an unsigned LEB128 format in the DWARF
specification. Basically, an unsigned integer value is split into chunks of
7 bits. Each 7-bit chunk is encoded in a 8-bit byte, where the highest bit
indicates if another 7-bit chunk follows. }
{$SCOPEDENUMS ON}
interface
const
{ Signature of line number files. }
LINE_NUMBER_SIGNATURE = $4E4C4F47; // 'GOLN'
{ Current version of line number information. }
LINE_NUMBER_VERSION = $00010000;
const
{ Opcodes for the state machine program }
OP_ADVANCE_ADDR = 252;
OP_ADVANCE_REL = 253;
OP_ADVANCE_ABS = 254;
type
{ .gol file header }
TgoLineNumberHeader = packed record
public
{ File signature. Should be LINE_NUMBER_SIGNATURE }
Signature: UInt32;
{ File version.
A change in minor version should not break the format.
A reader cannot read a file with a major version that is larger then the
one the reader is built for. }
Version: UInt32;
{ Total size of the file }
Size: UInt32;
{ Number of line number entries in the file }
Count: Int32;
{ ID of the mach-o executable and dSYM that was used to generate the file. }
ID: TGUID;
{ Starting VM address. }
StartVMAddress: UInt64;
{ Line number of start address. }
StartLine: UInt32;
end;
type
{ Possible values for TgoLineNumberInfo.Status }
TgoLineNumberStatus = (
{ Line number information is available }
Available,
{ Line number information file (.gol) not found }
FileNotFound,
{ Line number information file has invalid size (incomplete) }
InvalidSize,
{ Line number information file has invalid signature }
InvalidSignature,
{ Line number information file has unsupported version }
UnsupportedVersion,
{ Line number information file does not match corresponding executable }
ExecutableIDMismatch,
{ Line number information file is corrupt }
FileCorrupt,
{ Exception occurred during loading of the file number information file }
Exception);
type
{ Contains line number information for the currently loaded application. }
TgoLineNumberInfo = class
{$REGION 'Internal Declarations'}
private type
TLine = record
RelAddress: UInt32;
Line: Int32;
end;
private
FBaseAddress: UInt64;
FLines: TArray<TLine>;
FStatus: TgoLineNumberStatus;
function Load: TgoLineNumberStatus;
private
{$IF Defined(MACOS64) and not Defined(IOS)}
class function ReadVarInt(var ABuf: PByte; const ABufEnd: PByte;
out AValue: UInt32): Boolean; static;
{$ENDIF}
{$ENDREGION 'Internal Declarations'}
public
constructor Create;
{ Returns source line number corresponding to given address, or 0 if not
available. }
function Lookup(const AAddress: UIntPtr): Integer;
{ Status of the line number information file. }
property Status: TgoLineNumberStatus read FStatus;
end;
implementation
uses
System.Generics.Defaults,
System.Generics.Collections,
{$IF Defined(MACOS64) and not Defined(IOS)}
Grijjy.MachOApi,
Macapi.Foundation,
Macapi.Helpers,
System.IOUtils,
{$ENDIF}
System.Classes,
System.SysUtils;
{$IF Defined(MACOS64) and not Defined(IOS)}
const
libDyld = '/usr/lib/system/libdyld.dylib';
function _dyld_get_image_header(image_index: UInt32): Pmach_header_64;
cdecl; external libDyld;
function _dyld_get_image_vmaddr_slide(image_index: UInt32): UInt32;
cdecl; external libDyld;
function GetID: TGUID;
var
Header: Pmach_header_64;
Cmd: Pload_command;
Uuid: Puuid_command absolute Cmd;
I: Integer;
begin
Header := _dyld_get_image_header(0);
Cmd := Pointer(UIntPtr(Header) + SizeOf(mach_header_64));
for I := 0 to Header.ncmds - 1 do
begin
if (Cmd.cmd = LC_UUID) then
Exit(TGUID(Uuid.uuid));
Cmd := Pointer(UIntPtr(Cmd) + Cmd.cmdsize);
end;
Result := TGUID.Empty;
end;
{$ENDIF}
{ TgoLineNumberInfo }
constructor TgoLineNumberInfo.Create;
begin
inherited;
FStatus := Load;
end;
{$IF Defined(MACOS64) and not Defined(IOS)}
function TgoLineNumberInfo.Load: TgoLineNumberStatus;
var
Filename: String;
Stream: TFileStream;
Header: TgoLineNumberHeader;
Line: TLine;
Lines: TArray<TLine>;
StateMachineProgram: TBytes;
PC, PCEnd: PByte;
Opcode: Byte;
I: Integer;
A1, A2: UInt32;
ContentsResourcesPath: String;
begin
FBaseAddress := 0;
FLines := nil;
Filename := ParamStr(0) + '.gol';
if (not FileExists(Filename)) then
begin
{ MacOS only allows modules that are signable in the /Contents/MacOS/ path for signed/notarized apps }
ContentsResourcesPath := NSStrToStr(TNSBundle.Wrap(TNSBundle.OCClass.mainBundle).bundlePath) + '/Contents/Resources/';
Filename := ContentsResourcesPath + TPath.GetFileName(ParamStr(0)) + '.gol';
end;
if (not FileExists(Filename)) then
Exit(TgoLineNumberStatus.FileNotFound);
try
Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
try
if (Stream.Read(Header, SizeOf(Header)) <> SizeOf(Header)) then
Exit(TgoLineNumberStatus.InvalidSize);
if (Header.Signature <> LINE_NUMBER_SIGNATURE) then
Exit(TgoLineNumberStatus.InvalidSignature);
if ((Header.Version shr 16) > (LINE_NUMBER_VERSION shr 16)) then
Exit(TgoLineNumberStatus.UnsupportedVersion);
if (Header.Size <> Stream.Size) then
Exit(TgoLineNumberStatus.InvalidSize);
if (Header.ID <> GetID) then
Exit(TgoLineNumberStatus.ExecutableIDMismatch);
SetLength(StateMachineProgram, Header.Size - SizeOf(Header));
if (Stream.Read(StateMachineProgram[0], Length(StateMachineProgram)) <> Length(StateMachineProgram)) then
Exit(TgoLineNumberStatus.InvalidSize);
finally
Stream.Free;
end;
FBaseAddress := Header.StartVMAddress + _dyld_get_image_vmaddr_slide(0);
SetLength(Lines, Header.Count + 1);
{ Run state machine program }
Line.RelAddress := 0;
Line.Line := Header.StartLine;
Lines[0] := Line;
PC := @StateMachineProgram[0];
PCEnd := @StateMachineProgram[Length(StateMachineProgram)];
for I := 1 to Header.Count do
begin
if (PC >= PCEnd) then
Exit(TgoLineNumberStatus.FileCorrupt);
Opcode := PC^;
Inc(PC);
if (OpCode < OP_ADVANCE_ADDR) then
begin
{ 1-byte opcode }
Inc(Line.RelAddress, (OpCode shr 2) + 1);
Inc(Line.Line, (OpCode and 3) + 1);
end
else case OpCode of
OP_ADVANCE_ADDR:
begin
{ 2-byte opcode }
if (PC >= PCEnd) then
Exit(TgoLineNumberStatus.FileCorrupt);
Inc(Line.RelAddress, 63);
Opcode := PC^;
Inc(PC);
if (Opcode < OP_ADVANCE_ADDR) then
begin
Inc(Line.RelAddress, (OpCode shr 2) + 1);
Inc(Line.Line, (OpCode and 3) + 1);
end
else
Exit(TgoLineNumberStatus.FileCorrupt);
end;
OP_ADVANCE_REL,
OP_ADVANCE_ABS:
begin
{ Updates are provided in 2 VarInt parameters }
if (not ReadVarInt(PC, PCEnd, A1)) then
Exit(TgoLineNumberStatus.FileCorrupt);
if (not ReadVarInt(PC, PCEnd, A2)) then
Exit(TgoLineNumberStatus.FileCorrupt);
Inc(Line.RelAddress, A1 + 1);
if (Opcode = OP_ADVANCE_REL) then
Inc(Line.Line, A2 + 1)
else
Line.Line := A2;
end;
else
Exit(TgoLineNumberStatus.FileCorrupt);
end;
Lines[I] := Line;
end;
FLines := Lines;
Result := TgoLineNumberStatus.Available;
except
Result := TgoLineNumberStatus.Exception;
end;
end;
{$ELSE}
function TgoLineNumberInfo.Load: TgoLineNumberStatus;
begin
Result := TgoLineNumberStatus.FileNotFound;
end;
{$ENDIF}
function TgoLineNumberInfo.Lookup(const AAddress: UIntPtr): Integer;
var
RelAddress, ActualAddress: UInt64;
Line: TLine;
Index: Integer;
begin
if (FStatus <> TgoLineNumberStatus.Available) then
Exit(0);
if (AAddress < FBaseAddress) then
Exit(0);
RelAddress := AAddress - FBaseAddress;
if (RelAddress > $FFFFFFFF) then
Exit(0);
Line.RelAddress := RelAddress;
if (not TArray.BinarySearch<TLine>(FLines, Line, Index, TComparer<TLine>.Construct(
function(const ALeft, ARight: TLine): Integer
begin
Result := ALeft.RelAddress - ARight.RelAddress;
end)))
then
{ When there is not an exact match, Index is set to the index in the array
*before* which we would place the value. }
Dec(Index);
if (Index < 0) or (Index >= Length(FLines)) then
Exit(0);
{ Check if address at this index is close enough to the requested address.
If not, the resulting line number will be unreliable. This is common for
addresses which were not available in the dSYM, for example for RTL/VCL/FMX
addresses when the "Use debug .dcus" project option is not set. }
ActualAddress := FBaseAddress + FLines[Index].RelAddress;
if ((AAddress - ActualAddress) > 200) then
Exit(0);
Result := FLines[Index].Line;
end;
{$IF Defined(MACOS64) and not Defined(IOS)}
class function TgoLineNumberInfo.ReadVarInt(var ABuf: PByte; const ABufEnd: PByte;
out AValue: UInt32): Boolean;
var
Value: UInt32;
Shift: Integer;
B: Byte;
P: PByte;
begin
Value := 0;
Shift := 0;
P := ABuf;
while (True) do
begin
if (P >= ABufEnd) then
Exit(False);
B := P^;
Inc(P);
Value := Value or ((B and $7F) shl Shift);
if ((B and $80) = 0) then
Break;
Inc(Shift, 7);
end;
ABuf := P;
AValue := Value;
Result := True;
end;
{$ENDIF}
end.
|
unit InfraVCLInteractor;
interface
uses
InfraCommon,
InfraInteractor,
InfraCommonIntf,
InfraMVPVCLIntf;
type
TObjectSelectionUpdater = class(TInteractor, IObjectSelectionUpdater)
private
procedure ControlEnterEvent(const Event: IInfraEvent);
procedure ControlExitEvent(const Event: IInfraEvent);
protected
function ApplyFilter(const Event: IInfraEvent): Boolean;
public
procedure InfraInitInstance; override;
end;
TExitEventModelUpdater = class(TInteractor, IExitEventModelUpdater)
protected
procedure ControlExitEvent(const Event: IInfraEvent);
public
procedure InfraInitInstance; override;
end;
TClickEventModelUpdater = class(TInteractor, IClickEventModelUpdater)
protected
procedure ClickEvent(const Event: IInfraEvent);
public
procedure InfraInitInstance; override;
end;
TKeyBoardInteractor = class(TInteractor, IKeyBoardInteractor)
protected
procedure KeyDownEvent(const Event: IInfraEvent); virtual;
procedure KeyPressEvent(const Event: IInfraEvent); virtual;
procedure KeyUPEvent(const Event: IInfraEvent); virtual;
public
procedure InfraInitInstance; override;
end;
TInputNumberInteractor = class(TKeyBoardInteractor,
IInputNumberInteractor)
private
FAcceptDecimals: boolean;
FAcceptSignal: boolean;
protected
procedure KeyPressEvent(const Event: IInfraEvent); override;
function GetAcceptDecimals: boolean;
function GetAcceptSignal: boolean;
procedure SetAcceptDecimals(const Value: boolean);
procedure SetAcceptSignal(const Value: boolean);
property AcceptDecimals: boolean read GetAcceptDecimals write SetAcceptDecimals;
property AcceptSignal: boolean read GetAcceptSignal write SetAcceptSignal;
public
procedure InfraInitInstance; override;
end;
implementation
uses
SysUtils,
InfraMVPIntf,
InfraValueTypeIntf;
{ TObjectSelectionUpdater }
procedure TObjectSelectionUpdater.InfraInitInstance;
begin
inherited;
EventService.Subscribe(IExitEvent, Self as ISubscriber,
ControlExitEvent, EmptyStr, ApplyFilter);
EventService.Subscribe(IEnterEvent, Self as ISubscriber,
ControlEnterEvent, EmptyStr, ApplyFilter);
end;
function TObjectSelectionUpdater.ApplyFilter(const Event: IInfraEvent): Boolean;
begin
Result := View.HasSubViews and ((Event.Source as IView).ParentView = View);
end;
procedure TObjectSelectionUpdater.ControlExitEvent(const Event: IInfraEvent);
begin
inherited Inform(Event);
View.Model.Selection.Clear;
end;
procedure TObjectSelectionUpdater.ControlEnterEvent(const Event: IInfraEvent);
begin
inherited Inform(Event);
with View.Model do
Selection.Add(Value as IInfraType);
end;
{ TExitEventModelUpdater }
procedure TExitEventModelUpdater.InfraInitInstance;
begin
inherited;
EventService.Subscribe(IExitEvent, Self as ISubscriber,
ControlExitEvent, 'View');
end;
procedure TExitEventModelUpdater.ControlExitEvent(const Event: IInfraEvent);
begin
inherited Inform(Event);
View.UpdateModel;
end;
{ TClickEventModelUpdater }
procedure TClickEventModelUpdater.InfraInitInstance;
begin
inherited;
EventService.Subscribe(IClickEvent, Self as ISubscriber,
ClickEvent, 'View');
end;
procedure TClickEventModelUpdater.ClickEvent(const Event: IInfraEvent);
begin
View.UpdateModel;
end;
{ TKeyBoardInteractor }
procedure TKeyBoardInteractor.InfraInitInstance;
begin
inherited;
EventService.Subscribe(IKeyPressEvent, Self as ISubscriber,
KeyPressEvent, 'View');
EventService.Subscribe(IKeyDownEvent, Self as ISubscriber,
KeyDownEvent, 'View');
EventService.Subscribe(IKeyUpEvent, Self as ISubscriber,
KeyUPEvent, 'View');
end;
procedure TKeyBoardInteractor.KeyDownEvent(const Event: IInfraEvent);
begin
// implemented on descendents
end;
procedure TKeyBoardInteractor.KeyPressEvent(const Event: IInfraEvent);
begin
// implemented on descendents
end;
procedure TKeyBoardInteractor.KeyUpEvent(const Event: IInfraEvent);
begin
// implemented on descendents
end;
{ TInputNumberInteractor }
procedure TInputNumberInteractor.InfraInitInstance;
begin
inherited;
FAcceptDecimals := True;
FAcceptSignal := True;
end;
function TInputNumberInteractor.GetAcceptDecimals: boolean;
begin
Result := FAcceptDecimals;
end;
function TInputNumberInteractor.GetAcceptSignal: boolean;
begin
Result := FAcceptSignal;
end;
procedure TInputNumberInteractor.KeyPressEvent(const Event: IInfraEvent);
var
KeyPress: IKeyPressEvent;
OldText: string;
begin
inherited KeyPressEvent(Event);
OldText := (View as IVCLCustomEditView).Text;
KeyPress := Event as IKeyPressEvent;
if (not FAcceptSignal and (KeyPress.Key in [ThousandSeparator, '-'])) or
(not FAcceptDecimals and (KeyPress.Key = DecimalSeparator)) then
KeyPress.Key := #0
else if FAcceptSignal and (KeyPress.Key = '-') and
(Pos('-', OldText) <> 0) { TO_DO 001 } then
KeyPress.Key := #0
else if FAcceptDecimals and (KeyPress.Key = DecimalSeparator) and
(Pos(DecimalSeparator, OldText) <> 0) then
KeyPress.Key := #0
else if not (KeyPress.Key in ['0'..'9', #8, '-', DecimalSeparator,
ThousandSeparator]) then
KeyPress.Key := #0
end;
procedure TInputNumberInteractor.SetAcceptDecimals(
const Value: boolean);
begin
FAcceptDecimals := Value;
end;
procedure TInputNumberInteractor.SetAcceptSignal(
const Value: boolean);
begin
FAcceptSignal := Value;
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin,
Vcl.Buttons, Vcl.ComCtrls;
type
TMainForm = class(TForm)
lblCounter: TLabel;
edtDate: TEdit;
gpbBreakfast: TGroupBox;
gpbLunch: TGroupBox;
gpbDinner: TGroupBox;
seBreakfast: TSpinEdit;
seLunch: TSpinEdit;
seDinner: TSpinEdit;
memReport: TMemo;
btnTotalForToday: TButton;
btnDisplaySummary: TButton;
btnDisplayMiddayReport: TButton;
btnDisplayWarning: TButton;
btnGenerateRemark: TButton;
bmbReset: TBitBtn;
dtpDateToday: TDateTimePicker;
procedure FormShow(Sender: TObject);
procedure btnTotalForTodayClick(Sender: TObject);
procedure btnGenerateRemarkClick(Sender: TObject);
procedure btnDisplayMiddayReportClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.btnDisplayMiddayReportClick(Sender: TObject);
// Button to Display Midday report for BreakFast and Lunch Cals intake
// Declare required Vars
Var
iBreakfastCals,iLunchCals,iTotalCals : Integer;
sRemark : String;
begin
// Assign Values to var
iBreakfastCals := MainForm.seBreakfast.Value;
iLunchCals := MainForm.seLunch.Value;
iTotalCals := iBreakfastCals + iLunchCals;
// Check to see if total cals is > 0 if not display msg say no intake insteak of showing 0 else show total cals
If (iTotalCals > 0) Then Begin
sRemark := 'Total thus far: ' + IntToStr(iTotalCals) + ' calories.';
End Else Begin
sRemark := 'No calories entered/consumed yet!';
End;
// Display result to User
memReport.Lines.Add('Display Midday Report for:' + MainForm.edtDate.Text);
memReport.Lines.Add(sRemark);
memReport.Lines.Add('Always eat Healthy!');
memReport.Lines.Add('*** End of Midday Report ***');
memReport.Lines.Add(''); // Add Blank line after report
end;
procedure TMainForm.btnGenerateRemarkClick(Sender: TObject);
// Button to Generate a remark on Daily Cal intake
// Declare Vars needed
Var
iBreakFast, iLunch, iDinner, iCount : Integer;
sRemark : String;
begin
// Assign Values to Vars
iCount := 0;
iBreakFast := MainForm.seBreakfast.Value;
iLunch := MainForm.seBreakfast.Value;
iDinner := MainForm.seBreakfast.Value;
// Inc Counter for each meal time where cals > 0
If (iBreakFast > 0) Then Inc(iCount,1);
If (iLunch > 0) Then Inc(iCount,1);
If (iDinner > 0) Then Inc(iCount,1);
// Use counter in Case to see how many meal times cals consumed
Case iCount of
0 : sRemark := 'No calories consumed.';
1 : sRemark := 'Be careful not to skip another meal.';
2 : sRemark := 'Be careful not to skip another meal.';
3 : sRemark := 'Daily entry complete!';
End;
// Display result to User
memReport.Lines.Add('Generate Remark for:' + MainForm.edtDate.Text);
memReport.Lines.Add(sRemark);
memReport.Lines.Add('*** End of Remark ***');
memReport.Lines.Add(''); // Add Blank line after report
end;
procedure TMainForm.btnTotalForTodayClick(Sender: TObject);
begin
seBreakfast.Enabled := FALSE;
seLunch.Enabled := FALSE;
seDinner.Enabled := FALSE;
btnDisplaySummary.Enabled := TRUE;
btnGenerateRemark.Enabled := TRUE;
btnDisplayWarning.Enabled := TRUE;
end;
procedure TMainForm.FormShow(Sender: TObject);
var
dDate : TDate;
begin
//set the date to the current date
dDate := Date();
edtDate.Text := DateToStr(dDate);
edtDate.ReadOnly := TRUE;
dtpDateToday.Date := Date();
end;
end.
|
{$include kode.inc}
unit kode_surface_xlib;
{
pixmap
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
X, Xlib, Xutil,
{$ifdef KODE_XRENDER}
KODE_XRENDER_UNIT,//XRender,
{$endif}
kode_bitmap,
kode_surface_base;
//kode_xlib;
type
KSurface_Xlib = class(KSurface_Base)
private
FWidth : LongWord;
FHeight : LongWord;
FDepth : LongWord;
FBuffer : Pointer;
private
FDisplay : PDisplay;
FDrawable : TDrawable;
FPixmap : TPixmap;
{$ifdef KODE_XRENDER}
FPicture : longint;
{$endif}
public
property width : LongWord read FWidth;
property height : LongWord read FHeight;
property depth : LongWord read FDepth;
property buffer : Pointer read FBuffer;
public
property display : PDisplay read FDisplay;
property drawable : TDrawable read FDrawable;
property pixmap : TPixmap read FPixmap;
{$ifdef KODE_XRENDER}
property picture : longint read FPicture;
{$endif}
private
{$ifdef KODE_XRENDER}
function find_format(ADisplay:PDisplay; ADepth:longint) : PXRenderPictFormat;
{$endif}
public
constructor create(AWidth,AHeight,ADepth:LongWord; ADisplay:PDisplay; ADrawable:TDrawable);
//constructor create(AWidth,AHeight,ADepth:LongWord; AWindow:Pointer);
//constructor create(AWidth,AHeight,ADepth:LongWord; ASurface:Pointer);
//constructor create(AWidth,AHeight,ADepth:LongWord; ACanvas:Pointer);
destructor destroy; override;
end;
//----------
KSurface_Implementation = KSurface_Xlib;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
kode_debug,
kode_memory;
//----------
constructor KSurface_Xlib.create(AWidth,AHeight,ADepth:LongWord; ADisplay:PDisplay; ADrawable:TDrawable);
{$ifdef KODE_XRENDER}
var
fmt : PXRenderPictFormat;
pict_attr : TXRenderPictureAttributes;
pict_bits : longint;
{$endif}
begin
inherited Create;
//KTrace([' KSurface_Xlib.create',KODE_CR]);
FWidth := AWidth;
FHeight := AHeight;
FDepth := ADepth;
FBuffer := nil;
FDisplay := ADisplay;
FDrawable := ADrawable;
//KTrace([' 1', KODE_CR]);
//FDepth = DefaultDepth(FDisplay,DefaultScreen(mDisplay));
{
The server uses the specified drawable to determine on which screen
to create the pixmap. The pixmap can be used only on this screen and
only with other drawables of the same depth (see XCopyPlane for an
exception to this rule).
}
//KTrace(['KSurface_Xlib.create', KODE_CR]);
//KTrace([' FDisplay = ',FDisplay, KODE_CR]);
//KTrace([' FDrawable = ',Pointer(FDrawable), KODE_CR]);
FPixmap := XCreatePixmap(FDisplay,FDrawable,FWidth,FHeight,FDepth);
//KTrace([' FPixmap = ',Pointer(FPixmap), KODE_CR]);
//KTrace([' 2', KODE_CR]);
{$ifdef KODE_XRENDER}
if FDepth = 24 then fmt := XRenderFindStandardFormat(FDisplay,PictStandardRGB24)
else fmt := XRenderFindStandardFormat(FDisplay,PictStandardARGB32);
//KTrace([' 3', KODE_CR]);
//if FDepth = 24 then fmt := find_format(FDisplay,24{PictStandardRGB24})
//else fmt := find_format(FDisplay,32{PictStandardARGB32});
pict_attr.poly_edge := PolyEdgeSmooth;
pict_attr.poly_mode := PolyModeImprecise;
//pict_attr.component_alpha = true;
pict_bits := {CPComponentAlpha or} CPPolyEdge or CPPolyMode;
FPicture := XRenderCreatePicture(FDisplay,FPixmap,fmt,pict_bits,@pict_attr);
//KTrace([' 4', KODE_CR]);
{$endif}
end;
//----------
destructor KSurface_Xlib.destroy;
begin
{$ifdef KODE_XRENDER}
XRenderFreePicture(FDisplay,FPicture);
{$endif}
{
The XFreePixmap() function first deletes the association between the pixmap ID and the pixmap.
Then, the X server frees the pixmap storage when there are no references to it.
}
XFreePixmap(FDisplay,FPixmap);
inherited;
end;
//----------------------------------------------------------------------
{
http://www.winehq.org/pipermail/wine-patches/2005-August/020119.html
Avoid using XRenderFindStandardFormat as older libraries don't have it
src_format = pXRenderFindStandardFormat(gdi_display, PictStandardARGB32);
src_format = pXRenderFindStandardFormat(gdi_display, PictStandardARGB32);
-->
XRenderPictFormat argb32_templ = {
0, // id
PictTypeDirect, // type
32, // depth
{ // direct
16, // direct.red
0xff, // direct.redMask
8, // direct.green
0xff, // direct.greenMask
0, // direct.blue
0xff, // direct.blueMask
24, // direct.alpha
0xff, // direct.alphaMask
},
0, // colormap
};
unsigned long argb32_templ_mask =
PictFormatType |
PictFormatDepth |
PictFormatRed |
PictFormatRedMask |
PictFormatGreen |
PictFormatGreenMask |
PictFormatBlue |
PictFormatBlueMask |
PictFormatAlpha |
PictFormatAlphaMask;
src_format = pXRenderFindFormat(gdi_display, argb32_templ_mask, &argb32_templ, 0);
}
//----------
{$ifdef KODE_XRENDER}
var
argb_templ : TXRenderPictFormat =
(
id : 0;
_type : PictTypeDirect;
depth : 32;
direct :
(
red:16;
redMask:$ff;
green:8;
greenMask:$ff;
blue:0;
blueMask:$ff;
alpha:24;
alphaMask:$ff;
);
colormap : 0;
);
argb_templ_mask : longword =
PictFormatType or
PictFormatDepth or
PictFormatRed or
PictFormatRedMask or
PictFormatGreen or
PictFormatGreenMask or
PictFormatBlue or
PictFormatBlueMask or
PictFormatAlpha or
PictFormatAlphaMask;
//----------
function KSurface_Xlib.find_format(ADisplay:PDisplay; ADepth:longint) : PXRenderPictFormat;
begin
//case ADepth of
// 24: result := XRenderFindStandardFormat(FDisplay,PictStandardRGB24);
// 32: result := XRenderFindStandardFormat(FDisplay,PictStandardRGB32);
//end;
case ADepth of
24: argb_templ.depth := 24;
32: argb_templ.depth := 32;
end;
result := XRenderFindFormat(FDisplay, argb_templ_mask, @argb_templ, 0);
end;
{$endif} // KODE_XRENDER
//----------------------------------------------------------------------
end.
|
Unit AnsiStringBuilder;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
Classes,
SysUtils,
AdvObjects,
AdvStreams;
Type
TAnsiStringBuilder = Class(TAdvObject)
Private
FContent : AnsiString;
FLength : Integer;
FBufferSize : integer;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function AsString : AnsiString;
Function ToString : String; override;
Procedure Clear;
Procedure Append(ch : AnsiChar); Overload;
Procedure Append(Const sStr : AnsiString); Overload;
Procedure AppendLine(Const sStr : AnsiString); Overload;
Procedure Append(Const iInt : Integer); Overload;
Procedure AppendPadded(Const sStr : AnsiString; iCount : Integer; cPad : AnsiChar = ' ');
Procedure AppendFixed(Const sStr : AnsiString; iCount : Integer; cPad : AnsiChar = ' ');
Procedure Append(const bBytes : Array of Byte; amount : Integer); Overload;
Procedure Append(Const oBuilder : TAnsiStringBuilder); Overload;
Procedure AppendEOL;
Procedure CommaAdd(Const sStr : AnsiString); Overload;
Procedure AddByteAsBytes(iVal : Byte);
Procedure AddWordAsBytes(iVal : word);
Procedure AddCardinalAsBytes(iVal : Cardinal);
Procedure AddInt64AsBytes(iVal : Int64);
// index is zero based. zero means insert before first character
Procedure Insert(Const sStr : AnsiString; iIndex : Integer); Overload;
Procedure Insert(Const oBuilder : TAnsiStringBuilder; iIndex : Integer); Overload;
Procedure Delete(iIndex, iLength : Integer);
Property BufferSize : integer read FBufferSize write FBufferSize;
Function IndexOf(Const sStr : AnsiString; bCase : Boolean = False) : Integer;
Function LastIndexOf(Const sStr : AnsiString; bCase : Boolean = False) : Integer;
Property Length : Integer Read FLength;
Procedure Read(index : integer; var buffer; ilength : integer);
Procedure Overwrite(index : integer; content : AnsiString);
End;
type
TAnsiCharSet = set of AnsiChar;
Function AnsiStringSplit(Const sValue : AnsiString; Const aDelimiters : TAnsiCharSet; Var sLeft, sRight: AnsiString) : Boolean;
Function AnsiPadString(const AStr: AnsiString; AWidth: Integer; APadChar: AnsiChar; APadLeft: Boolean): AnsiString;
Implementation
Uses
MathSupport,
StringSupport;
Const
BUFFER_INCREMENT_SIZE = 1024;
Constructor TAnsiStringBuilder.Create;
Begin
Inherited;
FBufferSize := BUFFER_INCREMENT_SIZE;
End;
Destructor TAnsiStringBuilder.Destroy;
Begin
inherited;
End;
Procedure TAnsiStringBuilder.Clear;
Begin
FContent := '';
FLength := 0;
End;
Function TAnsiStringBuilder.ToString : String;
Begin
Result := Copy(String(FContent), 1, FLength);
End;
Procedure TAnsiStringBuilder.AppendPadded(Const sStr : AnsiString; iCount : Integer; cPad : AnsiChar = ' ');
Var
iLen : Integer;
Begin
iLen := IntegerMax(System.Length(sStr), iCount);
If (iLen > 0) Then
Begin
If FLength + iLen > System.Length(FContent) Then
SetLength(FContent, System.Length(FContent) + IntegerMax(FBufferSize, iLen));
Move(sStr[1], FContent[FLength + 1], System.Length(sStr));
If iLen = iCount Then
FillChar(FContent[FLength + 1 + System.Length(sStr)], (iCount - System.Length(sStr)), cPad);
Inc(FLength, iLen);
End;
End;
Function TAnsiStringBuilder.AsString: AnsiString;
Begin
Result := Copy(FContent, 1, FLength);
End;
Procedure TAnsiStringBuilder.AppendFixed(Const sStr : AnsiString; iCount : Integer; cPad : AnsiChar = ' ');
Begin
If (iCount > 0) Then
Begin
If FLength + iCount > System.Length(FContent) Then
SetLength(FContent, System.Length(FContent) + IntegerMax(FBufferSize, iCount));
Move(sStr[1], FContent[FLength + 1], IntegerMin(System.Length(sStr), iCount));
If System.Length(sStr) < iCount Then
FillChar(FContent[FLength + 1 + System.Length(sStr)], (iCount - System.Length(sStr)), cPad);
Inc(FLength, iCount);
End;
End;
Procedure TAnsiStringBuilder.Append(ch : AnsiChar);
Begin
If FLength + 1 > System.Length(FContent) Then
SetLength(FContent, System.Length(FContent) + FBufferSize);
Move(ch, FContent[FLength + 1], 1);
Inc(FLength);
End;
Procedure TAnsiStringBuilder.Append(Const sStr : AnsiString);
Begin
If (sStr <> '') Then
Begin
If FLength + System.Length(sStr) > System.Length(FContent) Then
SetLength(FContent, System.Length(FContent) + IntegerMax(FBufferSize, System.Length(sStr)));
Move(sStr[1], FContent[FLength + 1], System.Length(sStr));
Inc(FLength, System.Length(sStr));
End;
End;
Procedure TAnsiStringBuilder.Append(Const oBuilder : TAnsiStringBuilder);
Begin
Append(oBuilder.AsString);
End;
Procedure TAnsiStringBuilder.AppendEOL;
Begin
Append(cReturn);
End;
Procedure TAnsiStringBuilder.Append(Const iInt : Integer);
Begin
Append(AnsiString(IntegerToString(iInt)));
End;
Procedure TAnsiStringBuilder.Insert(Const sStr : AnsiString; iIndex : Integer);
Begin
If (sStr <> '') Then
Begin
If FLength + System.Length(sStr) > System.Length(FContent) Then
SetLength(FContent, System.Length(FContent) + IntegerMax(FBufferSize, System.Length(sStr)));
If (iIndex) <> FLength Then
Move(FContent[iIndex+1], FContent[iIndex+1 + System.Length(sStr)], (FLength - iIndex));
Move(sStr[1], FContent[iIndex+1], System.Length(sStr));
Inc(FLength, System.Length(sStr));
End;
End;
Procedure TAnsiStringBuilder.Insert(Const oBuilder : TAnsiStringBuilder; iIndex : Integer);
Begin
Insert(oBuilder.AsString, iIndex);
End;
Procedure TAnsiStringBuilder.Delete(iIndex, iLength : Integer);
Begin
System.Delete(FContent, iIndex+1, iLength);
Dec(FLength, iLength);
End;
Function TAnsiStringBuilder.IndexOf(Const sStr : AnsiString; bCase : Boolean = False) : Integer;
Var
iLoop : Integer;
iUpper : Integer;
iLen : Integer;
Begin
Result := -1;
iLoop := 1;
iLen := System.Length(sStr);
iUpper := FLength - iLen + 1;
While (Result = -1) And (iLoop <= iUpper) Do
Begin
If (bCase And (Copy(FContent, iLoop, iLen) = sStr)) Or (Not bCase And (Copy(FContent, iLoop, iLen) = sStr)) Then
Result := iLoop - 1;
Inc(iLoop);
End;
End;
Function TAnsiStringBuilder.LastIndexOf(Const sStr : AnsiString; bCase : Boolean = False) : Integer;
Var
iLoop : Integer;
iUpper : Integer;
iLen : Integer;
Begin
Result := -1;
iLen := System.Length(sStr);
iUpper := FLength - iLen + 1;
iLoop := iUpper;
While (Result = -1) And (iLoop > 0) Do
Begin
If (bCase And (Copy(FContent, iLoop, iLen) = sStr)) Or (Not bCase And (Copy(FContent, iLoop, iLen) = sStr)) Then
Result := iLoop - 1;
Dec(iLoop);
End;
End;
Procedure TAnsiStringBuilder.CommaAdd(const sStr: AnsiString);
Begin
if Length > 0 Then
Append(', ');
Append(sStr);
End;
Procedure TAnsiStringBuilder.AddCardinalAsBytes(iVal: Cardinal);
Var
s : AnsiString;
Begin
SetLength(s, 4);
move(iVal, s[1], 4);
Append(s);
End;
Procedure TAnsiStringBuilder.AddWordAsBytes(iVal: word);
Var
s : AnsiString;
Begin
SetLength(s, 2);
move(iVal, s[1], 2);
Append(s);
End;
Procedure TAnsiStringBuilder.AddInt64AsBytes(iVal: Int64);
Var
s : AnsiString;
Begin
SetLength(s, 8);
move(iVal, s[1], 8);
Append(s);
End;
Procedure TAnsiStringBuilder.AddByteAsBytes(iVal: Byte);
Var
s : AnsiString;
Begin
SetLength(s, 1);
move(iVal, s[1], 1);
Append(s);
End;
Procedure TAnsiStringBuilder.AppendLine(const sStr: AnsiString);
Begin
Append(sStr);
AppendEOL;
End;
procedure TAnsiStringBuilder.Append(const bBytes: array of Byte; amount: Integer);
var
i : integer;
begin
for i := 0 to amount - 1 Do
Append(AnsiChar(bBytes[i]));
end;
procedure TAnsiStringBuilder.Overwrite(index: integer; content: AnsiString);
begin
if index < 1 Then
RaiseError('Overwrite', 'index < 1');
if index + System.length(Content) > FLength Then
RaiseError('Overwrite', 'index > length');
if content <> '' Then
Move(Content[1], FContent[index], System.length(Content));
end;
procedure TAnsiStringBuilder.Read(index: integer; var buffer; ilength: integer);
begin
if index < 1 Then
RaiseError('Read', 'index < 1');
if index + ilength > FLength Then
RaiseError('Read', 'index > length');
Move(FContent[index], buffer, ilength);
end;
Function AnsiStringSplit(Const sValue : AnsiString; Const aDelimiters : TAnsiCharSet; Var sLeft, sRight: AnsiString) : Boolean;
Var
iIndex : Integer;
sA, sB : AnsiString;
Begin
// Find the delimiter within the source string
iIndex := StringFind(String(sValue), aDelimiters);
Result := iIndex <> 0;
If Not Result Then
Begin
sA := sValue;
sB := '';
End
Else
Begin
sA := Copy(sValue, 1, iIndex - 1);
sB := Copy(sValue, iIndex + 1, MaxInt);
End;
sLeft := sA;
sRight := sB;
End;
function AnsiPadString(const AStr: AnsiString; AWidth: Integer; APadChar: AnsiChar; APadLeft: Boolean): AnsiString;
begin
if Length(AStr) >= AWidth then
Result := AStr
else
begin
SetLength(Result, AWidth);
FillChar(Result[1], AWidth, APadChar);
if AStr <> '' then
if APadLeft then
Move(AStr[1], Result[(AWidth - Length(AStr)) + 1], Length(AStr))
else
Move(AStr[1], Result[1], Length(AStr))
end;
end;
End.
|
program usingRecords;
type
Books = record
title : packed array [1..50] of char;
author : packed array [1..50] of char;
subject : packed array [1..100] of char;
id : longint;
end;
var
book1, book2: Books;
procedure printBook(b : Books);
begin
writeln(' --- book #', b.id, ' --- ');
writeln(' Title: ', b.title);
writeln(' Author: ', b.author);
writeln(' Subject: ', b.subject);
writeln;
end;
begin
{ first book info }
book1.title := 'Project Oberon';
book1.author := 'Niklaus Wirth';
book1.subject := 'The Oberon Operating System';
book1.id := 1234;
{ second book info }
book2.title := 'Hyperion';
book2.author := 'Dan Simmons';
book2.subject := 'Hardcore SciFi';
book2.id := 4321;
{ print books }
printBook(book1);
printBook(book2);
end.
|
unit CRSlottingPlacementEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, CommonFrame, ComCtrls, StdCtrls, CommonObjectSelectFrame,
ExtCtrls, CRPartPlacementsEditorForm, Well, SlottingPlacement, BaseObjects,
CommonComplexCombo, CommonComplexIDCombo, OrganizationSelectForm;
type
TfrmSlottingPlacementEdit = class(TfrmCommonFrame)
gbxSlottingPlacement: TGroupBox;
frmSlottingPlacement: TfrmIDObjectSelect;
edtOwnerPartPlacement: TLabeledEdit;
edtBoxCount: TLabeledEdit;
edtFinalBoxCount: TLabeledEdit;
cmplxOrganization: TfrmIDObjectSelect;
frmLastCoretransfer: TfrmIDObjectSelect;
btnRefresh: TButton;
procedure btnRefreshClick(Sender: TObject);
private
{ Private declarations }
function GetWell: TWell;
function GetWellSlottingPlacement: TSlottingPlacement;
protected
procedure FillControls(ABaseObject: TIDObject); override;
procedure ClearControls; override;
procedure RegisterInspector; override;
function GetParentCollection: TIDObjects; override;
procedure CopyEditingValues(Dest: TIDObject); override;
public
{ Public declarations }
property Well: TWell read GetWell;
property WellSlottingPlacement: TSlottingPlacement read GetWellSlottingPlacement;
constructor Create(AOwner: TComponent); override;
procedure Save(AObject: TIDObject = nil); override;
end;
var
frmSlottingPlacementEdit: TfrmSlottingPlacementEdit;
implementation
uses CRSlottingPlacementEdit, CRCoreTransfersEditForm, BaseGUI, Facade, Organization, CoreTransfer, BaseConsts;
{$R *.dfm}
{ TfrmSlottingPlacementEdit }
procedure TfrmSlottingPlacementEdit.ClearControls;
begin
inherited;
frmSlottingPlacement.Clear;
edtOwnerPartPlacement.Clear;
edtBoxCount.Clear;
edtFinalBoxCount.Clear;
cmplxOrganization.Clear;
end;
procedure TfrmSlottingPlacementEdit.CopyEditingValues(Dest: TIDObject);
begin
if Assigned(WellSlottingPlacement) then
begin
(Dest as TSlottingPlacement).StatePartPlacement := WellSlottingPlacement.StatePartPlacement;
(Dest as TSlottingPlacement).OwnerPartPlacement := WellSlottingPlacement.OwnerPartPlacement;
(Dest as TSlottingPlacement).BoxCount := WellSlottingPlacement.BoxCount;
(Dest as TSlottingPlacement).FinalBoxCount := WellSlottingPlacement.FinalBoxCount;
(Dest as TSlottingPlacement).Organization := WellSlottingPlacement.Organization;
(Dest as TSlottingPlacement).LastCoreTransfer := WellSlottingPlacement.LastCoreTransfer;
(Dest as TSlottingPlacement).LastCoreTransferTask := WellSlottingPlacement.LastCoreTransferTask;
end;
end;
constructor TfrmSlottingPlacementEdit.Create(AOwner: TComponent);
begin
inherited;
EditingClass := TSlottingPlacement;
ParentClass := TWell;
frmSlottingPlacement.LabelCaption := 'Основное местоположение государственной части керна';
frmSlottingPlacement.SelectiveFormClass := TfrmPartPlacementsEditor;
frmSlottingPlacement.ObjectSelector := (frmSlottingPlacement.SelectorForm as TfrmPartPlacementsEditor);
frmLastCoretransfer.LabelCaption := 'Дата последнего переупорядочения (переукладки)';
frmLastCoretransfer.SelectiveFormClass := TfrmCoreTransfersEditForm;
frmLastCoretransfer.ObjectSelector := (frmLastCoretransfer.SelectorForm as TfrmCoreTransfersEditForm );
cmplxOrganization.LabelCaption := 'Ведомственная принадлежность/владелец керна';
cmplxOrganization.SelectiveFormClass := TfrmOrganizationSelect;
cmplxOrganization.ObjectSelector := (cmplxOrganization.SelectorForm as TfrmOrganizationSelect);
end;
procedure TfrmSlottingPlacementEdit.FillControls(ABaseObject: TIDObject);
var s: TSlottingPlacement;
begin
inherited;
s := ShadeEditingObject as TSlottingPlacement;
if Assigned(s) then
begin
frmSlottingPlacement.SelectedObject := s.StatePartPlacement;
cmplxOrganization.SelectedObject := s.Organization;
frmLastCoretransfer.SelectedObject := s.LastCoreTransfer;
edtOwnerPartPlacement.Text := s.OwnerPartPlacement;
edtBoxCount.Text := IntToStr(s.BoxCount);
edtFinalBoxCount.Text := IntToStr(s.FinalBoxCount);
end;
FillParentControls;
end;
function TfrmSlottingPlacementEdit.GetParentCollection: TIDObjects;
begin
Result := Well.SlottingPlacement.Collection;
end;
function TfrmSlottingPlacementEdit.GetWell: TWell;
begin
if EditingObject is TWell then
Result := EditingObject as TWell
else if EditingObject is TSlottingPlacement then
Result := (EditingObject as TSlottingPlacement).Collection.Owner as TWell
else
Result := nil;
end;
function TfrmSlottingPlacementEdit.GetWellSlottingPlacement: TSlottingPlacement;
begin
Result := EditingObject as TSlottingPlacement;
end;
procedure TfrmSlottingPlacementEdit.RegisterInspector;
begin
inherited;
Inspector.Add(frmSlottingPlacement.edtObject, nil, ptString, 'Местонахождение государственной части керна', false);
Inspector.Add(edtBoxCount, nil, ptInteger, 'Количество ящиков поступило', false);
Inspector.Add(edtFinalBoxCount, nil, ptInteger, 'Количество ящиков после упорядочения', false);
end;
procedure TfrmSlottingPlacementEdit.Save;
var ct: TCoreTransferTask;
begin
inherited;
if FEditingObject is TWell then
FEditingObject := Well.AddSlottingPlacement;
WellSlottingPlacement.StatePartPlacement := frmSlottingPlacement.SelectedObject as TPartPlacement;
WellSlottingPlacement.OwnerPartPlacement := edtOwnerPartPlacement.Text;
WellSlottingPlacement.BoxCount := StrToInt(edtBoxCount.Text);
WellSlottingPlacement.FinalBoxCount := StrToInt(edtFinalBoxCount.Text);
WellSlottingPlacement.Organization := cmplxOrganization.SelectedObject as TOrganization;
if Assigned(frmLastCoretransfer.SelectedObject) then
with frmLastCoretransfer.SelectedObject as TCoreTransfer do
begin
ct := CoreTransferTasks.GetTransferTaskByWellAndType(Well, TMainFacade.GetInstance.AllCoreTransferTypes.ItemsByID[CORE_TRANSFER_TYPE_REPLACING_ID] as TCoreTransferType);
if not Assigned(ct) then
begin
ct := CoreTransferTasks.Add as TCoreTransferTask;
ct.TransferringObject := Well;
ct.TransferType := TMainFacade.GetInstance.AllCoreTransferTypes.ItemsByID[CORE_TRANSFER_TYPE_REPLACING_ID] as TCoreTransferType;
end;
ct.TargetPlacement := WellSlottingPlacement.StatePartPlacement;
ct.BoxCount := WellSlottingPlacement.Boxes.Count;
WellSlottingPlacement.LastCoreTransferTask := ct;
WellSlottingPlacement.LastCoreTransfer := frmLastCoretransfer.SelectedObject as TCoreTransfer;
end;
end;
procedure TfrmSlottingPlacementEdit.btnRefreshClick(Sender: TObject);
begin
inherited;
edtFinalBoxCount.Text := IntToStr(Well.Slottings.Boxes.Count);
end;
end.
|
// GLBitmapFont
{: Bitmap Fonts management classes for GLScene<p>
<b>History : </b><font size=-1><ul>
<li>21/02/01 - Egg - Now XOpenGL based (multitexture)
<li>15/01/01 - EG - Creation
</ul></font>
}
unit GLBitmapFont;
interface
uses Classes, GLScene, Graphics, Geometry, GLMisc, StdCtrls;
type
// TBitmapFontRange
//
{: An individual character range in a bitmap font.<p>
A range allows mapping ASCII characters to character tiles in a font
bitmap, tiles are enumerated line then column (raster). }
TBitmapFontRange = class (TCollectionItem)
private
{ Private Declarations }
FStartASCII, FStopASCII : Char;
FStartGlyphIdx : Integer;
protected
{ Protected Declarations }
procedure SetStartASCII(const val : Char);
procedure SetStopASCII(const val : Char);
procedure SetStartGlyphIdx(const val : Integer);
function GetDisplayName : String; override;
public
{ Public Declarations }
constructor Create(Collection : TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
{ Published Declarations }
property StartASCII : Char read FStartASCII write SetStartASCII;
property StopASCII : Char read FStopASCII write SetStopASCII;
property StartGlyphIdx : Integer read FStartGlyphIdx write SetStartGlyphIdx;
end;
// TBitmapFontRanges
//
TBitmapFontRanges = class (TCollection)
protected
{ Protected Declarations }
owner : TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index : Integer; const val : TBitmapFontRange);
function GetItems(index : Integer) : TBitmapFontRange;
public
{ Public Declarations }
constructor Create(AOwner : TComponent);
function Add: TBitmapFontRange;
function FindItemID(ID: Integer): TBitmapFontRange;
property Items[index : Integer] : TBitmapFontRange read GetItems write SetItems; default;
{: Converts an ASCII character into a tile index.<p>
Return -1 if character cannot be rendered. }
function CharacterToTileIndex(aChar : Char) : Integer;
procedure NotifyChange;
end;
// TBitmapFont
//
{: Provides access to individual characters in a BitmapFont.<p>
Only fixed-width bitmap fonts are supported, the characters are enumerated
in a raster fashion (line then column).<br>
Transparency is all or nothing, the transparent color being that of the
top left pixel of the Glyphs bitmap.<p>
Performance note: as usual, for best performance, you base font bitmap
dimensions should be close to a power of two, and have at least 1 pixel
spacing between characters (horizontally and vertically) to avoid artefacts
when rendering with linear filtering. }
TBitmapFont = class (TComponent)
private
{ Private Declarations }
FRanges : TBitmapFontRanges;
FGlyphs : TPicture;
FCharWidth, FCharHeight : Integer;
FGlyphsIntervalX, FGlyphsIntervalY : Integer;
FHSpace, FVSpace : Integer;
FUsers : TList;
FHandle : Integer;
FHandleIsDirty : Boolean;
FMinFilter : TGLMinFilter;
FMagFilter : TGLMagFilter;
FTextureWidth, FTextureHeight : Integer;
protected
{ Protected Declarations }
procedure SetRanges(const val : TBitmapFontRanges);
procedure SetGlyphs(const val : TPicture);
procedure SetCharWidth(const val : Integer);
procedure SetCharHeight(const val : Integer);
procedure SetGlyphsIntervalX(const val : Integer);
procedure SetGlyphsIntervalY(const val : Integer);
procedure OnGlyphsChanged(Sender : TObject);
procedure SetHSpace(const val : Integer);
procedure SetVSpace(const val : Integer);
procedure SetMagFilter(AValue: TGLMagFilter);
procedure SetMinFilter(AValue: TGLMinFilter);
procedure InvalidateUsers;
function CharactersPerRow : Integer;
procedure TileIndexToTexCoords(tileIndex : Integer; var topLeft, bottomRight : TTexPoint);
procedure PrepareImage;
procedure PrepareParams;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RegisterUser(anObject : TGLBaseSceneObject);
procedure UnRegisterUser(anObject : TGLBaseSceneObject);
{: Invoke to free all OpenGL list and handles eventually allocated. }
procedure FreeList(glsceneOnly : Boolean);
{: Renders the given string at current position.<p>
The current matrix is blindly used, meaning you can render all kinds
of rotated and linear distorted text with this method. }
procedure RenderString(const aString : String; alignment : TAlignment;
layout : TTextLayout);
published
{ Published Declarations }
{: A single bitmap containing all the characters.<p>
The transparent color is that of the top left pixel. }
property Glyphs : TPicture read FGlyphs write SetGlyphs;
{: Nb of horizontal pixels between two columns in the Glyphs. }
property GlyphsIntervalX : Integer read FGlyphsIntervalX write SetGlyphsIntervalX;
{: Nb of vertical pixels between two rows in the Glyphs. }
property GlyphsIntervalY : Integer read FGlyphsIntervalY write SetGlyphsIntervalY;
{: Ranges allow converting between ASCII and tile indexes.<p>
See TBitmapFontRange. }
property Ranges : TBitmapFontRanges read FRanges write SetRanges;
{: Width of a single character. }
property CharWidth : Integer read FCharWidth write SetCharWidth default 16;
{: Height of a single character. }
property CharHeight : Integer read FCharHeight write SetCharHeight default 16;
{: Pixels in between rendered characters (horizontally). }
property HSpace : Integer read FHSpace write SetHSpace default 1;
{: Pixels in between rendered lines (vertically). }
property VSpace : Integer read FVSpace write SetVSpace default 1;
property MagFilter: TGLMagFilter read FMagFilter write SetMagFilter default maLinear;
property MinFilter: TGLMinFilter read FMinFilter write SetMinFilter default miLinear;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, OpenGL12, GLGraphics, XOpenGL;
// ------------------
// ------------------ TBitmapFontRange ------------------
// ------------------
// Create
//
constructor TBitmapFontRange.Create(Collection : TCollection);
begin
inherited Create(Collection);
end;
// Destroy
//
destructor TBitmapFontRange.Destroy;
begin
inherited Destroy;
end;
// Assign
//
procedure TBitmapFontRange.Assign(Source: TPersistent);
begin
if Source is TBitmapFontRange then begin
FStartASCII:=TBitmapFontRange(Source).FStartASCII;
FStopASCII:=TBitmapFontRange(Source).FStopASCII;
FStartGlyphIdx:=TBitmapFontRange(Source).FStartGlyphIdx;
end;
inherited Destroy;
end;
// GetDisplayName
//
function TBitmapFontRange.GetDisplayName : String;
begin
Result:=Format('ASCII [#%d, #%d] -> Glyphs [%d, %d]',
[Integer(StartASCII), Integer(StopASCII), StartGlyphIdx,
StartGlyphIdx+Integer(StopASCII)-Integer(StartASCII)]);
end;
// SetStartASCII
//
procedure TBitmapFontRange.SetStartASCII(const val : Char);
begin
FStartASCII:=val;
if FStartASCII>FStopASCII then
FStopASCII:=FStartASCII;
TBitmapFontRanges(Collection).NotifyChange;
end;
// SetStopASCII
//
procedure TBitmapFontRange.SetStopASCII(const val : Char);
begin
FStopASCII:=val;
if FStopASCII<FStartASCII then
FStartASCII:=FStopASCII;
TBitmapFontRanges(Collection).NotifyChange;
end;
// SetStartGlyphIdx
//
procedure TBitmapFontRange.SetStartGlyphIdx(const val : Integer);
begin
if val>=0 then
FStartGlyphIdx:=val
else FStartGlyphIdx:=0;
TBitmapFontRanges(Collection).NotifyChange;
end;
// ------------------
// ------------------ TBitmapFontRanges ------------------
// ------------------
constructor TBitmapFontRanges.Create(AOwner : TComponent);
begin
Owner:=AOwner;
inherited Create(TBitmapFontRange);
end;
function TBitmapFontRanges.GetOwner: TPersistent;
begin
Result:=Owner;
end;
procedure TBitmapFontRanges.SetItems(index : Integer; const val : TBitmapFontRange);
begin
inherited Items[index]:=val;
end;
function TBitmapFontRanges.GetItems(index : Integer) : TBitmapFontRange;
begin
Result:=TBitmapFontRange(inherited Items[index]);
end;
function TBitmapFontRanges.Add: TBitmapFontRange;
begin
Result:=(inherited Add) as TBitmapFontRange;
end;
function TBitmapFontRanges.FindItemID(ID: Integer): TBitmapFontRange;
begin
Result:=(inherited FindItemID(ID)) as TBitmapFontRange;
end;
// CharacterToTileIndex
//
function TBitmapFontRanges.CharacterToTileIndex(aChar : Char) : Integer;
var
i : Integer;
begin
Result:=-1;
for i:=0 to Count-1 do with Items[i] do
if (aChar>=StartASCII) and (aChar<=StopASCII) then begin
Result:=StartGlyphIdx+Integer(aChar)-Integer(StartASCII);
Break;
end;
end;
// NotifyChange
//
procedure TBitmapFontRanges.NotifyChange;
begin
if Assigned(Owner) and (Owner is TGLBaseSceneObject) then
TGLBaseSceneObject(Owner).StructureChanged;
end;
// ------------------
// ------------------ TBitmapFont ------------------
// ------------------
// Creat
//
constructor TBitmapFont.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRanges:=TBitmapFontRanges.Create(Self);
FGlyphs:=TPicture.Create;
FGlyphs.OnChange:=OnGlyphsChanged;
FCharWidth:=16;
FCharHeight:=16;
FHSpace:=1;
FVSpace:=1;
FUsers:=TList.Create;
FHandleIsDirty:=True;
FMinFilter:=miLinear;
FMagFilter:=maLinear;
end;
// Destroy
//
destructor TBitmapFont.Destroy;
begin
inherited Destroy;
FreeList(True);
FRanges.Free;
FGlyphs.Free;
Assert(FUsers.Count=0);
FUsers.Free;
end;
// SetRanges
//
procedure TBitmapFont.SetRanges(const val : TBitmapFontRanges);
begin
FRanges.Assign(val);
end;
// SetGlyphs
//
procedure TBitmapFont.SetGlyphs(const val : TPicture);
begin
FGlyphs.Assign(val);
end;
// SetCharWidth
//
procedure TBitmapFont.SetCharWidth(const val : Integer);
begin
if val>1 then
FCharWidth:=val
else FCharWidth:=1;
InvalidateUsers;
end;
// SetCharHeight
//
procedure TBitmapFont.SetCharHeight(const val : Integer);
begin
if val>1 then
FCharHeight:=val
else FCharHeight:=1;
InvalidateUsers;
end;
// SetGlyphsIntervalX
//
procedure TBitmapFont.SetGlyphsIntervalX(const val : Integer);
begin
if val>0 then
FGlyphsIntervalX:=val
else FGlyphsIntervalX:=0;
InvalidateUsers;
end;
// SetGlyphsIntervalY
//
procedure TBitmapFont.SetGlyphsIntervalY(const val : Integer);
begin
if val>0 then
FGlyphsIntervalY:=val
else FGlyphsIntervalY:=0;
InvalidateUsers;
end;
// SetHSpace
//
procedure TBitmapFont.SetHSpace(const val : Integer);
begin
if val>0 then
FHSpace:=val
else FHSpace:=0;
InvalidateUsers;
end;
// SetVSpace
//
procedure TBitmapFont.SetVSpace(const val : Integer);
begin
if val>0 then
FVSpace:=val
else FVSpace:=0;
InvalidateUsers;
end;
// SetMagFilter
//
procedure TBitmapFont.SetMagFilter(AValue: TGLMagFilter);
begin
if AValue <> FMagFilter then begin
FMagFilter:=AValue;
FHandleIsDirty:=True;
InvalidateUsers;
end;
end;
// SetMinFilter
//
procedure TBitmapFont.SetMinFilter(AValue: TGLMinFilter);
begin
if AValue <> FMinFilter then begin
FMinFilter:=AValue;
FHandleIsDirty:=True;
InvalidateUsers;
end;
end;
// OnGlyphsChanged
//
procedure TBitmapFont.OnGlyphsChanged(Sender : TObject);
begin
InvalidateUsers;
end;
// RegisterUser
//
procedure TBitmapFont.RegisterUser(anObject : TGLBaseSceneObject);
begin
Assert(FUsers.IndexOf(anObject)<0);
FUsers.Add(anObject);
end;
// UnRegisterUser
//
procedure TBitmapFont.UnRegisterUser(anObject : TGLBaseSceneObject);
begin
FUsers.Remove(anObject);
end;
// FreeList
//
procedure TBitmapFont.FreeList(glsceneOnly : Boolean);
begin
if FHandle<>0 then begin
if not glsceneOnly then begin
Assert(CurrentRenderingContextDC>0);
glDeleteTextures(1, @FHandle);
end;
FHandle:=0;
FHandleIsDirty:=True;
end;
end;
// PrepareImage
//
procedure TBitmapFont.PrepareImage;
var
bitmap : TBitmap;
bitmap32 : TGLBitmap32;
begin
bitmap:=TBitmap.Create;
with bitmap do begin
PixelFormat:=pf24bit;
Width:=RoundUpToPowerOf2(Glyphs.Width);
Height:=RoundUpToPowerOf2(Glyphs.Height);
Canvas.Draw(0, 0, Glyphs.Graphic);
end;
bitmap32:=TGLBitmap32.Create;
bitmap32.Assign(bitmap);
bitmap.Free;
with bitmap32 do begin
SetAlphaTransparentForColor(Data[Width*(Height-1)]);
RegisterAsOpenGLTexture(MinFilter);
FTextureWidth:=Width;
FTextureHeight:=Height;
Free;
end;
end;
// PrepareParams
//
procedure TBitmapFont.PrepareParams;
const
cTextureMagFilter : array [maNearest..maLinear] of TGLEnum =
( GL_NEAREST, GL_LINEAR );
cTextureMinFilter : array [miNearest..miLinearMipmapLinear] of TGLEnum =
( GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR );
begin
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, cTextureMinFilter[FMinFilter]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, cTextureMagFilter[FMagFilter]);
end;
// RenderString
//
procedure TBitmapFont.RenderString(const aString : String; alignment : TAlignment;
layout : TTextLayout);
function AlignmentAdjustement(p : Integer) : Single;
var
i : Integer;
begin
i:=0;
while (p<=Length(aString)) and (aString[p]<>#13) do begin
Inc(p); Inc(i);
end;
case alignment of
taLeftJustify : Result:=0;
taRightJustify : Result:=-(i*(CharWidth+HSpace)-HSpace)
else // taCenter
Result:=-(i*(CharWidth+HSpace)-HSpace)/2;
end;
end;
function LayoutAdjustement : Single;
var
i, n : Integer;
begin
n:=1;
for i:=1 to Length(aString) do
if aString[i]=#13 then Inc(n);
case layout of
tlTop : Result:=0;
tlBottom : Result:=(n*(CharHeight+VSpace)-VSpace);
else // tlCenter
Result:=(n*(CharHeight+VSpace)-VSpace)/2;
end;
end;
var
i, idx : Integer;
topLeft, bottomRight : TTexPoint;
vTopLeft, vBottomRight : TVector;
deltaH, deltaV : Single;
begin
if (Glyphs.Width=0) or (aString='') then Exit;
// prepare texture if necessary
if FHandleIsDirty then begin
// prepare handle
if FHandle = 0 then begin
glGenTextures(1, @FHandle);
Assert(FHandle<>0);
end;
glBindtexture(GL_TEXTURE_2D, FHandle);
// texture registration
if Glyphs.Width<>0 then begin
PrepareImage;
PrepareParams;
end;
FHandleIsDirty:=False;
end;
// precalcs
MakePoint(vTopLeft, AlignmentAdjustement(1), LayoutAdjustement, 0);
MakePoint(vBottomRight, vTopLeft[0]+CharWidth-1, vTopLeft[1]-(CharHeight-1), 0);
deltaH:=CharWidth+HSpace;
deltaV:=-(CharHeight+VSpace);
// set states
glEnable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture(GL_TEXTURE_2D, FHandle);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
// start rendering
glBegin(GL_QUADS);
for i:=1 to Length(aString) do begin
case aString[i] of
#0..#12, #14..#31 : ; // ignore
#13 : begin
vTopLeft[0]:=AlignmentAdjustement(i+1);
vTopLeft[1]:=vTopLeft[1]+deltaV;
vBottomRight[0]:=vTopLeft[0]+CharWidth-1;
vBottomRight[1]:=vBottomRight[1]+deltaV;
end
else
idx:=Ranges.CharacterToTileIndex(aString[i]);
if idx>0 then begin
TileIndexToTexCoords(idx, topLeft, bottomRight);
xglTexCoord2fv(@topLeft);
glVertex4fv(@vTopLeft);
xglTexCoord2f(topLeft.S, bottomRight.T);
glVertex2f(vTopLeft[0], vBottomRight[1]);
xglTexCoord2fv(@bottomRight);
glVertex4fv(@vBottomRight);
xglTexCoord2f(bottomRight.S, topLeft.T);
glVertex2f(vBottomRight[0], vTopLeft[1]);
end;
vTopLeft[0]:=vTopLeft[0]+deltaH;
vBottomRight[0]:=vBottomRight[0]+deltaH;
end;
end;
glEnd;
end;
// CharactersPerRow
//
function TBitmapFont.CharactersPerRow : Integer;
begin
if FGlyphs.Width>0 then
Result:=(FGlyphs.Width+FGlyphsIntervalX) div (FGlyphsIntervalX+FCharWidth)
else Result:=0;
end;
// TileIndexToTexCoords
//
procedure TBitmapFont.TileIndexToTexCoords(tileIndex : Integer;
var topLeft, bottomRight : TTexPoint);
var
carX, carY : Integer;
begin
carX:=(tileIndex mod CharactersPerRow)*(CharWidth+GlyphsIntervalX);
carY:=(tileIndex div CharactersPerRow)*(CharHeight+GlyphsIntervalY);
topLeft.S:=(carX+0.05)/FTextureWidth;
topLeft.T:=FTextureHeight-(carY+0.05)/FTextureHeight;
bottomRight.S:=(carX+CharWidth-1.05)/FTextureWidth;
bottomRight.T:=FTextureHeight-(carY+CharHeight-1.05)/FTextureHeight;
end;
// InvalidateUsers
//
procedure TBitmapFont.InvalidateUsers;
var
i : Integer;
begin
for i:=FUsers.Count-1 downto 0 do
TGLBaseSceneObject(FUsers[i]).NotifyChange(Self);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TBitmapFont]);
end.
|
unit wordpress_category_controller;
{$mode objfpc}{$H+}
{$include define.inc}
interface
uses
fpcgi, fastplaz_handler, httpdefs, fpHTTP,
Classes, SysUtils;
type
{ TWPCategoryWebModule }
TWPCategoryWebModule = class(TMyCustomWebModule)
procedure RequestHandler(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: boolean);
private
CategoryTitle, CategoryURL: string;
function GetCategoryList(FunctionName: string; Parameter: TStrings): string;
function Tag_MainContent_Handler(const TagName: string; Params: TStringList): string;
function Tag_Category_Handler(const TagName: string; Params: TStringList): string;
public
constructor CreateNew(AOwner: TComponent; CreateMode: integer); override;
destructor Destroy; override;
// Handler / Controller
procedure DoBlockController(Sender: TObject; FunctionName: string; Parameter: TStrings;
var ResponseString: string);
end;
implementation
uses wordpress_terms_model, wordpress_news_model, database_lib, html_lib,
common, language_lib, theme_controller;
{ TWPCategoryWebModule }
procedure TWPCategoryWebModule.RequestHandler(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: boolean);
begin
DataBaseInit;
LanguageInit;
if _GET['name'] = '' then
Redirect(BaseURL);
Tags['$maincontent'] := @Tag_MainContent_Handler;
Response.Content := ThemeUtil.Render(@TagController, '', True);
Handled := True;
end;
function TWPCategoryWebModule.GetCategoryList(FunctionName: string; Parameter: TStrings): string;
var
lst: TStringList;
Terms: TWordpressTerms;
url, title: string;
div_class: string;
begin
div_class := StringReplace(Parameter.Values['class'], '"', '', [rfReplaceAll]);
Terms := TWordpressTerms.Create();
Terms.AddJoin( 'term_taxonomy', 'term_id', 'terms.term_id', ['taxonomy']);
Terms.Find(['taxonomy="category"'], 'name');
if Terms.RecordCount > 0 then
begin
lst := TStringList.Create;
lst.Add('<div class="category-list">');
if Parameter.Values['title'] <> '' then
begin
title := StringReplace(Parameter.Values['title'], '"', '', [rfReplaceAll]);
lst.Add('<h3>' + title + '</h3>');
end;
lst.Add('<ul class="' + div_class + '">');
while not Terms.Data.EOF do
begin
url := BaseURL + 'category/' + Terms['slug'].AsString + '/';
lst.Add('<li><a href="' + url + '">' + Terms['name'].AsString + '</a></li>');
Terms.Data.Next;
end;
lst.Add('</ul>');
lst.Add('</div>');
Result := lst.Text;
FreeAndNil(lst);
end;
FreeAndNil(Terms);
end;
function TWPCategoryWebModule.Tag_MainContent_Handler(const TagName: string; Params: TStringList): string;
var
category_id: integer;
News: TWordpressNews;
begin
with TWordpressTerms.Create() do
begin
AddJoin( 'term_taxonomy', 'term_id', 'terms.term_id', ['taxonomy']);
FindFirst(['taxonomy="category"', 'slug="' + _GET['name'] + '"'], 'name');
if RecordCount = 0 then
begin
Result := H2(__(__Content_Not_Found), 'center');
Free;
Exit;
end;
category_id := Value['term_id'];
CategoryTitle := Value['name'];
CategoryURL := BaseURL + 'category/' + Value['slug'] + '/';
Free;
end;
News := TWordpressNews.Create();
News.AddJoin( 'term_relationships', 'object_id', 'posts.ID', ['object_id']);
News.Find(['post_status="publish"', 'post_type="post"', AppData.tablePrefix +
'term_relationships.term_taxonomy_id=' + i2s(category_id)], 'post_date desc', 10);
Tags['$category_title'] := @Tag_Category_Handler;
Tags['$category_url'] := @Tag_Category_Handler;
ThemeUtil.AssignVar['$news'] := @News.Data;
//or use this
//ThemeUtil.Assign('$news', @News.Data);
Result := ThemeUtil.RenderFromContent(@TagController, '', 'modules/wpnews/category.html');
FreeAndNil(News);
end;
function TWPCategoryWebModule.Tag_Category_Handler(const TagName: string; Params: TStringList): string;
begin
case TagName of
'$category_title':
begin
Result := CategoryTitle;
end;
'$category_url':
begin
Result := CategoryURL;
end;
end;
end;
constructor TWPCategoryWebModule.CreateNew(AOwner: TComponent; CreateMode: integer);
begin
inherited CreateNew(AOwner, CreateMode);
CreateSession := True;
OnRequest := @RequestHandler;
OnBlockController := @DoBlockController;
end;
destructor TWPCategoryWebModule.Destroy;
begin
inherited Destroy;
end;
procedure TWPCategoryWebModule.DoBlockController(Sender: TObject; FunctionName: string;
Parameter: TStrings; var ResponseString: string);
begin
case FunctionName of
'categorylist':
begin
ResponseString := GetCategoryList(FunctionName, Parameter);
end;
end;
end;
{$ifdef wordpress}
initialization
Route.Add( 'category', TWPCategoryWebModule);
{$endif}
end.
|
unit InfraSelection;
interface
uses
InfraMVPIntf,
InfraValueType;
type
TSelection = class(TInfraList, ISelection)
private
FMultiSelect: boolean;
protected
function GetMultiSelect: boolean;
procedure SetMultiSelect(const Value: boolean);
property MultiSelect: boolean read GetMultiSelect write SetMultiSelect;
end;
procedure RegisterOnReflection;
implementation
uses
InfraNotify,
InfraValueTypeIntf,
InfraCommonIntf;
procedure RegisterOnReflection;
begin
with TypeService do
AddType(ISelection, 'Selection', TSelection, IInfraType,
GetType(IInfraList));
end;
{ TSelection }
function TSelection.GetMultiSelect: boolean;
begin
Result := FMultiSelect;
end;
procedure TSelection.SetMultiSelect(const Value: boolean);
begin
if Value <> FMultiSelect then
begin
FMultiSelect := Value;
if not FMultiSelect then
Clear;
Publisher.Publish(TInfraEvent.Create(Self,
IInfraMultiSelectChanged) as IInfraEvent);
end;
end;
end.
|
unit u_input_email_settings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, JvExControls, JvEnterTab, DateUtils,
Mask, JvExMask, JvSpin, JvComponentBase, u_utils, Vcl.Samples.Spin;
type
TEmailAttachment = record
Name: String[100];
FileName: string[200];
FileSize: Int64;
end;
TSendEmailSettings = record
From,
Email: String[100];
SMTPServer,
SMTPUserName,
SMTPPassword: String[100];
SMTPPort: Word;
SMTPAutoTLS,
SMTPFullSSL: Boolean;
Attachment: TEmailAttachment;
procedure Clear;
end;
TFInputEmailSettings = class(TForm)
eSMTPUsername: TEdit;
eSMTPServer: TEdit;
eSMTPPassword: TEdit;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Panel2: TPanel;
Bevel2: TBevel;
Button1: TButton;
Button2: TButton;
JvEnterAsTab1: TJvEnterAsTab;
Label10: TLabel;
Label3: TLabel;
Label6: TLabel;
eMail: TEdit;
Label8: TLabel;
eAttachment: TButtonedEdit;
Label5: TLabel;
eSMTPPort: TSpinEdit;
procedure JvEnterAsTab1HandleEnter(Sender: TObject; AControl: TWinControl;
var Handled: Boolean);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function InputSendMailSettings(var EmailSettings: TSendEmailSettings): Boolean;
implementation
uses umain;
{$R *.dfm}
function InputSendMailSettings;
var
s: string;
d: TDate;
i: integer;
begin
Result := False;
with TFInputEmailSettings.Create(Application) do
begin
try
eMail.Text := EmailSettings.Email;
eAttachment.Text := EmailSettings.Attachment.FileName;
eAttachment.HiddenText := '';
eAttachment.HiddenInt := 0;
eSMTPServer.Text := EmailSettings.SMTPServer;
eSMTPUsername.Text := EmailSettings.SMTPUserName;
eSMTPPassword.Text := EmailSettings.SMTPPassword;
if EmailSettings.SMTPPort = 0 then
eSMTPPort.Value := 25
else
eSMTPPort.Value := EmailSettings.SMTPPort;
Tag := mrNone;
ShowModal;
Result := Tag = mrOk;
if Result then
begin
EmailSettings.SMTPServer := eSMTPServer.Text;
EmailSettings.SMTPUserName := eSMTPUsername.Text;
EmailSettings.SMTPPassword := eSMTPPassword.Text;
EmailSettings.SMTPPort := eSMTPPort.Value;
EmailSettings.Email := eMail.Text;
if FileExists(eAttachment.Text) then
begin
with EmailSettings.Attachment do
begin
Name := ExtractFileName(eAttachment.Text);
FileName := eAttachment.Text;
// FileSize := u_utils.FileSize(eAttachment.Text);
end;
end;
end;
finally
Free;
end;
end;
end;
procedure TFInputEmailSettings.Button1Click(Sender: TObject);
begin
if eMail.WarnForEmpty() then exit;
if eSMTPServer.WarnForEmpty() then exit;
if eSMTPUsername.WarnForEmpty() then exit;
if eSMTPPassword.WarnForEmpty() then exit;
Tag := mrOk;
Close;
end;
procedure TFInputEmailSettings.Button2Click(Sender: TObject);
begin
Tag := mrCancel;
Close;
end;
procedure TFInputEmailSettings.JvEnterAsTab1HandleEnter(Sender: TObject;
AControl: TWinControl; var Handled: Boolean);
begin
Handled := AControl = Button1;
end;
{ TSendEmailSettings }
procedure TSendEmailSettings.Clear;
begin
From := '';
Email := '';
SMTPServer := '';
SMTPUserName := '';
SMTPPassword := '';
SMTPPort := 0;
SMTPAutoTLS := true;
SMTPFullSSL := false;
Attachment.Name := '';
Attachment.FileName := '';
Attachment.FileSize := 0;
end;
end.
|
unit GaugeBar;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics;
type
{>>TGaugeBar}
TGaugeBar = class(TCustomControl)
private
fMin:Integer;
fMax:Integer;
fPos:Integer;
fStickColor:TColor;
fBackGroundColor:TColor;
fFullColor:TColor;
fText:String;
fOnChange:TNotifyEvent;
Procedure SetStickColor(Value:TColor);
Procedure SetBackGroundColor(Value:TColor);
Procedure SetFullColor(Value:TColor);
Procedure SetMin(Value:Integer);
Procedure SetMax(Value:Integer);
Procedure SetPos(Value:Integer);
Procedure SetText(Value:String);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
Procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
Procedure Resize; override;
published
Property StickColor:TColor Read fStickColor Write SetStickColor;
Property BackGroundColor:TColor Read fBackGroundColor Write SetBackGroundColor;
Property FullColor:TColor Read fFullColor Write SetFullColor;
Property Color;
Property Min:Integer Read fMin Write SetMin;
Property Max:Integer Read fMax Write SetMax;
Property Pos:Integer Read fPos Write SetPos;
Property Text:String Read fText Write SetText;
Property OnChange:TNotifyEvent Read fOnChange Write fOnChange;
Property OnMouseDown;
Property OnMouseMove;
Property OnMouseUp;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MUSIC_PRO', [TGaugeBar]);
end;
{>>TGaugeBar}
constructor TGaugeBar.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
DoubleBuffered:=True;
fMin:=0;
fMax:=100;
fPos:=50;
Width:=100;
fStickColor:=ClRed;
Color:=$00C08000;
BackGroundColor:=$00C8D7DD;
FullColor:=$00400080;
fText:='Value';
end;
destructor TGaugeBar.Destroy;
begin
inherited;
end;
Procedure TGaugeBar.SetMin(Value:Integer);
Begin
If (Value<=fMax) And (Value<=fPos) Then
Begin
fMin:=Value;
Invalidate;
End;
End;
Procedure TGaugeBar.SetMax(Value:Integer);
Begin
If (Value>=fMin) And (Value>=fPos) Then
Begin
fMax:=Value;
Invalidate;
End;
End;
Procedure TGaugeBar.SetPos(Value:Integer);
Begin
If (Pos<>Value) And (Value>=fMin) And (Value<=fMax) Then
Begin
fPos:=Value;
Invalidate;
If Assigned(fOnChange) Then fOnChange(Self);
End;
End;
Procedure TGaugeBar.SetStickColor(Value:TColor);
Begin
fStickColor:=Value;
Invalidate;
End;
Procedure TGaugeBar.SetBackGroundColor(Value:TColor);
Begin
fBackGroundColor:=Value;
Invalidate;
End;
Procedure TGaugeBar.SetFullColor(Value:TColor);
Begin
fFullColor:=Value;
Invalidate;
End;
Procedure TGaugeBar.SetText(Value:String);
Begin
fText:=Value;
Invalidate;
End;
Procedure TGaugeBar.Resize;
begin
inherited;
Height:=40;
end;
Procedure TGaugeBar.Paint;
Var
LeftRect,StickRect,BackGroundRect:TRect;
UpperCorner,LowerCorner:Array [0..2] Of TPoint;
WidthText,IndexLine:Integer;
Str:String;
begin
inherited;
With Canvas Do
Begin
Pen.Width:=4;
UpperCorner[0]:=Point(Width,0);
UpperCorner[1]:=Point(0,0);
UpperCorner[2]:=Point(0,Height);
LowerCorner[0]:=Point(0,Height);
LowerCorner[1]:=Point(Width,Height);
LowerCorner[2]:=Point(Width,0);
Brush.Color:=ClWhite;
Pen.Color:=ClWhite;
Polyline(UpperCorner);
Brush.Color:=$005F5F5F;
Pen.Color:=$005F5F5F;
Polyline(LowerCorner);
Pen.Color:=ClBlack;
Font.Size:=8;
Str:=fText+' '+IntToStr(fPos);
WidthText:=(Width-TextWidth(Str)) Div 2;
Brush.Style:=BsClear;
Font.Color:=ClWhite;
TextOut(WidthText,26,Str);
Pen.Width:=0;
With BackGroundRect Do
Begin
Left:=Width Div 10;
Right:=9*Width Div 10;
Top:=17;
Bottom:=23;
Brush.Color:=fBackGroundColor;
Rectangle(BackGroundRect);
End;
With LeftRect Do
Begin
Left:=Width Div 10;
Right:=Width Div 10+Round((8*Width Div 10)*(fPos-fMin) / (fMax-fMin));
Top:=17;
Bottom:=23;
Brush.Color:=fFullColor;
Rectangle(LeftRect);
End;
Brush.Color:=ClWhite;
Pen.Color:=ClWhite;
Pen.Width:=0;
MoveTo(Width Div 10+1,20);
LineTo(9*Width Div 10-1,20);
With StickRect Do
Begin
Left:=Round(Width Div 10+(8*Width Div 10)*((fPos-fMin) / (fMax-fMin))-0.01*Width);
Right:=Round(Width Div 10+(8*Width Div 10)*((fPos-fMin) / (fMax-fMin))+0.01*Width);
If Left<=0 Then
Begin
Left:=0;
Right:=Round(0.02*Width);
End;
If Right>=Width Then
Begin
Left:=Round(Width*0.98);
Right:=Width;
End;
Top:=13;
Bottom:=27;
Brush.Color:=fStickColor;
Pen.Color:=ClBlack;
Pen.Width:=2;
Rectangle(StickRect);
End;
Pen.Width:=0;
Pen.Color:=ClBlack;
For IndexLine:=0 To 10 Do
Begin
IF IndexLine>(Pos-Min)*10 Div (Max-Min) Then
Pen.Color:=ClBlack Else Pen.Color:=ClLime;
MoveTo((Width Div 10-1)+IndexLine*(8*Width Div 10) Div 10,10);
LineTo((Width Div 10-1)+IndexLine*(8*Width Div 10) Div 10,7-IndexLine Div 2);
End;
End;
End;
Procedure TGaugeBar.MouseDown(Button: TMouseButton; Shift: TShiftState;X, Y: integer);
Var
BnMax,BnMin : Integer;
begin
inherited;
If (Shift=[SSLeft]) Then
Begin
BnMin:=Round((8*Width Div 10)*((fPos-fMin) / (fMax-fMin))-0.01*Width)+Width Div 10;
BnMax:=Round((8*Width Div 10)*((fPos-fMin) / (fMax-fMin))+0.01*Width)+Width Div 10;
If (Shift=[SSLeft]) And (X>=BnMin) And (X<=BnMax) Then
SetPos((X-Width Div 10)*(fMax-fMin) Div (8*Width Div 10)+fMin);
Invalidate;
End;
End;
procedure TGaugeBar.MouseMove(Shift: TShiftState; X, Y: integer);
begin
inherited;
If (Shift=[SSLeft]) Then
Begin
SetPos((X-Width Div 10)*(fMax-fMin) Div (8*Width Div 10)+fMin);
Invalidate;
End;
End;
End. |
unit gkz_case_1;
interface
uses
DUnitX.TestFramework, IOTypes;
type
[TestFixture]
TGKZCase1 = class(TObject)
private
iarray: TISampleArray;
oarray: TOSampleArray;
function IsCase1: boolean;
function compareoutput: boolean;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure CheckCase1;
end;
implementation
uses
ExportFunctions, System.Math, IntervalClass;
procedure TGKZCase1.CheckCase1;
begin
Assert.IsTrue(IsCase1, 'case 1 gkz');
end;
function TGKZCase1.compareoutput: boolean;
begin
result := true;
if (oarray[0].ctype <> ord(itCondBal)) or
(not SameValue(oarray[0].length, 19, 0.01)) or
(not SameValue(oarray[0].grade, 2.56, 0.01)) or
(not SameValue(oarray[0].metergrade, 48.6, 0.01)) then
result := false;
end;
function TGKZCase1.IsCase1: boolean;
var
r: HRESULT;
begin
r := GetIntervals(iarray, oarray);
if r <> S_OK then
result := false
else
result := compareoutput;
end;
procedure TGKZCase1.Setup;
begin
SetConditionConstants(1.5, 8.0, 8.0, 0.5, false);
SetLength(oarray, 19);
SetLength(iarray, 19);
iarray[0]._length := 1.0;
iarray[0]._grade := 1.9;
iarray[1]._length := 1.0;
iarray[1]._grade := 1.8;
iarray[2]._length := 1.0;
iarray[2]._grade := 0.8;
iarray[3]._length := 1.0;
iarray[3]._grade := 2.2;
iarray[4]._length := 1.0;
iarray[4]._grade := 5.0;
iarray[5]._length := 1.0;
iarray[5]._grade := 1.9;
iarray[6]._length := 1.0;
iarray[6]._grade := 5.8;
iarray[7]._length := 1.0;
iarray[7]._grade := 2.9;
iarray[8]._length := 1.0;
iarray[8]._grade := 0.0;
iarray[9]._length := 1.0;
iarray[9]._grade := 1.5;
iarray[10]._length := 1.0;
iarray[10]._grade := 0.2;
iarray[11]._length := 1.0;
iarray[11]._grade := 1.8;
iarray[12]._length := 1.0;
iarray[12]._grade := 1.3;
iarray[13]._length := 1.0;
iarray[13]._grade := 1.9;
iarray[14]._length := 1.0;
iarray[14]._grade := 0.0;
iarray[15]._length := 1.0;
iarray[15]._grade := 3.0;
iarray[16]._length := 1.0;
iarray[16]._grade := 3.8;
iarray[17]._length := 1.0;
iarray[17]._grade := 1.2;
iarray[18]._length := 1.0;
iarray[18]._grade := 11.6;
end;
procedure TGKZCase1.TearDown;
begin
iarray := nil;
oarray := nil;
end;
initialization
TDUnitX.RegisterTestFixture(TGKZCase1);
end.
|
unit UDMService;
interface
uses
System.SysUtils,
System.Classes,
System.Android.Service,
FMX.Types,
System.Threading,
System.PushNotification,
System.JSON,
// System.Notification,
IPPeerClient, AndroidApi.JNI.GraphicsContentViewText, Androidapi.JNI.Os;
type
TDMService = class(TAndroidService)
function AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags,
StartId: Integer): Integer;
private
{ Private declarations }
aPush : TPushService;
aPushConnection : TPushServiceConnection;
procedure DoServiceConnectionChange(Sender : TObject; PushChanges : TPushService.TChanges);
procedure DoReceiveNotificationEvent(Sender : TObject; const ServiceNotification : TPushServiceNotification);
public
{ Public declarations }
// procedure AtivarPushNotification;
// procedure AlertNotification(const aName, aTitle, aMessage : String);
end;
var
DMService: TDMService;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
Androidapi.JNI.App, classes.Constantes;
//procedure TDMService.AlertNotification(const aName, aTitle, aMessage: String);
//var
// aNotificacao : TNotification;
//begin
// if NotificationCenter.Supported then
// begin
// aNotificacao := NotificationCenter.CreateNotification;
// try
// aNotificacao.Name := aName;
// aNotificacao.Title := aTitle;
// aNotificacao.AlertBody := aMessage;
// aNotificacao.Number := (NotificationCenter.ApplicationIconBadgeNumber + 1);
// aNotificacao.EnableSound := True;
// NotificationCenter.PresentNotification(aNotificacao);
// finally
// aNotificacao.DisposeOf;
// end;
// end;
//end;
function TDMService.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags,
StartId: Integer): Integer;
begin
// TTask.Run(
// procedure
// begin
// try
// aPush := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.GCM);
// aPush.AppProps[TPushService.TAppPropNames.GCMAppID] := APP_CODIGO_REMETENTE;
//
// aPushConnection := TPushServiceConnection.Create(aPush);
// aPushConnection.OnChange := DoServiceConnectionChange;
// aPushConnection.OnReceiveNotification := DoReceiveNotificationEvent;
// except
// end;
// end
// );
//
Result := TJService.JavaClass.START_STICKY; // Manterá o Serviço Executando
end;
//procedure TDMService.AtivarPushNotification;
//begin
// aPush := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.GCM);
// aPush.AppProps[TPushService.TAppPropNames.GCMAppID] := APP_CODIGO_REMETENTE;
//
// aPushConnection := TPushServiceConnection.Create(aPush);
// aPushConnection.OnChange := DoServiceConnectionChange;
// aPushConnection.OnReceiveNotification := DoReceiveNotificationEvent;
//
// TTask.Run(
// procedure
// begin
// try
// aPushConnection.Active := True;
// except
// end;
// end
// );
//end;
//
procedure TDMService.DoReceiveNotificationEvent(Sender: TObject;
const ServiceNotification: TPushServiceNotification);
begin
TThread.queue(nil,
procedure
var
aMessageTitle,
aMessageText ,
aJsonText : String;
x : Integer;
Obj : TJSONObject;
Pair : TJSONPair;
begin
// Recuperar notificação quando o APP estiver aberto
try
aMessageText := EmptyStr;
aJsonText := ServiceNotification.DataObject.ToJSON;
for x := 0 to ServiceNotification.DataObject.Count - 1 do
begin
if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'title') then
aMessageTitle := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value)
else
if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'message') then
aMessageText := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value);
end;
//
// if (Trim(aMessageText) <> EmptyStr) then
// AlertNotification(SERVICE_BURGER_HEROES, aMessageTitle, Trim(aMessageText));
except
;
end;
end);
end;
procedure TDMService.DoServiceConnectionChange(Sender: TObject; PushChanges: TPushService.TChanges);
begin
TThread.queue(nil,
procedure
var
aDispositivoID ,
aDispositivoToken : String;
begin
if (TPushService.TChange.DeviceToken in PushChanges) then
begin
aDispositivoID := aPush.DeviceTokenValue[TPushService.TDeviceIDNames.DeviceID];
aDispositivoToken := aPush.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
end;
end);
end;
end.
|
unit View.CadastroProdutosVA;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky,
dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxTextEdit, cxMaskEdit, cxCheckBox, System.Actions,
Vcl.ActnList, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons;
type
Tview_CadastroProdutosVA = class(TForm)
lcgProdutosVA: TdxLayoutGroup;
lciRoot: TdxLayoutControl;
lblTitulo: TcxLabel;
lciTitulo: TdxLayoutItem;
tvProdutos: TcxGridDBTableView;
lvProdutos: TcxGridLevel;
grdProdutos: TcxGrid;
lciGrade: TdxLayoutItem;
dsProduto: TDataSource;
tvProdutosID_PRODUTO: TcxGridDBColumn;
tvProdutosCOD_PRODUTO: TcxGridDBColumn;
tvProdutosDES_PRODUTO: TcxGridDBColumn;
tvProdutosQTD_PADRAO: TcxGridDBColumn;
tvProdutosDOM_DIARIO: TcxGridDBColumn;
tvProdutosCOD_BARRAS: TcxGridDBColumn;
tvProdutosDES_LOG: TcxGridDBColumn;
actCadastro: TActionList;
actSair: TAction;
btnSair: TcxButton;
lciSair: TdxLayoutItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actSairExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
view_CadastroProdutosVA: Tview_CadastroProdutosVA;
implementation
{$R *.dfm}
uses udm;
procedure Tview_CadastroProdutosVA.actSairExecute(Sender: TObject);
begin
Perform(WM_CLOSE, 0, 0);
end;
procedure Tview_CadastroProdutosVA.FormClose(Sender: TObject; var Action: TCloseAction);
begin
dm.fdqProdutosVA.Close;
dm.FDConn.Close;
Action := caFree;
view_CadastroProdutosVA := Nil;
end;
procedure Tview_CadastroProdutosVA.FormShow(Sender: TObject);
begin
dm.FDConn.Open();
dm.fdqProdutosVA.Active := True
end;
end.
|
{
DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(DBEBr Framework)
@created(20 Jul 2016)
@author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>)
}
unit dbebr.driver.connection;
{$ifdef fpc}
{$mode delphi}{$H+}
{$endif}
interface
uses
DB,
Math,
Classes,
SysUtils,
Variants,
// DBEBr
dbebr.factory.interfaces;
type
// Classe de conexões abstract
TDriverConnection = class abstract
protected
FDriverName: TDriverName;
public
constructor Create(const AConnection: TComponent;
const ADriverName: TDriverName); virtual; abstract;
procedure Connect; virtual; abstract;
procedure Disconnect; virtual; abstract;
procedure ExecuteDirect(const ASQL: string); overload; virtual; abstract;
procedure ExecuteDirect(const ASQL: string;
const AParams: TParams); overload; virtual; abstract;
procedure ExecuteScript(const ASQL: string); virtual; abstract;
procedure AddScript(const ASQL: string); virtual; abstract;
procedure ExecuteScripts; virtual; abstract;
function IsConnected: Boolean; virtual; abstract;
function InTransaction: Boolean; virtual; abstract;
function CreateQuery: IDBQuery; virtual; abstract;
function CreateResultSet(const ASQL: string): IDBResultSet; virtual; abstract;
function ExecuteSQL(const ASQL: string): IDBResultSet; virtual; abstract;
property DriverName: TDriverName read FDriverName;
end;
// Classe de trasações abstract
TDriverTransaction = class abstract(TInterfacedObject, IDBTransaction)
public
constructor Create(AConnection: TComponent); virtual; abstract;
procedure StartTransaction; virtual; abstract;
procedure Commit; virtual; abstract;
procedure Rollback; virtual; abstract;
function InTransaction: Boolean; virtual; abstract;
end;
TDriverQuery = class(TInterfacedObject, IDBQuery)
protected
procedure SetCommandText(ACommandText: string); virtual; abstract;
function GetCommandText: string; virtual; abstract;
public
procedure ExecuteDirect; virtual; abstract;
function ExecuteQuery: IDBResultSet; virtual; abstract;
property CommandText: string read GetCommandText write SetCommandText;
end;
TDriverResultSetBase = class(TInterfacedObject, IDBResultSet)
private
function GetFetchingAll: Boolean;
procedure SetFetchingAll(const Value: Boolean);
protected
FField: TAsField;
FFieldNameInternal: string;
FRecordCount: Integer;
FFetchingAll: Boolean;
FFirstNext: Boolean;
public
constructor Create; overload; virtual;
destructor Destroy; override;
procedure Close; virtual; abstract;
function NotEof: Boolean; virtual; abstract;
function GetFieldValue(const AFieldName: string): Variant; overload; virtual; abstract;
function GetFieldValue(const AFieldIndex: Integer): Variant; overload; virtual; abstract;
function GetFieldType(const AFieldName: string): TFieldType; overload; virtual; abstract;
function GetField(const AFieldName: string): TField; virtual; abstract;
function FieldByName(const AFieldName: string): TAsField; virtual;
function RecordCount: Integer; virtual;
function FieldDefs: TFieldDefs; virtual; abstract;
function DataSet: TDataSet; virtual; abstract;
property FetchingAll: Boolean read GetFetchingAll write SetFetchingAll;
end;
TDriverResultSet<T: TDataSet> = class abstract(TDriverResultSetBase)
protected
FDataSet: T;
public
constructor Create(ADataSet: T); overload; virtual;
procedure Close; override;
function FieldDefs: TFieldDefs; override;
function DataSet: TDataSet; override;
end;
TDBEBrField = class(TAsField)
private
FOwner: TDriverResultSetBase;
public
constructor Create(AOwner: TDriverResultSetBase);
destructor Destroy; override;
function IsNull: Boolean; override;
function AsBlob: TMemoryStream; override;
function AsBlobPtr(out iNumBytes: Integer): Pointer; override;
function AsBlobText: string; override;
function AsBlobTextDef(const Def: string = ''): string; override;
function AsDateTime: TDateTime; override;
function AsDateTimeDef(const Def: TDateTime = 0.0): TDateTime; override;
function AsDouble: Double; override;
function AsDoubleDef(const Def: Double = 0.0): Double; override;
function AsInteger: Int64; override;
function AsIntegerDef(const Def: Int64 = 0): Int64; override;
function AsString: string; override;
function AsStringDef(const Def: string = ''): string; override;
function AsFloat: Double; override;
function AsFloatDef(const Def: Double = 0): Double; override;
function AsCurrency: Currency; override;
function AsCurrencyDef(const Def: Currency = 0): Currency; override;
function AsExtended: Extended; override;
function AsExtendedDef(const Def: Extended = 0): Extended; override;
function AsVariant: Variant; override;
function AsVariantDef(const Def: Variant): Variant; override;
function AsBoolean: Boolean; override;
function AsBooleanDef(const Def: Boolean = False): Boolean; override;
function Value: Variant; override;
function ValueDef(const Def: Variant): Variant; override;
end;
implementation
{ TDriverResultSet<T> }
constructor TDriverResultSet<T>.Create(ADataSet: T);
begin
Create;
// Guarda RecordCount do último SELECT executado no IDBResultSet
try
FRecordCount := FDataSet.RecordCount;
except
end;
end;
function TDriverResultSet<T>.DataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TDriverResultSet<T>.Close;
begin
inherited;
FDataSet.Close;
end;
function TDriverResultSet<T>.FieldDefs: TFieldDefs;
begin
inherited;
Result := FDataSet.FieldDefs;
end;
{ TDriverResultSetBase }
function TDriverResultSetBase.RecordCount: Integer;
begin
Result := FRecordCount;
end;
constructor TDriverResultSetBase.Create;
begin
FField := TDBEBrField.Create(Self);
end;
destructor TDriverResultSetBase.Destroy;
begin
FField.Free;
inherited;
end;
function TDriverResultSetBase.FieldByName(const AFieldName: string): TAsField;
begin
FField.AsFieldName := AFieldName;
Result := FField;
end;
function TDriverResultSetBase.GetFetchingAll: Boolean;
begin
Result := FFetchingAll;
end;
procedure TDriverResultSetBase.SetFetchingAll(const Value: Boolean);
begin
FFetchingAll := Value;
end;
{ TAsField }
constructor TDBEBrField.Create(AOwner: TDriverResultSetBase);
begin
FOwner := AOwner;
end;
destructor TDBEBrField.Destroy;
begin
FOwner := nil;
inherited;
end;
function TDBEBrField.AsBlob: TMemoryStream;
begin
// Result := TMemoryStream( FOwner.GetFieldValue(FAsFieldName) );
Result := nil;
end;
function TDBEBrField.AsBlobPtr(out iNumBytes: Integer): Pointer;
begin
// Result := Pointer( FOwner.GetFieldValue(FAsFieldName) );
Result := nil;
end;
function TDBEBrField.AsBlobText: string;
var
LResult: Variant;
begin
Result := '';
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := String(LResult);
end;
function TDBEBrField.AsBlobTextDef(const Def: string): string;
begin
try
Result := String(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsBoolean: Boolean;
var
LResult: Variant;
begin
Result := False;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := Boolean(Value);
end;
function TDBEBrField.AsBooleanDef(const Def: Boolean): Boolean;
begin
try
Result := Boolean(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsCurrency: Currency;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := Currency(LResult);
end;
function TDBEBrField.AsCurrencyDef(const Def: Currency): Currency;
begin
try
Result := Currency(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsDateTime: TDateTime;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := TDateTime(LResult);
end;
function TDBEBrField.AsDateTimeDef(const Def: TDateTime): TDateTime;
begin
try
Result := TDateTime( FOwner.GetFieldValue(FAsFieldName) );
except
Result := Def;
end;
end;
function TDBEBrField.AsDouble: Double;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := Double(LResult);
end;
function TDBEBrField.AsDoubleDef(const Def: Double): Double;
begin
try
Result := Double(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsExtended: Extended;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := Extended(LResult);
end;
function TDBEBrField.AsExtendedDef(const Def: Extended): Extended;
begin
try
Result := Extended(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsFloat: Double;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := Double(LResult);
end;
function TDBEBrField.AsFloatDef(const Def: Double): Double;
begin
try
Result := Double(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsInteger: Int64;
var
LResult: Variant;
begin
Result := 0;
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := LResult;
end;
function TDBEBrField.AsIntegerDef(const Def: Int64): Int64;
begin
try
Result := FOwner.GetFieldValue(FAsFieldName);
except
Result := Def;
end;
end;
function TDBEBrField.AsString: string;
var
LResult: Variant;
begin
Result := '';
LResult := FOwner.GetFieldValue(FAsFieldName);
if LResult <> Null then
Result := String(LResult);
end;
function TDBEBrField.AsStringDef(const Def: string): string;
begin
try
Result := String(FOwner.GetFieldValue(FAsFieldName));
except
Result := Def;
end;
end;
function TDBEBrField.AsVariant: Variant;
begin
Result := FOwner.GetFieldValue(FAsFieldName);
end;
function TDBEBrField.AsVariantDef(const Def: Variant): Variant;
begin
try
Result := FOwner.GetFieldValue(FAsFieldName);
except
Result := Def;
end;
end;
function TDBEBrField.IsNull: Boolean;
begin
Result := FOwner.GetFieldValue(FAsFieldName) = Null;
end;
function TDBEBrField.Value: Variant;
begin
Result := FOwner.GetFieldValue(FAsFieldName);
end;
function TDBEBrField.ValueDef(const Def: Variant): Variant;
begin
try
Result := FOwner.GetFieldValue(FAsFieldName);
except
Result := Def;
end;
end;
end.
|
unit utils;
interface
uses SysUtils, Windows, Forms, Classes, IdHTTP, ExtCtrls, jpeg, WinInet,
mimemess, mimepart, smtpsend, pop3send, blcksock, ssl_openssl,
synautil, synachar, ValEdit;
{
type
TypeSpace = record
Position : Integer;
NumberSpace : Integer;
end;
}
const
UNDEFINED = '<не определено>';
REGEDIT_PATH = 'SOFTWARE\Mail.Ru\M.Agent';
CNT_SITE_DATE = 'http://koder.kz/';
CNT_LICENSE = 'http://koder.kz/licenseBootMail.txt';
procedure AddResultFrends(Email, AjaxResult : String; List : TValueListEditor);
function IsConnectedToInternet: Boolean;
function GetImageJpeg(IdHTTP: TIdHTTP; URL: string; DrawToImage: TImage): TJpegImage;
function Pars(TextIn, Text, TextOut: string): string;
function GetSelfVersion: String;
function SendMsgMail(Host, Subject, pTo, From , TextBody, HTMLBody, login,password, port : string) : boolean;
function UrlEncode(S : Utf8String): String;
implementation
function UrlEncode(S : Utf8String): String;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S)do
if S[i] in ['a'..'z', 'A'..'Z'] then
Result := Result + S[i]
else
Result := Result + '%' + IntToHex(Ord(S[i]), 2);
end;
procedure AddResultFrends(Email, AjaxResult : String; List : TValueListEditor);
var
Status : string;
begin
//ListResultAddFrend.InsertRow('Email','frendusername',true);
//["AjaxResponse","OK","friendship_offer",0]
//["AjaxResponse","OK","already_friendship_offer_sent",0]
//already_friends
//ratelimited_emails
//разбираем ответ сервера
Status := AjaxResult;
if Pos('ratelimited_emails',AjaxResult) > 0 then
Status := 'Предложение дружбы временно не возможно';
if Pos('already_friends',AjaxResult) > 0 then
Status := 'Уже друзья';
if Pos('friendship_offer"',AjaxResult) > 0 then
Status := 'Предложение отправленно';
if Pos('already_friendship_offer_sent"',AjaxResult) > 0 then
Status := 'Вы уже предложили дружбу';
//добавляем в лист
List.InsertRow(Email, Status, true);
List.Row := List.RowCount-1;
end;
function SendMsgMail(Host, Subject, pTo, From , TextBody, HTMLBody, login,password, port : string) : boolean;
var
Msg : TMimeMess;
StringList : TStringList;
MIMEPart : TMimePart;
SMTPClient: TSMTPSend;
begin
SMTPClient := TSMTPSend.Create;
SMTPClient.SystemName := 'koder';
SMTPClient.TargetHost := Host;
SMTPClient.TargetPort := port;
SMTPClient.UserName := login;
SMTPClient.Password := password;
result := false;
Msg := TMimeMess.Create;
StringList := TStringList.Create;
try
Msg.Header.Subject := Subject;
Msg.Header.From := From;
Msg.Header.ToList.Add(pTo);
MIMEPart := Msg.AddPartMultipart('alternative', nil);
if length(TextBody) > 0 then
begin
StringList.Text := TextBody;
Msg.AddPartText(StringList, MIMEPart);
end;
Msg.EncodeMessage;
if (SMTPClient.Login) and (SMTPClient.AuthDone) then
begin
if SMTPClient.MailFrom(GetEmailAddr(Msg.Header.From), Length(Msg.Lines.Text)) then
begin
result := SMTPClient.MailTo(pTo);
if result then
result := SMTPClient.MailData(Msg.Lines);
end;
SMTPClient.Logout;
// result := smtpsend.SendToRaw(From, pTo, Host, Msg.Lines, login, password);
end;
finally
Msg.Free;
StringList.Free;
SMTPClient.Free;
end;
end;
function IsConnectedToInternet: Boolean;
var
dwConnectionTypes: DWORD;
begin
dwConnectionTypes := INTERNET_CONNECTION_MODEM +
INTERNET_CONNECTION_LAN +
INTERNET_CONNECTION_PROXY;
Result := InternetGetConnectedState(@dwConnectionTypes, 0);
end;
function GetSelfVersion: String;
var pVer: ^VS_FIXEDFILEINFO;
Buff: Pointer;
iVer: DWORD;
i: Integer;
VerStr: String;
begin
iVer:=FindResource(0,'#1',RT_VERSION);
if iVer=0 then
begin
Result:=UNDEFINED;
Exit;
end;
Buff:=Pointer(LoadResource(0,iVer));
pVer:=nil;
for i:=0 to (WORD(Buff^) div 4)-1 do
begin
if DWORD(Buff^)=$FEEF04BD then
begin
pVer:=Buff;
Break;
end;
Buff:=Ptr(DWORD(Buff)+4);
end;
if pVer^.dwSignature<>$FEEF04BD then
begin
Result:=UNDEFINED;
end
else
begin
VerStr:=IntToStr((pVer^.dwProductVersionMS shr $10) and $FFFF);
VerStr:=VerStr+'.'+IntToStr(pVer^.dwProductVersionMS and $FFFF);
VerStr:=VerStr+'.'+IntToStr((pVer^.dwProductVersionLS shr $10) and $FFFF);
VerStr:=VerStr+'.'+IntToStr(pVer^.dwProductVersionLS and $FFFF);
Result:=VerStr;
end;
end;
function GetImageJpeg(IdHTTP: TIdHTTP; URL: string; DrawToImage: TImage): TJpegImage;
var
MemoryStream: TMemoryStream;
Img: TJpegImage;
begin
MemoryStream := TMemoryStream.Create;
Img := TJpegImage.Create;
try
IdHTTP.Get(URL, MemoryStream);
MemoryStream.Position := 0;
Img.LoadFromStream(MemoryStream);
DrawToImage.Picture.Graphic := Img;
DrawToImage.Repaint;
finally
MemoryStream.Free;
Result := Img;
Img.Free;
end;
end;
function Pars(TextIn, Text, TextOut: string): string;
var
TempStr: string;
begin
Result := '';
TempStr := Text;
TempStr := Copy(TempStr, Pos(TextIn, TempStr) +7, Length(TempStr));
Delete(TempStr, Pos(TextOut, TempStr), Length(TempStr));
Result := TempStr;
end;
end.
|
unit Unit7;
interface
{
https://www.alberton.info/firebird_sql_meta_info.html
https://gist.github.com/martinusso/1278962
https://edn.embarcadero.com/article/25259
"c:\Program Files\Firebird\Firebird_3_0\isql.exe" -extract -a -output c:\bancos\sql.txt -u SYSDBA -p masterkey c:\bancos\banco.FDB
}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.ComCtrls, Vcl.StdCtrls, FireDAC.Phys.FBDef,
FireDAC.Phys.IBBase, FireDAC.Phys.FB, Vcl.Mask, Vcl.DBCtrls;
type
TFormPrincipal = class(TForm)
FDQuery1: TFDQuery;
Panel1: TPanel;
StatusBar1: TStatusBar;
DataSource1: TDataSource;
FDConnection: TFDConnection;
ButtonSelecionaDB: TButton;
LabeledEditDB: TLabeledEdit;
OpenDialogDB: TOpenDialog;
FDPhysFBDriverLink1: TFDPhysFBDriverLink;
ButtonListarTabela: TButton;
ButtonListarTrigger: TButton;
ButtonListarView: TButton;
ButtonListarProcedure: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
DBGrid1: TDBGrid;
DBEdit1: TDBEdit;
DBMemo1: TDBMemo;
procedure ButtonSelecionaDBClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FDQuery1AfterOpen(DataSet: TDataSet);
procedure ButtonListarTabelaClick(Sender: TObject);
procedure FDQuery1AfterScroll(DataSet: TDataSet);
procedure ButtonListarTriggerClick(Sender: TObject);
procedure ButtonListarViewClick(Sender: TObject);
procedure ButtonListarProcedureClick(Sender: TObject);
private
FDB: String;
FSQL: TStringList;
procedure ConfigurarFDConnection;
procedure ConectarFDConnection;
procedure DesconectarFDConnection;
procedure Executar;
procedure TotalizarItens(DataSet: TDataSet);
property DB: String read FDB write FDB;
property SQL: TStringList read FSQL write FSQL;
public
end;
var
FormPrincipal: TFormPrincipal;
implementation
{$R *.dfm}
procedure TFormPrincipal.ConfigurarFDConnection;
begin
FDB := LabeledEditDB.Text;
FDConnection.Params.Clear;
FDConnection.Params.Add('DriverID=FB');
FDConnection.Params.Add(Format('Database=%s', [FDB]));
FDConnection.Params.Add('User_Name=SYSDBA');
FDConnection.Params.Add('Password=masterkey');
end;
procedure TFormPrincipal.ConectarFDConnection;
begin
try
FDConnection.TxOptions.AutoCommit := True;
FDConnection.UpdateOptions.AutoCommitUpdates := True;
FDConnection.Connected := True;
except
on E: Exception do
ShowMessageFmt('ERRO: %S', [E.Message]);
end;
end;
procedure TFormPrincipal.DesconectarFDConnection;
begin
FDConnection.Connected := False;
end;
procedure TFormPrincipal.TotalizarItens(DataSet: TDataSet);
begin
StatusBar1.Panels[0].Text := Format('%D itens', [DataSet.RecordCount]);
end;
procedure TFormPrincipal.FDQuery1AfterOpen(DataSet: TDataSet);
begin
TotalizarItens(DataSet);
end;
procedure TFormPrincipal.FDQuery1AfterScroll(DataSet: TDataSet);
begin
TotalizarItens(DataSet);
end;
procedure TFormPrincipal.FormCreate(Sender: TObject);
begin
FDB := '';
FSQL := TStringList.Create;
end;
procedure TFormPrincipal.FormDestroy(Sender: TObject);
begin
FreeAndNil(FSQL);
end;
procedure TFormPrincipal.Executar;
begin
try
FDQuery1.Close;
FDQuery1.SQL.Clear;
FDQuery1.SQL.AddStrings(FSQL);
FDQuery1.Active := True;
FDQuery1.Last;
FDQuery1.First;
except
on E: Exception do
ShowMessageFmt('ERRO: %S', [E.Message]);
end;
end;
procedure TFormPrincipal.ButtonListarProcedureClick(Sender: TObject);
begin
{ SELECT
RDB$PROCEDURES.RDB$PROCEDURE_NAME,
RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_NAME,
RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_NUMBER,
RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_TYPE,
RDB$PROCEDURE_PARAMETERS.RDB$FIELD_SOURCE,
RDB$PROCEDURE_PARAMETERS.RDB$DESCRIPTION
FROM RDB$PROCEDURE_PARAMETERS
INNER JOIN RDB$PROCEDURES ON (RDB$PROCEDURES.RDB$PROCEDURE_NAME = RDB$PROCEDURE_PARAMETERS.RDB$PROCEDURE_NAME)
ORDER BY RDB$PROCEDURES.RDB$PROCEDURE_NAME, RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_NUMBER }
FSQL.Clear;
FSQL.Add('SELECT RDB$PROCEDURE_NAME AS NAME,');
FSQL.Add(' RDB$PROCEDURE_SOURCE AS SOURCE');
FSQL.Add(' FROM RDB$PROCEDURES');
FSQL.Add('ORDER BY 1');
Executar;
end;
procedure TFormPrincipal.ButtonListarTabelaClick(Sender: TObject);
begin
FSQL.Clear;
FSQL.Add('SELECT RDB$RELATION_NAME AS NAME,');
FSQL.Add(' NULL AS SOURCE');
FSQL.Add(' FROM RDB$RELATIONS');
FSQL.Add(' WHERE RDB$SYSTEM_FLAG = 0');
FSQL.Add(' AND RDB$VIEW_BLR IS NULL');
FSQL.Add('ORDER BY 1');
Executar;
end;
procedure TFormPrincipal.ButtonListarTriggerClick(Sender: TObject);
begin
FSQL.Clear;
FSQL.Add('SELECT RDB$TRIGGER_NAME AS NAME,');
FSQL.Add(' RDB$TRIGGER_SOURCE AS SOURCE');
FSQL.Add(' FROM RDB$TRIGGERS');
FSQL.Add(' WHERE RDB$SYSTEM_FLAG = 0');
FSQL.Add('ORDER BY 1');
Executar;
end;
procedure TFormPrincipal.ButtonListarViewClick(Sender: TObject);
begin
FSQL.Clear;
FSQL.Add('SELECT RDB$RELATION_NAME AS NAME,');
FSQL.Add(' RDB$VIEW_SOURCE AS SOURCE');
FSQL.Add(' FROM RDB$RELATIONS');
FSQL.Add(' WHERE RDB$VIEW_SOURCE IS NOT NULL ');
FSQL.Add('ORDER BY 1');
Executar;
end;
procedure TFormPrincipal.ButtonSelecionaDBClick(Sender: TObject);
begin
OpenDialogDB.InitialDir := ExtractFileDir(LabeledEditDB.Text);
if (OpenDialogDB.Execute) then
begin
LabeledEditDB.Text := OpenDialogDB.FileName;
DesconectarFDConnection;
ConfigurarFDConnection;
ConectarFDConnection;
end;
end;
end.
|
Procedure printArr;
var
i : Integer;
Begin
write('[');
for i := 1 to size do
begin
Write(arr[i], ', ');
end;
write(']');
end;
Function comparer(a, b : Integer) : Boolean;
begin
comparer := a > b;
end;
Procedure permuter(var a, b : integer);
var
tmp : integer;
begin
tmp := a;
a
:= b;
b := tmp;
end;
|
{
NPC Transmogrifier v1.0
Created by matortheeternal
*What it does*
Run this script on NPC_ records to randomly generate new faces for them.
You can select what aspects of the NPC's face you want to overwrite with
new, random values in the options form. Newly generated faces will use
all assets available in TES5Edit at the time of script application, so
you can generate new faces for vanilla Skyrim NPCs using your hair, eye,
brow, beard, etc. mods.
*Notes*
- Make sure you re-generate NPC face geometry data in the Creation Kit before
testing the NPCs ingame. Not doing so will result in weirdly colored NPCs.
To do this you have to open the file(s) the generated NPCs are in, select
their records in the Creation Kit, and then press Ctrl+Alt+F4.
}
unit UserScript;
uses mteFunctions;
const
vs = '1.0';
processesps = true;
var
slFemaleHairs, slFemaleBrows, slFemaleEyes, slFemaleScars, slFemaleFaces, slMaleHairs,
slMaleFacialHairs, slMaleBrows, slMaleEyes, slMaleScars, slMaleFaces, slHairColors, slMasters,
slDarkElfColors, slHighElfColors, slWoodElfColors, slHumanColors, slOrcColors, slRedguardColors,
slTintColors, slNPCs: TStringList;
separatefile, skipheadparts, skiphaircolor, skiplighting, skipmorphs, skipfaceparts, skiptintlayers,
cancel, skipbethhairs, skipbetheyes, skipbethbrows, skipbethfhairs: boolean;
scarchance, tattoochance: integer;
race: string;
ed01, ed02: TEdit;
btnOk: TButton;
//=========================================================================
// CopyTintLayer: Copies values from a source tint layer to another
function CopyTintLayer(source: IInterface; e: IInterface; index: integer): integer;
begin
senv(e, 'TINI', index);
Add(e, 'TINC', True);
Add(e, 'TINV', True);
senv(e, 'TINV', genv(source, 'TINV'));
senv(e, 'TINC\[0]', genv(source, 'TINC\[0]'));
senv(e, 'TINC\[1]', genv(source, 'TINC\[1]'));
senv(e, 'TINC\[2]', genv(source, 'TINC\[2]'));
end;
//=========================================================================
// CreateTintLayer: Creates a tint layer for the NPC using a tint list
function CreateTintLayer(e: IInterface; index: integer; list: TStringList; search: string; skipchance: integer; tinv: string): integer;
var
done: boolean;
s: string;
rn, tinvlow, tinvhigh: integer;
tintrecord: IInterface;
begin
tinvlow := StrToInt(Copy(tinv, 1, Pos('-', tinv) - 1));
tinvhigh := StrToInt(Copy(tinv, Pos('-', tinv) + 1, Length(tinv)));
senv(e, 'TINI', index);
Add(e, 'TINC', True);
Add(e, 'TINV', True);
senv(e, 'TINV', random(tinvhigh - tinvlow) + tinvlow);
if (random(100) + 1 < skipchance) then begin
seev(e, 'TINC\[0]', '255');
seev(e, 'TINC\[1]', '255');
seev(e, 'TINC\[2]', '255');
senv(e, 'TINV', 0);
exit;
end;
done := false;
While not done do begin
rn := random(list.Count);
if not SameText(search, '') then begin
if (Pos(search, list[rn]) > 0) then done := true;
end
else done := true;
end;
s := IntToHex(list.Objects[rn], 8);
tintrecord := RecordByFormID(FileByLoadOrder(StrToInt(Copy(s, 1, 2))), list.Objects[rn], True);
senv(e, 'TINC\[0]', genv(tintrecord, 'CNAM\Red'));
senv(e, 'TINC\[1]', genv(tintrecord, 'CNAM\Green'));
senv(e, 'TINC\[2]', genv(tintrecord, 'CNAM\Blue'));
end;
//=========================================================================
// ChooseHeadPart: Randomly selects a headpart from a list
function ChooseHeadPart(headpart: IInterface; list: TStringList): integer;
var
s, rs: string;
e: IInterface;
fails: integer;
done: boolean;
begin
rs := race;
done := false;
fails := 0;
While not done do begin
SetNativeValue(headpart, list.Objects[random(list.Count)]);
s := geev(LinksTo(ElementByPath(LinksTo(headpart), 'RNAM')), 'EDID');
if rs = 'NordRace' then begin
if s = 'HeadPartsHumansandVampires' then done := true;
if s = 'HeadPartsHuman' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'BretonRace' then begin
if s = 'HeadPartsHumansandVampires' then done := true;
if s = 'HeadPartsHuman' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'ImperialRace' then begin
if s = 'HeadPartsHumansandVampires' then done := true;
if s = 'HeadPartsHuman' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'ArgonianRace' then begin
if s = 'HeadPartsArgonianandVampire' then done := true;
if s = 'HeadPartsArgonian' then done := true;
end;
if rs = 'WoodElfRace' then begin
if s = 'HeadPartsElvesandVampires' then done := true;
if s = 'HeadPartsWoodElf' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'DarkElfRace' then begin
if s = 'HeadPartsElvesandVampires' then done := true;
if s = 'HeadPartsDarkElf' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'HighElfRace' then begin
if s = 'HeadPartsElvesandVampires' then done := true;
if s = 'HeadPartsHighElf' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'RedguardRace' then begin
if s = 'HeadPartsRedguardandVampire' then done := true;
if s = 'HeadPartsHumansandVampires' then done := true;
if s = 'HeadPartsHuman' then done := true;
if s = 'HeadPartsAllRacesMinusBeast' then done := true;
end;
if rs = 'KhajiitRace' then begin
if s = 'HeadPartsKhajiitandVampire' then done := true;
if s = 'HeadPartsKhajiit' then done := true;
end;
if rs = 'OrcRace' then begin
if s = 'HeadPartsOrcandVampire' then done := true;
if s = 'HeadPartsOrc' then done := true;
end;
Inc(fails);
if fails > 50 then begin
AddMessage(' !ERRROR: The script was unable to find a suitable head part.');
done := true; // terminate if suitable headpart not found after 50 attempts
end;
end;
end;
//=========================================================================
// OkButtonControl: Disables the OK button if invalid values entered
procedure OkButtonControl;
var
enable: boolean;
begin
enable := true;
try
if (StrToInt(StringReplace(ed01.Text, '%', '', [rfReplaceAll])) > 100) then enable := false;
if (StrToInt(StringReplace(ed02.Text, '%', '', [rfReplaceAll])) > 100) then enable := false;
except on Exception do
enable := false;
btnOk.Enabled := false;
end;
if enable then btnOk.Enabled := true
else btnOk.Enabled := false;
end;
//=========================================================================
// OptionsForm: The main options form
procedure OptionsForm;
var
frm: TForm;
g1, g2: TGroupbox;
cb01, cb02, cb03, cb04, cb05, cb06, cb07, cb08, cb09, cb10, cb11: TCheckbox;
lbl01, lbl02: TLabel;
btnCancel: TButton;
begin
frm := TForm.Create(nil);
try
frm.Caption := 'NPC Transmogrifier '+vs;
frm.Width := 300;
frm.Height := 340;
frm.Position := poScreenCenter;
frm.BorderStyle := bsDialog;
g1 := TGroupBox.Create(frm);
g1.Parent := frm;
g1.Top := 8;
g1.Left := 8;
g1.Width := 284;
g1.Height := 110;
g1.Caption := 'Transformation parameters';
g1.ClientWidth := 274;
g1.ClientHeight := 100;
cb01 := TCheckBox.Create(g1);
cb01.Parent := g1;
cb01.Top := 20;
cb01.Left := 8;
cb01.Width := 140;
cb01.Caption := 'Skip Head Parts';
cb02 := TCheckBox.Create(g1);
cb02.Parent := g1;
cb02.Top := cb01.Top;
cb02.Left := cb01.Left + cb01.Width + 8;
cb02.Width := 140;
cb02.Caption := 'Skip Hair color';
cb03 := TCheckBox.Create(g1);
cb03.Parent := g1;
cb03.Top := cb01.Top + cb01.Height + 8;
cb03.Left := cb01.Left;
cb03.Width := 140;
cb03.Caption := 'Skip Lighting';
cb04 := TCheckBox.Create(g1);
cb04.Parent := g1;
cb04.Top := cb03.Top;
cb04.Left := cb02.Left;
cb04.Width := 140;
cb04.Caption := 'Skip Morphs';
cb05 := TCheckBox.Create(g1);
cb05.Parent := g1;
cb05.Top := cb03.Top + cb03.Height + 8;
cb05.Left := cb01.Left;
cb05.Width := 140;
cb05.Caption := 'Skip Face Parts';
cb06 := TCheckBox.Create(g1);
cb06.Parent := g1;
cb06.Top := cb05.Top;
cb06.Left := cb02.Left;
cb06.Width := 140;
cb06.Caption := 'Skip Tint Layers';
g2 := TGroupBox.Create(frm);
g2.Parent := frm;
g2.Top := 120;
g2.Left := 8;
g2.Width := 284;
g2.Height := 85;
g2.Caption := 'Asset parameters';
g2.ClientWidth := 274;
g2.ClientHeight := 75;
cb07 := TCheckBox.Create(g2);
cb07.Parent := g2;
cb07.Top := 20;
cb07.Left := 8;
cb07.Width := 130;
cb07.Caption := 'Skip Bethesda hairs';
cb08 := TCheckBox.Create(g2);
cb08.Parent := g2;
cb08.Top := cb07.Top;
cb08.Left := cb07.Left + cb07.Width + 8;
cb08.Width := 130;
cb08.Caption := 'Skip Bethesda eyes';
cb09 := TCheckBox.Create(g2);
cb09.Parent := g2;
cb09.Top := cb07.Top + cb07.Height + 8;
cb09.Left := cb07.Left;
cb09.Width := 130;
cb09.Caption := 'Skip Bethesda brows';
cb10 := TCheckBox.Create(g2);
cb10.Parent := g2;
cb10.Top := cb09.Top;
cb10.Left := cb08.Left;
cb10.Width := 130;
cb10.Caption := 'Skip Bethesda fhairs';
lbl01 := TLabel.Create(frm);
lbl01.Parent := frm;
lbl01.Top := 210;
lbl01.Left := 16;
lbl01.Width := 120;
lbl01.Height := 25;
lbl01.Caption := 'Scar chance: ';
ed01 := TEdit.Create(frm);
ed01.Parent := frm;
ed01.Top := lbl01.Top;
ed01.Left := lbl01.Left + lbl01.Width + 36;
ed01.Width := 50;
ed01.Text := '15%';
ed01.OnChange := OkButtonControl;
lbl02 := TLabel.Create(frm);
lbl02.Parent := frm;
lbl02.Top := lbl01.Top + lbl01.Height + 16;
lbl02.Left := lbl01.Left;;
lbl02.Width := lbl01.Width;
lbl02.Height := lbl01.Height;
lbl02.Caption := 'Warpaint chance: ';
ed02 := TEdit.Create(frm);
ed02.Parent := frm;
ed02.Top := lbl02.Top;
ed02.Left := ed01.Left;
ed02.Width := ed01.Width;
ed02.Text := '10%';
ed02.OnChange := OkButtonControl;
btnOk := TButton.Create(frm);
btnOk.Parent := frm;
btnOk.Left := 70;
btnOk.Caption := 'OK';
btnOk.Top := frm.Height - btnOk.Height - 40;
btnOk.ModalResult := mrOk;
btnCancel := TButton.Create(frm);
btnCancel.Parent := frm;
btnCancel.Caption := 'Cancel';
btnCancel.ModalResult := mrCancel;
btnCancel.Left := btnOk.Left + btnOk.Width + 16;
btnCancel.Top := btnOk.Top;
if frm.ShowModal = mrOk then begin
if cb01.State = cbChecked then
skipheadparts := true;
if cb02.State = cbChecked then
skiphaircolors := true;
if cb03.State = cbChecked then
skiplighting := true;
if cb04.State = cbChecked then
skipmorphs := true;
if cb05.State = cbChecked then
skipfaceparts := true;
if cb06.State = cbChecked then
skiptintlayers := true;
if cb07.State = cbChecked then
skipbethhairs := true;
if cb08.State = cbChecked then
skipbetheyes := true;
if cb09.State = cbChecked then
skipbethbrows := true;
if cb10.State = cbChecked then
skipbethfhairs := true;
scarchance := StrToInt(StringReplace(ed01.Text, '%', '', [rfReplaceAll]));
tattoochance := StrToInt(StringReplace(ed02.Text, '%', '', [rfReplaceAll]));
cancel := false;
end;
finally
frm.Free;
end;
end;
//=========================================================================
// initialize stuff
function Initialize: integer;
var
i, j, k: integer;
e, f, group: IInterface;
s: string;
r: real;
begin
// welcome messages
AddMessage(#13#10#13#10);
AddMessage('---------------------------------------------------------------');
AddMessage('NPC Transmogrifier '+vs+': Generates faces for existing NPCs.');
AddMessage('---------------------------------------------------------------');
// separate file default override
//separatefile := true;
// creating stringlists
slMasters := TStringList.Create;
slMasters.Sorted := True;
slMasters.Duplicates := dupIgnore;
slFemaleHairs := TStringList.Create;
slFemaleBrows := TStringList.Create;
slFemaleEyes := TStringList.Create;
slFemaleScars := TStringList.Create;
slFemaleFaces := TStringList.Create;
slMaleHairs := TStringList.Create;
slMaleBrows := TStringList.Create;
slMaleFacialHairs := TStringList.Create;
slMaleEyes := TStringList.Create;
slMaleScars := TStringList.Create;
slMaleFaces := TStringList.Create;
slHairColors := TStringList.Create;
slDarkElfColors := TStringList.Create;
slHighElfColors := TStringList.Create;
slHumanColors := TStringList.Create;
slWoodElfColors := TStringList.Create;
slRedguardColors := TStringList.Create;
slOrcColors := TStringList.Create;
slTintColors := TStringList.Create;
slNPCs := TStringList.Create;
// stringlists created
AddMessage('Stringlists created.');
// options form
cancel := true;
OptionsForm;
if cancel then exit;
randomize();
// load stringlist data from available files
AddMessage('Loading data from available master files.'+#13#10);
for i := 0 to FileCount - 1 do begin
f := FileByIndex(i);
s := GetFileName(f);
if (Pos('.esm', s) > 0) then slMasters.Add(s) else begin
if processesps and (Pos('.esp', s) > 0) then begin
if MessageDlg('Process assets in: '+s+' ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then slMasters.Add(s);
end else Continue;
end;
group := GroupBySignature(f, 'CLFM'); //colors
for j := 0 to ElementCount(group) - 1 do begin
e := ElementByIndex(group, j);
s := geev(e, 'EDID');
if (Pos('HairColor', s) > 0) then
slHairColors.AddObject(s, TObject(FormID(e)))
else if (Pos('HighElf', s) > 0) then
slHighElfColors.AddObject(s, TObject(FormID(e)))
else if (Pos('DarkElf', s) > 0) then
slDarkElfColors.AddObject(s, TObject(FormID(e)))
else if (Pos('WoodElf', s) > 0) then
slWoodElfColors.AddObject(s, TObject(FormID(e)))
else if (Pos('Orc', s) > 0) then
slOrcColors.AddObject(s, TObject(FormID(e)))
else if (Pos('Human', s) > 0) then
slHumanColors.AddObject(s, TObject(FormID(e)))
else if (Pos('Redguard', s) > 0) then
slRedguardColors.AddObject(s, TObject(FormID(e)))
else if (Pos('Tint', s) > 0) and not SameText('RedTintPink', s) then
slTintColors.AddObject(s, TObject(FormID(e)));
end;
group := GroupBySignature(f, 'HDPT'); //head parts
for j := 0 to ElementCount(group) - 1 do begin
e := ElementByIndex(group, j);
if geev(e, 'DATA - Flags\Playable') = '1' then begin
if geev(e, 'DATA - Flags\Male') = '1' then begin
if geev(e, 'PNAM') = 'Hair' then begin
if skipbethhairs and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slMaleHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Facial Hair' then begin
if skipbethfhairs and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slMaleFacialHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Eyebrows' then begin
if skipbethbrows and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slMaleBrows.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Eyes' then begin
if skipbetheyes and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slMaleEyes.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Scar' then
slMaleScars.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
if geev(e, 'PNAM') = 'Face' then
slMaleFaces.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'DATA - Flags\Female') = '1' then begin
if geev(e, 'PNAM') = 'Hair' then begin
if skipbethhairs and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slFemaleHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Eyebrows' then begin
if skipbethbrows and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slFemaleBrows.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Eyes' then begin
if skipbetheyes and (Pos(GetFileName(f), bethesdaFiles) > 0) then
continue;
slFemaleEyes.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
if geev(e, 'PNAM') = 'Scar' then
slFemaleScars.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
if geev(e, 'PNAM') = 'Face' then
slFemaleFaces.AddObject(geev(e, 'EDID'), TObject(FormID(e)));
end;
end;
end;
end;
if (slFemaleHairs.Count = 0) or (slFemaleBrows.Count = 0) or (slFemaleEyes.Count = 0)
or (slMaleHairs.Count = 0) or (slMaleBrows.Count = 0) or (slMaleEyes.Count = 0) or (slMaleFacialHairs.Count = 0) then begin
AddMessage('Stringlist loading failed. Asset count in one or more essential stringlists was zero.');
cancel := true;
end;
end;
//=========================================================================
// process selected NPCs
function Process(e: IInterface): integer;
begin
if cancel then exit;
// skip non NPC records
if Signature(e) <> 'NPC_' then
exit;
// add records to list
slNPCs.AddObject(Name(e), TObject(e));
// if any NPC records are in bethesda master set separatefile to true
if (Pos(GetFileName(GetFile(e)), bethesdaFiles) > 0) then
separatefile := true;
end;
//=========================================================================
// finalize
function Finalize: integer;
var
npc, npcfile, layer, group: IInterface;
female: boolean;
s, name: string;
i, j: integer;
r: float;
begin
if cancel then begin
slFemaleHairs.Free;
slFemaleBrows.Free;
slFemaleEyes.Free;
slFemaleScars.Free;
slFemaleFaces.Free;
slMaleHairs;
slMaleFacialHairs.Free;
slMaleBrows.Free;
slMaleEyes.Free;
slMaleScars.Free;
slMaleFaces.Free;
slHairColors;
slMasters.Free;
slDarkElfColors.Free;
slHighElfColors.Free;
slWoodElfColors.Free;
slHumanColors.Free;
slOrcColors.Free;
slRedguardColors.Free;
slTintColors.Free;
slNPCs.Free;
exit;
end;
// have user select file if separatefile is true
if separatefile then begin
// have user select or create npc file
npcfile := FileSelect('Choose the file you want to use as your NPC file below');
if not Assigned(npcfile) then begin
AddMessage(' No npc file assigned, can''t create NPC override records.');
exit;
end
else AddMessage('Override NPCs will be stored in the file: '+GetFileName(npcfile));
for i := 0 to slMasters.Count - 1 do
if not SameText(GetFileName(npcfile), slMasters[i]) then
AddMasterIfMissing(npcfile, slMasters[i]);
Add(npcfile, 'NPC_', true);
end;
// transmogrify npcs
AddMessage(#13#10+'Transmogrifying NPCs...');
for i := 0 to Pred(slNPCs.Count) do begin
npc := ObjectToElement(slNPCs.Objects[i]);
if separatefile then
npc := wbCopyElementToFile(npc, npcfile, False, True);
// get npc name
name := geev(npc, 'FULL');
AddMessage(' Transmogrifying '+name);
// get npc gender
if (geev(npc, 'ACBS\Flags\female') = '1') then
female := true;
// get npc race
race := geev(LinksTo(ElementByPath(npc, 'RNAM')), 'EDID');
// set NPC head parts
if not skipheadparts then begin
Remove(ElementByPath(npc, 'Head Parts'));
group := Add(npc, 'Head Parts', True);
ElementAssign(group, HighInteger, nil, False);
if female then begin
ChooseHeadPart(ElementByIndex(group, 1), slFemaleHairs);
ChooseHeadPart(ElementByIndex(group, 0), slFemaleEyes);
if not SameText(race, 'KhajiitRace') then begin
ElementAssign(group, HighInteger, nil, False);
ChooseHeadPart(ElementByIndex(group, 0), slFemaleBrows);
end;
if (1 + Random(100) < scarchance) then begin
ElementAssign(group, HighInteger, nil, False);
ChooseHeadPart(ElementByIndex(group, 0), slFemaleScars);
AddMessage(' '+name+' has some new battle scars.');
end;
end
else begin
ChooseHeadPart(ElementByIndex(group, 1), slMaleHairs);
ChooseHeadPart(ElementByIndex(group, 0), slMaleEyes);
if not SameText(race, 'KhajiitRace') then begin
ElementAssign(group, HighInteger, nil, False);
ChooseHeadPart(ElementByIndex(group, 0), slMaleBrows);
end;
if (random(6) > 0) and not SameText(race, 'ArgonianRace') then begin
ElementAssign(group, HighInteger, nil, False);
ChooseHeadPart(ElementByIndex(group, 0), slMaleFacialHairs);
end;
if (1 + Random(100) < scarchance) then begin
ElementAssign(group, HighInteger, nil, False);
ChooseHeadPart(ElementByIndex(group, 0), slMaleScars);
AddMessage(' '+name+' has some battle scars.');
end;
end;
AddMessage(' '+name+' has a new face!');
end;
// set NPC hair color
if not skiphaircolor then begin
senv(npc, 'HCLF', slHairColors.Objects[random(slHairColors.Count)]);
AddMessage(' '+name+' has dyed their hair.');
end;
// set NPC texture lighting
if not skiplighting then begin
Add(npc, 'QNAM', True);
for j := 0 to ElementCount(ElementByPath(npc, 'QNAM')) - 1 do
senv(npc, 'QNAM\['+IntToStr(j)+']', ((Random(500001) + 30000)/1000000));
AddMessage(' '+name+' has new texture lighting.');
end;
// set NPC face morphs, product of two random numbers to reduce extreme facial deformation
if not skipmorphs then begin
Remove(ElementByPath(npc, 'NAM9'));
Add(npc, 'NAM9', True);
for j := 0 to ElementCount(ElementByPath(npc, 'NAM9')) - 2 do begin
r := (random(10)/10) * (random(10)/10);
if random(2) = 1 then r := -r;
senv(npc, 'NAM9\['+IntToStr(j)+']', r);
end;
AddMessage(' '+name+' has had their face stretched out!');
end;
// set NPC face parts
if not skipfaceparts then begin
Remove(ElementByPath(npc, 'NAMA'));
Add(npc, 'NAMA', True);
senv(npc, 'NAMA\[0]', (Random(20) + 1));
senv(npc, 'NAMA\[1]', -1);
senv(npc, 'NAMA\[2]', (Random(20) + 1));
senv(npc, 'NAMA\[3]', (Random(20) + 1));
AddMessage(' '+name+' has had their face scrambled!');
end;
// set NPC tint layers
if not skiptintlayers then begin
Remove(ElementByPath(npc, 'Tint Layers'));
Add(npc, 'Tint Layers', True);
if race = 'ArgonianRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
baselayer := ElementByIndex(group, 0);
CreateTintLayer(baselayer, 16, slTintColors, '', 40, '8-33'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CopyTintLayer(baselayer, layer, 32); //ArgonianNeck same as SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 17, slTintColors, '', 80, '10-50'); //ArgonianEyeSocketUpper
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 18, slTintColors, '', 80, '10-50'); //ArgonianEyeSocketLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 19, slTintColors, '', 70, '10-50'); //ArgonianCheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 20, slTintColors, '', 80, '10-50'); //ArgonianNostrils01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 21, slTintColors, '', 80, '10-50'); //ArgonianEyeLiner
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 22, slTintColors, '', 70, '10-50'); //ArgonianLips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23, slTintColors, '', 70, '10-50'); //ArgonianChin
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 24 + Random(5), slTintColors, '', 0, '60-100');
// 24 = ArgonianStripes01
// 25 = ArgonianStripes02
// 26 = ArgonianStripes03
// 27 = ArgonianStripes04
// 28 = ArgonianStripes05
end;
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 80, '10-50'); //ArgonianLaughline
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 80, '10-50'); //ArgonianForehead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 80, '10-50'); //ArgonianCheeksLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 45, slTintColors, '', 100, '60-100'); //ArgonianDirt
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 6, slTintColors, '', 80, '10-40'); //ArgonianEyeSocketUpper
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 80, '10-40'); //ArgonianEyeSocketLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 70, '10-40'); //ArgonianCheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 80, '10-40'); //ArgonianNostrils01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 80, '10-40'); //ArgonianEyeLiner
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 70, '10-40'); //ArgonianLips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 13, slTintColors, '', 70, '10-40'); //ArgonianChin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 80, '10-40'); //ArgonianCheeksLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 80, '10-40'); //ArgonianForehead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 80, '1-10'); //ArgonianLaughline
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 36, slTintColors, '', 100, '60-100'); //ArgonianDirt
baselayer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(baselayer, 38, slTintColors, '', 40, '8-33'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CopyTintLayer(baselayer, layer, 27); //ArgonianNeck same as SkinTone
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(6) + 1;
if r = 1 then
CreateTintLayer(layer, 14, slTintColors, '', 0, '60-100') //ArgonianStripes01
else if r = 2 then
CreateTintLayer(layer, 15, slTintColors, '', 0, '60-100') //ArgonianStripes02
else if r = 3 then
CreateTintLayer(layer, 35, slTintColors, '', 0, '60-100') //ArgonianStripes03
else if r = 4 then
CreateTintLayer(layer, 39, slTintColors, '', 0, '60-100') //ArgonianStripes04
else if r = 5 then
CreateTintLayer(layer, 40, slTintColors, '', 0, '60-100') //ArgonianStripes05
else if r = 6 then
CreateTintLayer(layer, 41, slTintColors, '', 0, '60-100'); //ArgonianStripes06
end;
end;
end
else if race = 'OrcRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 13, slOrcColors, 'OrcSkinFemale', 0, '30-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines.dds
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 70, '10-40'); //FemaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 36, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 47, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 48, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 49, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 37 + r, slTintColors, '', 0, '60-100')
// 37 = FemaleHeadWarPaint_01
// 38 = FemaleHeadWarPaint_02
// 39 = FemaleHeadWarPaint_03
// 40 = FemaleHeadWarPaint_04
// 41 = FemaleHeadWarPaint_05
// 42 = FemaleHeadWarPaint_06
// 43 = FemaleHeadWarPaint_07
// 44 = FemaleHeadWarPaint_08
// 45 = FemaleHeadWarPaint_09
// 46 = FemaleHeadWarPaint_10
else if r >= 10 then
CreateTintLayer(layer, 56 + r - 10, slTintColors, '', 0, '60-100');
// 56 = FemaleHeadOrcWarPaint_01
// 57 = FemaleHeadOrcWarPaint_02
// 58 = FemaleHeadOrcWarPaint_03
// 59 = FemaleHeadOrcWarPaint_04
// 60 = FemaleHeadOrcWarPaint_05
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slOrcColors, 'OrcSkin0', 0, '30-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 90, '5-20'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 70, '10-40'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 51, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 8 then
CreateTintLayer(layer, 14 + r, slTintColors, '', 0, '60-100')
// 14 = MaleHeadWarPaint_01
// 15 = MaleHeadWarPaint_02
// 16 = MaleHeadWarPaint_03
// 17 = MaleHeadWarPaint_04
// 18 = MaleHeadWarPaint_05
// 19 = MaleHeadWarPaint_06
// 20 = MaleHeadWarPaint_07
// 21 = MaleHeadWarPaint_09
else if r < 10 then
CreateTintLayer(layer, 15 + r, slTintColors, '', 0, '60-100')
// 23 = MaleHeadWarPaint_08
// 24 = MaleHeadWarPaint_10
else if r < 14 then
CreateTintLayer(layer, 52 + r - 10, slTintColors, '', 0, '60-100')
// 52 = MaleHeadOrcWarPaint_01
// 53 = MaleHeadOrcWarPaint_02
// 54 = MaleHeadOrcWarPaint_03
// 55 = MaleHeadOrcWarPaint_04
else
CreateTintLayer(layer, 61, slTintColors, '', 0, '60-100'); //MaleHeadOrcWarPaint_05
end;
end;
end
else if race = 'HighElfRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 24, slHighElfColors, 'HighElfSkinFemale', 33, '30-90'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 70, '10-30'); //FemaleHeadHighElf_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 46, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 47, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 48, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(14);
if r < 10 then
CreateTintLayer(layer, 36 + r, slTintColors, '', 0, '60-100')
// 36 = FemaleHeadWarPaint_01
// 37 = FemaleHeadWarPaint_02
// 38 = FemaleHeadWarPaint_03
// 39 = FemaleHeadWarPaint_04
// 40 = FemaleHeadWarPaint_05
// 41 = FemaleHeadWarPaint_06
// 42 = FemaleHeadWarPaint_07
// 43 = FemaleHeadWarPaint_08
// 44 = FemaleHeadWarPaint_09
// 45 = FemaleHeadWarPaint_10
else
CreateTintLayer(layer, 51 + r - 10, slTintColors, '', 0, '60-100');
// 51 = FemaleHeadHighElfWarPaint_01
// 52 = FemaleHeadHighElfWarPaint_02
// 53 = FemaleHeadHighElfWarPaint_03
// 54 = FemaleHeadHighElfWarPaint_04
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 5, slHighElfColors, 'HighElfSkin0', 10, '30-90'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 85, '5-25'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 70, '10-50'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 49, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 13 + Random(10), slTintColors, '', 0, '60-100');
// 13 = MaleHeadWarPaint_01
// 14 = MaleHeadWarPaint_02
// 15 = MaleHeadWarPaint_03
// 16 = MaleHeadWarPaint_04
// 17 = MaleHeadWarPaint_05
// 18 = MaleHeadWarPaint_06
// 19 = MaleHeadWarPaint_07
// 20 = MaleHeadWarPaint_08
// 21 = MaleHeadWarPaint_09
// 22 = MaleHeadWarPaint_10
end;
end;
end
else if race = 'DarkElfRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 24, slDarkElfColors, 'DarkElfSkinFemale', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 40, '50-90'); //FemaleHeadDarkElf_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 46, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 59, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 60, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 62, slTintColors, '', 100, '50-100'); //FemaleHeadBothiahTattoo_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(16);
if r < 10 then
CreateTintLayer(layer, 36 + r, slTintColors, '', 0, '50-100')
// 36 = FemaleHeadWarPaint_01
// 37 = FemaleHeadWarPaint_02
// 38 = FemaleHeadWarPaint_03
// 39 = FemaleHeadWarPaint_04
// 40 = FemaleHeadWarPaint_05
// 41 = FemaleHeadWarPaint_06
// 42 = FemaleHeadWarPaint_07
// 43 = FemaleHeadWarPaint_08
// 44 = FemaleHeadWarPaint_09
// 45 = FemaleHeadWarPaint_10
else if r < 15 then
CreateTintLayer(layer, 37 + r, slTintColors, '', 0, '50-100')
// 47 = FemaleHeadDarkElfWarPaint_01
// 48 = FemaleHeadDarkElfWarPaint_02
// 49 = FemaleHeadDarkElfWarPaint_03
// 50 = FemaleHeadDarkElfWarPaint_04
// 51 = FemaleHeadDarkElfWarPaint_05
else
CreateTintLayer(layer, 64, slTintColors, '', 0, '50-100'); //FemaleDarkElfWarPaint_06
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slDarkElfColors, 'DarkElfSkin0', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 63, slTintColors, '', 100, '50-100'); //MaleHeadBothiahTattoo_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(16);
if r < 10 then
CreateTintLayer(layer, 13 + r, slTintColors, '', 0, '50-100')
// 13 = MaleHeadWarPaint_01
// 14 = MaleHeadWarPaint_02
// 15 = MaleHeadWarPaint_03
// 16 = MaleHeadWarPaint_04
// 17 = MaleHeadWarPaint_05
// 18 = MaleHeadWarPaint_06
// 19 = MaleHeadWarPaint_07
// 20 = MaleHeadWarPaint_08
// 21 = MaleHeadWarPaint_09
// 22 = MaleHeadWarPaint_10
else if r < 15 then
CreateTintLayer(layer, 52 + r - 10, slTintColors, '', 0, '50-100')
// 52 = MaleHeadDarkElfWarPaint_01
// 53 = MaleHeadDarkElfWarPaint_02
// 54 = MaleHeadDarkElfWarPaint_03
// 55 = MaleHeadDarkElfWarPaint_04
// 56 = MaleHeadDarkElfWarPaint_05
else
CreateTintLayer(layer, 61, slTintColors, '', 0, '50-100'); // MaleHeadDarkElfWarPaint_06
end;
end;
end
else if race = 'WoodElfRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 24, slWoodElfColors, 'WoodElfSkinFemale', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 30, '20-90'); //FemaleHeadWoodElf_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 46, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 54, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 55, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 36 + r, slTintColors, '', 0, '50-100')
// 36 = FemaleHeadWarPaint_01
// 37 = FemaleHeadWarPaint_02
// 38 = FemaleHeadWarPaint_03
// 39 = FemaleHeadWarPaint_04
// 40 = FemaleHeadWarPaint_05
// 41 = FemaleHeadWarPaint_06
// 42 = FemaleHeadWarPaint_07
// 43 = FemaleHeadWarPaint_08
// 44 = FemaleHeadWarPaint_09
// 45 = FemaleHeadWarPaint_10
else
CreateTintLayer(layer, 47 + r - 10, slTintColors, '', 0, '50-100');
// 47 = FemaleHeadWoodElfWarPaint_01
// 48 = FemaleHeadWoodElfWarPaint_02
// 49 = FemaleHeadWoodElfWarPaint_03
// 50 = FemaleHeadWoodElfWarPaint_04
// 51 = FemaleHeadWoodElfWarPaint_05
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slWoodElfColors, 'WoodElfSkin0', 0, '50-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 52, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 53, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 13 + r, slTintColors, '', 0, '50-100')
// 13 = MaleHeadWarPaint_01
// 14 = MaleHeadWarPaint_02
// 15 = MaleHeadWarPaint_03
// 16 = MaleHeadWarPaint_04
// 17 = MaleHeadWarPaint_05
// 18 = MaleHeadWarPaint_06
// 19 = MaleHeadWarPaint_07
// 20 = MaleHeadWarPaint_08
// 21 = MaleHeadWarPaint_09
// 22 = MaleHeadWarPaint_10
else
CreatTintLayer(layer, 56 + r - 10, slTintColors, '', 0, '50-100');
// 56 = MaleHeadWoodElfWarPaint_01
// 57 = MaleHeadWoodElfWarPaint_02
// 58 = MaleHeadWoodElfWarPaint_03
// 59 = MaleHeadWoodElfWarPaint_04
// 60 = MaleHeadWoodElfWarPaint_05
end;
end;
end
else if race = 'RedguardRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 23, slHumanColors, 'HumanSkinDark', 0, '50-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 36, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 37, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 38, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 39, slTintColors, '', 30, '30-80'); //FemaleHeadRedguard_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 40, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 41, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 42, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 43, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 44, slTintColors, '', 70, '5-20'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 55, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 61, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 62, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 70, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 45 + Random(15), slTintColors, '', 0, '50-100');
// 45 = FemaleHeadWarPaint_01
// 46 = FemaleHeadWarPaint_02
// 47 = FemaleHeadWarPaint_03
// 48 = FemaleHeadWarPaint_04
// 49 = FemaleHeadWarPaint_05
// 50 = FemaleHeadWarPaint_06
// 51 = FemaleHeadWarPaint_07
// 52 = FemaleHeadWarPaint_08
// 53 = FemaleHeadWarPaint_09
// 54 = FemaleHeadWarPaint_10
// 56 = FemaleHeadRedguardWarPaint_01
// 57 = FemaleHeadRedguardWarPaint_02
// 58 = FemaleHeadRedguardWarPaint_03
// 59 = FemaleHeadRedguardWarPaint_04
// 60 = FemaleHeadRedguardWarPaint_05
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinDark', 10, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 13, slTintColors, '', 90, '5-20'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 14, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 15, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 16, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //MaleHeadRedguard_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 18, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 19, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 20, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 21, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 63, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 64, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 71, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r = 0 then
CreateTintLayer(layer, 22, slTintColors, '', 0, '50-100') //MaleHeadWarPaint_02
else if r < 10 then
CreateTintLayer(layer, 23 + r, slTintColors, '', 0, '50-100')
// 24 = MaleHeadWarPaint_01
// 25 = MaleHeadWarPaint_03
// 26 = MaleHeadWarPaint_04
// 27 = MaleHeadWarPaint_05
// 28 = MaleHeadWarPaint_06
// 29 = MaleHeadWarPaint_07
// 31 = MaleHeadWarPaint_08
// 30 = MaleHeadWarPaint_09
// 32 = MaleHeadWarPaint_10
else
CreateTintLayer(layer, 65 + r - 10, slTintColors, '', 0, '50-100');
// 65 = MaleHeadRedguardWarPaint_01
// 66 = MaleHeadRedguardWarPaint_02
// 67 = MaleHeadRedguardWarPaint_03
// 68 = MaleHeadRedguardWarPaint_04
// 69 = MaleHeadRedguardWarPaint_05
end;
end;
end
else if race = 'ImperialRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 13, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadImperial_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 36, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 47, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 59, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 60, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 37 + r, slTintColors, '', 0, '50-100')
// 37 = FemaleHeadWarPaint_01
// 38 = FemaleHeadWarPaint_02
// 39 = FemaleHeadWarPaint_03
// 40 = FemaleHeadWarPaint_04
// 41 = FemaleHeadWarPaint_05
// 42 = FemaleHeadWarPaint_06
// 43 = FemaleHeadWarPaint_07
// 44 = FemaleHeadWarPaint_08
// 45 = FemaleHeadWarPaint_09
// 46 = FemaleHeadWarPaint_10
else
CreateTintLayer(layer, 38 + r, slTintColors, '', 0, '50-100');
// 48 = FemaleHeadImperialWarPaint_01
// 49 = FemaleHeadImperialWarPaint_02
// 50 = FemaleHeadImperialWarPaint_03
// 51 = FemaleHeadImperialWarPaint_04
// 52 = FemaleHeadImperialWarPaint_05
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 24, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
if Random(100) < tatoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 14 + r, slTintColors, '', 0, '50-100')
// 14 = MaleHeadWarPaint_01
// 15 = MaleHeadWarPaint_02
// 16 = MaleHeadWarPaint_03
// 17 = MaleHeadWarPaint_04
// 18 = MaleHeadWarPaint_05
// 19 = MaleHeadWarPaint_06
// 20 = MaleHeadWarPaint_07
// 21 = MaleHeadWarPaint_08
// 22 = MaleHeadWarPaint_09
// 23 = MaleHeadWarPaint_10
else if r = 10 then
CreateTintLayer(layer, 25, slTintColors, '', 0, '50-100') //MaleHeadImperialWarPaint_01
else
CreateTintLayer(layer, 53 + r - 11, slTintColors, '', 0, '50-100');
// 53 = MaleHeadImperialWarPaint_02
// 54 = MaleHeadImperialWarPaint_03
// 55 = MaleHeadImperialWarPaint_04
// 56 = MaleHeadImperialWarPaint_05
end;
end;
end
else if race = 'NordRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 24, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 30, '20-80'); //FemaleHeadHighElf_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 36, slTintColors, '', 70, '5-20'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 54, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 65, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 66, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 70, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 73, slTintColors, '', 100, '1-10'); //FemaleHeadBlackBloodTattoo_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 74, slTintColors, '', 100, '1-10'); //FemaleHeadBlackBloodTattoo_02
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(15);
if r < 10 then
CreateTintLayer(layer, 44 + r, slTintColors, '', 0, '50-100')
// 44 = FemaleHeadWarPaint_01
// 45 = FemaleHeadWarPaint_02
// 46 = FemaleHeadWarPaint_03
// 47 = FemaleHeadWarPaint_04
// 48 = FemaleHeadWarPaint_05
// 49 = FemaleHeadWarPaint_06
// 50 = FemaleHeadWarPaint_07
// 51 = FemaleHeadWarPaint_08
// 52 = FemaleHeadWarPaint_09
// 53 = FemaleHeadWarPaint_10
else
CreateTintLayer(layer, 45 + r, slTintColors, '', 0, '50-100');
// 55 = FemaleHeadNordWarPaint_01
// 56 = FemaleHeadNordWarPaint_02
// 57 = FemaleHeadNordWarPaint_03
// 58 = FemaleHeadNordWarPaint_04
// 59 = FemaleHeadNordWarPaint_05
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 100, '5-20'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //MaleHead_Frekles_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 19, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 67, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 68, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 69, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 71, slTintColors, '', 100, '1-10'); //MaleHeadBlackBloodTattoo_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 72, slTintColors, '', 100, '1-10'); //MaleHeadBlackBloodTattoo_02
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(14);
if r = 0 then
CreateTintLayer(layer, 21, slTintColors, '', 0, '40-100') //MaleHeadWarPaint_02
else if r < 8 then
CreateTintLayer(layer, 36 + r, slTintColors, '', 0, '40-100')
// 37 = MaleHeadWarPaint_03
// 38 = MaleHeadWarPaint_04
// 39 = MaleHeadWarPaint_05
// 40 = MaleHeadWarPaint_06
// 41 = MaleHeadWarPaint_07
// 42 = MaleHeadWarPaint_08
// 43 = MaleHeadWarPaint_10
else if r = 8 then
CreateTintLayer(layer, 23, slTintColors, '', 0, '40-100') //MaleHeadWarPaint_09
else
CreateTintLayer(layer, 60 + r - 9, slTintColors, '', 0, '40-100');
// 60 = MaleHeadNordWarPaint_01
// 61 = MaleHeadNordWarPaint_02
// 62 = MaleHeadNordWarPaint_03
// 63 = MaleHeadNordWarPaint_04
// 64 = MaleHeadNordWarPaint_05
end;
end;
end
else if race = 'KhajiitRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 4, slTintColors, '', 40, '5-20'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketUpper
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 80, '5-30'); //KhajiitEyeliner
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 14, slTintColors, '', 80, '5-30'); //KhajiitCheekColorLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 15, slTintColors, '', 80, '5-30'); //KhajiitForehead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 16, slTintColors, '', 80, '5-30'); //KhajiitChin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 17, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 18, slTintColors, '', 80, '5-30'); //KhajiitCheekColor
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 19, slTintColors, '', 80, '5-30'); //KhajiitLipColor
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 20, slTintColors, '', 80, '5-30'); //KhajiitLaughline
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 31, slTintColors, '', 80, '5-30'); //KhajiitNeck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 40, slTintColors, '', 80, '5-20'); //KhajiitNose01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 41, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 32 + Random(8), slTintColors, '', 0, '30-100');
// 32 = KhajiitStripes01
// 33 = KhajiitStripes02
// 34 = KhajiitStripes03
// 35 = KhajiitStripes04
// 36 = KhajiitPaint01
// 37 = KhajiitPaint02
// 38 = KhajiitPaint03
// 39 = KhajiitPaint04
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 1, slTintColors, '', 40, '5-20'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 2, slTintColors, '', 80, '5-30'); //KhajiitCheekColorLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketUpper
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 80, '5-30'); //KhajiitCheekColor
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 80, '5-30'); //KhajiitForehead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 80, '5-30'); //KhajiitChin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 80, '5-30'); //KhajiitEyeliner
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 80, '5-30'); //KhajiitLipColor
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 80, '5-30'); //KhajiitLaughline
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 13, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketLower
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 21, slTintColors, '', 80, '5-30'); //KhajiitNeck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 22, slTintColors, '', 80, '5-30'); //KhajiitNose01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 42, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23 + Random(8), slTintColors, '', 0, '30-100');
// 23 = KhajiitStripes01
// 24 = KhajiitStripes02
// 25 = KhajiitStripes03
// 26 = KhajiitStripes04
// 27 = KhajiitPaint01
// 28 = KhajiitPaint02
// 29 = KhajiitPaint03
// 30 = KhajiitPaint04
end;
end;
end
else if race = 'BretonRace' then begin
if female then begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 16, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 18, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 19, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 20, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 21, slTintColors, '', 70, '10-40'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 22, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 23, slTintColors, '', 30, '20-80'); //FemaleHeadBreton_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 24, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 39, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 56, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 74, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(19);
if r < 15 then
CreateTintLayer(layer, 40 + r, slTintColors, '', 0, '50-100')
// 40 = FemaleHeadWarPaint_01
// 41 = FemaleHeadWarPaint_02
// 42 = FemaleHeadWarPaint_03
// 43 = FemaleHeadWarPaint_04
// 44 = FemaleHeadWarPaint_05
// 45 = FemaleHeadWarPaint_06
// 46 = FemaleHeadWarPaint_07
// 47 = FemaleHeadWarPaint_08
// 48 = FemaleHeadWarPaint_09
// 49 = FemaleHeadWarPaint_10
// 51 = FemaleHeadImperialWarPaint_01
// 52 = FemaleHeadImperialWarPaint_02
// 53 = FemaleHeadImperialWarPaint_05
// 54 = FemaleHeadBretonWarPaint_01
// 55 = FemaleHeadBretonWarPaint_02
else
CreateTintLayer(layer, 69 + r - 15, slTintColors, '', 0, '50-100');
// 69 FemaleHeadForswornTattoo_01
// 70 = FemaleHeadForswornTattoo_02
// 71 = FemaleHeadForswornTattoo_03
// 72 = FemaleHeadForswornTattoo_04
end;
end
else begin
group := ElementByPath(npc, 'Tint Layers');
layer := ElementByIndex(group, 0);
CreateTintLayer(layer, 2, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 4, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 5, slTintColors, '', 100, '5-20'); //RedGuardMaleEyeLinerStyle_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHead_Nose
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 13, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 39, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 59, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 28, slTintColors, '', 90, '10-40'); //MaleHead_Frekles_01
layer := ElementAssign(group, HighInteger, nil, False);
CreateTintLayer(layer, 73, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01
if Random(100) < tattoochance then begin
layer := ElementAssign(group, HighInteger, nil, False);
r := Random(19);
if r < 10 then
CreateTintLayer(layer, 29 + r, slTintColors, '', 0, '50-100')
// 29 = MaleHeadWarPaint_01
// 30 = MaleHeadWarPaint_02
// 31 = MaleHeadWarPaint_03
// 32 = MaleHeadWarPaint_04
// 33 = MaleHeadWarPaint_05
// 34 = MaleHeadWarPaint_06
// 35 = MaleHeadWarPaint_07
// 36 = MaleHeadWarPaint_08
// 37 = MaleHeadWarPaint_09
// 38 = MaleHeadWarPaint_10
else
CreateTintLayer(layer, 60 + r - 10, slTintColors, '', 0, '50-100');
// 60 = MaleHeadBretonWarPaint_01
// 61 = MaleHeadBretonWarPaint_02
// 62 = MaleHeadBretonWarPaint_03
// 63 = MaleHeadBretonWarPaint_04
// 64 = MaleHeadBretonWarPaint_05
// 65 = MaleHeadForswornTattoo_01
// 66 = MaleHeadForswornTattoo_02
// 67 = MaleHeadForswornTattoo_03
// 68 = MaleHeadForswornTattoo_04
end;
end;
end;
end;
AddMessage('');
end;
// free lists
slFemaleHairs.Free;
slFemaleBrows.Free;
slFemaleEyes.Free;
slFemaleScars.Free;
slFemaleFaces.Free;
slMaleHairs;
slMaleFacialHairs.Free;
slMaleBrows.Free;
slMaleEyes.Free;
slMaleScars.Free;
slMaleFaces.Free;
slHairColors;
slMasters.Free;
slDarkElfColors.Free;
slHighElfColors.Free;
slWoodElfColors.Free;
slHumanColors.Free;
slOrcColors.Free;
slRedguardColors.Free;
slTintColors.Free;
slNPCs.Free;
end;
end. |
unit ServerMethodsUnit1;
interface
uses System.SysUtils, System.Classes, System.Json,
DataSnap.DSProviderDataModuleAdapter,
DataSnap.DSServer, DataSnap.DSAuth;
type
TServerMethods1 = class(TDSServerModule)
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function RelatorioEmpregados(out size: int64): TStream;
end;
implementation
{$R *.dfm}
uses System.StrUtils, ufrmReport;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.RelatorioEmpregados(out size: int64): TStream;
var
ArquivoPDF: string;
begin
frmReport.RLReport1.Prepare;
ArquivoPDF := ExtractFilePath(ParamStr(0)) + 'relatorio.pdf';
frmReport.RLPDFFilter1.ShowProgress := false;
frmReport.RLPDFFilter1.FileName := ArquivoPDF;
frmReport.RLPDFFilter1.FilterPages(frmReport.RLReport1.Pages);
Result := TFileStream.Create(ArquivoPDF, fmOpenRead or fmShareDenyNone);
size := Result.size;
Result.Position := 0;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
{$include kode.inc}
unit syn_s2_voicemanager;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_object,
kode_voicemanager,
syn_s2_const,
syn_s2_master;
type
s2_voicemanager = class(KVoiceManager)
private
FMaster : s2_master_proc;
FModValues : array[0..s2m_count-1] of single;
//FNumCtrl : LongInt;
//FCtrlValues : array of single;
public
constructor create(APlugin:KObject);
destructor destroy; override;
procedure setModValue(AIndex:LongInt; AValue:Single);
function getModValue(AIndex:LongInt) : Single;
//procedure setNumControls(ANum:LongInt);
public
procedure on_process(outs:PSingle); override;
procedure on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
kode_control,
kode_debug,
kode_memory,
syn_s2,
syn_s2_voice;
//--------------------------------------------------
constructor s2_voicemanager.create(APlugin:KObject);
var
i : longint;
v : s2_voice;
begin
inherited;
for i := 0 to S2_MAX_VOICES-1 do
begin
v := s2_voice.create(self);
//v.getOsc(0).wave.type_ := s2w_off;
//v.getOsc(1).wave.type_ := s2w_off;
appendVoice( v );
end;
FMaster := s2_master_proc.create(self);
KMemset(@FModValues,0,sizeof(FModValues));
// modulation sources
FModValues[ s2m_const ] := 1; // const
//FNumCtrl := 0;
//SetLength(FCtrlValues,0);
end;
//----------
destructor s2_voicemanager.destroy;
begin
FMaster.destroy;
inherited;
end;
//--------------------------------------------------
procedure s2_voicemanager.setModValue(AIndex:LongInt; AValue:Single);
begin
FModValues[AIndex] := AValue;
end;
//----------
function s2_voicemanager.getModValue(AIndex:LongInt) : Single;
begin
result := FModValues[AIndex];
end;
//----------
//procedure s2_voicemanager.setNumControls(ANum:LongInt);
//begin
// //FNumCtrl:= ANum;
// //SetLength(FCtrlValues,ANum);
//end;
//--------------------------------------------------
procedure s2_voicemanager.on_process(outs:PSingle);
begin
inherited;
FMaster.process(outs);
end;
//----------
procedure s2_voicemanager.on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1);
begin
case AGroup of
s2g_master: FMaster.control(ASubGroup,AIndex,AVal);
end;
inherited; // send to all voices
end;
//----------------------------------------------------------------------
end.
|
Program trapezoidal_rule;
type
vector = array[0..256] of real;
var
//coefficients of polynomial
coefficients: vector;
//degree of polynomial
degree: integer;
//amount of parts
n: integer;
//step of the part
h: real;
//result of calculation
result: real;
//solution boundries
x1, x2: real;
//counter
i: integer;
procedure write_pl;
begin
write(coefficients[degree]:0:2,'*X^',degree);
for i:=degree-1 downto 0 do
write(' + ',coefficients[i]:0:2,'*X^',i);
end;
function pow (number: real; power: integer): real;
var result: real; i:integer;
begin
result := 1;
for i:= 1 to power do
result := result*number;
pow := result;
end;
function f(x: real): real;
var result: real; i:integer;
begin
result := 0;
for i:=0 to degree do begin
result := result + coefficients[i] * pow(x, i);
end;
f := result;
end;
Begin
write('Please enter the degree of polynomial: ');
readln(degree);
write('Please enter the aproximate sollution: ');
write('X^',degree,': ');
readln(coefficients[degree]);
for i:=degree-1 downto 0 do begin
write('X^',i,': ');
readln(coefficients[i]);
end;
writeln;
write('Your polynomial is: ');
write_pl;
write('Please enter the amount of division parts: ');
readln(n);
writeln('Please enter the integral bounds: ');
write('x1: ');
readln(x1);
write('x2: ');
readln(x2);
writeln;
h := (x2 - x1) / n;
result := f(x1)+f(x2);
for i:= 1 to n-1 do
result := result + 2*f(x1+i*h);
result := result*h/2;
write('Result: ',result:0:5);
end. |
{ Function STRING_V (CHAR80)
*
* Return a variable length string given 80 characters. The returned
* string will be the same as the 80 character string with all the
* trailing blanks removed. The returned string will have a max length
* of 80 characters. The input string is assumed to be either 80 characters
* long or up to but not including the first zero byte. This supports
* C quoted strings.
}
module string_v;
define string_v;
%include 'string2.ins.pas';
function string_v ( {convert Pascal STRING to variable string}
in char80: string) {input of STRING data type}
:string_var80_t; {unpadded variable length string}
var
e: sys_int_machine_t; {end of string index}
i: sys_int_machine_t; {running string index}
label
last_char;
begin
string_v.max := sizeof(char80); {set max size of returned string}
for e := sizeof(char80) downto 1 do {scan backwards thru input string}
if char80[e] <> ' ' then goto last_char; {found last char in input string ?}
{
* We scanned the whole string and found no non-blank characters.
* Pass back an empty string.
}
string_v.len := 0; {set length of returned string}
return;
{
* E is the index of the last non_blank character in the
* input string. Now copy the string.
}
last_char:
for i := 1 to e do begin {scan unpadded string}
if ord(char80[i]) = 0 then begin {found terminating zero byte ?}
string_v.len := i-1; {set returned string length}
return;
end;
string_v.str[i] := char80[i]; {copy one character}
end; {back and copy next character}
string_v.len := e; {set returned string length}
end;
|
unit UpgradePrompt;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, NppForms, Vcl.StdCtrls, Vcl.ExtCtrls, StringSupport,
Vcl.ComCtrls, Vcl.CheckLst, Vcl.Imaging.pngimage, nppplugin, shellapi;
type
TUpgradePromptForm = class(TNppForm)
Panel1: TPanel;
btnOk: TButton;
Panel2: TPanel;
Panel3: TPanel;
Label1: TLabel;
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure btnOkClick(Sender: TObject);
private
{ Private declarations }
FLink : String;
public
{ Public declarations }
end;
var
UpgradePromptForm: TUpgradePromptForm;
procedure ShowUpgradePrompt(owner : TNppPlugin; link, notes : String);
implementation
{$R *.dfm}
uses
FHIRPluginSettings, FHIRClient, FHIRResources, SmartOnFhirUtilities, SettingsForm;
procedure ShowUpgradePrompt(owner : TNppPlugin; link, notes : String);
begin
UpgradePromptForm := TUpgradePromptForm.create(owner);
try
UpgradePromptForm.Memo1.text := notes;
UpgradePromptForm.FLink := link;
UpgradePromptForm.ShowModal;
finally
FreeAndNil(UpgradePromptForm);
end;
end;
procedure TUpgradePromptForm.btnOkClick(Sender: TObject);
begin
Settings.BuildPrompt := FLink;
end;
procedure TUpgradePromptForm.Button1Click(Sender: TObject);
begin
ShellExecute(0, 'OPEN', PChar(FLink), '', '', SW_SHOWNORMAL);
end;
end.
|
unit ChatView;
interface
uses
Windows, Forms, Classes, Controls, Messages, Graphics, SysUtils, mwCustomEdit;
const
cvNone = -1;
cvBlack = 0;
cvMaroon = 1;
cvGreen = 2;
cvOlive = 3;
cvNavy = 4;
cvPurple = 5;
cvTeal = 6;
cvGray = 7;
cvSilver = 8;
cvRed = 9;
cvLime = 10;
cvYellow = 11;
cvBlue = 12;
cvFuchsia = 13;
cvAqua = 14;
cvWhite = 15;
cvHighColor = 8;
cvLowColor = 7;
cvBlink = 128;
cvNormalFg: Byte = cvGray;
cvNormalBg: Byte = cvBlack;
SymbolSet: set of Char = [' ','-'(*,'.',',','!','-',')','}',']',':',';','>'*)];
MaxLineLen: Integer = 1000;
type
TColorTable = array[0..15] of TColor;
TFollowMode = (cfOff, cfOn, cfAuto);
TmwChatView = class(TmwCustomEdit)
private
fFollowMode: TFollowMode;
fColorTable: TColorTable;
fMaxLines: Integer;
public
WordWrap: Integer;
AnsiColors: Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoColor(Fg, Bk: Byte);
procedure DoBlink(BlinkOn: Boolean);
procedure SetColor(Nr: Byte; Color: TColor);
procedure AddLine(S: string);
procedure UserActivity;
procedure ScrollPageUp;
procedure ScrollPageDown;
property ColorTable: TColorTable read fColorTable write fColorTable;
published
property FollowMode: TFollowMode read fFollowMode write fFollowMode;
end;
TChatViewHL = class(TmwHighLighter)
public
constructor Create(AOwner: TComponent); override;
function GetEOL: Boolean; override;
function GetRange: Pointer; override;
procedure SetLine(NewValue: String; LineNumber: Integer); override;
function GetToken: string; override;
function GetTokenAttribute: TmwHighLightAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
procedure SetRange(Value: Pointer); override;
procedure ReSetRange; override;
property CommentAttri: TmwHighLightAttributes read fCommentAttri write fCommentAttri;
end;
function DoColor(Fg, Bk: Byte): string;
implementation
function DoColor(Fg, Bk: Byte): string;
begin
Result:=#27'[0;';
if Fg and cvHighColor>0 then Result:=Result+'1;';
if Bk and cvBlink>0 then Result:=Result+'5;';
Result:=Result+IntToStr((Fg and cvLowColor)+30)+';'+IntToStr((Bk and cvLowColor)+40)+'m';
end;
constructor TmwChatView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ReadOnly:=True;
WordWrap:=1;
AnsiColors:=True;
fMaxLines:=500;
Font.Name:='Courier New';
Font.Size:=10;
Font.Color:=fColorTable[cvNormalFg];
Color:=fColorTable[cvNormalBg];
RightEdge:=0;
Gutter.Width:=0;
end;
destructor TmwChatView.Destroy;
begin
inherited Destroy;
end;
procedure TmwChatView.DoColor(Fg, Bk: Byte);
begin
end;
procedure TmwChatView.DoBlink(BlinkOn: Boolean);
begin
end;
procedure TmwChatView.SetColor(Nr: Byte; Color: TColor);
begin
fColorTable[Nr]:=Color;
end;
procedure TmwChatView.AddLine(S: string);
begin
Lines.Add(S);
end;
procedure TmwChatView.UserActivity;
begin
end;
procedure TmwChatView.ScrollPageUp;
begin
end;
procedure TmwChatView.ScrollPageDown;
begin
end;
(*procedure TmwChatView.Clear;
begin
end;*)
end.
|
unit Operation;
interface
uses
Classes, Types, SysUtils, DataType;
type
TOperation = class(TObject)
private
FLeftRawType: TRawType;
FLeftSize: Integer;
FResultType: TDataType;
FRightRawType: TRawType;
FRightSize: Integer;
FOpName: string;
FAssembly: string;
public
constructor Create(AOpName: string; ALeftType, ARightType: TRawType; ALeftSize, ARightSize: Integer;
AResultType: TDataType; AAssembly: string);
function GetAssembly(AOperands: array of string): string;
property LeftRawType: TRawType read FLeftRawType;
property RightRawType: TRawType read FRightRawType;
property LeftSize: Integer read FLeftSize;
property RightSize: Integer read FRightSize;
property OpName: string read FOpName;
property ResultType: TDataType read FResultType;
end;
implementation
{ TOperation }
constructor TOperation.Create(AOpName: string; ALeftType, ARightType: TRawType;
ALeftSize, ARightSize: Integer; AResultType: TDataType; AAssembly: string);
begin
FOpName := AOpName;
FLeftRawType := ALeftType;
FRightRawType := ARightType;
FLeftSize := ALeftSize;
FRightSize := ARightSize;
FResultType := AResultType;
FAssembly := AAssembly;
end;
function TOperation.GetAssembly(AOperands: array of string): string;
var
i: Integer;
begin
Result := FAssembly;
for i := 0 to High(AOperands) do
begin
Result := StringReplace(Result, '$' + IntToStr(i), AOperands[i], [rfReplaceAll, rfIgnoreCase]);
end;
end;
end.
|
unit KDictionaryFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, BaseGUI, UniButtonsFrame, CoreDescription;
type
TfrmDictionary = class;
TAllWordsGUIAdapter = class (TCollectionGUIAdapter)
private
function GetFrameOwner: TfrmDictionary;
function GetActiveWord: TDictionaryWord;
public
property FrameOwner: TfrmDictionary read GetFrameOwner;
property ActiveWord: TDictionaryWord read GetActiveWord;
procedure Reload; override;
function Add: integer; override;
function Delete: integer; override;
function StartFind: integer; override;
constructor Create(AOwner: TComponent); override;
end;
TfrmDictionary = class(TFrame, IGUIAdapter)
lstAllWords: TListBox;
frmButtons: TfrmButtons;
procedure lstAllWordsDblClick(Sender: TObject);
procedure lstAllWordsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstAllWordsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure lstAllWordsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstAllWordsMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
FFilter: string;
FActiveWord: TDictionaryWord;
FActiveWords: TDictionaryWords;
FClosing: boolean;
FEscaping: boolean;
FAllWordGUIAdapter: TAllWordsGUIAdapter;
FActiveDict: TDictionary;
FEntering: boolean;
function GetActiveWord: TDictionaryWord;
procedure SetActiveDict(const Value: TDictionary);
public
property ActiveWord: TDictionaryWord read GetActiveWord;
property ActiveWords: TDictionaryWords read FActiveWords write FActiveWords;
property Filter: string read FFilter write FFilter;
property Closing: boolean read FClosing write FClosing;
property Escaping: boolean read FEscaping write FEscaping;
property Entering: boolean read FEntering write FEntering;
property GUIAdapter: TAllWordsGUIAdapter read FAllWordGUIAdapter implements IGUIAdapter;
function GetActiveWords: TDictionaryWords;
procedure MakeListWords;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses Facade;
{$R *.dfm}
{ TfrmDictionary }
constructor TfrmDictionary.Create(AOwner: TComponent);
begin
inherited;
FActiveWords := TDictionaryWords.Create;
FAllWordGUIAdapter := TAllWordsGUIAdapter.Create(Self);
FAllWordGUIAdapter.List := lstAllWords;
frmButtons.GUIAdapter := FAllWordGUIAdapter;
FFilter := '';
FClosing := false;
FEscaping := false;
FEntering := false;
end;
destructor TfrmDictionary.Destroy;
begin
inherited;
end;
function TfrmDictionary.GetActiveWord: TDictionaryWord;
begin
Result := nil;
if (lstAllWords.ItemIndex > -1) and (lstAllWords.Count > 0) then
Result := lstAllWords.Items.Objects[lstAllWords.ItemIndex] as TDictionaryWord;
end;
function TfrmDictionary.GetActiveWords: TDictionaryWords;
var i: integer;
temp: string;
o: TDictionaryWord;
begin
FActiveWords.Clear;
for i := 0 to (TMainFacade.GetInstance as TMainFacade).AllWords.Count - 1 do
begin
temp := (TMainFacade.GetInstance as TMainFacade).AllWords.Items[i].Name;
delete (temp, Length (FFilter) + 1, Length(temp) - Length (FFilter));
if (AnsiUpperCase(temp) = AnsiUpperCase(FFilter)) or ((FFilter = #9) or (FFilter = #10) or (FFilter = #13)) then
begin
o := (TMainFacade.GetInstance as TMainFacade).AllWords.Items[i];
FActiveWords.Add(o, false, false);
end;
end;
Result := FActiveWords;
end;
procedure TfrmDictionary.lstAllWordsDblClick(Sender: TObject);
begin
(Parent as TForm).Close;
end;
procedure TfrmDictionary.MakeListWords;
begin
GetActiveWords;
ActiveWords.MakeList(lstAllWords.Items);
if lstAllWords.Count > 0 then lstAllWords.ItemIndex := 0;
end;
procedure TfrmDictionary.lstAllWordsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = 13) or (Key = 27) then
(Parent as TForm).Close;
if Key = 27 then FEscaping := true;
if Key = 13 then FEntering := true
else FEntering := false;
end;
procedure TfrmDictionary.SetActiveDict(const Value: TDictionary);
begin
GUIAdapter.BeforeReload;
if FActiveDict <> Value then
begin
FActiveDict := Value;
GUIAdapter.Reload;
end;
if not Assigned(FActiveDict) then GUIAdapter.Clear;
end;
{ TAllWordsGUIAdapter }
function TAllWordsGUIAdapter.Add: integer;
var o: TDictionaryWord;
begin
Result := 0;
try
o := (TMainFacade.GetInstance as TMainFacade).AllWords.Add as TDictionaryWord;
except
Result := -1;
end;
if Result >= 0 then inherited Add;
end;
constructor TAllWordsGUIAdapter.Create(AOwner: TComponent);
begin
inherited;
Buttons := [abReload, abAdd, abDelete, abSort];
end;
function TAllWordsGUIAdapter.Delete: integer;
var os: TDictionaryWords;
i: integer;
begin
Result := 0;
os := FrameOwner.ActiveWords;
for i := os.Count - 1 downto 0 do
(TMainFacade.GetInstance as TMainFacade).AllWords.Remove(os.Items[i]);
inherited Delete;
end;
function TAllWordsGUIAdapter.GetActiveWord: TDictionaryWord;
begin
Result := FrameOwner.FActiveWord;
end;
function TAllWordsGUIAdapter.GetFrameOwner: TfrmDictionary;
begin
Result := Owner as TfrmDictionary;
end;
procedure TAllWordsGUIAdapter.Reload;
begin
if StraightOrder then (TMainFacade.GetInstance as TMainFacade).AllWords.Sort(SortOrders.Items[OrderBY].Compare)
else (TMainFacade.GetInstance as TMainFacade).AllWords.Sort(SortOrders.Items[OrderBY].ReverseCompare);
(TMainFacade.GetInstance as TMainFacade).AllWords.MakeList(FrameOwner.lstAllWords.Items, true, true);
inherited;
end;
function TAllWordsGUIAdapter.StartFind: integer;
begin
Result := 0;
end;
procedure TfrmDictionary.lstAllWordsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox).Canvas do
begin
try
Font.Name := (((lstAllWords.Items.Objects[Index] as TDictionaryWord).Owner as TRoot).Owner as TDictionary).Font.Name;
Font.Color := (((lstAllWords.Items.Objects[Index] as TDictionaryWord).Owner as TRoot).Owner as TDictionary).Font.Color;
Font.Style := (((lstAllWords.Items.Objects[Index] as TDictionaryWord).Owner as TRoot).Owner as TDictionary).Font.Style;
Brush.Color := clWhite;
except
end;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;
end;
procedure TfrmDictionary.lstAllWordsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 13 then FEntering := true
end;
procedure TfrmDictionary.lstAllWordsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then FEntering := true
else FEntering := false;
end;
end.
|
unit SessaoUsuario;
interface
uses Classes, DSHTTP, Biblioteca, UsuarioVO, Windows, IniFiles, SysUtils,
Generics.Collections, FuncaoVO, EmpresaVO, DataSnap.DSHTTPClient, FMX.Dialogs;
type
TSessaoUsuario = class
private
FHttp: TDSHTTP;
FUrl: String;
FIdSessao: String;
FUsuario: TUsuarioVO;
FEmpresa: TEmpresaVO;
ListaPermissoes: TObjectList<TFuncaoVO>;
FCamadas: Integer;
class var FInstance: TSessaoUsuario;
public
constructor Create;
destructor Destroy; override;
class function Instance: TSessaoUsuario;
function AutenticaUsuario(pLogin, pSenha: String): Boolean;
//Permissões
procedure AtualizaPermissoes;
function TemAcesso(pFormulario, pNome: String): Boolean;
function Autenticado: Boolean;
property HTTP: TDSHTTP read FHttp;
property URL: String read FUrl;
property IdSessao: String read FIdSessao;
property Usuario: TUsuarioVO read FUsuario;
property Empresa: TEmpresaVO read FEmpresa write FEmpresa;
property Camadas: Integer read FCamadas write FCamadas;
end;
implementation
uses UsuarioController, FuncaoController, EmpresaController, Controller;
{ TSessaoUsuario }
constructor TSessaoUsuario.Create;
var
Ini: TIniFile;
Servidor: String;
Porta: Integer;
begin
inherited Create;
FHttp := TDSHTTP.Create;
Ini := TIniFile.Create(CaminhoApp + 'Conexao.ini');
try
with Ini do
begin
if not SectionExists('ServidorApp') then
begin
WriteString('ServidorApp','Servidor','localhost');
WriteInteger('ServidorApp','Porta',8080);
end;
Servidor := ReadString('ServidorApp','Servidor','localhost');
Porta := ReadInteger('ServidorApp','Porta',8080);
Camadas := ReadInteger('ServidorApp','Camadas',3);
end;
finally
Ini.Free;
end;
FUrl := 'http://'+Servidor+':'+IntToStr(Porta)+'/datasnap/restT2Ti/TController/ObjetoJson/';
ListaPermissoes := TObjectList<TFuncaoVO>.Create;
end;
destructor TSessaoUsuario.Destroy;
begin
FHttp.Free;
FreeAndNil(FUsuario);
FreeAndNil(FEmpresa);
FreeAndNil(ListaPermissoes);
inherited;
end;
class function TSessaoUsuario.Instance: TSessaoUsuario;
begin
if not Assigned(FInstance) then
FInstance := TSessaoUsuario.Create;
Result := FInstance;
end;
procedure TSessaoUsuario.AtualizaPermissoes;
begin
ListaPermissoes.Free;
//se o usuário tem acesso completo, não precisa carregar as funções
if Usuario.PapelVO.AcessoCompleto <> 'S' then
ListaPermissoes := TFuncaoController.FuncoesUsuario
else
ListaPermissoes := TObjectList<TFuncaoVO>.Create;
end;
function TSessaoUsuario.Autenticado: Boolean;
begin
Result := Assigned(FUsuario);
end;
function TSessaoUsuario.TemAcesso(pFormulario, pNome: String): Boolean;
var
Enumerator: TEnumerator<TFuncaoVO>;
begin
Result := False;
//se o usuário tiver acesso completo já retorna True
if Usuario.PapelVO.AcessoCompleto = 'S' then
begin
Result := True
end
else
begin
Enumerator := ListaPermissoes.GetEnumerator;
try
//with ListaPermissoes.GetEnumerator do
with Enumerator do
begin
while MoveNext do
begin
if (Current.Formulario = pFormulario) and (Current.Nome = pNome) then
begin
Result := (Current.Habilitado = 'S');
Break;
end;
end;
end;
finally
Enumerator.Free;
end;
end;
end;
function TSessaoUsuario.AutenticaUsuario(pLogin, pSenha: String): Boolean;
var
SenhaCript: String;
begin
FIdSessao := CriaGuidStr;
FIdSessao := MD5String(FIdSessao);
try
//Senha é criptografada com a senha digitada + login
SenhaCript := TUsuarioController.CriptografarLoginSenha(pLogin,pSenha);
FHttp.SetBasicAuthentication(pLogin+'|'+FIdSessao, SenhaCript);
TController.ExecutarMetodo('UsuarioController.TUsuarioController', 'Usuario', [pLogin, pSenha], 'GET', 'Objeto');
FUsuario := TUsuarioVO(TController.ObjetoConsultado);
if Assigned(FUsuario) then
FUsuario.Senha := pSenha;
Result := Assigned(FUsuario);
except
ShowMessage('Erro ao autenticar usuário.');
raise;
end;
if Result then
begin
AtualizaPermissoes;
end;
end;
end.
|
program VectorProcessing;
const
N_MAX = 20;
type
Vector = array [1..N_MAX] of Integer;
procedure InputVector(var V: Vector; var N: Integer);
var
I: Integer;
begin
repeat
Write('N = ');
ReadLn(N);
until (N >= 1) and (N <= N_MAX);
for I := 1 to N do
Read(V[I]);
ReadLn;
end;
procedure RandomVector(var V: Vector; var N: Integer);
var
I: Integer;
begin
repeat
Write('N = ');
ReadLn(N);
until (N >= 1) and (N <= N_MAX);
for I := 1 to N do
V[I] := Random(100); // 0 .. 100
end;
procedure WriteVector(const V: Vector; const N: Integer);
var
I: Integer;
begin
if N = 0 then
begin
WriteLn('Vector is empty');
Exit;
end;
for I := 1 to N - 1 do
Write(V[I], ', ');
WriteLn(V[N]);
end;
procedure DeleteMaxNumber(var V: Vector; var N: Integer);
var
I, MaxI: Integer;
begin
if N = 0 then
Exit;
MaxI := 1;
for I := 2 to N do
if V[I] > V[MaxI] then
MaxI := I;
for I := MaxI to N - 1 do
V[I] := V[I + 1];
N := N - 1;
end;
function IndexOfMinNumber(const V: Vector; const N: Integer; const Left: Integer; const Right: Integer): Integer;
var
I, MinI: Integer;
begin
MinI := 0;
for I := Left to Right do
begin
if (MinI < 1) or (V[I] < V[MinI]) then
MinI := I;
end;
Exit(MinI);
end;
procedure SortVector(var V: Vector; var N: Integer);
var
I, MinI, Tmp: Integer;
begin
for I := 1 to N do
begin
MinI := IndexOfMinNumber(V, N, I, N);
Tmp := V[MinI];
V[MinI] := V[I];
V[I] := Tmp;
end
end;
var
S: Integer;
M: Vector;
Length: Integer;
begin
Length := 0;
while True do
begin
WriteLn('1. Input array');
WriteLn('2. Generate random array');
WriteLn('3. Delete maximum');
WriteLn('4. Sort array');
WriteLn('0. Exit');
Write('> ');
ReadLn(S);
case S of
1: InputVector(M, Length);
2: RandomVector(M, Length);
3: DeleteMaxNumber(M, Length);
4: SortVector(M, Length);
0: break;
end;
WriteVector(M, Length);
WriteLn;
end
end. |
unit ULangManager;
interface
uses UxlExtClasses, UxlList, UxlDialog;
type
TLangManager = class (TxlLanguage, IOptionObserver)
private
protected
procedure FillItems (var lang: widestring; itemlist: TxlStrList); override;
public
procedure OptionChanged ();
end;
function LangMan(): TLangManager;
procedure RefreshItemText (DlgParent: TxlDialogSuper; arritems: array of word; captionid: word = 0);
implementation
uses Windows, UOptionManager, UGlobalObj, UxlStrUtils, UxlFunctions, UTypeDef, Resource;
var FLangMan: TLangManager;
function LangMan (): TLangManager;
begin
if not assigned (FLangMan) then
begin
FLangMan := TLangManager.Create;
FLangMan.SetInnerLanguage('Chinese');
OptionMan.AddObserver(FLangMan);
end;
result := FLangMan;
end;
procedure RefreshItemText (DlgParent: TxlDialogSuper; arritems: array of word; captionid: word = 0);
var i: integer;
begin
with DlgParent do
begin
if captionid > 0 then
Text := LangMan.GetItem (captionid, Text);
for i := Low(arritems) to High(arritems) do
ItemText[arritems[i]] := LangMan.GetItem (arritems[i], ItemText[arritems[i]]);
end;
end;
//-------------------
procedure TLangManager.FillItems (var lang: widestring; itemlist: TxlStrList);
procedure f_loadchinese (itemlist: TxlStrList);
begin
with itemlist do
begin
AddByIndex (mc_workspace, '文件(&F)');
AddByIndex (m_newnote, '新建笔记页(&N)');
// AddByIndex (m_newsiblingnote, '新建笔记页(&N)');
AddByIndex (m_newpage, '新建功能页(&T)');
AddByIndex (m_newcalc, '新建计算页(&C)');
AddByIndex (m_newmemo, '新建备忘页(&M)');
AddByIndex (m_newdict, '新建词典页(&D)');
AddByIndex (m_newlink, '新建链接页(&L)');
AddByIndex (m_newcontact, '新建通讯页(&T)');
AddByIndex (m_newgroup, '新建组(&G)');
AddByIndex (m_rename, '重命名(&A)');
AddByIndex (m_switchlock, '加锁切换(&K)');
AddByIndex (m_save, '保存(&S)');
AddByIndex (m_deletepage, '删除(&D)');
AddByIndex (m_closepage, '关闭(&C)');
AddByIndex (m_property, '属性(&P)...');
AddByIndex (m_view, '视图(&V)');
AddByIndex (m_import, '导入(&I)...');
AddByIndex (m_export, '导出(&E)...');
AddByIndex (m_sendmail, '发送邮件(&M)...');
AddByIndex (m_exit, '退出(&X)');
AddByIndex (mc_edit, '编辑(&E)');
AddByIndex (m_clear, '清空(&L)');
AddByIndex (m_undo, '撤销(&U)');
AddByIndex (m_redo, '重做(&R)');
AddByIndex (m_selectall, '全选(&A)');
AddByIndex (m_cut, '剪切(&T)');
AddByIndex (m_copy, '复制(&C)');
AddByIndex (m_paste, '粘贴(&P)');
AddByIndex (m_delete, '删除(&D)');
AddByIndex (m_newitem, '新建项目(&N)');
AddByIndex (m_insertitem, '插入项目(&I)');
AddByIndex (m_edititem, '编辑项目(&E)');
AddByIndex (m_deleteitem, '删除项目(&D)');
AddByIndex (m_removeitem, '移除项目(&R)');
AddByINdex (m_wordwrap, '自动换行(&W)');
AddByIndex (m_texttools, '文字工具(&T)');
AddByIndex (m_highlight1, '高亮 1');
AddByIndex (m_highlight2, '高亮 2');
AddByIndex (m_highlight3, '高亮 3');
AddByIndex (m_highlight4, '高亮 4');
AddByIndex (m_removehighlight, '移除高亮效果');
AddByIndex (m_ul1, '无序列表 1');
AddByIndex (m_ul2, '无序列表 2');
AddByIndex (m_ol, '有序列表');
AddByIndex (m_removelist, '移除列表');
AddByIndex (m_noemptyline, '删除空行');
AddByIndex (m_oneemptyline, '只空一行');
AddByIndex (m_find, '查找/替换(&F)...');
AddByIndex (m_subsequentfind, '后续查找');
AddByIndex (m_findnext, '查找下一个');
AddByIndex (m_findprevious, '查找上一个');
AddByIndex (m_replace, '替换并查找下一个');
AddByIndex (m_replace_p, '替换并查找上一个');
AddByIndex (m_replaceall, '全部替换');
AddByINdex (m_highlightmatch, '高亮查找结果');
AddByINdex (m_insertlink, '插入链接(&L)...');
AddByIndex (m_inserttemplate, '插入模板文字(&M)');
AddByIndex (m_insertcliptext, '插入剪贴文字(&X)');
AddByIndex (mc_navigation, '导航(&N)');
AddByIndex (m_prior, '后退(&P)');
AddByIndex (m_next, '前进(&N)');
AddByIndex (m_levelup, '上一层(&U)');
AddByINdex (m_recentroot, '最近的笔记(&R)');
AddByIndex (m_recentcreate, '最近创建(&C)');
AddByIndex (m_recentmodify, '最近修改(&M)');
AddByIndex (m_recentvisit, '最近访问(&V)');
AddByINdex (m_managerecent, '管理最近的笔记(&M)');
AddByIndex (m_favorite, '收藏夹(&F)');
AddByIndex (m_addfavorite, '添加至收藏夹(&A)');
AddByIndex (m_removefavorite, '从收藏夹移除(&R)');
AddByINdex (m_managefavorite, '收藏夹管理(&M)');
AddByIndex (m_search, '搜索(&S)...');
AddByINdex (m_tag, '分类检索(&T)');
AddByINdex (m_recyclebin, '回收站管理(&R)');
AddByIndex (mc_tools, '工具(&T)');
AddByIndex (m_ShowTree, '显示目录树(&T)');
AddByIndex (m_stayontop, '总在最前(&S)');
AddByIndex (m_transparent, '透明效果(&R)');
AddByIndex (m_specialmode, '自动隐藏(&H)');
AddByIndex (m_template, '文字模板管理(&P)');
AddByIndex (m_fastlink, '快速链接管理(&L)');
AddByIndex (m_watchclipboard, '剪贴板监视(&W)');
AddByIndex (m_clearclipboard, '清空剪贴条目(&C)');
AddByIndex (m_clipboard, '剪贴板管理(&M)');
AddByIndex (m_statistics, '统计信息(&A)...');
AddByIndex (m_definetoolbar, '自定义工具栏(&D)...');
AddByIndex (m_options, '选项(&O)...');
AddByIndex (mc_help, '帮助(&H)');
AddByIndex (m_helptopic, '帮助主题(&H)');
AddByIndex (m_homepage, '主页(&P)');
AddByIndex (m_forum, '论坛(&F)');
AddByIndex (m_donate, '捐助(&D)');
AddByIndex (m_about, '关于(&A)...');
AddByIndex (ob_program, '程序设置');
AddByIndex (ob_edit, '编辑设置');
AddByIndex (ob_notes, '笔记摘录');
AddByIndex (ob_import_export, '导入导出');
AddByIndex (ob_behavior, '操作习惯');
AddByIndex (ob_login, '登录设置');
AddByIndex (ob_backup, '保存与备份');
AddByIndex (ob_specialmode, '自动隐藏');
AddByIndex (ob_appearance, '界面设置');
AddByIndex (ob_treeview, '树窗口');
AddByIndex (ob_tabcontrol, '标签栏');
AddByIndex (ob_listview, '列表窗口');
AddByIndex (ob_editor, '编辑器');
AddByIndex (ob_othercontrols, '其它');
AddByIndex (ob_extfuncs, '扩展功能');
AddByIndex (ob_calcpage, '计算页');
AddByIndex (ob_dictpage, '词典页');
AddByIndex (ob_linkpage, '链接页');
AddByIndex (ob_clipboard, '多重剪贴板');
AddByINdex (ob_template, '文字模板');
AddByIndex (m_openfastlink, '快速链接');
AddByIndex (m_restore, '还原');
AddByIndex (m_minimize, '最小化');
AddByIndex (m_newnoteforeground, '新建笔记');
AddByIndex (m_autorecord, '自动记录');
AddByIndex (sr_filefilter, '所有文件(*.*)|*.*|可执行文件(*.exe)|*.exe|DOC 文件(*.doc)|*.doc|XLS 文件(*.xls)|*.xls|PPT 文件(*.ppt)|*.ppt|PDF 文件(*.pdf)|*.pdf|文本文件(*.txt)|*.txt');
AddByIndex (sr_selectfile, '选择文件');
AddByIndex (sr_selectfolder, '选择文件夹');
AddByINdex (sr_selectbackupfolder, '选择备份文件夹');
AddByIndex (sr_ExeFilter, '可执行文件(*.exe)|*.exe');
AddByINdex (sr_selectsoundfile, '选择声音文件');
AddByIndex (sr_soundfilefilter, '声音文件(*.wav)|*.wav');
AddByIndex (sr_free, '自由');
AddByIndex (sr_left, '左');
AddByINdex (sr_top, '上');
AddByIndex (sr_right, '右');
AddByIndex (sr_bottom, '下');
AddByIndex (sr_NewReminder, '新建备忘条目');
AddByIndex (sr_EditReminder, '编辑备忘条目');
AddByINdex (sr_NewLink, '新建链接');
AddByIndex (sr_EditLink, '编辑链接');
AddByIndex (sr_NewTemplate, '新建文字模板');
AddByIndex (sr_EditTemplate, '编辑文字模板');
AddByINdex (sr_EditContact, '编辑联系人');
AddByINdex (sr_NewContact, '新建联系人');
AddByINdex (sr_MemoAction, '定时提醒');
AddByIndex (sr_MemoAction + 1, '执行任务');
AddByIndex (sr_MemoAction + 2, '无操作');
AddByINdex (sr_Time, '时间');
AddByIndex (sr_Action, '操作');
AddByIndex (sr_Description, '描述');
AddByIndex (sr_UseSound, '提示音');
AddByIndex (sr_SoundFile, '声音文件');
AddByIndex (sr_today, '当天');
AddByIndex (sr_daily, '每天');
AddByIndex (sr_weekly, '每周');
AddByIndex (sr_monthly, '每月');
AddByIndex (sr_yearly, '每年');
AddByIndex (sr_timespan, '日程');
AddByIndex (sr_notime, '无时间');
AddByIndex (sr_LinkTypes, '程序/文件');
AddByIndex (sr_LinkTypes + 1, '文件夹');
AddByIndex (sr_LinkTypes + 2, '网址');
AddByIndex (sr_LinkTypes + 3, '收件地址');
AddByIndex (sr_LinkTypes + 4, '节点');
AddByIndex (sr_LinkTypes + 5, '其他');
AddByIndex (sr_LinkTypes + 6, '批处理');
AddByIndex (sr_LinkType, '类别');
AddByIndex (sr_Link, '链接');
AddByIndex (sr_Hotkey, '热键');
AddByIndex (sr_Abbrev, '缩写');
AddByIndex (sr_boy, '男');
AddByIndex (sr_girl, '女');
AddByIndex (sr_Name, '姓名');
AddByIndex (sr_Sex, '性别');
AddByIndex (sr_Mobile, '手机');
AddByIndex (sr_Email, 'Email');
AddByIndex (sr_IM1, 'QQ');
AddByIndex (sr_IM2, 'MSN');
AddByIndex (sr_Company, '单位');
AddByIndex (sr_Department, '部门/职务');
AddByIndex (sr_Address, '地址');
AddByIndex (sr_Zipcode, '邮编');
AddByIndex (sr_Tel, '电话');
AddByIndex (sr_Fax, '传真');
AddByIndex (sr_Others, '其他');
AddByIndex (sr_NewClipItem, '新建剪贴条目');
AddByIndex (sr_EditClipItem, '编辑剪贴条目');
AddByIndex (IDOK, '确 定');
AddByIndex (IDCancel, '取 消');
AddByIndex (sr_prompt, '注意!');
AddByINdex (sr_info, '提示!');
AddByIndex (sr_optionalitems, '可选项目');
AddByIndex (sr_SelectImportFile, '选择导入文件');
AddByIndex (sr_ImportFilter, '文本文件(*.txt)|*.txt|minipad2 导出文件(*.mep)|*.mep|所有文件(*.*)|*.*');
AddByIndex (sr_NameExportFile, '设定导出文件名');
AddByIndex (sr_ExportFilter1, '文本文件(*.txt)|*.txt|所有文件(*.*)|*.*');
AddByIndex (sr_ExportFilter2, '文本文件(*.txt)|*.txt|minipad2 导出文件(*.mep)|*.mep|所有文件(*.*)|*.*');
AddByIndex (sr_ExportFilter3, 'minipad2 导出文件(*.mep)|*.mep|文本文件(*.txt)|*.txt|所有文件(*.*)|*.*');
AddByIndex (sr_ListCopied, '列表内容已复制到剪贴板!');
AddByIndex (sr_BrowseMailClient, '选择邮件客户端可执行文件');
AddByIndex (sr_TemplateCaptured, '所选文字已被添加到 minipad2 的文字模板列表。');
AddByIndex (sr_TemplateExists, '模板列表中相同内容的条目(第 %0 项)已存在!');
AddByIndex (sr_TableOfContents, '目录');
AddByIndex (sr_codetransfer, '词典字符编码转换中, 请等待...');
AddByIndex (sr_SelectIcon, '选择图标文件');
AddByIndex (sr_IconFilter, '图标文件(*.ico)|*.ico|所有文件(*.*)|*.*');
AddByIndex (sr_RemoveFastLinkItemsPrompt, '是否将所选项目从快速链接列表中移除?');
AddByIndex (sr_DeleteItemsPrompt, '是否删除所选项目?');
AddByIndex (sr_RemoveItemsPrompt, '是否移除所选项目?');
AddByIndex (sr_DeletePagesPrompt, '是否删除所选标签页?');
AddByIndex (sr_deletegroupprompt, '当前组包含子节点。真的要全部删除吗?');
AddByINdex (sr_clearprompt, '真的要清空当前标签页的内容吗?');
AddByINdex (sr_deleteprompt, '真的要删除当前页吗?');
AddByIndex (sr_clearclipboardprompt, '是否清空所有剪贴板条目?');
AddByIndex (sr_UnsupportedOperation, '操作不支持!');
AddByIndex (sr_NewNoteCreated, '已创建新笔记,标题为:');
AddByIndex (sr_SnapTextSuccess, '已抓取如下文字:');
AddByIndex (sr_newnotebgandsnaptextsuccess, '已创建新笔记并抓取如下文字:');
AddByIndex (sr_DataSaved, '数据已保存.');
AddByIndex (sr_SaveSnapText, '保存捕捉文字');
AddByIndex (sr_SnapTextSavedToFile, '以下文字已保存到文件');
AddByIndex (sr_ExportedToFolder, '当前节点(及其子节点)已导出到文件夹:');
AddByIndex (sr_PageExportedToFile, '当前页内容已导出到文件:');
AddByIndex (sr_PageExportedToClipboard, '当前页内容已导出到剪贴板');
AddByIndex (sr_GroupExportedToFile, '当前节点(及其子节点)内容已导出到文件:');
AddByINdex (sr_mepversionnotmatch, 'mep 文件版本不匹配!');
AddByINdex (sr_invalidnodelink, '节点链接无效!');
AddByIndex (sr_importingPrompt, '文件导入中,按住 ESC 可终止...');
AddByIndex (sr_userabortimport, '用户终止导入');
AddByIndex (sr_exportingprompt, '页面导出中,按住 ESC 可终止...');
AddByIndex (sr_userabortexport, '用户终止导出');
AddByIndex (sr_deletingprompt, '项目删除中,按住 ESC 可终止...');
AddByIndex (sr_userabortdelete, '用户终止删除');
AddByIndex (sr_TemplatePage, '文字模板');
AddByIndex (sr_FastLink, '快速链接');
AddByIndex (sr_Clipboard, '剪贴文字');
AddByIndex (sr_RecentRoot, '最近的笔记');
AddByIndex (sr_RecentCreate, '最近创建');
AddByIndex (sr_RecentModify, '最近修改');
AddByIndex (sr_RecentVisit, '最近访问');
AddByINdex (sr_FavoritePage, '收藏夹');
AddByIndex (sr_SearchPage, '搜索');
AddByIndex (sr_TagRoot, '分类');
AddByIndex (sr_GroupRoot, '全部');
AddByIndex (sr_RecycleBin, '回收站');
AddByINdex (sr_Normal, '常规');
AddByIndex (sr_Locked, '加锁');
AddByIndex (sr_Protected, '追加');
AddByIndex (sr_ReadOnly, '只读');
AddByIndex (sr_saves, '次保存');
AddByIndex (sr_minutes, '分钟');
AddByIndex (sr_hours, '小时');
AddByIndex (sr_days, '天');
AddByIndex (rb_icon, '大图标');
AddByIndex (rb_smallicon, '小图标');
AddByIndex (rb_list, '列表');
AddByINdex (rb_report, '详细信息');
AddByIndex (rb_blog, '摘要');
AddByIndex (Property_General, '常规');
AddByINdex (Property_Edit, '保存');
AddByIndex (Property_List, '列表');
AddByIndex (sr_Title, '标题');
AddByIndex (sr_CreateTime, '创建时间');
AddByIndex (sr_ModifyTime, '修改时间');
AddByIndex (sr_VisitTime, '访问时间');
AddByIndex (sr_ExportFile, '文件');
AddByIndex (sr_ExternalSave, '外部存储');
AddByIndex (sr_Abstract, '内容');
AddByIndex (sr_SearchResult, '检索摘要');
AddByIndex (sr_Remark, '备注');
AddByIndex (sr_Text, '内容');
AddByIndex (sr_NodePath, '节点路径');
AddByINdex (sr_GroupPage, '组');
AddByINdex (sr_GroupPage + Ord(ptNote), '笔记页');
AddByIndex (sr_GroupPage + Ord(ptCalc), '计算页');
AddByIndex (sr_GroupPage + Ord(ptMemo), '备忘页');
AddByIndex (sr_GroupPage + Ord(ptDict), '词典页');
AddByIndex (sr_GroupPage + Ord(ptLink), '链接页');
AddByIndex (sr_GroupPage + Ord(ptContact), '通讯页');
AddByIndex (sr_GroupPage + Ord(ptMemoItem), '备忘项');
AddByIndex (sr_GroupPage + Ord(ptLinkItem), '链接项');
AddByIndex (sr_GroupPage + Ord(ptContactItem), '联系人');
AddByIndex (sr_GroupPage + Ord(ptTemplateItem), '文字模板');
AddByIndex (sr_GroupPage + Ord(ptClipItem), '剪贴项目');
AddByIndex (sr_Include, '包含');
AddByINdex (sr_NotInclude, '不包含');
AddByIndex (tp_CurrentPage, '当前页');
AddByIndex (tp_Database, '数据库');
end;
end;
var s_file: widestring;
begin
itemlist.clear;
s_file := LangDir + lang + '.lng';
if IsSameStr (lang, 'Chinese') then
f_loadchinese (itemlist)
else if pathfileexists (s_file) then
begin
itemlist.IndexDeli := '=';
itemlist.loadfromfile (s_file);
end;
end;
procedure TLangManager.OptionChanged ();
begin
SetLanguage (OptionMan.options.Language);
end;
initialization
finalization
FreeAndNil (FLangMan);
end.
|
unit ZmqImpl;
interface
uses
SysUtils, Classes, Windows, ZmqIntf, ZmqApiImpl, ActiveX;
type
EZMQException = class(Exception)
private
fErrorCode: Integer;
public
constructor Create; overload;
constructor Create(aErrorCode: Integer); overload;
property ErrorCode: Integer read fErrorCode;
end;
TZMQFrame = class;
PZMQFreeHint = ^TZMQFreeHint;
TZMQFreeHint = record
frame: TZMQFrame;
fn: TZMQFreeProc;
hint: Pointer;
end;
TZMQInterfacedObject = class(TInterfacedObject)
private
FDestroying: Boolean;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
procedure BeforeDestruction; override;
end;
TZMQFrame = class(TZMQInterfacedObject, IZMQFrame)
private
fMessage: zmq_msg_t;
fFreeHint: TZMQFreeHint;
private
function GetHandle: Pointer;
function GetI: Integer;
function GetF: Single;
function GetD: Double;
function GetC: Currency;
function GetDT: TDateTime;
function GetH: WideString;
function GetS: WideString;
function GetProp(prop: TZMQMessageProperty): Integer;
procedure SetI(const Value: Integer);
procedure SetF(const Value: Single);
procedure SetD(const Value: Double);
procedure SetC(const Value: Currency);
procedure SetDT(const Value: TDateTime);
procedure SetH(const Value: WideString);
procedure SetS(const Value: WideString);
procedure SetProp(prop: TZMQMessageProperty; value: Integer);
procedure CheckResult(rc: Integer);
public
constructor Create; overload;
constructor Create(size: Cardinal); overload;
constructor Create(data: Pointer; size: Cardinal; ffn: TZMQFreeProc; hint: Pointer = nil); overload;
destructor Destroy; override;
function Implementor: Pointer;
procedure Rebuild; overload;
procedure Rebuild(size: Cardinal); overload;
procedure Rebuild(data: Pointer; size: Cardinal; ffn: TZMQFreeProc; hint: Pointer = nil); overload;
procedure Move(const msg: IZMQFrame);
procedure Copy(const msg: IZMQFrame);
function Data: Pointer;
function Size: Cardinal;
function More: Boolean;
function Dup: IZMQFrame;
// convert the data into a readable string.
function Dump: WideString;
// copy the whole content of the stream to the message.
procedure LoadFromStream(const strm: IStream);
procedure SaveToStream(const strm: IStream);
property Handle: Pointer read GetHandle;
property S: WideString read GetS write SetS;
property H: WideString read GetH write SetH;
property I: Integer read GetI write SetI;
property F: Single read GetF write SetF;
property D: Double read GetD write SetD;
property C: Currency read GetC write SetC;
property DT: TDateTime read GetDT write SetDT;
property Prop[prop: TZMQMessageProperty]: Integer read GetProp;
end;
TZMQMsg = class(TZMQInterfacedObject, IZMQMsg)
private
fMsgs: IInterfaceList;
fSize: Cardinal;
fCursor: Integer;
private
function GetItem(indx: Integer): IZMQFrame;
public
constructor Create;
destructor Destroy; override;
function Implementator: Pointer;
// Push frame to the front of the message, i.e. before all other frames.
// Message takes ownership of frame, will destroy it when message is sent.
// Set the cursor to 0
// Returns 0 on success, -1 on error.
function Push(const msg: IZMQFrame): Integer;
function PushStr(const str: WideString): Integer;
function PushInt(const msg: Integer): Integer;
// Remove first frame from message, if any. Returns frame, or NULL. Caller
// now owns frame and must destroy it when finished with it.
// Set the cursor to 0
function Pop: IZMQFrame;
function PopStr: WideString;
function PopInt: Integer;
// Add frame to the end of the message, i.e. after all other frames.
// Message takes ownership of frame, will destroy it when message is sent.
// Set the cursor to 0
// Returns 0 on success
function Add(const msg: IZMQFrame): Integer;
function AddStr(const msg: WideString): Integer;
function AddInt(const msg: Integer): Integer;
// Push frame plus empty frame to front of message, before first frame.
// Message takes ownership of frame, will destroy it when message is sent.
procedure Wrap(const msg: IZMQFrame);
// Pop frame off front of message, caller now owns frame
// If next frame is empty, pops and destroys that empty frame.
function Unwrap: IZMQFrame;
// Set cursor to first frame in message. Returns frame, or NULL.
function First: IZMQFrame;
// Return the next frame. If there are no more frames, returns NULL. To move
// to the first frame call zmsg_first(). Advances the cursor.
function Next: IZMQFrame;
// Return the last frame. If there are no frames, returns NULL.
// Set the cursor to the last
function Last: IZMQFrame;
// Create copy of message, as new message object
function Dup: IZMQMsg;
// dumpt message
function Dump: WideString;
function SaveAsHex: WideString;
procedure LoadFromHex(const data: WideString);
procedure Clear;
// Remove specified frame from list, if present. Does not destroy frame.
// Set the cursor to 0
procedure Remove(const msg: IZMQFrame);
// Return size of message, i.e. number of frames (0 or more).
function Size: Integer;
// Return size of message, i.e. number of frames (0 or more).
function ContentSize: Integer;
property Item[indx: Integer]: IZMQFrame read GetItem; default;
end;
TZMQContext = class;
TZMQSocketImpl = class
protected
fData: TZMQSocketRec;
fSocket: Pointer;
fContext: TZMQContext;
fRaiseEAgain: Boolean;
fAcceptFilter: TStringList;
fMonitorRec: PZMQMonitorRec;
fMonitorThread: THandle;
private
procedure Close;
procedure SetSockOpt(option: Integer; optval: Pointer; optvallen: Cardinal);
procedure GetSockOpt(option: Integer; optval: Pointer; var optvallen: Cardinal);
function Send(var msg: IZMQFrame; flags: Integer = 0): Integer; overload;
function Recv(var msg: IZMQFrame; flags: Integer = 0): Integer; overload;
function CheckResult(rc: Integer): Integer;
function GetSockOptInt64(option: Integer): Int64;
function GetSockOptInteger(option: Integer): Integer;
procedure SetSockOptInt64(option: Integer; const Value: Int64);
procedure SetSockOptInteger(option: Integer; const Value: Integer);
protected
function GetData: PZMQSocket;
function GetSocketType: TZMQSocketType;
function GetRcvMore: Boolean;
function GetRcvTimeout: Integer;
function GetSndTimeout: Integer;
function GetAffinity: UInt64;
function GetIdentity: WideString;
function GetRate: Integer;
function GetRecoveryIVL: Integer;
function GetSndBuf: Integer;
function GetRcvBuf: Integer;
function GetLinger: Integer;
function GetReconnectIVL: Integer;
function GetReconnectIVLMax: Integer;
function GetBacklog: Integer;
function GetFD: Pointer;
function GetEvents: TZMQPollEvents;
function GetHWM: Integer;
function GetSndHWM: Integer;
function GetRcvHWM: Integer;
function GetMaxMsgSize: Int64;
function GetMulticastHops: Integer;
function GetIPv4Only: Boolean;
function GetLastEndpoint: WideString;
function GetKeepAlive: TZMQKeepAlive;
function GetKeepAliveIdle: Integer;
function GetKeepAliveCnt: Integer;
function GetKeepAliveIntvl: Integer;
function GetAcceptFilter(indx: Integer): WideString;
function GetContext: IZMQContext;
function GetSocket: Pointer;
function GetRaiseEAgain: Boolean;
procedure SetHWM(const Value: Integer);
procedure SetRcvTimeout(const Value: Integer);
procedure SetSndTimeout(const Value: Integer);
procedure SetAffinity(const Value: UInt64);
procedure SetIdentity(const Value: WideString);
procedure SetRate(const Value: Integer);
procedure SetRecoveryIvl(const Value: Integer);
procedure SetSndBuf(const Value: Integer);
procedure SetRcvBuf(const Value: Integer);
procedure SetLinger(const Value: Integer);
procedure SetReconnectIvl(const Value: Integer);
procedure SetReconnectIvlMax(const Value: Integer);
procedure SetBacklog(const Value: Integer);
procedure SetSndHWM(const Value: Integer);
procedure SetRcvHWM(const Value: Integer);
procedure SetMaxMsgSize(const Value: Int64);
procedure SetMulticastHops(const Value: Integer);
procedure SetIPv4Only(const Value: Boolean);
procedure SetKeepAlive(const Value: TZMQKeepAlive);
procedure SetKeepAliveIdle(const Value: Integer);
procedure SetKeepAliveCnt(const Value: Integer);
procedure SetKeepAliveIntvl(const Value: Integer);
procedure SetAcceptFilter(indx: Integer; const Value: WideString);
procedure SetRouterMandatory(const Value: Boolean);
procedure SetRaiseEAgain(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
function Implementator: Pointer;
procedure Bind(const addr: WideString);
procedure Unbind(const addr: WideString);
procedure Connect(const addr: WideString);
function ConnectEx(const addr: WideString): Integer;
procedure Disconnect(const addr: WideString);
procedure Free;
procedure Subscribe(const filter: WideString);
procedure UnSubscribe(const filter: WideString);
procedure AddAcceptFilter(const addr: WideString);
function Send(var msg: IZMQFrame; flags: TZMQSendFlags = []): Integer; overload;
function Send(const strm: IStream; size: Integer; flags: TZMQSendFlags = []): Integer; overload;
function Send(const msg: WideString; flags: TZMQSendFlags = []): Integer; overload;
function Send(var msgs: IZMQMsg; dontwait: Boolean = false): Integer; overload;
function Send(const msg: array of WideString; dontwait: Boolean = false): Integer; overload;
function SendBuffer(const Buffer; len: Size_t; flags: TZMQSendFlags = []): Integer;
function Recv(var msg: IZMQFrame; flags: TZMQRecvFlags = []): Integer; overload;
function Recv(const strm: IStream; flags: TZMQRecvFlags = []): Integer; overload;
function Recv(var msg: WideString; flags: TZMQRecvFlags = []): Integer; overload;
function Recv(var msgs: IZMQMsg; flags: TZMQRecvFlags = []): Integer; overload;
function RecvBuffer(var Buffer; len: size_t; flags: TZMQRecvFlags = []): Integer;
procedure RegisterMonitor(proc: TZMQMonitorProc; events: TZMQMonitorEvents = cZMQMonitorEventsAll);
procedure UnregisterMonitor;
property Data: PZMQSocket read GetData;
property SocketType: TZMQSocketType read GetSocketType;
property RcvMore: Boolean read GetRcvMore;
property SndHWM: Integer read GetSndHWM write SetSndHwm;
property RcvHWM: Integer read GetRcvHWM write SetRcvHwm;
property MaxMsgSize: Int64 read GetMaxMsgSize write SetMaxMsgSize;
property MulticastHops: Integer read GetMulticastHops write SetMulticastHops;
property IPv4Only: Boolean read GetIPv4Only write SetIPv4Only;
property LastEndpoint: WideString read GetLastEndpoint;
property KeepAlive: TZMQKeepAlive read GetKeepAlive write SetKeepAlive;
property KeepAliveIdle: Integer read GetKeepAliveIdle write SetKeepAliveIdle;
property KeepAliveCnt: Integer read GetKeepAliveCnt write SetKeepAliveCnt;
property KeepAliveIntvl: Integer read GetKeepAliveIntvl write SetKeepAliveIntvl;
property AcceptFilter[indx: Integer]: WideString read GetAcceptFilter write SetAcceptFilter;
property RouterMandatory: Boolean write SetRouterMandatory;
property HWM: Integer read GetHWM write SetHWM;
property RcvTimeout: Integer read GetRcvTimeout write SetRcvTimeout;
property SndTimeout: Integer read GetSndTimeout write SetSndTimeout;
property Affinity: UInt64 read GetAffinity write SetAffinity;
property Identity: WideString read GetIdentity write SetIdentity;
property Rate: Integer read GetRate write SetRate;
property RecoveryIvl: Integer read GetRecoveryIvl write SetRecoveryIvl;
property SndBuf: Integer read GetSndBuf write SetSndBuf;
property RcvBuf: Integer read GetRcvBuf write SetRcvBuf;
property Linger: Integer read GetLinger write SetLinger;
property ReconnectIvl: Integer read GetReconnectIvl write SetReconnectIvl;
property ReconnectIvlMax: Integer read GetReconnectIvlMax write SetReconnectIvlMax;
property Backlog: Integer read GetBacklog write SetBacklog;
property FD: Pointer read GetFD;
property Events: TZMQPollEvents read GetEvents;
property Context: IZMQContext read GetContext;
property SocketPtr: Pointer read GetSocket;
property RaiseEAgain: Boolean read GetRaiseEAgain write SetRaiseEAgain;
end;
TZMQContext = class(TZMQInterfacedObject, IZMQContext)
private
fContext: Pointer;
fSockets: TThreadList;
fLinger: Integer;
private
function GetContextPtr: Pointer;
function GetLinger: Integer;
function GetTerminated: Boolean;
function GetOption( option: Integer ): Integer;
function GetIOThreads: Integer;
function GetMaxSockets: Integer;
procedure SetLinger(const Value: Integer);
procedure SetOption(option, optval: Integer);
procedure SetIOThreads(const Value: Integer);
procedure SetMaxSockets(const Value: Integer);
protected
fTerminated: Boolean;
fMainThread: Boolean;
constructor CreateShadow(const Context: TZMQContext);
procedure CheckResult(rc: Integer);
procedure RemoveSocket(const socket: TZMQSocketImpl );
public
constructor Create;
destructor Destroy; override;
function Shadow: IZMQContext;
function Socket(stype: TZMQSocketType): PZMQSocket;
procedure Terminate;
property ContextPtr: Pointer read GetContextPtr;
// < -1 means dont change linger when destroy
property Linger: Integer read GetLinger write SetLinger;
property Terminated: Boolean read GetTerminated;
property IOThreads: Integer read GetIOThreads write SetIOThreads;
property MaxSockets: Integer read GetMaxSockets write SetMaxSockets;
end;
TZMQPoller = class;
TZMQPollerThread = class(TThread)
private
fOwner: TZMQPoller;
fContext: IZMQContext;
fPair: TZMQSocketImpl;
fAddr: WideString;
fPollItem: array of zmq_pollitem_t;
fPollSocket: array of TZMQSocketImpl;
fPollItemCapacity,
fPollItemCount: Integer;
fTimeOut: Integer;
fPollNumber: Integer;
fLock: TRTLCriticalSection;
fSync: Boolean;
fOnException: TZMQExceptionProc;
fOnTimeOut: TZMQTimeOutProc;
fOnEvent: TZMQPollEventProc;
private
function GetPollItem(const Index: Integer): TZMQPollItem;
function GetPollResult(const Index: Integer): TZMQPollItem;
procedure CheckResult(rc: Integer);
procedure AddToPollItems(const socket: TZMQSocketImpl; events: TZMQPollEvents);
procedure DelFromPollItems(const socket: TZMQSocketImpl; events: TZMQPollEvents; index: Integer);
protected
procedure Execute; override;
public
constructor Create(aOwner: TZMQPoller; aSync: Boolean = false; const aContext: IZMQContext = nil);
destructor Destroy; override;
procedure Register(const socket: PZMQSocket; events: TZMQPollEvents; bWait: Boolean = false);
procedure Deregister(const socket: PZMQSocket; events: TZMQPollEvents; bWait: Boolean = false);
procedure SetPollNumber(const Value: Integer; bWait: Boolean = false);
function Poll(timeout: Longint = -1; lPollNumber: Integer = -1): Integer;
property PollResult[const Index: Integer]: TZMQPollItem read GetPollResult;
property PollNumber: Integer read fPollNumber;
property PollItem[const Index: Integer]: TZMQPollItem read GetPollItem;
property OnEvent: TZMQPollEventProc read fOnEvent write fOnEvent;
property OnException: TZMQExceptionProc read fOnException write fOnException;
property OnTimeOut: TZMQTimeOutProc read fOnTimeOut write fOnTimeOut;
end;
TZMQPoller = class(TZMQInterfacedObject, IZMQPoller)
private
FThread: TZMQPollerThread;
protected
function GetPollResult(const Index: Integer): TZMQPollItem;
function GetPollNumber: Integer;
function GetPollItem(const Index: Integer): TZMQPollItem;
function GetFreeOnTerminate: Boolean;
function GetHandle: THandle;
function GetSuspended: Boolean;
function GetThreadID: THandle;
function GetOnTerminate: TNotifyEvent;
function GetOnEvent: TZMQPollEventProc;
function GetOnException: TZMQExceptionProc;
function GetOnTimeOut: TZMQTimeOutProc;
procedure SetPollNumber(const AValue: Integer);
procedure SetFreeOnTerminate(const Value: Boolean);
procedure SetOnTerminate(const Value: TNotifyEvent);
procedure SetSuspended(const Value: Boolean);
procedure SetOnEvent(const AValue: TZMQPollEventProc);
procedure SetOnException(const AValue: TZMQExceptionProc);
procedure SetOnTimeOut(const AValue: TZMQTimeOutProc);
public
constructor Create(aSync: Boolean = false; const aContext: IZMQContext = nil);
destructor Destroy; override;
procedure Resume;
procedure Suspend;
procedure Terminate;
function WaitFor: LongWord;
procedure Register(const socket: PZMQSocket; const events: TZMQPollEvents; bWait: Boolean = False);
procedure Unregister(const socket: PZMQSocket; const events: TZMQPollEvents; bWait: Boolean = False);
procedure SetPollNumberAndWait(const Value: Integer);
function Poll(timeout: Longint = -1; lPollNumber: Integer = -1): Integer;
property PollResult[const Index: Integer]: TZMQPollItem read GetPollResult;
property PollNumber: Integer read GetPollNumber write SetPollNumber;
property PollItem[const Index: Integer]: TZMQPollItem read GetPollItem;
property FreeOnTerminate: Boolean read GetFreeOnTerminate write SetFreeOnTerminate;
property Handle: THandle read GetHandle;
property Suspended: Boolean read GetSuspended write SetSuspended;
property ThreadID: THandle read GetThreadID;
property OnTerminate: TNotifyEvent read GetOnTerminate write SetOnTerminate;
property OnEvent: TZMQPollEventProc read GetOnEvent write SetOnEvent;
property OnException: TZMQExceptionProc read GetOnException write SetOnException;
property OnTimeOut: TZMQTimeOutProc read GetOnTimeOut write SetOnTimeOut;
end;
TZMQInternalThread = class(TThread)
private
fPipe: TZMQSocketImpl; //attached thread pipe
thrPipe: TZMQSocketImpl; // attached thread pipe in the new thread.
fContext: IZMQContext;
fArgs: Pointer;
fDetachedMeth: TDetachedThreadMethod;
fAttachedMeth: TAttachedThreadMethod;
fDetachedProc: TDetachedThreadProc;
fAttachedProc: TAttachedThreadProc;
fOnExecute: TZMQThreadExecuteMethod;
public
constructor Create(lArgs: Pointer; const ctx: IZMQContext);
constructor CreateAttached(lAttachedMeth: TAttachedThreadMethod; const ctx: IZMQContext; lArgs: Pointer);
constructor CreateDetached(lDetachedMeth: TDetachedThreadMethod; lArgs: Pointer);
constructor CreateAttachedProc(lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext; lArgs: Pointer);
constructor CreateDetachedProc(lDetachedProc: TDetachedThreadProc; lArgs: Pointer);
destructor Destroy; override;
protected
procedure Execute; override;
procedure DoExecute; virtual;
public
property Pipe: TZMQSocketImpl read fPipe;
property Args: Pointer read fArgs;
property Context: IZMQContext read fContext;
property OnExecute: TZMQThreadExecuteMethod read fOnExecute write fOnExecute;
end;
TZMQThread = class(TZMQInterfacedObject, IZMQThread)
private
FThread: TZMQInternalThread;
protected
function GetPipe: PZMQSocket;
function GetArgs: Pointer;
function GetContext: IZMQContext;
function GetFreeOnTerminate: Boolean;
function GetHandle: THandle;
function GetSuspended: Boolean;
function GetThreadID: THandle;
function GetOnExecute: TZMQThreadExecuteMethod;
function GetOnTerminate: TNotifyEvent;
procedure SetFreeOnTerminate(const AValue: Boolean);
procedure SetSuspended(const AValue: Boolean);
procedure SetOnExecute(const AValue: TZMQThreadExecuteMethod);
procedure SetOnTerminate(const AValue: TNotifyEvent);
public
constructor Create(lArgs: Pointer; const ctx: IZMQContext);
constructor CreateAttached(lAttachedMeth: TAttachedThreadMethod; const ctx: IZMQContext; lArgs: Pointer );
constructor CreateDetached(lDetachedMeth: TDetachedThreadMethod; lArgs: Pointer );
constructor CreateAttachedProc(lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext; lArgs: Pointer );
constructor CreateDetachedProc(lDetachedProc: TDetachedThreadProc; lArgs: Pointer );
destructor Destroy; override;
procedure Resume;
procedure Suspend;
procedure Terminate;
function WaitFor: LongWord;
property Pipe: PZMQSocket read GetPipe;
property Args: Pointer read GetArgs;
property Context: IZMQContext read GetContext;
property FreeOnTerminate: Boolean read GetFreeOnTerminate write SetFreeOnTerminate;
property Handle: THandle read GetHandle;
property Suspended: Boolean read GetSuspended write SetSuspended;
property ThreadID: THandle read GetThreadID;
property OnExecute: TZMQThreadExecuteMethod read GetOnExecute write SetOnExecute;
property OnTerminate: TNotifyEvent read GetOnTerminate write SetOnTerminate;
end;
TZMQMananger = class(TInterfacedObject, IZMQMananger)
private
FContext: IZMQContext;
FTerminated: Boolean;
function GetVersion: TZMQVersion;
protected
function GetTerminated: Boolean;
function GetDriverFile: WideString;
function GetContext: IZMQContext;
procedure SetTerminated(const Value: Boolean);
procedure SetDriverFile(const Value: WideString);
public
function CreateFrame: IZMQFrame; overload;
function CreateFrame(size: Cardinal): IZMQFrame; overload;
function CreateFrame(data: Pointer; size: Cardinal; ffn: TZMQFreeProc; hint: Pointer = nil): IZMQFrame; overload;
function CreateMsg: IZMQMsg;
function CreateContext: IZMQContext;
function CreatePoller(aSync: Boolean = false; const aContext: IZMQContext = nil): IZMQPoller;
function CreateThread(lArgs: Pointer; const ctx: IZMQContext): IZMQThread;
function CreateAttached(lAttachedMeth: TAttachedThreadMethod; const ctx: IZMQContext; lArgs: Pointer): IZMQThread;
function CreateDetached(lDetachedMeth: TDetachedThreadMethod; lArgs: Pointer): IZMQThread;
function CreateAttachedProc(lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext; lArgs: Pointer): IZMQThread;
function CreateDetachedProc(lDetachedProc: TDetachedThreadProc; lArgs: Pointer): IZMQThread;
function Poll(var pia: TZMQPollItemArray; timeout: Integer = -1): Integer; overload;
function Poll(var pi: TZMQPollItem; timeout: Integer = -1): Integer; overload;
procedure Proxy(const frontend, backend, capture: PZMQSocket);
procedure Device(device: TZMQDevice; const insocket, outsocket: PZMQSocket);
procedure FreeAndNilSocket(var socket: PZMQSocket);
function StartStopWatch: Pointer;
function StopStopWatch(watch: Pointer): LongWord;
procedure Sleep(const seconds: Integer);
procedure Terminate;
function IsZMQException(AExcetpion: Exception): Boolean;
property Version: TZMQVersion read GetVersion;
property Terminated: Boolean read GetTerminated write SetTerminated;
property Context: IZMQContext read GetContext;
end;
procedure _zmq_free_fn(data, hint: Pointer); cdecl;
var
varApi: ZmqIntf.TZmqApi;
procedure _RegZmqClass;
procedure _UnregZmqClass;
procedure _InitZmqApi(const Api: PPointer; const Instance: HINST);
procedure _FinalZmqApi(const Api: PPointer; const Instance: HINST);
procedure __MonitorProc(ZMQMonitorRec: PZMQMonitorRec);
function __ZMQManager: PIZMQMananger;
function ZMQMonitorEventsToInt(const events: TZMQMonitorEvents): Integer;
function ZMQSendFlagsToInt(const flags: TZMQSendFlags): Integer;
function ZMQRecvFlagsToInt(const flags: TZMQRecvFlags): Integer;
function ZMQPollEventsToInt(const events: TZMQPollEvents): Integer;
function IntToZMQPollEvents(const events: Integer): TZMQPollEvents;
implementation
var
varContexts: TList;
varZMQManager: IZMQMananger;
varWC: TWndClassA;
const
cZMQPoller_Register = 'reg';
cZMQPoller_SyncRegister = 'syncreg';
cZMQPoller_DeRegister = 'dereg';
cZMQPoller_SyncDeRegister = 'syncdereg';
cZMQPoller_Terminate = 'term';
cZMQPoller_PollNumber = 'pollno';
cZMQPoller_SyncPollNumber = 'syncpollno';
procedure _zmq_free_fn(data, hint: Pointer); cdecl;
var
h: PZMQFreeHint;
begin
h := hint;
h.fn(data, h.hint);
end;
{$IF CompilerVersion <= 18.5}
procedure BinToHex(Buffer: PAnsiChar; Text: PWideChar; BufSize: Integer);
const
Convert: array[0..15] of WideChar = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
var
I: Integer;
begin
for I := 0 to BufSize - 1 do
begin
Text[0] := Convert[Byte(Buffer[I]) shr 4];
Text[1] := Convert[Byte(Buffer[I]) and $F];
Inc(Text, 2);
end;
end;
function HexToBin(Text : PWideChar; Buffer: PAnsiChar; BufSize: Integer): Integer;
const
Convert: array['0'..'f'] of SmallInt =
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15);
var
I: Integer;
TextH, TextL: AnsiChar;
begin
I := BufSize;
while I > 0 do
begin
TextH := AnsiChar(Word(Text[0]));
TextL := AnsiChar(Word(Text[1]));
if ((TextH in [':'..'@']) or (TextH in ['G'..#96])) or
((TextL in [':'..'@']) or (TextL in ['G'..#96])) then
Break;
if not (TextH in ['0'..'f']) or not (TextL in ['0'..'f']) then Break;
Buffer[0] := AnsiChar((Convert[AnsiChar(TextH)] shl 4) + Convert[AnsiChar(TextL)]);
Inc(Buffer);
Inc(Text, 2);
Dec(I);
end;
Result := BufSize - I;
end;
{$IFEND}
function ZMQMonitorEventsToInt(const events: TZMQMonitorEvents): Integer;
begin
Result := 0;
if meConnected in events then
Result := Result or ZMQ_EVENT_CONNECTED;
if meConnectDelayed in events then
Result := Result or ZMQ_EVENT_CONNECT_DELAYED;
if meConnectRetried in events then
Result := Result or ZMQ_EVENT_CONNECT_RETRIED;
if meListening in events then
Result := Result or ZMQ_EVENT_LISTENING;
if meBindFailed in events then
Result := Result or ZMQ_EVENT_BIND_FAILED;
if meAccepted in events then
Result := Result or ZMQ_EVENT_ACCEPTED;
if meAcceptFailed in events then
Result := Result or ZMQ_EVENT_ACCEPT_FAILED;
if meClosed in events then
Result := Result or ZMQ_EVENT_CLOSED;
if meCloseFailed in events then
Result := Result or ZMQ_EVENT_CLOSE_FAILED;
if meDisconnected in events then
Result := Result or ZMQ_EVENT_DISCONNECTED;
end;
function ZMQSendFlagsToInt(const flags: TZMQSendFlags): Integer;
begin
Result := 0;
if sfDontWait in flags then
Result := Result or ZMQ_DONTWAIT;
if sfSndMore in flags then
Result := Result or ZMQ_SNDMORE;
end;
function ZMQRecvFlagsToInt(const flags: TZMQRecvFlags): Integer;
begin
Result := 0;
if rfDontWait in flags then
Result := Result or ZMQ_DONTWAIT;
end;
function ZMQPollEventsToInt(const events: TZMQPollEvents): Integer;
begin
Result := 0;
if pePollIn in events then
Result := Result or ZMQ_POLLIN;
if pePollOut in events then
Result := Result or ZMQ_POLLOUT;
if pePollErr in events then
Result := Result or ZMQ_POLLERR;
end;
function IntToZMQPollEvents(const events: Integer): TZMQPollEvents;
begin
Result := [];
if ZMQ_POLLIN and events = ZMQ_POLLIN then
Result := Result + [pePollIn];
if ZMQ_POLLOUT and events = ZMQ_POLLOUT then
Result := Result + [pePollOut];
if ZMQ_POLLERR and events = ZMQ_POLLERR then
Result := Result + [pePollErr];
end;
procedure _RegZmqClass;
begin
varApi.Flags := 'ZMQ';
varApi.Instance := SysInit.HInstance;
varApi.InitProc := _InitZMQApi;
varApi.FinalProc := _FinalZMQApi;
varApi.FuncsCount := ZmqApi_FuncsCount;
SetLength(varApi.Funcs, ZmqApi_FuncsCount);
varApi.Funcs[FuncIdx_ZMQMananger] := @__ZMQManager;
FillChar(varWC, SizeOf(varWC), 0);
varWC.lpszClassName := CLASSNAME_Zmq4D;
varWC.style := CS_GLOBALCLASS;
varWC.hInstance := SysInit.HInstance;
varWC.lpfnWndProc := @varApi;
if Windows.RegisterClassA(varWC)=0 then
Halt;
end;
procedure _UnregZmqClass;
begin
Windows.UnregisterClassA(CLASSNAME_Zmq4D, SysInit.HInstance);
end;
procedure _InitZmqApi(const Api: PPointer; const Instance: HINST);
begin
end;
procedure _FinalZmqApi(const Api: PPointer; const Instance: HINST);
begin
end;
function __ZMQManager: PIZMQMananger;
begin
if varZMQManager = nil then
varZMQManager := TZMQMananger.Create;
Result := @varZMQManager;
end;
{
This function is called when a CTRL_C_EVENT received, important that this
function is executed in a separate thread, because Terminate terminates the
context, which blocks until there are open sockets.
}
function Console_handler(dwCtrlType: DWORD): BOOL;
var
i: Integer;
begin
if CTRL_C_EVENT = dwCtrlType then
begin
ZMQ.Terminated := true;
for i := varContexts.Count - 1 downto 0 do
TZMQContext(varContexts[i]).Terminate;
Result := True;
// if I set to True than the app won't exit,
// but it's not the solution.
// ZMQTerminate;
end
else
Result := False;
end;
{ EZMQException }
constructor EZMQException.Create;
begin
fErrorCode := ZAPI.zmq_errno;
inherited Create(String(Utf8String( ZAPI.zmq_strerror( fErrorCode ) ) ) );
end;
constructor EZMQException.Create(aErrorCode: Integer);
begin
fErrorCode := aErrorCode;
inherited Create(String(Utf8String(ZAPI.zmq_strerror(fErrorCode))));
end;
{ TZMQInterfacedObject }
procedure TZMQInterfacedObject.BeforeDestruction;
begin
FDestroying := True;
inherited;
end;
function TZMQInterfacedObject._AddRef: Integer;
begin
if FDestroying then
Result := FRefCount
else
Result := inherited _AddRef;
end;
function TZMQInterfacedObject._Release: Integer;
begin
if FDestroying then
Result := FRefCount
else
Result := inherited _Release;
end;
{ TZMQFrame }
procedure TZMQFrame.CheckResult(rc: Integer);
begin
if rc = 0 then
begin
// ok
end
else
if rc = -1 then
begin
raise EZMQException.Create;
end
else
raise EZMQException.Create('Function result is not 0, or -1!');
end;
procedure TZMQFrame.Copy(const msg: IZMQFrame);
begin
CheckResult(ZAPI.zmq_msg_copy(@fMessage, msg.Handle));
end;
constructor TZMQFrame.Create;
begin
CheckResult(ZAPI.zmq_msg_init(@fMessage));
end;
constructor TZMQFrame.Create(data: Pointer; size: Cardinal;
ffn: TZMQFreeProc; hint: Pointer);
begin
fFreeHint.frame := Self;
fFreeHint.fn := ffn;
fFreeHint.hint := hint;
CheckResult(ZAPI.zmq_msg_init_data(@fMessage, data, size, _zmq_free_fn, @fFreeHint));
end;
constructor TZMQFrame.Create(size: Cardinal);
begin
CheckResult(ZAPI.zmq_msg_init_size(@fMessage, size));
end;
function TZMQFrame.Data: Pointer;
begin
Result := ZAPI.zmq_msg_data(@fMessage);
end;
destructor TZMQFrame.Destroy;
begin
CheckResult(ZAPI.zmq_msg_close(@fMessage));
inherited;
end;
function TZMQFrame.Dump: WideString;
var
iSize: Integer;
begin
// not complete.
iSize := size;
if iSize = 0 then
result := ''
else
if WideChar(data^) = #0 then
begin
SetLength( Result, iSize * 2 );
BinToHex( data, PWideChar(Result), iSize );
end
else
result := Self.S;
end;
function TZMQFrame.Dup: IZMQFrame;
begin
Result := TZMQFrame.create(size);
System.Move(data^, Result.data^, size);
end;
function TZMQFrame.GetC: Currency;
begin
Result := Currency(data^);
end;
function TZMQFrame.GetDT: TDateTime;
begin
Result := TDateTime(data^);
end;
function TZMQFrame.GetD: Double;
begin
Result := Double(data^);
end;
function TZMQFrame.GetF: Single;
begin
Result := Single(data^);
end;
function TZMQFrame.GetH: WideString;
begin
SetLength(result, size * 2 div ZMQ_CHAR_SIZE);
BinToHex(data, PWideChar(result), size);
end;
function TZMQFrame.GetI: Integer;
begin
Result := Integer(data^);
end;
function TZMQFrame.GetS: WideString;
begin
SetString(Result, PWideChar(data), size div ZMQ_CHAR_SIZE);
end;
function TZMQFrame.GetHandle: Pointer;
begin
Result := @fMessage
end;
function TZMQFrame.GetProp(prop: TZMQMessageProperty): Integer;
begin
result := ZAPI.zmq_msg_get( @fMessage, Byte( prop ) );
if result = -1 then
raise EZMQException.Create
else
raise EZMQException.Create( 'zmq_msg_more return value undefined!' );
end;
function TZMQFrame.Implementor: Pointer;
begin
Result := Self;
end;
procedure TZMQFrame.LoadFromStream(const strm: IStream);
var
statstg: TStatStg;
cbRead: LongInt;
begin
Assert(strm.Stat(statstg, 0)=0, 'IStream.Stat has error!');
if statstg.cbSize <> size then
rebuild( statstg.cbSize );
strm.Read(data, statstg.cbSize, @cbRead);
end;
function TZMQFrame.More: Boolean;
var
rc: Integer;
begin
rc := ZAPI.zmq_msg_more(@fMessage);
if rc = 0 then
result := false
else
if rc = 1 then
result := true
else
raise EZMQException.Create( 'zmq_msg_more return value undefined!' );
end;
procedure TZMQFrame.Move(const msg: IZMQFrame);
begin
CheckResult(ZAPI.zmq_msg_move(@fMessage, msg.Handle));
end;
procedure TZMQFrame.Rebuild;
begin
CheckResult(ZAPI.zmq_msg_close(@fMessage));
CheckResult(ZAPI.zmq_msg_init(@fMessage));
end;
procedure TZMQFrame.Rebuild(size: Cardinal);
begin
CheckResult(ZAPI.zmq_msg_close(@fMessage));
CheckResult(ZAPI.zmq_msg_init_size(@fMessage, size));
end;
procedure TZMQFrame.Rebuild(data: Pointer; size: Cardinal;
ffn: TZMQFreeProc; hint: Pointer);
begin
CheckResult(ZAPI.zmq_msg_close(@fMessage));
fFreeHint.frame := Self;
fFreeHint.fn := ffn;
fFreeHint.hint := hint;
CheckResult(ZAPI.zmq_msg_init_data(@fMessage, data, size, _zmq_free_fn, @fFreeHint));
end;
procedure TZMQFrame.SaveToStream(const strm: IStream);
var
cbWritten: Longint;
begin
strm.Write( data, size, @cbWritten);
end;
procedure TZMQFrame.SetC(const Value: Currency);
var
iSize: Integer;
begin
iSize := SizeOf( Value );
Rebuild( iSize );
Currency(data^) := Value;
end;
procedure TZMQFrame.SetDT(const Value: TDateTime);
var
iSize: Integer;
begin
iSize := SizeOf( Value );
Rebuild( iSize );
TDateTime(data^) := Value;
end;
procedure TZMQFrame.SetD(const Value: Double);
var
iSize: Integer;
begin
iSize := SizeOf( Value );
Rebuild( iSize );
Double(data^) := Value;
end;
procedure TZMQFrame.SetF(const Value: Single);
var
iSize: Integer;
begin
iSize := SizeOf( Value );
Rebuild( iSize );
Single(data^) := Value;
end;
procedure TZMQFrame.SetH(const Value: WideString);
var
iSize: Integer;
begin
iSize := Length(Value) div 2;
rebuild(iSize*ZMQ_CHAR_SIZE);
HexToBin(PWideChar(value), data, iSize);
end;
procedure TZMQFrame.SetI(const Value: Integer);
var
iSize: Integer;
begin
iSize := SizeOf( Value );
Rebuild( iSize );
Integer(data^) := Value;
end;
procedure TZMQFrame.SetS(const Value: WideString);
var
iSize: Integer;
begin
iSize := Length(Value);
rebuild(iSize*ZMQ_CHAR_SIZE);
System.Move(Value[1], data^, iSize*ZMQ_CHAR_SIZE);
end;
procedure TZMQFrame.SetProp(prop: TZMQMessageProperty; value: Integer);
begin
CheckResult( ZAPI.zmq_msg_set( @fMessage, Byte( prop ), value ) );
end;
function TZMQFrame.Size: Cardinal;
begin
Result := ZAPI.zmq_msg_size(@fMessage);
end;
{ TZMQMsg }
function TZMQMsg.Add(const msg: IZMQFrame): Integer;
begin
try
Result := fMsgs.Add(msg);
fSize := fSize + msg.size;
fCursor := 0;
except
on e: Exception do
begin
Result := -1;
TraceException('[TZMQMsg.Add]'+e.Message);
end;
end;
end;
function TZMQMsg.AddInt(const msg: Integer): Integer;
var
frame: IZMQFrame;
begin
frame := TZMQFrame.create( sizeOf( Integer ) );
frame.I := msg;
Result := add( frame );
end;
function TZMQMsg.AddStr(const msg: WideString): Integer;
var
frame: IZMQFrame;
begin
frame := TZMQFrame.Create;
frame.S := msg;
Result := Add( frame );
end;
procedure TZMQMsg.Clear;
begin
fMsgs.Clear;
fSize := 0;
fCursor := 0;
end;
function TZMQMsg.ContentSize: Integer;
begin
Result := fSize;
end;
constructor TZMQMsg.Create;
begin
fMsgs := TInterfaceList.Create;
fSize := 0;
fCursor := 0;
end;
destructor TZMQMsg.Destroy;
begin
Clear;
fMsgs := nil;
inherited;
end;
function TZMQMsg.Dump: WideString;
var
i: Integer;
begin
Result := '';
for i := 0 to size - 1 do
begin
if i > 0 then
Result := Result + #13#10;
Result := Result + item[i].Dump;
end;
end;
function TZMQMsg.Dup: IZMQMsg;
var
msg, msgnew: IZMQFrame;
iSize: Integer;
begin
Result := TZMQMsg.create;
msg := first;
while msg <> nil do
begin
iSize := msg.size;
msgnew := TZMQFrame.create( iSize );
{$ifdef UNIX}
Move( msg.data^, msgnew.data^, iSize );
{$else}
CopyMemory( msgnew.data, msg.data, iSize );
{$endif}
Result.Add( msgnew );
msg := next;
end;
TZMQMsg(Result.Implementator).fSize := fSize;
TZMQMsg(Result.Implementator).fCursor := fCursor;
end;
function TZMQMsg.First: IZMQFrame;
begin
if size > 0 then
begin
Result := fMsgs[0] as IZMQFrame;
fCursor := 1;
end
else
begin
Result := nil;
fCursor := 0;
end;
end;
function TZMQMsg.GetItem(indx: Integer): IZMQFrame;
begin
Result := fMsgs[indx] as IZMQFrame;
end;
function TZMQMsg.Implementator: Pointer;
begin
Result := Self;
end;
function TZMQMsg.Last: IZMQFrame;
begin
if Size > 0 then
Result := fMsgs[Size - 1] as IZMQFrame
else
Result := nil;
fCursor := Size;
end;
procedure TZMQMsg.LoadFromHex(const data: WideString);
var
tsl: TStringList;
i: Integer;
frame: IZMQFrame;
begin
Clear;
tsl := TStringList.Create;
try
tsl.Text := data;
for i := 0 to tsl.Count - 1 do
begin
frame := TZMQFrame.create;
frame.H := tsl[i];
Add( frame );
end;
finally
tsl.Free;
end;
end;
function TZMQMsg.Next: IZMQFrame;
begin
if fCursor < size then
begin
Result := fMsgs[fCursor] as IZMQFrame;
inc(fCursor);
end
else
Result := nil;
end;
function TZMQMsg.Pop: IZMQFrame;
begin
if Size > 0 then
begin
Result := fMsgs[0] as IZMQFrame;
fSize := fSize - Result.Size;
fMsgs.Delete(0);
fCursor := 0;
end
else
Result := nil;
end;
function TZMQMsg.PopInt: Integer;
var
frame: IZMQFrame;
begin
frame := pop;
try
Result := frame.I;
finally
frame := nil;
end;
end;
function TZMQMsg.PopStr: WideString;
var
frame: IZMQFrame;
begin
frame := pop;
try
Result := frame.S;
finally
frame := nil;
end;
end;
function TZMQMsg.Push(const msg: IZMQFrame): Integer;
begin
try
fMsgs.Insert(0, msg);
fSize := fSize + msg.size;
fCursor := 0;
Result := 0;
except
on e: Exception do
begin
Result := -1;
TraceException('[TZMQMsg.Push]'+e.Message);
end;
end;
end;
function TZMQMsg.PushInt(const msg: Integer): Integer;
var
frame: IZMQFrame;
begin
frame := TZMQFrame.create( sizeOf( Integer ) );
frame.I := msg;
Result := Push( frame );
end;
function TZMQMsg.PushStr(const str: WideString): Integer;
var
frm: IZMQFrame;
begin
frm := TZMQFrame.create;
frm.S := str;
Result := push( frm );
end;
procedure TZMQMsg.Remove(const msg: IZMQFrame);
var
i: Integer;
begin
i := fMsgs.IndexOf(msg);
if i > 0 then
begin
fSize := fSize - Item[i].size;
fMsgs.Delete(i);
fCursor := 0;
end;
end;
function TZMQMsg.SaveAsHex: WideString;
var
i: Integer;
begin
for i := 0 to size - 1 do
begin
Result := Result + item[i].H;
if i < size - 1 then
Result := Result + #13 + #10;
end;
end;
function TZMQMsg.Size: Integer;
begin
Result := fMsgs.Count;
end;
function TZMQMsg.Unwrap: IZMQFrame;
begin
Result := pop;
if (size > 0) and (Item[0].size = 0) then
pop;
end;
procedure TZMQMsg.Wrap(const msg: IZMQFrame);
var
frame: IZMQFrame;
begin
frame := TZMQFrame.Create(0);
push(frame);
push(msg);
end;
{ TZMQSocketImpl }
procedure TZMQSocketImpl.AddAcceptFilter(const addr: WideString);
var
saddr: UTF8String;
begin
saddr := UTF8Encode(addr);
SetSockOpt( ZMQ_TCP_ACCEPT_FILTER, PAnsiChar(saddr), Length( saddr ) );
{$IF CompilerVersion > 18.5}
fAcceptFilter.Add( addr );
{$ELSE}
fAcceptFilter.Add( saddr );
{$IFEND}
end;
procedure TZMQSocketImpl.Bind(const addr: WideString);
begin
CheckResult(ZAPI.zmq_bind(SocketPtr, PAnsiChar(UTF8String(addr))));
end;
function TZMQSocketImpl.CheckResult(rc: Integer): Integer;
var
errn: Integer;
begin
Result := rc;
if rc = -1 then
begin
errn := ZAPI.zmq_errno;
if ( errn <> ZMQEAGAIN ) or fRaiseEAgain then
raise EZMQException.Create( errn );
end
else
if rc <> 0 then
raise EZMQException.Create('Function result is not 0, or -1!');
end;
procedure TZMQSocketImpl.Close;
begin
if SocketPtr = nil then
Exit;
CheckResult(ZAPI.zmq_close(SocketPtr));
fSocket := nil;
end;
procedure TZMQSocketImpl.Connect(const addr: WideString);
begin
CheckResult( ConnectEx(addr) );
end;
constructor TZMQSocketImpl.Create();
begin
fRaiseEAgain := False;
fAcceptFilter := TStringList.Create;
fMonitorRec := nil;
fData.SocketType := GetSocketType;
fData.RcvMore := GetRcvMore;
fData.RcvTimeout := GetRcvTimeout;
fData.SndTimeout := GetSndTimeout;
fData.Affinity := GetAffinity;
fData.Identity := GetIdentity;
fData.Rate := GetRate;
fData.RecoveryIVL := GetRecoveryIVL;
fData.SndBuf := GetSndBuf;
fData.RcvBuf := GetRcvBuf;
fData.Linger := GetLinger;
fData.ReconnectIVL := GetReconnectIVL;
fData.ReconnectIVLMax := GetReconnectIVLMax;
fData.Backlog := GetBacklog;
fData.FD := GetFD;
fData.Events := GetEvents;
fData.HWM := GetHWM;
fData.SndHWM := GetSndHWM;
fData.RcvHWM := GetRcvHWM;
fData.MaxMsgSize := GetMaxMsgSize;
fData.MulticastHops := GetMulticastHops;
fData.IPv4Only := GetIPv4Only;
fData.LastEndpoint := GetLastEndpoint;
fData.KeepAlive := GetKeepAlive;
fData.KeepAliveIdle := GetKeepAliveIdle;
fData.KeepAliveCnt := GetKeepAliveCnt;
fData.KeepAliveIntvl := GetKeepAliveIntvl;
fData.AcceptFilter := GetAcceptFilter;
fData.Context := GetContext;
fData.Socket := GetSocket;
fData.RaiseEAgain := GetRaiseEAgain;
fData.SetHWM := SetHWM;
fData.SetRcvTimeout := SetRcvTimeout;
fData.SetSndTimeout := SetSndTimeout;
fData.SetAffinity := SetAffinity;
fData.SetIdentity := SetIdentity;
fData.SetRate := SetRate;
fData.SetRecoveryIvl := SetRecoveryIvl;
fData.SetSndBuf := SetSndBuf;
fData.SetRcvBuf := SetRcvBuf;
fData.SetLinger := SetLinger;
fData.SetReconnectIvl := SetReconnectIvl;
fData.SetReconnectIvlMax := SetReconnectIvlMax;
fData.SetBacklog := SetBacklog;
fData.SetSndHWM := SetSndHWM;
fData.SetRcvHWM := SetRcvHWM;
fData.SetMaxMsgSize := SetMaxMsgSize;
fData.SetMulticastHops := SetMulticastHops;
fData.SetIPv4Only := SetIPv4Only;
fData.SetKeepAlive := SetKeepAlive;
fData.SetKeepAliveIdle := SetKeepAliveIdle;
fData.SetKeepAliveCnt := SetKeepAliveCnt;
fData.SetKeepAliveIntvl := SetKeepAliveIntvl;
fData.SetAcceptFilter := SetAcceptFilter;
fData.SetRouterMandatory := SetRouterMandatory;
fData.SetRaiseEAgain := SetRaiseEAgain;
fData.Implementator := Implementator;
fData.Bind := Bind;
fData.Unbind := Unbind;
fData.Connect := Connect;
fData.ConnectEx := ConnectEx;
fData.Disconnect := Disconnect;
fData.Free := Free;
fData.Subscribe := Subscribe;
fData.UnSubscribe := UnSubscribe;
fData.AddAcceptFilter := AddAcceptFilter;
fData.SendFrame := Send;
fData.SendStream := Send;
fData.SendString := Send;
fData.SendMsg := Send;
fData.SendStrings := Send;
fData.SendBuffer := SendBuffer;
fData.RecvFrame := Recv;
fData.RecvStream := Recv;
fData.RecvString := Recv;
fData.RecvMsg := Recv;
fData.RecvBuffer := RecvBuffer;
fData.RegisterMonitor := RegisterMonitor;
fData.UnregisterMonitor := UnregisterMonitor;
end;
procedure TZMQSocketImpl.UnregisterMonitor;
var
rc: Cardinal;
begin
if fMonitorRec <> nil then
begin
fMonitorRec.Terminated := True;
rc := WaitForSingleObject( fMonitorThread, INFINITE );
if rc = WAIT_FAILED then
raise Exception.Create( 'error in WaitForSingleObject for Monitor Thread' );
CheckResult(ZAPI.zmq_socket_monitor( SocketPtr, nil ,0 ) );
Dispose( fMonitorRec );
fMonitorRec := nil;
end;
end;
destructor TZMQSocketImpl.Destroy;
begin
if fMonitorRec <> nil then
begin
UnregisterMonitor;
fMonitorRec := nil;
end;
Close;
if fContext <> nil then
begin
fContext.RemoveSocket( Self );
fContext := nil;
end;
if fAcceptFilter <> nil then
begin
fAcceptFilter.Free;
fAcceptFilter := nil;
end;
inherited;
end;
procedure TZMQSocketImpl.Disconnect(const addr: WideString);
begin
CheckResult(ZAPI.zmq_disconnect(SocketPtr, PAnsiChar(UTF8String(addr))));
end;
procedure TZMQSocketImpl.Free;
begin
TObject(Self).Free;
end;
function TZMQSocketImpl.GetAcceptFilter(indx: Integer): WideString;
begin
if ( indx < 0 ) or ( indx >= fAcceptFilter.Count ) then
raise EZMQException.Create( '[getAcceptFilter] Index out of bounds.' );
Result := fAcceptFilter[indx];
end;
function TZMQSocketImpl.GetAffinity: UInt64;
begin
Result := GetSockOptInt64(ZMQ_AFFINITY);
end;
function TZMQSocketImpl.GetBacklog: Integer;
begin
Result := GetSockOptInteger( ZMQ_BACKLOG );
end;
function TZMQSocketImpl.GetContext: IZMQContext;
begin
Result := fContext;
end;
function TZMQSocketImpl.GetData: PZMQSocket;
begin
Result := @fData;
end;
function TZMQSocketImpl.GetEvents: TZMQPollEvents;
var
optvallen: size_t;
i: Cardinal;
begin
optvallen := SizeOf( i );
GetSockOpt( ZMQ_EVENTS, @i, optvallen );
Result := IntToZMQPollEvents(i);
end;
function TZMQSocketImpl.GetFD: Pointer;
var
optvallen: size_t;
begin
// Not sure this works, haven't tested.
optvallen := SizeOf( result );
GetSockOpt( ZMQ_FD, @result, optvallen );
end;
function TZMQSocketImpl.GetHWM: Integer;
begin
Result := GetRcvHWM;
// warning deprecated.
end;
function TZMQSocketImpl.GetIdentity: WideString;
var
s: ShortString;
optvallen: size_t;
begin
optvallen := 255;
GetSockOpt( ZMQ_IDENTITY, @s[1], optvallen );
SetLength( s, optvallen );
{$IF CompilerVersion > 18.5}
Result := UTF8ToString(s);
{$ELSE}
Result := UTF8Decode(s);
{$IFEND}
end;
function TZMQSocketImpl.GetIPv4Only: Boolean;
begin
Result := GetSockOptInteger( ZMQ_IPV4ONLY ) <> 0;
end;
function TZMQSocketImpl.GetKeepAlive: TZMQKeepAlive;
begin
Result := TZMQKeepAlive(GetSockOptInteger( ZMQ_TCP_KEEPALIVE ) + 1 );
end;
function TZMQSocketImpl.GetKeepAliveCnt: Integer;
begin
Result := GetSockOptInteger( ZMQ_TCP_KEEPALIVE_CNT );
end;
function TZMQSocketImpl.GetKeepAliveIdle: Integer;
begin
Result := GetSockOptInteger( ZMQ_TCP_KEEPALIVE_IDLE );
end;
function TZMQSocketImpl.GetKeepAliveIntvl: Integer;
begin
Result := GetSockOptInteger( ZMQ_TCP_KEEPALIVE_INTVL );
end;
function TZMQSocketImpl.GetLastEndpoint: WideString;
var
s: ShortString;
optvallen: size_t;
begin
optvallen := 255;
getSockOpt( ZMQ_LAST_ENDPOINT, @s[1], optvallen );
SetLength( s, optvallen - 1);
{$IF CompilerVersion > 18.5}
Result := UTF8ToString(s);
{$ELSE}
Result := UTF8Decode(s);
{$IFEND}
end;
function TZMQSocketImpl.GetLinger: Integer;
begin
Result := GetSockOptInteger( ZMQ_LINGER );
end;
function TZMQSocketImpl.GetMaxMsgSize: Int64;
begin
Result := GetSockOptInt64( ZMQ_MAXMSGSIZE );
end;
function TZMQSocketImpl.GetMulticastHops: Integer;
begin
Result := GetSockOptInteger( ZMQ_MULTICAST_HOPS );
end;
function TZMQSocketImpl.GetRaiseEAgain: Boolean;
begin
Result :=fRaiseEAgain;
end;
function TZMQSocketImpl.GetRate: Integer;
begin
Result := GetSockOptInteger( ZMQ_RATE );
end;
function TZMQSocketImpl.GetRcvBuf: Integer;
begin
Result := GetSockOptInteger( ZMQ_RCVBUF );
end;
function TZMQSocketImpl.GetRcvHWM: Integer;
begin
Result := GetSockOptInteger( ZMQ_RCVHWM );
end;
function TZMQSocketImpl.GetRcvMore: Boolean;
begin
Result := GetSockOptInteger( ZMQ_RCVMORE ) = 1;
end;
function TZMQSocketImpl.GetRcvTimeout: Integer;
begin
Result := GetSockOptInteger(ZMQ_RCVTIMEO);
end;
function TZMQSocketImpl.GetReconnectIVL: Integer;
begin
Result := GetSockOptInteger( ZMQ_RECONNECT_IVL );
end;
function TZMQSocketImpl.GetReconnectIVLMax: Integer;
begin
Result := GetSockOptInteger( ZMQ_RECONNECT_IVL_MAX );
end;
function TZMQSocketImpl.GetRecoveryIVL: Integer;
begin
Result := GetSockOptInteger( ZMQ_RECOVERY_IVL );
end;
function TZMQSocketImpl.GetSndBuf: Integer;
begin
Result := GetSockOptInteger( ZMQ_SNDBUF );
end;
function TZMQSocketImpl.GetSndHWM: Integer;
begin
Result := GetSockOptInteger( ZMQ_SNDHWM );
end;
function TZMQSocketImpl.GetSndTimeout: Integer;
begin
Result := GetSockOptInteger(ZMQ_SNDTIMEO);
end;
function TZMQSocketImpl.GetSocket: Pointer;
begin
Result := fSocket;
end;
function TZMQSocketImpl.GetSocketType: TZMQSocketType;
begin
Result := TZMQSocketType(getSockOptInteger(ZMQ_TYPE));
end;
procedure TZMQSocketImpl.GetSockOpt(option: Integer; optval: Pointer;
var optvallen: Cardinal);
begin
CheckResult(ZAPI.zmq_getsockopt(SocketPtr, option, optval, optvallen));
end;
function TZMQSocketImpl.GetSockOptInt64(option: Integer): Int64;
var
optvallen: size_t;
begin
optvallen := SizeOf( result );
GetSockOpt( option, @result, optvallen );
end;
function TZMQSocketImpl.GetSockOptInteger(option: Integer): Integer;
var
optvallen: size_t;
begin
optvallen := SizeOf( result );
GetSockOpt( option, @result, optvallen );
end;
function TZMQSocketImpl.Implementator: Pointer;
begin
Result := Self;
end;
function TZMQSocketImpl.Recv(var msg: IZMQFrame;
flags: TZMQRecvFlags): Integer;
begin
Result := Recv(msg, ZMQRecvFlagsToInt(flags));
end;
function TZMQSocketImpl.Recv(const strm: IStream;
flags: TZMQRecvFlags): Integer;
var
frame: IZMQFrame;
cbWritten: LongInt;
begin
frame := TZMQFrame.Create;
try
Result := recv( frame, flags );
strm.Write(frame.data, result, @cbWritten);
finally
frame := nil;
end;
end;
function TZMQSocketImpl.Recv(var msg: IZMQFrame; flags: Integer): Integer;
var
errn: Integer;
begin
if msg = nil then
msg := TZMQFrame.Create;
if msg.size > 0 then
msg.rebuild;
Result := ZAPI.zmq_recvmsg( SocketPtr, msg.Handle, flags );
if Result < -1 then
raise EZMQException.Create('zmq_recvmsg return value less than -1.')
else
if Result = -1 then
begin
errn := ZAPI.zmq_errno;
if ( errn <> ZMQEAGAIN ) or fRaiseEAgain then
raise EZMQException.Create( errn );
end;
end;
function TZMQSocketImpl.Recv(var msgs: IZMQMsg; flags: TZMQRecvFlags): Integer;
var
msg: IZMQFrame;
bRcvMore: Boolean;
rc: Integer;
begin
if msgs = nil then
msgs := TZMQMsg.Create;
bRcvMore := True;
result := 0;
while bRcvMore do
begin
msg := TZMQFrame.create;
rc := recv( msg, flags );
if rc <> -1 then
begin
msgs.Add(msg);
inc(result);
end
else
begin
result := -1;
msg := nil;
break;
end;
bRcvMore := RcvMore;
end;
end;
function TZMQSocketImpl.Recv(var msg: WideString;
flags: TZMQRecvFlags): Integer;
var
frame: IZMQFrame;
begin
frame := TZMQFrame.Create;
try
Result := recv( frame, flags );
msg := frame.S;
finally
frame := nil;
end;
end;
function TZMQSocketImpl.RecvBuffer(var Buffer; len: size_t;
flags: TZMQRecvFlags): Integer;
var
errn: Integer;
begin
result := ZAPI.zmq_recv( SocketPtr, Buffer, len, ZMQRecvFlagsToInt(flags) );
if result < -1 then
raise EZMQException.Create('zmq_recv return value less than -1.')
else if result = -1 then
begin
errn := ZAPI.zmq_errno;
if ( errn <> ZMQEAGAIN ) or fRaiseEAgain then
raise EZMQException.Create( errn );
end;
end;
procedure __MonitorProc(ZMQMonitorRec: PZMQMonitorRec);
var
socket: TZMQSocketImpl;
msg: IZMQFrame;
msgsize: Integer;
event: zmq_event_t;
zmqEvent: TZMQEvent;
i: Integer;
begin
socket := TZMQContext(ZMQMonitorRec.context).Socket( stPair ).Implementator;
try
socket.RcvTimeout := 100; // 1 sec.
socket.connect( ZMQMonitorRec.Addr );
msg := TZMQFrame.create;
while not ZMQMonitorRec.Terminated do
begin
try
msgsize := socket.Recv( msg, [] );
if ZMQMonitorRec.Terminated then
Break;
if msgsize > -1 then
begin
CopyMemory(@event, msg.data, SizeOf(event));
i := 0;
while event.event <> 0 do
begin
event.event := event.event shr 1;
inc( i );
end;
zmqEvent.event := TZMQMonitorEvent( i - 1 );
{$IF CompilerVersion > 18.5}
zmqEvent.addr := UTF8ToString(event.addr);
{$ELSE}
zmqEvent.addr := UTF8Decode(event.addr);
{$IFEND}
zmqEvent.fd := event.fd;
if ZMQMonitorRec.Terminated then
Break;
ZMQMonitorRec.proc( zmqEvent );
msg.rebuild;
end;
except
on e: EZMQException do
if e.ErrorCode <> ZMQEAGAIN then
raise;
end;
Sleep(10);
end;
msg := nil;
finally
if not TZMQContext(ZMQMonitorRec.context).FDestroying then
socket.Free;
end;
end;
procedure TZMQSocketImpl.RegisterMonitor(proc: TZMQMonitorProc;
events: TZMQMonitorEvents);
var
tid: Cardinal;
begin
if fMonitorRec <> nil then
UnregisterMonitor;
New( fMonitorRec );
fMonitorRec.Terminated := False;
fMonitorRec.context := fContext;
fMonitorRec.Addr := 'inproc://monitor.' + IntToHex( Integer( SocketPtr ),8 );
fMonitorRec.Proc := proc;
CheckResult(ZAPI.zmq_socket_monitor( SocketPtr,
PAnsiChar( Utf8String( fMonitorRec.Addr ) ), ZMQMonitorEventsToInt(events) ) );
fMonitorThread := BeginThread( nil, 0, @__MonitorProc, fMonitorRec, 0, tid );
sleep(1);
end;
// send single or multipart message, in blocking or nonblocking mode,
// depending on the flags.
function TZMQSocketImpl.Send(const msg: WideString; flags: TZMQSendFlags): Integer;
var
frame: IZMQFrame;
begin
frame := TZMQFrame.create;
try
frame.S := msg;
Result := send( frame, flags );
finally
frame := nil;
end;
end;
function TZMQSocketImpl.Send(var msgs: IZMQMsg; dontwait: Boolean): Integer;
var
flags: TZMQSendFlags;
frame: IZMQFrame;
rc: Integer;
begin
Result := 0;
if dontwait then
flags := [sfDontWait]
else
flags := [];
while msgs.size > 0 do
begin
frame := msgs.pop;
if msgs.size = 0 then
rc := send( frame, flags )
else
rc := send( frame, flags + [sfSndMore] );
if rc = -1 then
begin
result := -1;
break;
end
else
inc( result )
end;
if result <> -1 then
msgs := nil;
end;
function TZMQSocketImpl.Send(const msg: array of WideString;
dontwait: Boolean): Integer;
var
msgs: IZMQMsg;
frame: IZMQFrame;
i: Integer;
begin
msgs := TZMQMsg.create;
try
for i := 0 to Length( msg ) - 1 do
begin
frame := TZMQFrame.create;
frame.S := msg[i];
msgs.Add( frame );
end;
Result := Send( msgs, dontwait );
finally
msgs := nil;
end;
end;
function TZMQSocketImpl.Send(var msg: IZMQFrame;
flags: TZMQSendFlags): Integer;
begin
Result := Send(msg, ZMQSendFlagsToInt(flags));
end;
function TZMQSocketImpl.Send(var msg: IZMQFrame; flags: Integer): Integer;
var
errn: Integer;
begin
Result := ZAPI.zmq_sendmsg(SocketPtr, msg.Handle, flags );
if Result < -1 then
raise EZMQException.Create('zmq_sendmsg return value less than -1.')
else
if Result = -1 then
begin
errn := ZAPI.zmq_errno;
if ( errn <> ZMQEAGAIN ) or fRaiseEAgain then
raise EZMQException.Create( errn );
end
else
msg := nil;
end;
function TZMQSocketImpl.Send(const strm: IStream; size: Integer;
flags: TZMQSendFlags): Integer;
var
frame: IZMQFrame;
cbRead: LongInt;
begin
frame := TZMQFrame.Create( size );
try
strm.Read( frame.data, size, @cbRead);
result := send( frame, flags );
finally
frame := nil;
end;
end;
function TZMQSocketImpl.SendBuffer(const Buffer; len: Size_t;
flags: TZMQSendFlags): Integer;
var
errn: Integer;
begin
result := ZAPI.zmq_send(SocketPtr, Buffer, len, ZMQSendFlagsToInt(flags));
if result < -1 then
raise EZMQException.Create('zmq_send return value less than -1.')
else
if result = -1 then
begin
errn := ZAPI.zmq_errno;
if ( errn <> ZMQEAGAIN ) or fRaiseEAgain then
raise EZMQException.Create( errn );
end;
end;
procedure TZMQSocketImpl.SetAcceptFilter(indx: Integer;
const Value: WideString);
var
i,num: Integer;
sValue: UTF8String;
begin
num := 0;
if ( indx < 0 ) or ( indx >= fAcceptFilter.Count ) then
raise EZMQException.Create( '[getAcceptFilter] Index out of bounds.' );
SetSockOpt( ZMQ_TCP_ACCEPT_FILTER, nil, 0 );
for i := 0 to fAcceptFilter.Count - 1 do
begin
try
if i <> indx then
begin
sValue := UTF8Encode(fAcceptFilter[i]);
SetSockOpt( ZMQ_TCP_ACCEPT_FILTER, @sValue[1], Length(sValue) )
end
else
begin
sValue := UTF8Encode(Value);
SetSockOpt( ZMQ_TCP_ACCEPT_FILTER, @sValue[1], Length(sValue) );
{$IF CompilerVersion > 18.5}
fAcceptFilter.Add( Value );
{$ELSE}
fAcceptFilter.Add( sValue );
{$IFEND}
end;
except
on e: EZMQException do
begin
num := e.ErrorCode;
if i = indx then
SetSockOpt( ZMQ_TCP_ACCEPT_FILTER, @fAcceptFilter[i][1], Length( fAcceptFilter[i] ) )
end
else
raise;
end;
end;
if num <> 0 then
raise EZMQException.Create( num );
end;
procedure TZMQSocketImpl.SetAffinity(const Value: UInt64);
begin
SetSockOptInt64( ZMQ_AFFINITY, Value );
end;
procedure TZMQSocketImpl.SetBacklog(const Value: Integer);
begin
SetSockOptInteger( ZMQ_BACKLOG, Value );
end;
procedure TZMQSocketImpl.SetHWM(const Value: Integer);
begin
SndHWM := Value;
RcvHWM := Value;
end;
procedure TZMQSocketImpl.SetIdentity(const Value: WideString);
var
s: UTF8String;
begin
s := UTF8Encode(Value);
SetSockOpt( ZMQ_IDENTITY, @s[1], Length( s ) );
end;
procedure TZMQSocketImpl.SetIPv4Only(const Value: Boolean);
begin
SetSockOptInteger( ZMQ_IPV4ONLY, Integer(Value) );
end;
procedure TZMQSocketImpl.SetKeepAlive(const Value: TZMQKeepAlive);
begin
SetSockOptInteger( ZMQ_TCP_KEEPALIVE, Byte(Value) - 1 );
end;
procedure TZMQSocketImpl.SetKeepAliveCnt(const Value: Integer);
begin
SetSockOptInteger( ZMQ_TCP_KEEPALIVE_CNT, Value );
end;
procedure TZMQSocketImpl.SetKeepAliveIdle(const Value: Integer);
begin
SetSockOptInteger( ZMQ_TCP_KEEPALIVE_IDLE, Value );
end;
procedure TZMQSocketImpl.SetKeepAliveIntvl(const Value: Integer);
begin
SetSockOptInteger( ZMQ_TCP_KEEPALIVE_INTVL, Value );
end;
procedure TZMQSocketImpl.SetLinger(const Value: Integer);
begin
SetSockOptInteger( ZMQ_LINGER, Value );
end;
procedure TZMQSocketImpl.SetMaxMsgSize(const Value: Int64);
begin
SetSockOptInt64( ZMQ_MAXMSGSIZE, Value );
end;
procedure TZMQSocketImpl.SetMulticastHops(const Value: Integer);
begin
SetSockOptInteger( ZMQ_MULTICAST_HOPS, Value );
end;
procedure TZMQSocketImpl.SetRaiseEAgain(const Value: Boolean);
begin
fRaiseEAgain := Value;
end;
procedure TZMQSocketImpl.SetRate(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RATE, Value );
end;
procedure TZMQSocketImpl.SetRcvBuf(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RCVBUF, Value );
end;
procedure TZMQSocketImpl.SetRcvHWM(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RCVHWM, Value );
end;
procedure TZMQSocketImpl.SetRcvTimeout(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RCVTIMEO, Value );
end;
procedure TZMQSocketImpl.SetReconnectIvl(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RECONNECT_IVL, Value );
end;
procedure TZMQSocketImpl.SetReconnectIvlMax(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RECONNECT_IVL_MAX, Value );
end;
procedure TZMQSocketImpl.SetRecoveryIvl(const Value: Integer);
begin
SetSockOptInteger( ZMQ_RECOVERY_IVL, Value );
end;
procedure TZMQSocketImpl.SetRouterMandatory(const Value: Boolean);
var
i: Integer;
begin
if Value then
i := 1
else
i := 0;
SetSockOptInteger( ZMQ_ROUTER_MANDATORY, i );
end;
procedure TZMQSocketImpl.SetSndBuf(const Value: Integer);
begin
SetSockOptInteger( ZMQ_SNDBUF, Value );
end;
procedure TZMQSocketImpl.SetSndHWM(const Value: Integer);
begin
SetSockOptInteger( ZMQ_SNDHWM, Value );
end;
procedure TZMQSocketImpl.SetSndTimeout(const Value: Integer);
begin
SetSockOptInteger( ZMQ_SNDTIMEO, Value );
end;
procedure TZMQSocketImpl.SetSockOpt(option: Integer; optval: Pointer;
optvallen: Cardinal);
begin
CheckResult(ZAPI.zmq_setsockopt(SocketPtr, option, optval, optvallen));
end;
procedure TZMQSocketImpl.SetSockOptInt64(option: Integer; const Value: Int64);
var
optvallen: size_t;
begin
optvallen := SizeOf( Value );
SetSockOpt( option, @Value, optvallen );
end;
procedure TZMQSocketImpl.SetSockOptInteger(option: Integer;
const Value: Integer);
var
optvallen: size_t;
begin
optvallen := SizeOf( Value );
SetSockOpt( option, @Value, optvallen );
end;
procedure TZMQSocketImpl.Subscribe(const filter: WideString);
begin
if filter = '' then
SetSockOpt( ZMQ_SUBSCRIBE, nil, 0 )
else
SetSockOpt( ZMQ_SUBSCRIBE, @filter[1], Length(filter)*ZMQ_CHAR_SIZE );
end;
procedure TZMQSocketImpl.Unbind(const addr: WideString);
begin
CheckResult(ZAPI.zmq_unbind(SocketPtr, PAnsiChar(UTF8String(addr))));
end;
procedure TZMQSocketImpl.UnSubscribe(const filter: WideString);
begin
if filter = '' then
SetSockOpt(ZMQ_UNSUBSCRIBE, nil, 0)
else
SetSockOpt(ZMQ_UNSUBSCRIBE, @filter[1], Length(filter)*ZMQ_CHAR_SIZE);
end;
function TZMQSocketImpl.ConnectEx(const addr: WideString): Integer;
begin
Result := ZAPI.zmq_connect(SocketPtr, PAnsiChar(UTF8Encode(addr)));
end;
{ TZMQContext }
procedure TZMQContext.CheckResult(rc: Integer);
begin
if rc = 0 then
begin
// ok
end
else
if rc = -1 then
begin
raise EZMQException.Create;
end
else
raise EZMQException.Create('Function result is not 0, or -1!');
end;
constructor TZMQContext.Create;
begin
fTerminated := false;
fMainThread := true;
varContexts.Add( Self );
fContext := ZAPI.zmq_ctx_new;
fLinger := -2;
if fContext = nil then
raise EZMQException.Create;
fSockets := TThreadList.Create;
end;
constructor TZMQContext.CreateShadow(const Context: TZMQContext);
begin
fTerminated := false;
fMainThread := false;
varContexts.Add( Self );
fContext := Context.ContextPtr;
fLinger := Context.Linger;
fSockets := TThreadList.Create;
end;
destructor TZMQContext.Destroy;
var
i: Integer;
LList: TList;
begin
if fSockets <> nil then
begin
LList := fSockets.LockList;
try
if fLinger >= -1 then
for i:= 0 to LList.Count - 1 do
TZMQSocketImpl(LList[i]).Linger := fLinger;
while LList.Count > 0 do
TZMQSocketImpl(LList[LList.Count-1]).Free;
LList.Clear;
finally
fSockets.UnlockList;
end;
FreeAndNil(fSockets);
end;
if (fContext <> nil) and fMainThread then
CheckResult(ZAPI.zmq_ctx_destroy(fContext));
fContext := nil;
varContexts.Delete(varContexts.IndexOf(Self));
inherited;
end;
function TZMQContext.GetContextPtr: Pointer;
begin
Result := fContext;
end;
function TZMQContext.GetIOThreads: Integer;
begin
Result := GetOption( ZMQ_IO_THREADS );
end;
function TZMQContext.GetLinger: Integer;
begin
Result := fLinger;
end;
function TZMQContext.GetMaxSockets: Integer;
begin
Result := GetOption( ZMQ_MAX_SOCKETS );
end;
function TZMQContext.GetOption(option: Integer): Integer;
begin
result := ZAPI.zmq_ctx_get( ContextPtr, option );
if Result = -1 then
raise EZMQException.Create
else
if Result < -1 then
raise EZMQException.Create('Function result is less than -1!');
end;
function TZMQContext.GetTerminated: Boolean;
begin
Result := fTerminated;
end;
procedure TZMQContext.RemoveSocket(const socket: TZMQSocketImpl);
var
i: Integer;
LList: TList;
begin
LList := fSockets.LockList;
try
i := LList.IndexOf(socket);
if i < 0 then
raise EZMQException.Create( 'Socket not in context' );
LList.Delete(i);
finally
fSockets.UnlockList;
end;
end;
procedure TZMQContext.SetIOThreads(const Value: Integer);
begin
SetOption( ZMQ_IO_THREADS, Value );
end;
procedure TZMQContext.SetLinger(const Value: Integer);
begin
fLinger := Value;
end;
procedure TZMQContext.SetMaxSockets(const Value: Integer);
begin
SetOption(ZMQ_MAX_SOCKETS, Value);
end;
procedure TZMQContext.SetOption(option, optval: Integer);
begin
CheckResult(ZAPI.zmq_ctx_set( ContextPtr, option, optval ) );
end;
function TZMQContext.Shadow: IZMQContext;
begin
Result := TZMQContext.CreateShadow(self);
end;
function TZMQContext.Socket(stype: TZMQSocketType): PZMQSocket;
var
LSocket: TZMQSocketImpl;
LList: TList;
begin
LList := fSockets.LockList;
try
LSocket := TZMQSocketImpl.Create();
LSocket.fSocket := ZAPI.zmq_socket(fContext, Byte(stype));
if LSocket.fSocket = nil then
begin
Result := nil;
LSocket.Free;
raise EZMQException.Create;
end;
LSocket.fContext := Self;
LList.Add(LSocket);
Result := LSocket.Data;
finally
fSockets.UnlockList;
end;
end;
procedure TZMQContext.Terminate;
var
p: Pointer;
begin
if not Terminated then
begin
fTerminated := true;
p := fContext;
fContext := nil;
if fMainThread then
CheckResult(ZAPI.zmq_ctx_destroy(p));;
end;
end;
{ TZMQPollerThread }
procedure TZMQPollerThread.AddToPollItems(const socket: TZMQSocketImpl; events: TZMQPollEvents);
begin
EnterCriticalSection(FLock);
try
if fPollItemCapacity = fPollItemCount then
begin
fPollItemCapacity := fPollItemCapacity + 10;
SetLength(fPollItem, fPollItemCapacity);
SetLength(fPollSocket, fPollItemCapacity);
end;
fPollSocket[fPollItemCount] := socket;
fPollItem[fPollItemCount].socket := socket.SocketPtr;
fPollItem[fPollItemCount].fd := 0;
fPollItem[fPollItemCount].events := ZMQPollEventsToInt(events);
fPollItem[fPollItemCount].revents := 0;
fPollItemCount := fPollItemCount + 1;
fPollNumber := fPollItemCount;
finally
LeaveCriticalSection(FLock);
end;
end;
procedure TZMQPollerThread.CheckResult(rc: Integer);
begin
if rc = -1 then
raise EZMQException.Create
else
if rc < -1 then
raise EZMQException.Create('Function result is less than -1!');
end;
constructor TZMQPollerThread.Create(aOwner: TZMQPoller; aSync: Boolean;
const aContext: IZMQContext);
begin
fOwner := aOwner;
fSync := aSync;
InitializeCriticalSection(fLock);
fOnException := nil;
if not fSync then
begin
if aContext = nil then
fContext := TZMQContext.create
else
fContext := aContext;
fAddr := 'inproc://poller' + IntToHex(Integer(Self), 8);
fPair := fContext.Socket(stPair).Implementator;
fPair.bind(fAddr);
end;
fPollItemCapacity := 10;
fPollItemCount := 0;
fPollNumber := 0;
SetLength(fPollItem, fPollItemCapacity);
SetLength(fPollSocket, fPollItemCapacity);
fTimeOut := -1;
inherited Create(fSync);
end;
procedure TZMQPollerThread.DelFromPollItems(const socket: TZMQSocketImpl;
events: TZMQPollEvents; index: Integer);
var
i: Integer;
begin
EnterCriticalSection(FLock);
try
fPollItem[index].events := fPollItem[index].events and not ZMQPollEventsToInt(events);
if fPollItem[index].events = 0 then
begin
for i := index to fPollItemCount - 2 do
begin
fPollItem[i] := fPollItem[i + 1];
fPollSocket[i] := fPollSocket[i + 1];
end;
Dec(fPollItemCount);
end;
finally
LeaveCriticalSection(FLock);
end;
end;
procedure TZMQPollerThread.Deregister(const socket: PZMQSocket;
events: TZMQPollEvents; bWait: Boolean);
var
s: WideString;
i: Integer;
begin
if fSync then
begin
i := 0;
while (i < fPollItemCount) and (fPollSocket[i].Implementator <> socket.Implementator) do
inc(i);
if i = fPollItemCount then
raise EZMQException.Create( 'socket not in pollitems!' );
DelFromPollItems(TZMQSocketImpl(socket.Implementator), events, i);
end
else
begin
if bWait then
s := cZMQPoller_SyncDeregister
else
s := cZMQPoller_Deregister;
fPair.Send([s, IntToStr(Integer(socket.Implementator)), IntToStr(ZMQPollEventsToInt(events))]);
if bWait then
fPair.recv( s );
end;
end;
destructor TZMQPollerThread.Destroy;
begin
if not fSync then
begin
fPair.send(cZMQPoller_Terminate);
fPair := nil;
fContext := nil;
end;
DeleteCriticalSection(fLock);
inherited;
end;
procedure TZMQPollerThread.Execute;
type
TTempRec = record
socket: TZMQSocketImpl;
events: TZMQPollEvents;
reg, // true if reg, false if dereg.
sync: Boolean; // if true, socket should send back a message
end;
var
LPairThread: TZMQSocketImpl;
rc: Integer;
i,j: Integer;
pes: TZMQPollEvents;
msg: IZMQMsg;
sMsg: WideString;
reglist: array of TTempRec;
reglistcap,
reglistcount: Integer;
procedure _AddToRegList(const so: TZMQSocketImpl; ev: TZMQPollEvents; reg: Boolean; sync: Boolean);
begin
if reglistcap = reglistcount then
begin
reglistcap := reglistcap + 10;
SetLength( reglist, reglistcap );
end;
reglist[reglistcount].socket := so;
reglist[reglistcount].events := ev;
reglist[reglistcount].reg := reg;
reglist[reglistcount].sync := sync;
inc( reglistcount );
end;
begin
reglistcap := 10;
reglistcount := 0;
SetLength(reglist, reglistcap);
LPairThread := fContext.Socket(stPair).Implementator;
try
LPairThread.Connect(fAddr);
fPollItemCount := 1;
fPollNumber := 1;
fPollSocket[0] := LPairThread;
fPollItem[0].socket := LPairThread.SocketPtr;
fPollItem[0].fd := 0;
fPollItem[0].events := ZMQ_POLLIN;
fPollItem[0].revents := 0;
msg := TZMQMsg.Create;
while not Terminated do
try
rc := ZAPI.zmq_poll(@fPollItem[0], fPollNumber, fTimeOut);
CheckResult(rc);
if rc = 0 then
begin
if @fOnTimeOut <> nil then
fOnTimeOut(fOwner);
end
else
begin
for i := 0 to fPollNumber - 1 do
if fPollItem[i].revents > 0 then
begin
if i = 0 then
begin
// control messages.
msg.Clear;
fPollSocket[0].recv(msg);
sMsg := msg[0].S;
if (sMsg = cZMQPoller_Register) or (sMsg = cZMQPoller_SyncRegister)then
begin
pes := IntToZMQPollEvents(msg[2].I);
_AddToRegList(TZMQSocketImpl(StrToInt(msg[1].S)), pes, True, sMsg = cZMQPoller_SyncRegister);
end
else
if (sMsg = cZMQPoller_DeRegister) or (sMsg = cZMQPoller_SyncDeRegister) then
begin
pes := IntToZMQPollEvents(msg[2].I);
_AddToRegList(TZMQSocketImpl(StrToInt(msg[1].S)), pes, False, sMsg = cZMQPoller_SyncDeRegister);
end
else
if (sMsg = cZMQPoller_PollNumber) or (sMsg = cZMQPoller_SyncPollNumber) then
begin
fPollNumber := msg[1].I;
if sMsg = cZMQPoller_SyncPollNumber then
LPairThread.send('');
end
else
if sMsg = cZMQPoller_Terminate then
Terminate;
end
else
if @fOnEvent <> nil then
begin
pes := IntToZMQPollEvents(fPollItem[i].revents);
fOnEvent(fPollSocket[i].Data, pes);
end;
end;
if reglistcount > 0 then
begin
for i := 0 to reglistcount - 1 do
begin
j := 1;
while (j < fPollItemCount) and (fPollSocket[j] <> reglist[i].socket) do
inc( j );
if j < fPollItemCount then
begin
if reglist[i].reg then
fPollItem[j].events := fPollItem[j].events or ZMQPollEventsToInt(reglist[i].events)
else
DelFromPollItems( reglist[i].socket, reglist[i].events, j );
end
else
begin
if reglist[i].reg then
AddToPollItems( reglist[i].socket, reglist[i].events )
//else
//warn not found, but want to delete.
end;
if reglist[i].sync then
LPairThread.send('');
end;
reglistcount := 0;
end;
end;
except
on e: Exception do
begin
if (e is EZMQException) and (EZMQException(e).ErrorCode = ETERM) then
Terminate;
if Assigned(fOnException) then
fOnException(e);
end;
end;
msg := nil;
finally
LPairThread.Free;
end;
end;
function TZMQPollerThread.GetPollItem(const Index: Integer): TZMQPollItem;
begin
EnterCriticalSection(fLock);
try
Result.socket := fPollSocket[Index].Data;
Byte(Result.events) := fPollItem[Index].events;
Byte(Result.revents) := fPollItem[Index].revents;
finally
LeaveCriticalSection(fLock);
end;
end;
function TZMQPollerThread.GetPollResult(
const Index: Integer): TZMQPollItem;
var
i,j: Integer;
begin
if not fSync then
raise EZMQException.Create('Poller created in Synchronous mode');
i := 0;
j := -1;
while (i < fPollItemCount) and (j < Index) do
begin
if (fPollItem[i].revents and fPollItem[i].events) > 0 then
inc(j);
if j < Index then
inc(i);
end;
Result.socket := fPollSocket[i].Data;
Byte(Result.events) := fPollItem[i].revents;
end;
function TZMQPollerThread.Poll(timeout, lPollNumber: Integer): Integer;
var
pc, i: Integer;
begin
if not fSync then
raise EZMQException.Create('Poller hasn''t created in Synchronous mode');
if fPollItemCount = 0 then
raise EZMQException.Create( 'Nothing to poll!' );
if lPollNumber = -1 then
pc := fPollItemCount
else
if (lpollNumber > -1) and (lpollNumber <= fPollItemCount) then
pc := lpollNumber
else
raise EZMQException.Create( 'wrong pollCount parameter.' );
for i := 0 to fPollItemCount - 1 do
fPollItem[i].revents := 0;
Result := ZAPI.zmq_poll(@fPollItem[0], pc, timeout);
if result < 0 then
raise EZMQException.Create
end;
procedure TZMQPollerThread.Register(const socket: PZMQSocket;
events: TZMQPollEvents; bWait: Boolean);
var
s: WideString;
begin
if fSync then
AddToPollItems(socket.Implementator, events)
else
begin
if bWait then
s := cZMQPoller_SyncRegister
else
s := cZMQPoller_Register;
fPair.Send([s, IntToStr(Integer(socket.Implementator)), IntToStr(ZMQPollEventsToInt(events))]);
if bWait then
fPair.recv(s);
end;
end;
procedure TZMQPollerThread.SetPollNumber(const Value: Integer;
bWait: Boolean);
var
s: WideString;
begin
if fSync then
fPollNumber := Value
else
begin
if bWait then
s := cZMQPoller_PollNumber
else
s := cZMQPoller_SyncPollNumber;
fPair.Send([s, IntToStr(Value)]);
if bWait then
fPair.Recv(s);
end;
end;
{ TZMQPoller }
constructor TZMQPoller.Create(aSync: Boolean; const aContext: IZMQContext);
begin
FThread := TZMQPollerThread.Create(Self, aSync, aContext);
end;
destructor TZMQPoller.Destroy;
begin
if (FThread <> nil) and (not FThread.FreeOnTerminate) then
FreeAndNil(FThread);
FThread := nil;
inherited;
end;
function TZMQPoller.GetFreeOnTerminate: Boolean;
begin
Result := FThread.FreeOnTerminate;
end;
function TZMQPoller.GetHandle: THandle;
begin
Result := FThread.Handle;
end;
function TZMQPoller.GetOnEvent: TZMQPollEventProc;
begin
Result := FThread.OnEvent;
end;
function TZMQPoller.GetOnException: TZMQExceptionProc;
begin
Result := FThread.OnException;
end;
function TZMQPoller.GetOnTerminate: TNotifyEvent;
begin
Result := FThread.OnTerminate;
end;
function TZMQPoller.GetOnTimeOut: TZMQTimeOutProc;
begin
Result := FThread.OnTimeOut;
end;
function TZMQPoller.GetPollItem(const Index: Integer): TZMQPollItem;
begin
Result := FThread.PollItem[index];
end;
function TZMQPoller.GetPollNumber: Integer;
begin
Result := FThread.PollNumber;
end;
function TZMQPoller.GetPollResult(const Index: Integer): TZMQPollItem;
begin
Result := FThread.GetPollResult(Index);
end;
function TZMQPoller.GetSuspended: Boolean;
begin
Result := FThread.Suspended;
end;
function TZMQPoller.GetThreadID: THandle;
begin
Result := FThread.ThreadID;
end;
function TZMQPoller.Poll(timeout, lPollNumber: Integer): Integer;
begin
Result := FThread.Poll(timeout, lPollNumber)
end;
procedure TZMQPoller.Register(const socket: PZMQSocket;
const events: TZMQPollEvents; bWait: Boolean);
begin
FThread.Register(socket, events, bWait);
end;
procedure TZMQPoller.Resume;
begin
{$WARNINGS OFF}
FThread.Resume;
{$WARNINGS ON}
end;
procedure TZMQPoller.SetFreeOnTerminate(const Value: Boolean);
begin
FThread.FreeOnTerminate := Value;
end;
procedure TZMQPoller.SetOnEvent(const AValue: TZMQPollEventProc);
begin
FThread.OnEvent := AValue;
end;
procedure TZMQPoller.SetOnException(const AValue: TZMQExceptionProc);
begin
FThread.OnException := AValue;
end;
procedure TZMQPoller.SetOnTerminate(const Value: TNotifyEvent);
begin
FThread.OnTerminate := Value;
end;
procedure TZMQPoller.SetOnTimeOut(const AValue: TZMQTimeOutProc);
begin
FThread.OnTimeOut := AValue;
end;
procedure TZMQPoller.SetPollNumber(const AValue: Integer);
begin
FThread.SetPollNumber(AValue, False);
end;
procedure TZMQPoller.SetPollNumberAndWait(const Value: Integer);
begin
FThread.SetPollNumber(Value, True);
end;
procedure TZMQPoller.SetSuspended(const Value: Boolean);
begin
FThread.Suspended := Value;
end;
procedure TZMQPoller.Suspend;
begin
{$WARNINGS OFF}
FThread.Suspend;
{$WARNINGS ON}
end;
procedure TZMQPoller.Terminate;
begin
FThread.Terminate;
end;
procedure TZMQPoller.Unregister(const socket: PZMQSocket;
const events: TZMQPollEvents; bWait: Boolean);
begin
FThread.Deregister(socket, events, bWait);
end;
function TZMQPoller.WaitFor: LongWord;
begin
Result := FThread.WaitFor;
end;
{ TZMQThread }
constructor TZMQThread.Create(lArgs: Pointer; const ctx: IZMQContext);
begin
FThread := TZMQInternalThread.Create(lArgs, ctx);
end;
constructor TZMQThread.CreateAttached(lAttachedMeth: TAttachedThreadMethod;
const ctx: IZMQContext; lArgs: Pointer);
begin
FThread := TZMQInternalThread.CreateAttached(lAttachedMeth, ctx, lArgs);
end;
constructor TZMQThread.CreateAttachedProc(
lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext;
lArgs: Pointer);
begin
FThread := TZMQInternalThread.CreateAttachedProc(lAttachedProc, ctx, lArgs);
end;
constructor TZMQThread.CreateDetached(lDetachedMeth: TDetachedThreadMethod;
lArgs: Pointer);
begin
FThread := TZMQInternalThread.CreateDetached(lDetachedMeth, lArgs);
end;
constructor TZMQThread.CreateDetachedProc(
lDetachedProc: TDetachedThreadProc; lArgs: Pointer);
begin
FThread := TZMQInternalThread.CreateDetachedProc(lDetachedProc, lArgs);
end;
destructor TZMQThread.Destroy;
begin
if (FThread <> nil) and (not FThread.FreeOnTerminate) then
FreeAndNil(FThread);
inherited;
end;
function TZMQThread.GetArgs: Pointer;
begin
Result := FThread.Args;
end;
function TZMQThread.GetContext: IZMQContext;
begin
Result := FThread.Context;
end;
function TZMQThread.GetFreeOnTerminate: Boolean;
begin
Result := FThread.FreeOnTerminate;
end;
function TZMQThread.GetHandle: THandle;
begin
Result := FThread.Handle;
end;
function TZMQThread.GetOnExecute: TZMQThreadExecuteMethod;
begin
Result := FThread.OnExecute;
end;
function TZMQThread.GetOnTerminate: TNotifyEvent;
begin
Result := FThread.OnTerminate;
end;
function TZMQThread.GetPipe: PZMQSocket;
begin
Result := FThread.Pipe.Data;
end;
function TZMQThread.GetSuspended: Boolean;
begin
Result := FThread.Suspended;
end;
function TZMQThread.GetThreadID: THandle;
begin
Result := FThread.ThreadID;
end;
procedure TZMQThread.Resume;
begin
{$WARNINGS OFF}
FThread.Resume;
{$WARNINGS ON}
end;
procedure TZMQThread.SetFreeOnTerminate(const AValue: Boolean);
begin
FThread.FreeOnTerminate := AValue;
end;
procedure TZMQThread.SetOnExecute(const AValue: TZMQThreadExecuteMethod);
begin
FThread.OnExecute := AValue;
end;
procedure TZMQThread.SetOnTerminate(const AValue: TNotifyEvent);
begin
FThread.OnTerminate := AValue;
end;
procedure TZMQThread.SetSuspended(const AValue: Boolean);
begin
FThread.Suspended := AValue;
end;
procedure TZMQThread.Suspend;
begin
{$WARNINGS OFF}
FThread.Suspend;
{$WARNINGS ON}
end;
procedure TZMQThread.Terminate;
begin
FThread.Terminate;
end;
function TZMQThread.WaitFor: LongWord;
begin
Result := FThread.WaitFor;
end;
{ TZMQInternalThread }
constructor TZMQInternalThread.Create(lArgs: Pointer;
const ctx: IZMQContext);
begin
inherited Create(True);
fArgs := lArgs;
if ctx = nil then
fContext := TZMQContext.Create
else
begin
fContext := ctx.Shadow;
fPipe := Context.Socket(stPair).Implementator;
fPipe.Bind(Format( 'inproc://zmqthread-pipe-%p', [@fPipe]));
end;
end;
constructor TZMQInternalThread.CreateAttached(
lAttachedMeth: TAttachedThreadMethod; const ctx: IZMQContext;
lArgs: Pointer);
begin
Create(lArgs, ctx);
fAttachedMeth := lAttachedMeth;
end;
constructor TZMQInternalThread.CreateAttachedProc(
lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext;
lArgs: Pointer);
begin
Create(lArgs, ctx);
fAttachedProc := lAttachedProc;
end;
constructor TZMQInternalThread.CreateDetached(
lDetachedMeth: TDetachedThreadMethod; lArgs: Pointer);
begin
Create(lArgs, nil);
fDetachedMeth := lDetachedMeth;
end;
constructor TZMQInternalThread.CreateDetachedProc(
lDetachedProc: TDetachedThreadProc; lArgs: Pointer);
begin
Create(lArgs, nil);
fDetachedProc := lDetachedProc;
end;
destructor TZMQInternalThread.Destroy;
begin
fContext := nil;
inherited;
end;
procedure TZMQInternalThread.DoExecute;
begin
if @fAttachedMeth <> nil then
fAttachedMeth(fArgs, Context, thrPipe.Data)
else
if @fDetachedMeth <> nil then
fDetachedMeth(fArgs, Context)
else
if @fAttachedProc <> nil then
fAttachedProc(fArgs, Context, thrPipe.Data)
else
if @fDetachedProc <> nil then
fDetachedProc(fArgs, Context);
end;
procedure TZMQInternalThread.Execute;
begin
if @fOnExecute <> nil then
fOnExecute(Self)
else
if (@fAttachedProc <> nil) or (@fAttachedMeth <> nil) then
begin // attached thread
thrPipe := Context.Socket(stPair).Implementator;
thrPipe.Connect(Format('inproc://zmqthread-pipe-%p', [@fPipe]));
end;
DoExecute;
end;
{ TZMQMananger }
function TZMQMananger.CreateFrame: IZMQFrame;
begin
Result := TZMQFrame.Create;
end;
function TZMQMananger.CreateFrame(size: Cardinal): IZMQFrame;
begin
Result := TZMQFrame.Create(size);
end;
function TZMQMananger.CreateContext: IZMQContext;
begin
Result := TZMQContext.Create;
end;
function TZMQMananger.CreateFrame(data: Pointer; size: Cardinal;
ffn: TZMQFreeProc; hint: Pointer): IZMQFrame;
begin
Result := TZMQFrame.Create(data, size, ffn, hint);
end;
function TZMQMananger.CreateMsg: IZMQMsg;
begin
Result := TZMQMsg.Create;
end;
procedure TZMQMananger.Device(device: TZMQDevice; const insocket,
outsocket: PZMQSocket);
begin
if ZAPI.zmq_device(Ord(device), insocket.Socket, outsocket.Socket) <> -1 then
raise EZMQException.Create( 'Device does not return -1' );
end;
function TZMQMananger.GetTerminated: Boolean;
begin
Result := FTerminated;
end;
function TZMQMananger.GetVersion: TZMQVersion;
begin
ZAPI.zmq_version(Result.major, Result.minor, Result.patch);
end;
function TZMQMananger.Poll(var pia: TZMQPollItemArray; timeout: Integer): Integer;
var
PollItem: array of zmq_pollitem_t;
i,l,n: Integer;
begin
l := Length( pia );
if l = 0 then
raise EZMQException.Create( 'Nothing to poll!' );
SetLength( PollItem, l );
try
for i := 0 to l - 1 do
begin
PollItem[i].socket := pia[i].Socket.Socket;
PollItem[i].fd := 0;
PollItem[i].events := ZMQPollEventsToInt( pia[i].events );
PollItem[i].revents := 0;
end;
n := l;
result := ZAPI.zmq_poll(@PollItem[0], n, timeout);
if result < 0 then
raise EZMQException.Create;
for i := 0 to l - 1 do
pia[i].revents := IntToZMQPollEvents(PollItem[i].revents);
finally
PollItem := nil;
end;
end;
function TZMQMananger.Poll(var pi: TZMQPollItem; timeout: Integer): Integer;
var
PollItem: zmq_pollitem_t;
begin
PollItem.socket := pi.Socket.Socket;
PollItem.fd := 0;
PollItem.events := ZMQPollEventsToInt( pi.events );
PollItem.revents := 0;
result := ZAPI.zmq_poll(@PollItem, 1, timeout );
if result < 0 then
raise EZMQException.Create;
pi.revents := IntToZMQPollEvents(PollItem.revents);
end;
procedure TZMQMananger.Proxy(const frontend, backend, capture: PZMQSocket);
var
p: Pointer;
begin
if capture <> nil then
p := capture.Socket
else
p := nil;
if ZAPI.zmq_proxy(frontend.Socket, backend.Socket, p) <> -1 then
raise EZMQException.Create('Proxy does not return -1');
end;
procedure TZMQMananger.SetTerminated(const Value: Boolean);
begin
FTerminated := Value;
end;
procedure TZMQMananger.Terminate;
begin
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
end;
function TZMQMananger.CreatePoller(aSync: Boolean;
const aContext: IZMQContext): IZMQPoller;
begin
Result := TZMQPoller.Create(aSync, aContext);
end;
function TZMQMananger.CreateAttached(lAttachedMeth: TAttachedThreadMethod;
const ctx: IZMQContext; lArgs: Pointer): IZMQThread;
begin
Result := TZMQThread.CreateAttached(lAttachedMeth, ctx, lArgs);
end;
function TZMQMananger.CreateAttachedProc(
lAttachedProc: TAttachedThreadProc; const ctx: IZMQContext;
lArgs: Pointer): IZMQThread;
begin
Result := TZMQThread.CreateAttachedProc(lAttachedProc, ctx, lArgs);
end;
function TZMQMananger.CreateDetached(lDetachedMeth: TDetachedThreadMethod;
lArgs: Pointer): IZMQThread;
begin
Result := TZMQThread.CreateDetached(lDetachedMeth, lArgs);
end;
function TZMQMananger.CreateDetachedProc(
lDetachedProc: TDetachedThreadProc; lArgs: Pointer): IZMQThread;
begin
Result := TZMQThread.CreateDetachedProc(lDetachedProc, lArgs);
end;
function TZMQMananger.CreateThread(lArgs: Pointer;
const ctx: IZMQContext): IZMQThread;
begin
Result := TZMQThread.Create(lArgs, ctx);
end;
function TZMQMananger.IsZMQException(AExcetpion: Exception): Boolean;
begin
Result := AExcetpion is EZMQException;
end;
function TZMQMananger.GetDriverFile: WideString;
begin
Result := varDriverFile;
end;
procedure TZMQMananger.SetDriverFile(const Value: WideString);
begin
varDriverFile := Value;
end;
procedure TZMQMananger.Sleep(const seconds: Integer);
begin
ZAPI.zmq_sleep(seconds);
end;
function TZMQMananger.StartStopWatch: Pointer;
begin
Result := ZAPI.zmq_stopwatch_start;
end;
function TZMQMananger.StopStopWatch(watch: Pointer): LongWord;
begin
Result := ZAPI.zmq_stopwatch_stop(watch);
end;
procedure TZMQMananger.FreeAndNilSocket(var socket: PZMQSocket);
var
s: TZMQSocketImpl;
begin
s := TZMQSocketImpl(socket.Implementator);
socket := nil;
s.Free;
end;
function TZMQMananger.GetContext: IZMQContext;
begin
if FContext = nil then
FContext := ZMQ.CreateContext;
Result := FContext;
end;
initialization
varContexts := TList.Create;
Windows.SetConsoleCtrlHandler(@Console_handler, True);
_RegZmqClass;
finalization
_UnregZmqClass;
varContexts.Free;
end.
|
program carre_magic;
uses crt;
{nb lignes et colonnes}
const Nb_lign_col=5;
{le tableau du carré magique}
TYPE carre_tab=array[1..Nb_lign_col, 1..Nb_lign_col] of integer;
var somme : integer;
{affiche le carré à l'écran }
procedure AffichCarre(tab:carre_tab; nb:integer);
var i, j : integer;
BEGIN
for i:=1 to nb do
begin
for j:=1 to nb do
begin
write(tab[i,j], Nb_lign_col);
end;
writeln;
end;
writeln;
END;
function VerifCarreMagique(tab:carre_tab; nb:integer): boolean;
var i, j, somme, magic : integer;
result : boolean;
BEGIN
result := true;
{somme def par la diagonale}
somme := 0;
for i := 1 to nb do
begin
somme := somme + tab[i,i];
end;
magic := somme;
{voir si c'est bien la même dans les autres colonnes, lignes et dia}
somme := 0;
for i := 1 to nb do
begin
somme := somme + tab[i,nb-i+1];
end;
if somme <> magic then
begin
result := false;
end;
for i := 1 to nb do
begin
somme:= 0;
for j := 1 to nb do
begin
somme := somme + tab[i,j];
end;
if somme <> magic then
begin
result := false;
end;
end;
for j := 1 to nb do
begin
somme:= 0;
for i := 1 to nb do
begin
somme := somme + tab[i,j];
end;
if somme <> magic then
begin
result := false;
end;
end;
VerifCarreMagique := result;
END;
function VraiCarre(tab : carre_tab; nb : integer): boolean;
var i, j , k: integer;
result : boolean;
carre : array[1..(Nb_lign_col*Nb_lign_col)] of boolean;
BEGIN
result := true;
{ init de tab }
for k := 1 to nb*nb do carre[k] := false;
{ parcours tableau }
for i := 1 to nb do
begin
for j := 1 to nb do
begin
k := tab[i,j];
if (k < 1) or (k > nb*nb) then
begin
result := false
end
else if carre[k] then
begin
result := false
end
else carre[k] := true;
end;
end;
VraiCarre := result;
END;
BEGIN
write('La somme magique est ', somme);
readln(somme);
END.
|
unit uFractionsTests;
interface
uses
DUnitX.TestFramework
, uFractions
;
type
[TestFixture]
TFractionTests = class(TObject)
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestSimpleAddition;
[Test]
procedure TestWhereResultBiggerThanOne;
[Test]
procedure TestSimpleSubtraction;
[Test]
procedure TestSubtractionResultLessThanZero;
[Test]
procedure TestSimpleMultiplication;
[Test]
procedure TestSimpleDivision;
[Test]
procedure TestSimpleNegation;
[Test]
procedure TestEquals;
[Test]
procedure TestNotEquals;
[Test]
procedure TestLessThanOrEqualsWhenEqual;
[Test]
procedure TestGreaterThanOrEqualsWhenEqual;
[Test]
procedure TestLessThanOrEqualsWhenLessThan;
[Test]
procedure TestGreaterThanOrEqualsWhenGreaterThan;
[Test]
procedure TestImplicitAssignement;
[Test]
procedure TestImplicitFromInteger;
[Test]
procedure TestAddDouble;
[Test]
procedure TestImplicitAssignmentDouble;
[Test]
procedure TestLessThan;
[Test]
procedure TestGreaterThan;
[Test]
procedure TestBothAreNegativeMeansAPositive;
[Test]
procedure TestNumeratorIsNegativeAndResultIsNegative;
[Test]
procedure TestDenominatorNegativeMeansANegative;
[Test]
procedure TestNegativeGetsMovedToNumerator;
[Test]
procedure TestNegativeWithNegativeDenominator;
[Test]
procedure TestNegativeWithNegativeNumerator;
[Test]
procedure TestNegativeWithBothNegative;
end;
implementation
procedure TFractionTests.Setup;
begin
end;
procedure TFractionTests.TearDown;
begin
end;
procedure TFractionTests.TestSimpleMultiplication;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(5, 2);
b := TFraction.CreateFrom(1, 3);
c := a * b;
Assert.AreEqual(5, c.Numerator);
Assert.AreEqual(6, c.Denominator);
end;
procedure TFractionTests.TestSimpleNegation;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := -a;
Assert.AreEqual(-1, b.Numerator);
Assert.AreEqual(2, b.Denominator);
end;
procedure TFractionTests.TestAddDouble;
var
a: TFraction;
Actual: Double;
Expected: Double;
begin
a := TFraction.CreateFrom(1, 3);
Actual := a + 0.5;
Expected := 5/6;
Assert.AreEqual(Expected, Actual);
end;
procedure TFractionTests.TestBothAreNegativeMeansAPositive;
var
a: TFraction;
begin
a := TFraction.CreateFrom(-1, -2);
Assert.Istrue(a > 0);
Assert.AreEqual(a.Numerator, 1);
Assert.AreEqual(a.Denominator, 2);
end;
procedure TFractionTests.TestDenominatorNegativeMeansANegative;
var
a: TFraction;
begin
a := TFraction.CreateFrom(1, -2);
Assert.Istrue(a < 0);
end;
procedure TFractionTests.TestEquals;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(2, 4);
Assert.Istrue(a = b);
end;
procedure TFractionTests.TestGreaterThan;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(24, 25);
b := TFraction.CreateFrom(2, 5);
Assert.Istrue(a > b);
end;
procedure TFractionTests.TestGreaterThanOrEqualsWhenEqual;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(2, 4);
Assert.Istrue(a >= b);
end;
procedure TFractionTests.TestGreaterThanOrEqualsWhenGreaterThan;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(2, 9);
Assert.Istrue(a >= b);
end;
procedure TFractionTests.TestImplicitAssignement;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := a;
Assert.IsTrue(a = b);
end;
procedure TFractionTests.TestImplicitAssignmentDouble;
var
a: TFraction;
D: Double;
begin
a := TFraction.CreateFrom(1, 2);
D := a;
Assert.IsTrue(D = 0.5);
end;
procedure TFractionTests.TestImplicitFromInteger;
var
a: TFraction;
begin
a := 4;
Assert.AreEqual(4, a.Numerator);
Assert.AreEqual(1, a.Denominator);
end;
procedure TFractionTests.TestLessThan;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 200);
b := TFraction.CreateFrom(2, 4);
Assert.Istrue(a < b);
end;
procedure TFractionTests.TestLessThanOrEqualsWhenEqual;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(2, 4);
Assert.Istrue(a <= b);
end;
procedure TFractionTests.TestLessThanOrEqualsWhenLessThan;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 100);
b := TFraction.CreateFrom(2, 9);
Assert.Istrue(a <= b);
end;
procedure TFractionTests.TestNegativeWithBothNegative;
var
a: TFraction;
begin
a := TFraction.CreateFrom(-1, -2);
a := -a;
Assert.IsTrue(a < 0);
end;
procedure TFractionTests.TestNegativeWithNegativeDenominator;
var
a: TFraction;
begin
a := TFraction.CreateFrom(1, -2);
a := -a;
Assert.IsTrue(a > 0);
end;
procedure TFractionTests.TestNegativeWithNegativeNumerator;
var
a: TFraction;
begin
a := TFraction.CreateFrom(-1, 2);
a := -a;
Assert.IsTrue(a > 0);
end;
procedure TFractionTests.TestNegativeGetsMovedToNumerator;
var
a: TFraction;
begin
a := TFraction.CreateFrom(1, -2);
Assert.AreEqual(a.Numerator, -1);
Assert.AreEqual(a.Denominator, 2);
end;
procedure TFractionTests.TestNotEquals;
var
a, b: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(37, 992);
Assert.Istrue(a <> b);
end;
procedure TFractionTests.TestNumeratorIsNegativeAndResultIsNegative;
var
a: TFraction;
begin
a := TFraction.CreateFrom(-1, 2);
Assert.Istrue(a < 0);
end;
procedure TFractionTests.TestSimpleAddition;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(1, 2);
b := TFraction.CreateFrom(1, 3);
c := a + b;
Assert.AreEqual(5, c.Numerator);
Assert.AreEqual(6, c.Denominator);
end;
procedure TFractionTests.TestSimpleDivision;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(5, 6);
b := TFraction.CreateFrom(1, 3);
c := a / b;
Assert.AreEqual(5, c.Numerator);
Assert.AreEqual(2, c.Denominator);
end;
procedure TFractionTests.TestSimpleSubtraction;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(5, 6);
b := TFraction.CreateFrom(1, 3);
c := a - b;
Assert.AreEqual(1, c.Numerator);
Assert.AreEqual(2, c.Denominator);
end;
procedure TFractionTests.TestSubtractionResultLessThanZero;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(1, 3);
b := TFraction.CreateFrom(5, 6);
c := a - b;
Assert.AreEqual(-1, c.Numerator);
Assert.AreEqual(2, c.Denominator);
end;
procedure TFractionTests.TestWhereResultBiggerThanOne;
var
a, b, c: TFraction;
begin
a := TFraction.CreateFrom(5, 6);
b := TFraction.CreateFrom(1, 3);
c := a + b;
Assert.AreEqual(7, c.Numerator);
Assert.AreEqual(6, c.Denominator);
end;
initialization
TDUnitX.RegisterTestFixture(TFractionTests);
end.
|
unit uMethodFactory;
interface
uses
uSmartPhone
;
type
TSmartPhoneFactory = class of TBaseSmartPhone;
TSmartPhoneAssemblyPlant = class
class function MakeUnAssembledSmartPhone(aSmartPhoneFactory: TSmartPhoneFactory): TBaseSmartPhone;
class function MakeAssembledSmartPhone(aSmartPhoneFactory: TSmartPhoneFactory): TBaseSmartPhone;
end;
procedure DoItAgain;
implementation
procedure DoItAgain;
var
SmartPhone: TBaseSmartPhone;
begin
SmartPhone := TSmartPhoneAssemblyPlant.MakeUnAssembledSmartPhone(TDeluxeSmartPhone);
SmartPhone.GatherParts;
SmartPhone.Assemble;
WriteLn(SmartPhone.Name, ' is completely assembled');
WriteLn;
SmartPhone := TSmartPhoneAssemblyPlant.MakeAssembledSmartPhone(TCheapCrappySmartPhone);
// Phone is already assembled.
WriteLn(SmartPhone.Name, ' is completely assembled');
end;
{ TSmartPhoneAssemblyPlant }
class function TSmartPhoneAssemblyPlant.MakeAssembledSmartPhone(aSmartPhoneFactory: TSmartPhoneFactory): TBaseSmartPhone;
begin
Result := aSmartPhoneFactory.Create;
Result.GatherParts;
Result.Assemble;
end;
class function TSmartPhoneAssemblyPlant.MakeUnAssembledSmartPhone(aSmartPhoneFactory: TSmartPhoneFactory): TBaseSmartPhone;
begin
Result := aSmartPhoneFactory.Create;
end;
end.
|
unit Thread.ImportaBancasJones;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil, Messages, Controls, System.DateUtils, System.StrUtils,
Model.DistribuidorVA, DAO.DistribuidorVA, Model.BancaVA, DAO.BancaVA, System.Generics.Collections;
type
Thread_ImportaBancasJones = class(TThread)
private
{ Private declarations }
FArquivo: String;
FErro: TStringList;
FdPos: Double;
banca : TBancaVA;
bancaTMP: TBancaVA;
bancas : TObjectList<TBancaVA>;
bancaDAO : TBancaVADAO;
distribuidor : TDistribuidorVA;
distribuidorTMP: TDistribuidorVA;
distribuidores : TObjectList<TDistribuidorVA>;
distribuidorDAO : TDistribuidorVADAO;
protected
procedure Execute; override;
procedure IniciaProcesso;
procedure AtualizaLog(sTexto: String);
procedure AtualizaProgress;
procedure TerminaProcesso;
function TrataLinha(sLinha: String): String;
procedure PopulaDistribuidor;
public
property Arquivo: String read FArquivo write FArquivo;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure thrImportarEntregas.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ thrImportarEntregas }
uses
View.CadastroBanca, uGlobais, udm, View.ResultatoProcesso;
function Thread_ImportaBancasJones.TrataLinha(sLinha: String): String;
var
iConta: Integer;
sLin: String;
bFlag: Boolean;
begin
if Pos('"', sLinha) = 0 then
begin
Result := sLinha;
Exit;
end;
iConta := 1;
bFlag := False;
sLin := '';
while sLinha[iConta] >= ' ' do
begin
if sLinha[iConta] = '"' then
begin
if bFlag then
bFlag := False
else
bFlag := True;
end;
if bFlag then
begin
if sLinha[iConta] = ';' then
sLin := sLin + ' '
else
sLin := sLin + sLinha[iConta];
end
else
sLin := sLin + sLinha[iConta];
Inc(iConta);
end;
Result := sLin;
end;
procedure Thread_ImportaBancasJones.Execute;
var
ArquivoCSV: TextFile;
sDetalhe: TStringList;
sLogB: TStringList;
sLogd: TStringList;
sCEP: String;
sEndereco: String;
sCidade: String;
sEstado: String;
sLinha: String;
iLinhasTotal: Integer;
iContador : Integer;
iPos: Integer;
bFlagBanca: Boolean;
begin
Synchronize(IniciaProcesso);
Screen.Cursor := crHourGlass;
iLinhasTotal := TUtil.NumeroDeLinhasTXT(FArquivo);
// Carregando o arquivo ...
AssignFile(ArquivoCSV, FArquivo);
try
banca := TBancaVA.Create();
bancaDAO := TBancaVADAO.Create();
distribuidor := TDistribuidorVA.Create();
distribuidorDAO := TDistribuidorVADAO.Create();
sLogB := TStringList.Create;
sLogD := TStringList.Create;
FErro := TStringList.Create;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
if Copy(sLinha, 0, 23) <> 'Bancas por Distribuidor' then
begin
MessageDlg
('Arquivo informado não foi identificado como a Planila de Bancas por Distribuidor do Jones!', mtWarning, [mbOK], 0);
Abort;
end;
Readln(ArquivoCSV, sLinha);
iContador := 2;
FdPos := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
if TUtil.ENumero(sDetalhe[0]) then
begin
sLogB.Clear;
sLogD.Clear;
iPos := Pos('CEP:',sDetalhe[10]) + 5;
sCEP := Trim(Copy(sDetalhe[10], iPos, 5)) + '-' + Trim(Copy(sDetalhe[10], iPos + 6, 3));
sEndereco := Trim(Copy(sDetalhe[10], 0, iPos - 9));
iPos := Pos(' - ',sDetalhe[11]);
sCidade := Trim(Copy(sDetalhe[11],0,iPos));
sEstado := Trim(Copy(sDetalhe[11], iPos + 3, 2));
banca.ID := 0;
banca.Codigo := StrToIntDef(sDetalhe[4],0);
banca.Distribuidor := StrToIntDef(sDetalhe[0],0);
banca.Nome := sDetalhe[5];
banca.CEP := sCEP;
banca.Endereco := sEndereco;
banca.Complemento := '';
banca.Bairro := '';
banca.Cidade := sCidade;
banca.Estado := sEstado;
banca.Ordem := TUtil.AlinhaD(Trim(sDetalhe[3]),10);
bancas := bancaDAO.FindByCodigo(banca.Codigo);
if bancas.Count > 0 then
begin
banca.ID := bancas[0].ID;
sLogB.Text := bancas[0].Log;
end;
distribuidor.ID := 0;
distribuidor.Codigo := StrToIntDef(sDetalhe[0],0);
distribuidor.Nome := sDetalhe[1];
distribuidores := distribuidorDAO.FindByCodigo(StrToIntDef(sDetalhe[0],0));
if distribuidores.Count > 0 then
begin
distribuidor.ID := distribuidores[0].ID;
sLogD.Text := distribuidores[0].Log;
end;
bFlagBanca := True;
if distribuidor.ID = 0 then
begin
sLogD.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' inserido por importação de planilha Jones por ' +
uGlobais.sUsuario);
distribuidor.Log := sLogD.Text;
if not distribuidorDAO.Insert(distribuidor) then
begin
AtualizaLog('Erro ao incluir Distribuidor código ' + IntToStr(distribuidor.Codigo));
bFlagBanca := False;
end;
{ end
else
begin
sLogD.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' alterado por importação de planilha Jones por ' +
uGlobais.sUsuario);
distribuidor.Log := sLogD.Text;
if not distribuidorDAO.Update(distribuidor) then
begin
AtualizaLog('Erro ao alterar Distribuidor código ' + IntToStr(distribuidor.Codigo));
bFlagBanca := False;
end;}
end;
if bFlagBanca then
begin
if banca.ID = 0 then
begin
sLogB.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' inserida por importação de planilha Jones por ' +
uGlobais.sUsuario);
banca.Log := sLogB.Text;
if not bancaDAO.Insert(banca) then
begin
AtualizaLog('Erro ao incluir Banca código ' + IntToStr(banca.Codigo));
end;
{end
else
begin
sLogB.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' alterada por importação de planilha Jones por ' +
uGlobais.sUsuario);
banca.Log := sLogB.Text;
if not bancaDAO.Update(banca) then
begin
AtualizaLog('Erro ao alterar Banca código ' + IntToStr(banca.Codigo));
end;}
end;
end;
end;
iContador := iContador + 1;
FdPos := (iContador / iLinhasTotal) * 100;
Synchronize(AtualizaProgress);
end;
finally
CloseFile(ArquivoCSV);
Screen.Cursor := crDefault;
Application.MessageBox('Importação concluída!', 'Importação Planilha Jones', MB_OK + MB_ICONINFORMATION);
banca.Free;
bancaDAO.Free;
distribuidor.Free;
distribuidorDAO.Free;
Synchronize(TerminaProcesso);
end;
end;
procedure Thread_ImportaBancasJones.IniciaProcesso;
begin
view_CadastroBanca.pbBanca.Visible := True;
view_CadastroBanca.pbBanca.Position := 0;
view_CadastroBanca.pbBanca.Refresh;
view_CadastroBanca.Modo('M');
end;
procedure Thread_ImportaBancasJones.AtualizaLog(sTexto: String);
begin
FErro.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' ' + sTexto)
end;
procedure Thread_ImportaBancasJones.AtualizaProgress;
begin
view_CadastroBanca.pbBanca.Position := FdPos;
view_CadastroBanca.pbBanca.Properties.Text := FormatFloat('0.00%',FdPos);
view_CadastroBanca.pbBanca.Refresh;
end;
procedure Thread_ImportaBancasJones.TerminaProcesso;
begin
PopulaDistribuidor;
view_CadastroBanca.pbBanca.Position := 0;
view_CadastroBanca.pbBanca.Properties.Text := '';
view_CadastroBanca.pbBanca.Visible := False;
view_CadastroBanca.pbBanca.Refresh;
view_CadastroBanca.bFlagImporta := False;
view_CadastroBanca.Modo('');
if FErro.Count > 0 then
begin
if not Assigned(view_ResultadoProcesso) then
begin
view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application);
end;
view_ResultadoProcesso.edtResultado.Text := FErro.Text;
view_ResultadoProcesso.ShowModal;
FreeAndNil(view_ResultadoProcesso);
FErro.Clear;
end;
end;
procedure Thread_ImportaBancasJones.PopulaDistribuidor;
var
distribuidorTMP: TDistribuidorVA;
distribuidores: TObjectList<TDistribuidorVA>;
distribuidorDAO: TDistribuidorVADAO;
begin
distribuidorDAO := TDistribuidorVADAO.Create();
if dm.tbDistribuidorVA.Active then dm.tbDistribuidorVA.Close;
dm.tbDistribuidorVA.Open;
distribuidorTMP := TDistribuidorVA.Create();
distribuidores := distribuidorDAO.FindByID(-1);
for distribuidorTMP in distribuidores do
begin
dm.tbDistribuidorVA.Insert;
dm.tbDistribuidorVAID_DISTRIBUIDOR.AsInteger := distribuidorTMP.ID;
dm.tbDistribuidorVACOD_DISTRIBUIDOR.AsInteger := distribuidorTMP.Codigo;
dm.tbDistribuidorVANOM_DISTRIBUIDOR.AsString := distribuidorTMP.Nome;
dm.tbDistribuidorVA.Post;
end;
end;
end.
|
unit unApplyUpdate;
interface
uses
Classes, uPatcher;
{
This object is shared by the Launcher and the ClientUpdateService. It is
responsible for the application of updates from the Pending subdir. If the
update is marked to be applied by the service, then the client update service
will apply the update and the launcher will ignore the update if it happens to
run and see that an update is available. Normally, the launcher runs only
when there are users logged into the machine, and any updates to be performed
by the ClientUpdateService would occur when users are not logged in, or at a
time when the application being updated is unlikely to be active (ie: 5 am).
}
type
ThcApplyUpdateEvent = procedure (UpdateVersion :string; WhatsNew :string) of object;
ThcApplyUpdateErrorEvent = procedure (UpdateVersion, UpdateErrorMessage :string) of object;
ThcUpdateApplier = class(TObject)
private
FErrorEncountered :boolean;
FApplySilentUpdates :boolean;
FProgress :TStrings;
FOnProgressUpdate :TNotifyEvent;
FOnApplyUpdate :ThcApplyUpdateEvent;
FOnPatchProgress :TOnPatchProgress;
FOnApplyUpdateError :ThcApplyUpdateErrorEvent;
function MoveDir(const fromDir, toDir: string): Boolean;
procedure ApplyUpdate(const UpdateSubDir :string);
procedure DoPatcherComplete(ASender: TObject; const AStatusCode: LongWord;
const AStatusMessage: string);
procedure DoPatchFileBegin(ASender: TObject; APatchItem: TPatchItem; const APatchItemNumber,
APatchItemCount: Integer; var AContinueIfError: Boolean);
procedure DoPatchFileEnd(ASender: TObject; APatchItem: TPatchItem; const APatchItemNumber,
APatchItemCount: Integer);
procedure DoPatcherProgress(ASender: TObject; const ACurrentPosition,
AMaximumPosition: LongWord; var ACanContinue: LongBool);
procedure OnProgressChange(Sender :TObject);
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
function CheckForUpdatesAndApply :integer; //returns the # of updates applied/found
property Progress :TStrings read FProgress;
property OnProgressUpdate :TNotifyEvent read FOnProgressUpdate write FOnProgressUpdate; //fired when progress messages are added to Progress
property OnApplyUpdate :ThcApplyUpdateEvent read FOnApplyUpdate write FOnApplyUpdate;
property OnApplyUpdateError :ThcApplyUpdateErrorEvent read FOnApplyUpdateError write FOnApplyUpdateError;
property OnPatchProgress :TOnPatchProgress read FOnPatchProgress write FOnPatchProgress;
property ApplySilentUpdates :boolean read FApplySilentUpdates write FApplySilentUpdates;
end;
implementation
uses
ShellAPI
,SysUtils
,iniFiles
,hcVersionList
,Forms
,Controls
,Windows
,XMLDoc
,XMLIntf
,JvJCLUtils
,unIUpdateService
,hcUpdateConsts
,ActiveX
,System.Zip, hcUpdateSettings
;
function ThcUpdateApplier.MoveDir(const fromDir, toDir: string): Boolean;
var
fos: TSHFileOpStruct;
nErrorCode :integer;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_MOVE;
fFlags := FOF_NOERRORUI or FOF_FILESONLY;
pFrom := PChar(fromDir + #0);
pTo := PChar(toDir + #0)
end;
nErrorCode := ShFileOperation(fos);
Result := (0 = nErrorCode);
if not Result then
Progress.Add(Format('Attempt to Move %s to %s failed with Error Code: %d',[fromDir,toDir,nErrorCode]));
end;
procedure ThcUpdateApplier.OnProgressChange(Sender: TObject);
{
This event is called whenever the progress string list is changed.
}
begin
if assigned(FOnProgressUpdate) then
FOnProgressUpdate(Self);
end;
function ThcUpdateApplier.CheckForUpdatesAndApply :integer;
{
We assume this EXE is in the same directory as the TargetEXE by default.
}
var
I :integer;
sr :TSearchRec;
FileAttrs :Integer;
slDirs :ThcVersionList;
begin
Progress.Add('Checking for Updates on File System...');
//get directories of pending updates
slDirs := ThcVersionList.Create;
try
//get directory listing under UpdateRootDir of all Pending Updates
FileAttrs := faDirectory;
if SysUtils.FindFirst(AutoUpdateSettings.UpdateRootDir + 'Pending\*.*', FileAttrs, sr) = 0 then
begin
repeat
//commented out condition since it's not true when update is in C:\Users\<user>\AppData\Local\ subfolder
if {((sr.Attr and FileAttrs) = sr.Attr) and} (sr.Name <> '.') and (sr.Name <> '..') then
begin
slDirs.Add(sr.Name);
end;
until FindNext(sr) <> 0;
SysUtils.FindClose(sr);
end;
//sort the directories in Ascending order so we will apply the latest version update last
slDirs.Sort;
//if we have multiple directories make sure to select the lowest version #
for I := 0 to slDirs.Count - 1 do
begin
if not FErrorEncountered then
ApplyUpdate(slDirs[I]);
end;
Result := slDirs.Count;
finally
slDirs.Free;
end;
end;
procedure ThcUpdateApplier.AfterConstruction;
begin
inherited;
FProgress := TStringList.Create;
TStringList(FProgress).OnChange := OnProgressChange;
end;
procedure ThcUpdateApplier.ApplyUpdate(const UpdateSubDir :string);
var
SaveCursor :TCursor;
aPatcher :TPatcher;
I,
nMax :Integer;
XMLDoc : IXMLDocument;
iRootNode,
iNode : IXMLNode;
sTempDirName,
sManifestFileName,
sPatchedFileName,
sErrorMessage,
SourceFile,
DestinationFile,
UpdateResult,
ApplicationGUID,
InstallationGUID,
UpdateDir,
AppliedDir,
BackupDir,
TargetPath :string;
bIsSilent :boolean;
UpdateService :IUpdateService;
WinResult :integer;
ZipFile :TZipFile;
begin
CoInitialize(nil);
try
try
//load manifest
XMLDoc := TXMLDocument.Create(nil);
try
UpdateDir := LongToShortPath(Format('%s%s\%s\',[AutoUpdateSettings.UpdateRootDir,'Pending',UpdateSubDir]));
sManifestFileName := UpdateDir + ManifestFileName;
Progress.Add(Format('Loading Update Manifest from %s',[sManifestFileName]));
XMLDoc.LoadFromFile(sManifestFileName);
XMLDoc.Active := True;
iRootNode := XMLDoc.ChildNodes.First;
Progress.Add(Format('Getting InstallationGUID: %s ',[AutoUpdateSettings.InstallionGUID]));
InstallationGUID := AutoUpdateSettings.InstallionGUID;
ApplicationGUID := iRootNode.Attributes['ApplicationGUID'];
//if the INI file says we're to apply silent updates then proceed otherwise
//log that we're ignoring the update and exit
bIsSilent := iRootNode.Attributes['IsSilent'];
if (bIsSilent and not FApplySilentUpdates) then
Exit;
if assigned(FOnApplyUpdate) then
FOnApplyUpdate(iRootNode.Attributes['UpdateVersion'],iRootNode.Attributes['WhatsNew']);
//---backup files about to be replaced
Progress.Add('Backing Up Files...');
BackupDir := Format('%s%s\%s\',[AutoUpdateSettings.UpdateRootDir,'Backup',LongToShortPath(UpdateSubDir)]);
Progress.Add(Format('Creating Backup Folder: %s',[BackupDir]));
if not SysUtils.ForceDirectories(BackupDir) then
raise Exception.Create(Format('Unable to create folder: %s',[BackupDir]));
nMax := iRootNode.ChildNodes.Count - 1;
Progress.Add(Format('Processing Manifest: %d Items',[iRootNode.ChildNodes.Count]));
for I := 0 to nMax do
begin
iNode := iRootNode.ChildNodes[I];
if iNode.Attributes['TargetPath'] = AppDir then
TargetPath := AutoUpdateSettings.AppDir
else
TargetPath := iNode.Attributes['TargetPath'];
//backup the file
SourceFile := TargetPath + iNode.Attributes['FileName'];
DestinationFile := BackupDir + iNode.Attributes['FileName'];
if FileExists(SourceFile) then
begin
Progress.Add(Format('Copying %s to %s',[SourceFile,DestinationFile]));
CopyFile(PWideChar(WideString(SourceFile)), PWideChar(WideString(DestinationFile)),False);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
if iNode.Attributes['IsAZip'] then
begin
ZipFile := TZipFile.Create;
try
SourceFile := UpdateDir + iNode.Attributes['FileName'];
Progress.Add(Format('Unzipping %s to %s',[SourceFile,TargetPath]));
ZipFile.ExtractZipFile(SourceFile,TargetPath + '\',nil);
finally
ZipFile.Free;
end;
end
else
if iNode.Attributes['IsAPatch'] then
begin //apply the patch
SourceFile := ChangeFileExt(UpdateDir + iNode.Attributes['FileName'],PatchFileExtension);
DestinationFile := TargetPath + iNode.Attributes['FileName'];
sPatchedFileName := ChangeFileExt(DestinationFile,'.new');
if FileExists(sPatchedFileName) then
begin
SysUtils.DeleteFile(sPatchedFileName);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
SaveCursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
aPatcher := uPatcher.TPatcher.Create;
try
aPatcher.AlwaysRaiseExceptions := True;
aPatcher.PatchFileExtension := PatchFileExtension;
aPatcher.PatchFilePath := UpdateDir;
aPatcher.AddFileToPatch
(DestinationFile
,sPatchedFileName
,SourceFile
);
aPatcher.OnPatchProgress := DoPatcherProgress;
aPatcher.OnPatchesComplete := DoPatcherComplete;
aPatcher.OnPatchFileBegin := DoPatchFileBegin;
aPatcher.OnPatchFileEnd := DoPatchFileEnd;
Progress.Add(Format('Applying Patch %s to %s creating %s',[SourceFile,DestinationFile,sPatchedFileName]));
aPatcher.ApplyPatches;
finally
aPatcher.Free;
end;
//delete the original EXE and rename the Patched version
SysUtils.DeleteFile(DestinationFile);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
RenameFile(sPatchedFileName,DestinationFile);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
finally
Screen.Cursor := SaveCursor;
end;
end
else
begin
//copy in the new version
SourceFile := UpdateDir + iNode.Attributes['FileName'];
DestinationFile := TargetPath + iNode.Attributes['FileName'];
Progress.Add(Format('Copying %s to %s',[SourceFile,DestinationFile]));
CopyFile(PWideChar(WideString(SourceFile)), PWideChar(WideString(DestinationFile)),False);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
end;
//launch any items necessary after all files have been processed since there may be some dependances
//items are launched from the Target directory so that a file can be patched and then launched
for I := 0 to nMax do
begin
iNode := iRootNode.ChildNodes[I];
if iNode.Attributes['Launch'] then
begin
DestinationFile := TargetPath + iNode.Attributes['FileName'];
Progress.Add(Format('Launching %s',[DestinationFile]));
WinResult := ShellExecute(0, 'open',PChar(DestinationFile), PChar(''), PChar(TargetPath), SW_SHOWNORMAL) ;
Progress.Add(Format('ShellExecute reported: %d',[WinResult]));
end;
end;
finally
XMLDoc.Active := False; //close the manifest
XMLDoc := nil; //release the interface
end;
//---copy the new manifest file - this is an implied file to be updated
//backup the original file
SourceFile := TargetPath + ManifestFileName;
DestinationFile := BackupDir + ManifestFileName;
Progress.Add(Format('Moving %s to %s',[SourceFile,DestinationFile]));
if not FileExists(DestinationFile) then
begin
MoveFile(PWideChar(WideString(SourceFile)), PWideChar(WideString(DestinationFile)));
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
//copy in the new version
SourceFile := UpdateDir + ManifestFileName;
DestinationFile := TargetPath + ManifestFileName;
Progress.Add(Format('Copying %s to %s',[SourceFile,DestinationFile]));
CopyFile(PWideChar(WideString(SourceFile)), PWideChar(WideString(DestinationFile)),False);
if GetLastError <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
//move the Update from Pending into Applied
AppliedDir := AutoUpdateSettings.UpdateRootDir + 'Applied\';
if not SysUtils.ForceDirectories(AppliedDir) then
raise Exception.Create(Format('Unable to create folder: %s',[AppliedDir]));
sTempDirName := ExcludeTrailingPathDelimiter(UpdateDir);
Progress.Add(Format('Moving %s to %s',[sTempDirName,AppliedDir]));
if not MoveDir(sTempDirName,AppliedDir) then
raise Exception.Create(Format('Unable to Move %s to Applied folder',[sTempDirName]));
//tell the UpdateServer we applied the update
UpdateResult := UpdateResultNames[urSuccess];
UpdateService := GetIUpdateService(False, AutoUpdateSettings.WebServiceURI);
Progress.Add('Calling Web Service to Report Update Applied SuccessFully!');
try
UpdateService.UpdateApplied(ApplicationGUID,InstallationGUID,iRootNode.Attributes['UpdateVersion'],UpdateResult,Progress.Text);
except
on E: Exception do //server is likely not running
begin //translate the exception and re-raise (consumer must handle)
sErrorMessage := Format('Application was updated successfully but could not contact Head Office. If you have any problems, contact technical support and advise them of the following: Error making UpdateApplied web service call to %s. '#13#10'The original error reported is: %s',[AutoUpdateSettings.WebServiceURI,E.Message]);
Progress.Add(sErrorMessage);
end;
end;
except
on E: Exception do
begin
//EPatcherExceptions are always logged by the DoPatcherComplete event handler
if not(E is EPatcherException) then
begin
Progress.Add('Error:');
Progress.Add(E.Message);
end;
//tell the UpdateServer we failed during application of the update
UpdateResult := UpdateResultNames[urFailure];
if not Assigned(UpdateService) then
UpdateService := GetIUpdateService(False, AutoUpdateSettings.WebServiceURI);
Progress.Add('Calling Web Service to Report Update Failed!');
try
UpdateService.UpdateApplied(ApplicationGUID,InstallationGUID,iRootNode.Attributes['UpdateVersion'],UpdateResult,Progress.Text);
except
on E: Exception do //server is likely not running
begin
sErrorMessage := Format('Error making UpdateApplied web service call to %s. '#13#10'The error reported is: %s',[AutoUpdateSettings.WebServiceURI,E.Message]);
Progress.Add(sErrorMessage);
end;
end;
if assigned(FOnApplyUpdateError) then
FOnApplyUpdateError(UpdateDir,E.Message);
FErrorEncountered := True;
end;
end;
finally
CoUninitialize;
end;
end;
procedure ThcUpdateApplier.BeforeDestruction;
begin
FProgress.Free;
inherited;
end;
procedure ThcUpdateApplier.DoPatchFileBegin(
ASender : TObject;
APatchItem : TPatchItem;
const APatchItemNumber : Integer;
const APatchItemCount : Integer;
var AContinueIfError : Boolean);
begin
Progress.Add('Performing patch action on item [' + IntToStr(APatchItemNumber) + '] of [' + IntToStr(APatchItemCount) + ']');
Progress.Add('-------------------------------------------------------------------');
Progress.Add('Old File Version: [' + APatchItem.OldFileName + ']');
Progress.Add('New File Version: [' + APatchItem.NewFileName + ']');
Progress.Add('Patch Filename: [' + APatchItem.PatchFileName + ']');
Progress.Add('-------------------------------------------------------------------');
end;
procedure ThcUpdateApplier.DoPatchFileEnd(ASender : TObject; APatchItem : TPatchItem;
const APatchItemNumber, APatchItemCount : Integer);
begin
Progress.Add('Finished patching [' + IntToStr(APatchItemNumber) + '] of [' + IntToStr(APatchItemCount) + ']');
end;
procedure ThcUpdateApplier.DoPatcherComplete(ASender : TObject;
const AStatusCode : LongWord; const AStatusMessage : string);
var
LMsg : string;
begin
if AStatusCode <> 0 then
begin
LMsg := 'ERROR: 0x' + IntToHex(AStatusCode, 8) + ':'#13#10 + AStatusMessage;
end
else
begin
LMsg := 'Patching successfully completed';
end;
Progress.Add(LMsg);
end;
procedure ThcUpdateApplier.DoPatcherProgress(ASender : TObject;
const ACurrentPosition : LongWord;
const AMaximumPosition : LongWord;
var ACanContinue : LongBool);
var
LStr : string;
begin
LStr := 'Complete: ' + FormatFloat('#,##0', ACurrentPosition) + ' of ' + FormatFloat('#,##0', AMaximumPosition);
Progress.Add(LStr);
if assigned(FOnPatchProgress) then
FOnPatchProgress(ASender,ACurrentPosition,AMaximumPosition,ACanContinue);
end;
end.
|
unit Editor;
interface
uses
Windows, Messages, AvL, NotesFile, DataNode;
type
TEditAction = (eaUndo, eaRedo, eaSelectAll, eaCut, eaCopy, eaPaste);
TPages = (pText, pImages, pAttaches);
TEditor = class;
TEditorPage = class(TSimplePanel)
protected
FNode: TDataNode;
FEditor: TEditor;
procedure SetNode(Value: TDataNode); virtual;
procedure Modify;
public
constructor Create(Parent: TEditor); virtual;
procedure Save; virtual; abstract;
procedure DoEditAction(Action: TEditAction); virtual; abstract;
property Node: TDataNode read FNode write SetNode;
end;
TEditor = class(TSimplePanel)
Tabs: TTabControl;
Pages: array[TPages] of TEditorPage;
private
FOnModify: TOnEvent;
FNode: TDataNode;
FCurPage: TEditorPage;
procedure Modify;
procedure Resize(Sender: TObject);
procedure SetNode(const Value: TDataNode);
procedure TabChange(Sender: TObject);
procedure WMNotify(var Msg: TWMNotify); message WM_NOTIFY;
public
constructor Create(AParent: TWinControl);
procedure Save;
procedure DoEditAction(Action: TEditAction);
property Node: TDataNode read FNode write SetNode;
property OnModify: TOnEvent read FOnModify write FOnModify;
end;
implementation
uses
TextEditor, ImagesEditor, StreamsEditor;
type
TEditorPageClass = class of TEditorPage;
const
TabNames: array[TPages] of string = ('Text', 'Images', 'Attachments');
EditorPages: array[TPages] of TEditorPageClass = (TTextEditor, TImagesEditor, TStreamsEditor);
{ TEditor }
constructor TEditor.Create(AParent: TWinControl);
var
Page: TPages;
begin
inherited Create(AParent, '');
Border := 2;
ExStyle := 0;
Tabs := TTabControl.Create(Self);
Tabs.Style := tsTabs;
//Tabs.TabPosition := tpBottom;
Tabs.SetPosition(0, 0);
for Page := Low(TPages) to High(TPages) do
begin
Pages[Page] := EditorPages[Page].Create(Self);
Pages[Page].BringToFront;
Pages[Page].Visible := false;
Tabs.TabAdd(TabNames[Page]);
end;
FCurPage := Pages[Low(TPages)];
FCurPage.Visible := true;
Tabs.TabIndex := 0;
OnResize := Resize;
end;
procedure TEditor.DoEditAction(Action: TEditAction);
begin
FCurPage.DoEditAction(Action);
end;
procedure TEditor.Modify;
begin
if Assigned(FOnModify) then
FOnModify(Self);
end;
procedure TEditor.Resize(Sender: TObject);
var
Rect: TRect;
Page: TPages;
begin
Tabs.SetSize(ClientWidth, ClientHeight);
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := Tabs.ClientWidth;
Rect.Bottom := Tabs.ClientHeight;
Tabs.Perform(TCM_ADJUSTRECT, 0, Integer(@Rect));
for Page := Low(TPages) to High(TPages) do
Pages[Page].SetBounds(Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top);
end;
procedure TEditor.Save;
begin
FCurPage.Save;
end;
procedure TEditor.SetNode(const Value: TDataNode);
begin
FNode := Value;
FCurPage.Node := FNode;
end;
procedure TEditor.TabChange(Sender: TObject);
begin
FCurPage.Save;
FCurPage.Visible := false;
FCurPage := Pages[TPages(Tabs.TabIndex)];
FCurPage.Node := FNode;
FCurPage.Visible := true;
end;
procedure TEditor.WMNotify(var Msg: TWMNotify);
begin
if Assigned(Tabs) and (Msg.NMHdr.hwndFrom = Tabs.Handle) and (Msg.NMHdr.code = TCN_SELCHANGE) then
TabChange(Tabs);
end;
{ TEditorPage }
constructor TEditorPage.Create(Parent: TEditor);
begin
inherited Create(Parent, '');
FEditor := Parent;
Border := 2;
ExStyle := 0;
end;
procedure TEditorPage.SetNode(Value: TDataNode);
begin
FNode := Value;
end;
procedure TEditorPage.Modify;
begin
FEditor.Modify;
end;
end. |
unit fOptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExStdCtrls, JvButton, JvCtrls, ActnList, JvBaseDlg,
JvSelectDirectory, ImgList, StdCtrls, ExtCtrls;
type
TfrmOptions = class(TForm)
edtDefaultTransLoc: TLabeledEdit;
edtDefaultSaveLoc: TLabeledEdit;
btnOk: TButton;
btnCancel: TButton;
cbUseFileExt: TCheckBox;
edtDefaultExt: TLabeledEdit;
ilOptions: TImageList;
dlgSelectDir: TJvSelectDirectory;
ActionList1: TActionList;
actOpenDlgTransLoc: TAction;
actOpenDlgSaveLoc: TAction;
btnOpenDlgTransLoc: TJvImgBtn;
btnOpenDlgSaveLoc: TJvImgBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtDefaultTransLocChange(Sender: TObject);
procedure cbUseFileExtKeyPress(Sender: TObject; var Key: Char);
procedure cbUseFileExtClick(Sender: TObject);
procedure actOpenDlgTransLocExecute(Sender: TObject);
procedure actOpenDlgSaveLocExecute(Sender: TObject);
private
FHasChanged: boolean;
function GetHasChanged: boolean;
procedure SetHasChanged(const Value: boolean);
{ Private declarations }
protected
property HasChanged: boolean read GetHasChanged write SetHasChanged;
public
{ Public declarations }
end;
var
frmOptions: TfrmOptions;
implementation
{$R *.dfm}
procedure TfrmOptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if HasChanged and not(ModalResult = mrCancel) then
Self.ModalResult := mrOK
else
Self.ModalResult := mrCancel;
end;
function TfrmOptions.GetHasChanged: boolean;
begin
Result := FHasChanged;
end;
procedure TfrmOptions.SetHasChanged(const Value: boolean);
begin
FHasChanged := Value;
end;
procedure TfrmOptions.edtDefaultTransLocChange(Sender: TObject);
begin
HasChanged := True;
end;
procedure TfrmOptions.cbUseFileExtKeyPress(Sender: TObject; var Key: Char);
begin
HasChanged := True;
end;
procedure TfrmOptions.cbUseFileExtClick(Sender: TObject);
begin
HasChanged := True;
end;
procedure TfrmOptions.actOpenDlgTransLocExecute(Sender: TObject);
begin
if dlgSelectDir.Execute then
edtDefaultTransLoc.Text := dlgSelectDir.Directory;
end;
procedure TfrmOptions.actOpenDlgSaveLocExecute(Sender: TObject);
begin
if dlgSelectDir.Execute then
edtDefaultSaveLoc.Text := dlgSelectDir.Directory;
end;
end.
|
program compilefail61(output);
{string literal of incorrect size, being assigned to a string-type}
type
Length = 1..10;
mystring = packed array[Length] of char;
var alpha:mystring;
begin
alpha := 'hello!'; {needed to be padded with spaces to a length of 10}
writeln(alpha);
end.
|
{
Delphi/Kylix compatibility unit: String handling routines.
This file is part of the Free Pascal run time library.
Copyright (c) 1999-2005 by the Free Pascal development team
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{$mode objfpc}
{$h+}
{$inline on}
unit strutils;
interface
uses
SysUtils{, Types};
{ ---------------------------------------------------------------------
Case insensitive search/replace
---------------------------------------------------------------------}
Function AnsiResemblesText(const AText, AOther: string): Boolean;
Function AnsiContainsText(const AText, ASubText: string): Boolean;
Function AnsiStartsText(const ASubText, AText: string): Boolean;
Function AnsiEndsText(const ASubText, AText: string): Boolean;
Function AnsiReplaceText(const AText, AFromText, AToText: string): string;inline;
Function AnsiMatchText(const AText: string; const AValues: array of string): Boolean;inline;
Function AnsiIndexText(const AText: string; const AValues: array of string): Integer;
{ ---------------------------------------------------------------------
Case sensitive search/replace
---------------------------------------------------------------------}
Function AnsiContainsStr(const AText, ASubText: string): Boolean;inline;
Function AnsiStartsStr(const ASubText, AText: string): Boolean;
Function AnsiEndsStr(const ASubText, AText: string): Boolean;
Function AnsiReplaceStr(const AText, AFromText, AToText: string): string;inline;
Function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean;inline;
Function AnsiIndexStr(const AText: string; const AValues: array of string): Integer;
Function MatchStr(const AText: UnicodeString; const AValues: array of UnicodeString): Boolean;
Function IndexStr(const AText: UnicodeString; const AValues: array of UnicodeString): Integer;
{ ---------------------------------------------------------------------
Miscellaneous
---------------------------------------------------------------------}
Function DupeString(const AText: string; ACount: Integer): string;
Function ReverseString(const AText: string): string;
Function AnsiReverseString(const AText: AnsiString): AnsiString;inline;
Function StuffString(const AText: string; AStart, ALength: Cardinal; const ASubText: string): string;
Function RandomFrom(const AValues: array of string): string; overload;
Function IfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; overload;
function NaturalCompareText (const S1 , S2 : string ): Integer ;
function NaturalCompareText(const Str1, Str2: string; const ADecSeparator, AThousandSeparator: Char): Integer;
{ ---------------------------------------------------------------------
VB emulations.
---------------------------------------------------------------------}
Function LeftStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
Function RightStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;
Function MidStr(const AText: AnsiString; const AStart, ACount: SizeInt): AnsiString;inline;
Function RightBStr(const AText: AnsiString; const AByteCount: SizeInt): AnsiString;inline;
Function MidBStr(const AText: AnsiString; const AByteStart, AByteCount: SizeInt): AnsiString;inline;
Function AnsiLeftStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
Function AnsiRightStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
Function AnsiMidStr(const AText: AnsiString; const AStart, ACount: SizeInt): AnsiString;inline;
Function LeftBStr(const AText: AnsiString; const AByteCount: SizeInt): AnsiString;inline;
Function LeftStr(const AText: WideString; const ACount: SizeInt): WideString;inline;
Function RightStr(const AText: WideString; const ACount: SizeInt): WideString;
Function MidStr(const AText: WideString; const AStart, ACount: SizeInt): WideString;inline;
{ ---------------------------------------------------------------------
Extended search and replace
---------------------------------------------------------------------}
const
{ Default word delimiters are any character except the core alphanumerics. }
WordDelimiters: set of Char = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0'];
resourcestring
SErrAmountStrings = 'Amount of search and replace strings don''t match';
type
TStringSearchOption = (soDown, soMatchCase, soWholeWord);
TStringSearchOptions = set of TStringSearchOption;
TStringSeachOption = TStringSearchOption;
Function SearchBuf(Buf: PChar; BufLen: SizeInt; SelStart, SelLength: SizeInt; SearchString: String; Options: TStringSearchOptions): PChar;
Function SearchBuf(Buf: PChar; BufLen: SizeInt; SelStart, SelLength: SizeInt; SearchString: String): PChar;inline; // ; Options: TStringSearchOptions = [soDown]
Function PosEx(const SubStr, S: string; Offset: SizeUint): SizeInt;
Function PosEx(const SubStr, S: string): SizeInt;inline; // Offset: Cardinal = 1
Function PosEx(c:char; const S: string; Offset: SizeUint): SizeInt;
Function PosEx(const SubStr, S: UnicodeString; Offset: SizeUint): SizeInt;
Function PosEx(c: WideChar; const S: UnicodeString; Offset: SizeUint): SizeInt;
Function PosEx(const SubStr, S: UnicodeString): Sizeint;inline; // Offset: Cardinal = 1
function StringsReplace(const S: string; OldPattern, NewPattern: array of string; Flags: TReplaceFlags): string;
{ ---------------------------------------------------------------------
Delphi compat
---------------------------------------------------------------------}
Function ReplaceStr(const AText, AFromText, AToText: string): string;inline;
Function ReplaceText(const AText, AFromText, AToText: string): string;inline;
{ ---------------------------------------------------------------------
Soundex Functions.
---------------------------------------------------------------------}
type
TSoundexLength = 1..MaxInt;
Function Soundex(const AText: string; ALength: TSoundexLength): string;
Function Soundex(const AText: string): string;inline; // ; ALength: TSoundexLength = 4
type
TSoundexIntLength = 1..8;
Function SoundexInt(const AText: string; ALength: TSoundexIntLength): Integer;
Function SoundexInt(const AText: string): Integer;inline; //; ALength: TSoundexIntLength = 4
Function DecodeSoundexInt(AValue: Integer): string;
Function SoundexWord(const AText: string): Word;
Function DecodeSoundexWord(AValue: Word): string;
Function SoundexSimilar(const AText, AOther: string; ALength: TSoundexLength): Boolean;inline;
Function SoundexSimilar(const AText, AOther: string): Boolean;inline; //; ALength: TSoundexLength = 4
Function SoundexCompare(const AText, AOther: string; ALength: TSoundexLength): Integer;inline;
Function SoundexCompare(const AText, AOther: string): Integer;inline; //; ALength: TSoundexLength = 4
Function SoundexProc(const AText, AOther: string): Boolean;
type
TCompareTextProc = Function(const AText, AOther: string): Boolean;
Const
AnsiResemblesProc: TCompareTextProc = @SoundexProc;
{ ---------------------------------------------------------------------
Other functions, based on RxStrUtils.
---------------------------------------------------------------------}
type
TRomanConversionStrictness = (rcsStrict, rcsRelaxed, rcsDontCare);
resourcestring
SInvalidRomanNumeral = '%s is not a valid Roman numeral';
function IsEmptyStr(const S: string; const EmptyChars: TSysCharSet): Boolean;
function DelSpace(const S: string): string;
function DelChars(const S: string; Chr: Char): string;
function DelSpace1(const S: string): string;
function Tab2Space(const S: string; Numb: Byte): string;
function NPos(const C: string; S: string; N: Integer): SizeInt;
Function RPosEX(C:char;const S : AnsiString;offs:cardinal):SizeInt; overload;
Function RPosex (Const Substr : AnsiString; Const Source : AnsiString;offs:cardinal) : SizeInt; overload;
Function RPos(c:char;const S : AnsiString):SizeInt; overload;
Function RPos (Const Substr : AnsiString; Const Source : AnsiString) : SizeInt; overload;
function AddChar(C: Char; const S: string; N: Integer): string;
function AddCharR(C: Char; const S: string; N: Integer): string;
function PadLeft(const S: string; N: Integer): string;inline;
function PadRight(const S: string; N: Integer): string;inline;
function PadCenter(const S: string; Len: SizeInt): string;
function Copy2Symb(const S: string; Symb: Char): string;
function Copy2SymbDel(var S: string; Symb: Char): string;
function Copy2Space(const S: string): string;inline;
function Copy2SpaceDel(var S: string): string;inline;
function AnsiProperCase(const S: string; const WordDelims: TSysCharSet): string;
function WordCount(const S: string; const WordDelims: TSysCharSet): SizeInt;
function WordPosition(const N: Integer; const S: string; const WordDelims: TSysCharSet): SizeInt;
function ExtractWord(N: Integer; const S: string; const WordDelims: TSysCharSet): string;inline;
{$IF SIZEOF(SIZEINT)<>SIZEOF(INTEGER)}
function ExtractWordPos(N: Integer; const S: string; const WordDelims: TSysCharSet; out Pos: SizeInt): string;
{$ENDIF}
function ExtractWordPos(N: Integer; const S: string; const WordDelims: TSysCharSet; out Pos: Integer): string;
function ExtractDelimited(N: Integer; const S: string; const Delims: TSysCharSet): string;
{$IF SIZEOF(SIZEINT)<>SIZEOF(INTEGER)}
function ExtractSubstr(const S: string; var Pos: SizeInt; const Delims: TSysCharSet): string;
{$ENDIF}
function ExtractSubstr(const S: string; var Pos: Integer; const Delims: TSysCharSet): string;
function IsWordPresent(const W, S: string; const WordDelims: TSysCharSet): Boolean;
function FindPart(const HelpWilds, InputStr: string): SizeInt;
function IsWild(InputStr, Wilds: string; IgnoreCase: Boolean): Boolean;
function XorString(const Key, Src: ShortString): ShortString;
function XorEncode(const Key, Source: string): string;
function XorDecode(const Key, Source: string): string;
function GetCmdLineArg(const Switch: string; SwitchChars: TSysCharSet): string;
function Numb2USA(const S: string): string;
function Hex2Dec(const S: string): Longint;
function Dec2Numb(N: Longint; Len, Base: Byte): string;
function Numb2Dec(S: string; Base: Byte): Longint;
function IntToBin(Value: Longint; Digits, Spaces: Integer): string;
function IntToBin(Value: Longint; Digits: Integer): string;
function intToBin(Value: int64; Digits:integer): string;
function IntToRoman(Value: Longint): string;
function TryRomanToInt(S: String; out N: LongInt; Strictness: TRomanConversionStrictness = rcsRelaxed): Boolean;
function RomanToInt(const S: string; Strictness: TRomanConversionStrictness = rcsRelaxed): Longint;
function RomanToIntDef(Const S : String; const ADefault: Longint = 0; Strictness: TRomanConversionStrictness = rcsRelaxed): Longint;
procedure BinToHex(BinValue, HexValue: PChar; BinBufSize: Integer);
function HexToBin(HexValue, BinValue: PChar; BinBufSize: Integer): Integer;
const
DigitChars = ['0'..'9'];
Brackets = ['(',')','[',']','{','}'];
StdWordDelims = [#0..' ',',','.',';','/','\',':','''','"','`'] + Brackets;
StdSwitchChars = ['-','/'];
function PosSet (const c:TSysCharSet;const s : ansistring ):SizeInt;
function PosSet (const c:string;const s : ansistring ):SizeInt;
function PosSetEx (const c:TSysCharSet;const s : ansistring;count:Integer ):SizeInt;
function PosSetEx (const c:string;const s : ansistring;count:Integer ):SizeInt;
Procedure Removeleadingchars(VAR S : AnsiString; Const CSet:TSysCharset);
Procedure RemoveTrailingChars(VAR S : AnsiString;Const CSet:TSysCharset);
Procedure RemovePadChars(VAR S : AnsiString;Const CSet:TSysCharset);
function TrimLeftSet(const S: String;const CSet:TSysCharSet): String;
Function TrimRightSet(const S: String;const CSet:TSysCharSet): String;
function TrimSet(const S: String;const CSet:TSysCharSet): String;
type
SizeIntArray = array of SizeInt;
procedure FindMatchesBoyerMooreCaseSensitive(const S,OldPattern: PChar; const SSize, OldPatternSize: SizeInt; out aMatches: SizeIntArray; const aMatchAll: Boolean);
procedure FindMatchesBoyerMooreCaseSensitive(const S,OldPattern: String; out aMatches: SizeIntArray; const aMatchAll: Boolean);
procedure FindMatchesBoyerMooreCaseInSensitive(const S, OldPattern: PChar; const SSize, OldPatternSize: SizeInt; out aMatches: SizeIntArray; const aMatchAll: Boolean);
procedure FindMatchesBoyerMooreCaseInSensitive(const S, OldPattern: String; out aMatches: SizeIntArray; const aMatchAll: Boolean);
Type
TStringReplaceAlgorithm = (sraDefault, // Default algoritm as used in StringUtils.
sraManySmall, // Algorithm optimized for many small replacements.
sraBoyerMoore // Algorithm optimized for long replacements.
);
Function StringReplace(const S, OldPattern, NewPattern: string; Flags: TReplaceFlags; Algorithm : TStringReplaceAlgorithm = sraDefault): string; overload;
{ We need these for backwards compatibility:
The compiler will stop searching and convert to ansistring if the widestring version of stringreplace is used.
They currently simply refer to sysutils, till the new mechanisms are proven to work with unicode.}
Function StringReplace(const S, OldPattern, NewPattern: unicodestring; Flags: TReplaceFlags): unicodestring; overload;
Function StringReplace(const S, OldPattern, NewPattern: widestring; Flags: TReplaceFlags): widestring; overload;
implementation
(*
FindMatchesBoyerMooreCaseSensitive
Finds one or many ocurrences of an ansistring in another ansistring.
It is case sensitive.
* Parameters:
S: The PChar to be searched in. (Read only).
OldPattern: The PChar to be searched. (Read only).
SSize: The size of S in Chars. (Read only).
OldPatternSize: The size of OldPatter in chars. (Read only).
aMatches: SizeInt array where match indexes are returned (zero based) (write only).
aMatchAll: Finds all matches, not just the first one. (Read only).
* Returns:
Nothing, information returned in aMatches parameter.
The function is based in the Boyer-Moore algorithm.
*)
procedure FindMatchesBoyerMooreCaseSensitive(const S, OldPattern: PChar;
const SSize, OldPatternSize: SizeInt; out aMatches: SizeIntArray;
const aMatchAll: Boolean);
const
ALPHABET_LENGHT=256;
MATCHESCOUNTRESIZER=100; //Arbitrary value. Memory used = MATCHESCOUNTRESIZER * sizeof(SizeInt)
var
//Stores the amount of replaces that will take place
MatchesCount: SizeInt;
//Currently allocated space for matches.
MatchesAllocatedLimit: SizeInt;
type
AlphabetArray=array [0..ALPHABET_LENGHT-1] of SizeInt;
function Max(const a1,a2: SizeInt): SizeInt;
begin
if a1>a2 then Result:=a1 else Result:=a2;
end;
procedure MakeDeltaJumpTable1(out DeltaJumpTable1: AlphabetArray; const aPattern: PChar; const aPatternSize: SizeInt);
var
i: SizeInt;
begin
for i := 0 to ALPHABET_LENGHT-1 do begin
DeltaJumpTable1[i]:=aPatternSize;
end;
//Last char do not enter in the equation
for i := 0 to aPatternSize - 1 - 1 do begin
DeltaJumpTable1[Ord(aPattern[i])]:=aPatternSize -1 - i;
end;
end;
function IsPrefix(const aPattern: PChar; const aPatternSize, aPos: SizeInt): Boolean;
var
i: SizeInt;
SuffixLength: SizeInt;
begin
SuffixLength:=aPatternSize-aPos;
for i := 0 to SuffixLength-1 do begin
if (aPattern[i] <> aPattern[aPos+i]) then begin
exit(false);
end;
end;
Result:=true;
end;
function SuffixLength(const aPattern: PChar; const aPatternSize, aPos: SizeInt): SizeInt;
var
i: SizeInt;
begin
i:=0;
while (aPattern[aPos-i] = aPattern[aPatternSize-1-i]) and (i < aPos) do begin
inc(i);
end;
Result:=i;
end;
procedure MakeDeltaJumpTable2(var DeltaJumpTable2: SizeIntArray; const aPattern: PChar; const aPatternSize: SizeInt);
var
Position: SizeInt;
LastPrefixIndex: SizeInt;
SuffixLengthValue: SizeInt;
begin
LastPrefixIndex:=aPatternSize-1;
Position:=aPatternSize-1;
while Position>=0 do begin
if IsPrefix(aPattern,aPatternSize,Position+1) then begin
LastPrefixIndex := Position+1;
end;
DeltaJumpTable2[Position] := LastPrefixIndex + (aPatternSize-1 - Position);
Dec(Position);
end;
Position:=0;
while Position<aPatternSize-1 do begin
SuffixLengthValue:=SuffixLength(aPattern,aPatternSize,Position);
if aPattern[Position-SuffixLengthValue] <> aPattern[aPatternSize-1 - SuffixLengthValue] then begin
DeltaJumpTable2[aPatternSize - 1 - SuffixLengthValue] := aPatternSize - 1 - Position + SuffixLengthValue;
end;
Inc(Position);
end;
end;
//Resizes the allocated space for replacement index
procedure ResizeAllocatedMatches;
begin
MatchesAllocatedLimit:=MatchesCount+MATCHESCOUNTRESIZER;
SetLength(aMatches,MatchesAllocatedLimit);
end;
//Add a match to be replaced
procedure AddMatch(const aPosition: SizeInt); inline;
begin
if MatchesCount = MatchesAllocatedLimit then begin
ResizeAllocatedMatches;
end;
aMatches[MatchesCount]:=aPosition;
inc(MatchesCount);
end;
var
i,j: SizeInt;
DeltaJumpTable1: array [0..ALPHABET_LENGHT-1] of SizeInt;
DeltaJumpTable2: SizeIntArray;
begin
MatchesCount:=0;
MatchesAllocatedLimit:=0;
SetLength(aMatches,MatchesCount);
if OldPatternSize=0 then begin
Exit;
end;
SetLength(DeltaJumpTable2,OldPatternSize);
MakeDeltaJumpTable1(DeltaJumpTable1,OldPattern,OldPatternSize);
MakeDeltaJumpTable2(DeltaJumpTable2,OldPattern,OldPatternSize);
i:=OldPatternSize-1;
while i < SSize do begin
j:=OldPatternSize-1;
while (j>=0) and (S[i] = OldPattern[j]) do begin
dec(i);
dec(j);
end;
if (j<0) then begin
AddMatch(i+1);
//Only first match ?
if not aMatchAll then break;
inc(i,OldPatternSize);
inc(i,OldPatternSize);
end else begin
i:=i + Max(DeltaJumpTable1[ord(s[i])],DeltaJumpTable2[j]);
end;
end;
SetLength(aMatches,MatchesCount);
end;
procedure FindMatchesBoyerMooreCaseINSensitive(const S, OldPattern: PChar;
const SSize, OldPatternSize: SizeInt; out aMatches: SizeIntArray;
const aMatchAll: Boolean);
const
ALPHABET_LENGHT=256;
MATCHESCOUNTRESIZER=100; //Arbitrary value. Memory used = MATCHESCOUNTRESIZER * sizeof(SizeInt)
var
//Lowercased OldPattern
lPattern: string;
//Array of lowercased alphabet
lCaseArray: array [0..ALPHABET_LENGHT-1] of char;
//Stores the amount of replaces that will take place
MatchesCount: SizeInt;
//Currently allocated space for matches.
MatchesAllocatedLimit: SizeInt;
type
AlphabetArray=array [0..ALPHABET_LENGHT-1] of SizeInt;
function Max(const a1,a2: SizeInt): SizeInt;
begin
if a1>a2 then Result:=a1 else Result:=a2;
end;
procedure MakeDeltaJumpTable1(out DeltaJumpTable1: AlphabetArray; const aPattern: PChar; const aPatternSize: SizeInt);
var
i: SizeInt;
begin
for i := 0 to ALPHABET_LENGHT-1 do begin
DeltaJumpTable1[i]:=aPatternSize;
end;
//Last char do not enter in the equation
for i := 0 to aPatternSize - 1 - 1 do begin
DeltaJumpTable1[Ord(aPattern[i])]:=aPatternSize - 1 - i;
end;
end;
function IsPrefix(const aPattern: PChar; const aPatternSize, aPos: SizeInt): Boolean; inline;
var
i: SizeInt;
SuffixLength: SizeInt;
begin
SuffixLength:=aPatternSize-aPos;
for i := 0 to SuffixLength-1 do begin
if (aPattern[i+1] <> aPattern[aPos+i]) then begin
exit(false);
end;
end;
Result:=true;
end;
function SuffixLength(const aPattern: PChar; const aPatternSize, aPos: SizeInt): SizeInt; inline;
var
i: SizeInt;
begin
i:=0;
while (aPattern[aPos-i] = aPattern[aPatternSize-1-i]) and (i < aPos) do begin
inc(i);
end;
Result:=i;
end;
procedure MakeDeltaJumpTable2(var DeltaJumpTable2: SizeIntArray; const aPattern: PChar; const aPatternSize: SizeInt);
var
Position: SizeInt;
LastPrefixIndex: SizeInt;
SuffixLengthValue: SizeInt;
begin
LastPrefixIndex:=aPatternSize-1;
Position:=aPatternSize-1;
while Position>=0 do begin
if IsPrefix(aPattern,aPatternSize,Position+1) then begin
LastPrefixIndex := Position+1;
end;
DeltaJumpTable2[Position] := LastPrefixIndex + (aPatternSize-1 - Position);
Dec(Position);
end;
Position:=0;
while Position<aPatternSize-1 do begin
SuffixLengthValue:=SuffixLength(aPattern,aPatternSize,Position);
if aPattern[Position-SuffixLengthValue] <> aPattern[aPatternSize-1 - SuffixLengthValue] then begin
DeltaJumpTable2[aPatternSize - 1 - SuffixLengthValue] := aPatternSize - 1 - Position + SuffixLengthValue;
end;
Inc(Position);
end;
end;
//Resizes the allocated space for replacement index
procedure ResizeAllocatedMatches;
begin
MatchesAllocatedLimit:=MatchesCount+MATCHESCOUNTRESIZER;
SetLength(aMatches,MatchesAllocatedLimit);
end;
//Add a match to be replaced
procedure AddMatch(const aPosition: SizeInt); inline;
begin
if MatchesCount = MatchesAllocatedLimit then begin
ResizeAllocatedMatches;
end;
aMatches[MatchesCount]:=aPosition;
inc(MatchesCount);
end;
var
i,j: SizeInt;
DeltaJumpTable1: array [0..ALPHABET_LENGHT-1] of SizeInt;
DeltaJumpTable2: SizeIntArray;
//Pointer to lowered OldPattern
plPattern: PChar;
begin
MatchesCount:=0;
MatchesAllocatedLimit:=0;
SetLength(aMatches,MatchesCount);
if OldPatternSize=0 then begin
Exit;
end;
//Build an internal array of lowercase version of every possible char.
for j := 0 to Pred(ALPHABET_LENGHT) do begin
lCaseArray[j]:=AnsiLowerCase(char(j))[1];
end;
//Create the new lowercased pattern
SetLength(lPattern,OldPatternSize);
for j := 0 to Pred(OldPatternSize) do begin
lPattern[j+1]:=lCaseArray[ord(OldPattern[j])];
end;
SetLength(DeltaJumpTable2,OldPatternSize);
MakeDeltaJumpTable1(DeltaJumpTable1,@lPattern[1],OldPatternSize);
MakeDeltaJumpTable2(DeltaJumpTable2,@lPattern[1],OldPatternSize);
plPattern:=@lPattern[1];
i:=OldPatternSize-1;
while i < SSize do begin
j:=OldPatternSize-1;
while (j>=0) and (lCaseArray[Ord(S[i])] = plPattern[j]) do begin
dec(i);
dec(j);
end;
if (j<0) then begin
AddMatch(i+1);
//Only first match ?
if not aMatchAll then break;
inc(i,OldPatternSize);
inc(i,OldPatternSize);
end else begin
i:=i + Max(DeltaJumpTable1[Ord(lCaseArray[Ord(s[i])])],DeltaJumpTable2[j]);
end;
end;
SetLength(aMatches,MatchesCount);
end;
function StringReplaceFast(const S, OldPattern, NewPattern: string;
Flags: TReplaceFlags): string;
const
MATCHESCOUNTRESIZER=100; //Arbitrary value. Memory used = MATCHESCOUNTRESIZER * sizeof(SizeInt)
var
//Stores where a replace will take place
Matches: array of SizeInt;
//Stores the amount of replaces that will take place
MatchesCount: SizeInt;
//Currently allocated space for matches.
MatchesAllocatedLimit: SizeInt;
//Uppercase version of pattern
PatternUppercase: string;
//Lowercase version of pattern
PatternLowerCase: string;
//Index
MatchIndex: SizeInt;
MatchLimit: SizeInt;
MatchInternal: SizeInt;
MatchTarget: SizeInt;
AdvanceIndex: SizeInt;
//Miscelanous variables
OldPatternSize: SizeInt;
NewPatternSize: SizeInt;
//Resizes the allocated space for replacement index
procedure ResizeAllocatedMatches;
begin
MatchesAllocatedLimit:=MatchesCount+MATCHESCOUNTRESIZER;
SetLength(Matches,MatchesAllocatedLimit);
end;
//Add a match to be replaced
procedure AddMatch(const aPosition: SizeInt); inline;
begin
if MatchesCount = MatchesAllocatedLimit then begin
ResizeAllocatedMatches;
end;
Matches[MatchesCount]:=aPosition;
inc(MatchesCount);
end;
begin
if (OldPattern='') or (Length(OldPattern)>Length(S)) then begin
//This cases will never match nothing.
Result:=S;
exit;
end;
Result:='';
OldPatternSize:=Length(OldPattern);
MatchesCount:=0;
MatchesAllocatedLimit:=0;
if rfIgnoreCase in Flags then begin
//Different algorithm for case sensitive and insensitive
//This is insensitive, so 2 new ansistrings are created for search pattern, one upper and one lower case.
//It is easy, usually, to create 2 versions of the match pattern than uppercased and lowered case each
//character in the "to be matched" string.
PatternUppercase:=AnsiUpperCase(OldPattern);
PatternLowerCase:=AnsiLowerCase(OldPattern);
MatchIndex:=Length(OldPattern);
MatchLimit:=Length(S);
NewPatternSize:=Length(NewPattern);
while MatchIndex <= MatchLimit do begin
if (S[MatchIndex]=PatternLowerCase[OldPatternSize]) or (S[MatchIndex]=PatternUppercase[OldPatternSize]) then begin
//Match backwards...
MatchInternal:=OldPatternSize-1;
MatchTarget:=MatchIndex-1;
while MatchInternal>=1 do begin
if (S[MatchTarget]=PatternLowerCase[MatchInternal]) or (S[MatchTarget]=PatternUppercase[MatchInternal]) then begin
dec(MatchInternal);
dec(MatchTarget);
end else begin
break;
end;
end;
if MatchInternal=0 then begin
//Match found, all char meet the sequence
//MatchTarget points to char before, so matching is +1
AddMatch(MatchTarget+1);
inc(MatchIndex,OldPatternSize);
if not (rfReplaceAll in Flags) then begin
break;
end;
end else begin
//Match not found
inc(MatchIndex);
end;
end else begin
inc(MatchIndex);
end;
end;
end else begin
//Different algorithm for case sensitive and insensitive
//This is sensitive, so just 1 binary comprare
MatchIndex:=Length(OldPattern);
MatchLimit:=Length(S);
NewPatternSize:=Length(NewPattern);
while MatchIndex <= MatchLimit do begin
if (S[MatchIndex]=OldPattern[OldPatternSize]) then begin
//Match backwards...
MatchInternal:=OldPatternSize-1;
MatchTarget:=MatchIndex-1;
while MatchInternal>=1 do begin
if (S[MatchTarget]=OldPattern[MatchInternal]) then begin
dec(MatchInternal);
dec(MatchTarget);
end else begin
break;
end;
end;
if MatchInternal=0 then begin
//Match found, all char meet the sequence
//MatchTarget points to char before, so matching is +1
AddMatch(MatchTarget+1);
inc(MatchIndex,OldPatternSize);
if not (rfReplaceAll in Flags) then begin
break;
end;
end else begin
//Match not found
inc(MatchIndex);
end;
end else begin
inc(MatchIndex);
end;
end;
end;
//Create room enougth for the result string
SetLength(Result,Length(S)-OldPatternSize*MatchesCount+NewPatternSize*MatchesCount);
MatchIndex:=1;
MatchTarget:=1;
//Matches[x] are 1 based offsets
for MatchInternal := 0 to Pred(MatchesCount) do begin
//Copy information up to next match
AdvanceIndex:=Matches[MatchInternal]-MatchIndex;
if AdvanceIndex>0 then begin
move(S[MatchIndex],Result[MatchTarget],AdvanceIndex);
inc(MatchTarget,AdvanceIndex);
inc(MatchIndex,AdvanceIndex);
end;
//Copy the new replace information string
if NewPatternSize>0 then begin
move(NewPattern[1],Result[MatchTarget],NewPatternSize);
inc(MatchTarget,NewPatternSize);
end;
inc(MatchIndex,OldPatternSize);
end;
if MatchTarget<=Length(Result) then begin
//Add remain data at the end of source.
move(S[MatchIndex],Result[MatchTarget],Length(Result)-MatchTarget+1);
end;
end;
(*
StringReplaceBoyerMoore
Replaces one or many ocurrences of an ansistring in another ansistring by a new one.
It can perform the compare ignoring case (ansi).
* Parameters (Read only):
S: The string to be searched in.
OldPattern: The string to be searched.
NewPattern: The string to replace OldPattern matches.
Flags:
rfReplaceAll: Replace all occurrences.
rfIgnoreCase: Ignore case in OldPattern matching.
* Returns:
The modified string (if needed).
It is memory conservative, just sizeof(SizeInt) per match in blocks off 100 matches
plus Length(OldPattern)*2 in the case of ignoring case.
Memory copies are the minimun necessary.
Algorithm based in the Boyer-Moore string search algorithm.
It is faster when the "S" string is very long and the OldPattern is also
very big. As much big the OldPattern is, faster the search is too.
It uses 2 different helper versions of Boyer-Moore algorithm, one for case
sensitive and one for case INsensitive for speed reasons.
*)
function StringReplaceBoyerMoore(const S, OldPattern, NewPattern: string;Flags: TReplaceFlags): string;
var
Matches: SizeIntArray;
OldPatternSize: SizeInt;
NewPatternSize: SizeInt;
MatchesCount: SizeInt;
MatchIndex: SizeInt;
MatchTarget: SizeInt;
MatchInternal: SizeInt;
AdvanceIndex: SizeInt;
begin
OldPatternSize:=Length(OldPattern);
NewPatternSize:=Length(NewPattern);
if (OldPattern='') or (Length(OldPattern)>Length(S)) then begin
Result:=S;
exit;
end;
if rfIgnoreCase in Flags then begin
FindMatchesBoyerMooreCaseINSensitive(@s[1],@OldPattern[1],Length(S),Length(OldPattern),Matches, rfReplaceAll in Flags);
end else begin
FindMatchesBoyerMooreCaseSensitive(@s[1],@OldPattern[1],Length(S),Length(OldPattern),Matches, rfReplaceAll in Flags);
end;
MatchesCount:=Length(Matches);
//Create room enougth for the result string
SetLength(Result,Length(S)-OldPatternSize*MatchesCount+NewPatternSize*MatchesCount);
MatchIndex:=1;
MatchTarget:=1;
//Matches[x] are 0 based offsets
for MatchInternal := 0 to Pred(MatchesCount) do begin
//Copy information up to next match
AdvanceIndex:=Matches[MatchInternal]+1-MatchIndex;
if AdvanceIndex>0 then begin
move(S[MatchIndex],Result[MatchTarget],AdvanceIndex);
inc(MatchTarget,AdvanceIndex);
inc(MatchIndex,AdvanceIndex);
end;
//Copy the new replace information string
if NewPatternSize>0 then begin
move(NewPattern[1],Result[MatchTarget],NewPatternSize);
inc(MatchTarget,NewPatternSize);
end;
inc(MatchIndex,OldPatternSize);
end;
if MatchTarget<=Length(Result) then begin
//Add remain data at the end of source.
move(S[MatchIndex],Result[MatchTarget],Length(Result)-MatchTarget+1);
end;
end;
Function StringReplace(const S, OldPattern, NewPattern: string; Flags: TReplaceFlags; Algorithm : TStringReplaceAlgorithm = sraDefault): string;
begin
Case Algorithm of
sraDefault : Result:=sysutils.StringReplace(S,OldPattern,NewPattern,Flags);
sraManySmall : Result:=StringReplaceFast(S,OldPattern,NewPattern,Flags);
sraBoyerMoore : Result:=StringReplaceBoyerMoore(S,OldPattern,NewPattern,Flags);
end;
end;
Function StringReplace(const S, OldPattern, NewPattern: unicodestring; Flags: TReplaceFlags): unicodestring; overload;
begin
Result:=sysutils.StringReplace(S,OldPattern,NewPattern,Flags);
end;
Function StringReplace(const S, OldPattern, NewPattern: widestring; Flags: TReplaceFlags): widestring; overload;
begin
Result:=sysutils.StringReplace(S,OldPattern,NewPattern,Flags);
end;
procedure FindMatchesBoyerMooreCaseSensitive(const S,OldPattern: String; out aMatches: SizeIntArray; const aMatchAll: Boolean);
Var
I : SizeInt;
begin
FindMatchesBoyerMooreCaseSensitive(PChar(S),Pchar(OldPattern),Length(S),Length(OldPattern),aMatches,aMatchAll);
For I:=0 to pred(Length(AMatches)) do
Inc(AMatches[i]);
end;
procedure FindMatchesBoyerMooreCaseInSensitive(const S, OldPattern: String; out aMatches: SizeIntArray; const aMatchAll: Boolean);
Var
I : SizeInt;
begin
FindMatchesBoyerMooreCaseInSensitive(PChar(S),Pchar(OldPattern),Length(S),Length(OldPattern),aMatches,aMatchAll);
For I:=0 to pred(Length(AMatches)) do
Inc(AMatches[i]);
end;
{ ---------------------------------------------------------------------
Possibly Exception raising functions
---------------------------------------------------------------------}
function Hex2Dec(const S: string): Longint;
var
HexStr: string;
begin
if Pos('$',S)=0 then
HexStr:='$'+ S
else
HexStr:=S;
Result:=StrToInt(HexStr);
end;
{
We turn off implicit exceptions, since these routines are tested, and it
saves 20% codesize (and some speed) and don't throw exceptions, except maybe
heap related. If they don't, that is consider a bug.
In the future, be wary with routines that use strtoint, floating point
and/or format() derivatives. And check every divisor for 0.
}
{$IMPLICITEXCEPTIONS OFF}
{ ---------------------------------------------------------------------
Case insensitive search/replace
---------------------------------------------------------------------}
Function AnsiResemblesText(const AText, AOther: string): Boolean;
begin
if Assigned(AnsiResemblesProc) then
Result:=AnsiResemblesProc(AText,AOther)
else
Result:=False;
end;
Function AnsiContainsText(const AText, ASubText: string): Boolean;
begin
AnsiContainsText:=AnsiPos(AnsiUppercase(ASubText),AnsiUppercase(AText))>0;
end;
Function AnsiStartsText(const ASubText, AText: string): Boolean;
begin
if (Length(AText) >= Length(ASubText)) and (ASubText <> '') then
Result := AnsiStrLIComp(PChar(ASubText), PChar(AText), Length(ASubText)) = 0
else
Result := False;
end;
Function AnsiEndsText(const ASubText, AText: string): Boolean;
begin
if Length(AText) >= Length(ASubText) then
Result := AnsiStrLIComp(PChar(ASubText),
PChar(AText) + Length(AText) - Length(ASubText), Length(ASubText)) = 0
else
Result := False;
end;
Function AnsiReplaceText(const AText, AFromText, AToText: string): string;inline;
begin
Result := StringReplace(AText,AFromText,AToText,[rfReplaceAll,rfIgnoreCase]);
end;
Function AnsiMatchText(const AText: string; const AValues: array of string): Boolean;
begin
Result:=(AnsiIndexText(AText,AValues)<>-1)
end;
Function AnsiIndexText(const AText: string; const AValues: array of string): Integer;
var
i : Integer;
begin
Result:=-1;
if (high(AValues)=-1) or (High(AValues)>MaxInt) Then
Exit;
for i:=low(AValues) to High(Avalues) do
if CompareText(avalues[i],atext)=0 Then
exit(i); // make sure it is the first val.
end;
{ ---------------------------------------------------------------------
Case sensitive search/replace
---------------------------------------------------------------------}
Function AnsiContainsStr(const AText, ASubText: string): Boolean;inline;
begin
Result := AnsiPos(ASubText,AText)>0;
end;
Function AnsiStartsStr(const ASubText, AText: string): Boolean;
begin
if (Length(AText) >= Length(ASubText)) and (ASubText <> '') then
Result := AnsiStrLComp(PChar(ASubText), PChar(AText), Length(ASubText)) = 0
else
Result := False;
end;
Function AnsiEndsStr(const ASubText, AText: string): Boolean;
begin
if Length(AText) >= Length(ASubText) then
Result := AnsiStrLComp(PChar(ASubText),
PChar(AText) + Length(AText) - Length(ASubText), Length(ASubText)) = 0
else
Result := False;
end;
Function AnsiReplaceStr(const AText, AFromText, AToText: string): string;inline;
begin
Result := StringReplace(AText,AFromText,AToText,[rfReplaceAll]);
end;
Function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean;
begin
Result:=AnsiIndexStr(AText,Avalues)<>-1;
end;
Function AnsiIndexStr(const AText: string; const AValues: array of string): Integer;
var
i : longint;
begin
result:=-1;
if (high(AValues)=-1) or (High(AValues)>MaxInt) Then
Exit;
for i:=low(AValues) to High(Avalues) do
if (avalues[i]=AText) Then
exit(i); // make sure it is the first val.
end;
Function MatchStr(const AText: UnicodeString; const AValues: array of UnicodeString): Boolean;
begin
Result := IndexStr(AText,AValues) <> -1;
end;
Function IndexStr(const AText: UnicodeString; const AValues: array of UnicodeString): Integer;
var
i: longint;
begin
Result := -1;
if (high(AValues) = -1) or (High(AValues) > MaxInt) Then
Exit;
for i := low(AValues) to High(Avalues) do
if (avalues[i] = AText) Then
exit(i); // make sure it is the first val.
end;
{ ---------------------------------------------------------------------
Playthingies
---------------------------------------------------------------------}
Function DupeString(const AText: string; ACount: Integer): string;
var i,l : SizeInt;
begin
result:='';
if aCount>=0 then
begin
l:=length(atext);
SetLength(result,aCount*l);
for i:=0 to ACount-1 do
move(atext[1],Result[l*i+1],l);
end;
end;
Function ReverseString(const AText: string): string;
var
i,j : SizeInt;
begin
setlength(result,length(atext));
i:=1; j:=length(atext);
while (i<=j) do
begin
result[i]:=atext[j-i+1];
inc(i);
end;
end;
Function AnsiReverseString(const AText: AnsiString): AnsiString;inline;
begin
Result:=ReverseString(AText);
end;
Function StuffString(const AText: string; AStart, ALength: Cardinal; const ASubText: string): string;
var i,j,k : SizeUInt;
begin
j:=length(ASubText);
i:=length(AText);
if AStart>i then
aStart:=i+1;
k:=i+1-AStart;
if ALength> k then
ALength:=k;
SetLength(Result,i+j-ALength);
move (AText[1],result[1],AStart-1);
move (ASubText[1],result[AStart],j);
move (AText[AStart+ALength], Result[AStart+j],i+1-AStart-ALength);
end;
Function RandomFrom(const AValues: array of string): string; overload;
begin
if high(AValues)=-1 then exit('');
result:=Avalues[random(High(AValues)+1)];
end;
Function IfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; overload;
begin
if avalue then
result:=atrue
else
result:=afalse;
end;
function NaturalCompareText(const Str1, Str2: string; const ADecSeparator, AThousandSeparator: Char): Integer;
{
NaturalCompareBase compares strings in a collated order and
so numbers are sorted too. It sorts like this:
01
001
0001
and
0
00
000
000_A
000_B
in a intuitive order.
}
var
Num1, Num2: double;
pStr1, pStr2: PChar;
Len1, Len2: SizeInt;
TextLen1, TextLen2: SizeInt;
TextStr1: string = '';
TextStr2: string = '';
i: SizeInt;
j: SizeInt;
function Sign(const AValue: sizeint): integer;inline;
begin
If Avalue<0 then
Result:=-1
else If Avalue>0 then
Result:=1
else
Result:=0;
end;
function IsNumber(ch: char): boolean;
begin
Result := ch in ['0'..'9'];
end;
function GetInteger(var pch: PChar; var Len: sizeint): double;
begin
Result := 0;
while (pch^ <> #0) and IsNumber(pch^) do
begin
Result := Result * 10 + Ord(pch^) - Ord('0');
Inc(Len);
Inc(pch);
end;
end;
procedure GetChars;
begin
TextLen1 := 0;
while not ((pStr1 + TextLen1)^ in ['0'..'9']) and ((pStr1 + TextLen1)^ <> #0) do
Inc(TextLen1);
SetLength(TextStr1, TextLen1);
i := 1;
j := 0;
while i <= TextLen1 do
begin
TextStr1[i] := (pStr1 + j)^;
Inc(i);
Inc(j);
end;
TextLen2 := 0;
while not ((pStr2 + TextLen2)^ in ['0'..'9']) and ((pStr2 + TextLen2)^ <> #0) do
Inc(TextLen2);
SetLength(TextStr2, TextLen2);
i := 1;
j := 0;
while i <= TextLen2 do
begin
TextStr2[i] := (pStr2 + j)^;
Inc(i);
Inc(j);
end;
end;
begin
if (Str1 <> '') and (Str2 <> '') then
begin
pStr1 := PChar(Str1);
pStr2 := PChar(Str2);
Result := 0;
while not ((pStr1^ = #0) or (pStr2^ = #0)) do
begin
TextLen1 := 1;
TextLen2 := 1;
Len1 := 0;
Len2 := 0;
while (pStr1^ = ' ') do
begin
Inc(pStr1);
Inc(Len1);
end;
while (pStr2^ = ' ') do
begin
Inc(pStr2);
Inc(Len2);
end;
if IsNumber(pStr1^) and IsNumber(pStr2^) then
begin
Num1 := GetInteger(pStr1, Len1);
Num2 := GetInteger(pStr2, Len2);
if Num1 < Num2 then
Result := -1
else if Num1 > Num2 then
Result := 1
else
begin
Result := Sign(Len1 - Len2);
end;
Dec(pStr1);
Dec(pStr2);
end
else
begin
GetChars;
if TextStr1 <> TextStr2 then
Result := WideCompareText(UTF8Decode(TextStr1), UTF8Decode(TextStr2))
else
Result := 0;
end;
if Result <> 0 then
Break;
Inc(pStr1, TextLen1);
Inc(pStr2, TextLen2);
end;
end;
Num1 := Length(Str1);
Num2 := Length(Str2);
if (Result = 0) and (Num1 <> Num2) then
begin
if Num1 < Num2 then
Result := -1
else
Result := 1;
end;
end;
function NaturalCompareText (const S1 , S2 : string ): Integer ;
begin
Result := NaturalCompareText(S1, S2,
DefaultFormatSettings.DecimalSeparator,
DefaultFormatSettings.ThousandSeparator);
end;
{ ---------------------------------------------------------------------
VB emulations.
---------------------------------------------------------------------}
Function LeftStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
begin
Result:=Copy(AText,1,ACount);
end;
Function RightStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;
var j,l:SizeInt;
begin
l:=length(atext);
j:=ACount;
if j>l then j:=l;
Result:=Copy(AText,l-j+1,j);
end;
Function MidStr(const AText: AnsiString; const AStart, ACount: SizeInt): AnsiString;inline;
begin
if (ACount=0) or (AStart>length(atext)) then
exit('');
Result:=Copy(AText,AStart,ACount);
end;
Function LeftBStr(const AText: AnsiString; const AByteCount: SizeInt): AnsiString;inline;
begin
Result:=LeftStr(AText,AByteCount);
end;
Function RightBStr(const AText: AnsiString; const AByteCount: SizeInt): AnsiString;inline;
begin
Result:=RightStr(Atext,AByteCount);
end;
Function MidBStr(const AText: AnsiString; const AByteStart, AByteCount: SizeInt): AnsiString;inline;
begin
Result:=MidStr(AText,AByteStart,AByteCount);
end;
Function AnsiLeftStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
begin
Result := copy(AText,1,ACount);
end;
Function AnsiRightStr(const AText: AnsiString; const ACount: SizeInt): AnsiString;inline;
begin
Result := copy(AText,length(AText)-ACount+1,ACount);
end;
Function AnsiMidStr(const AText: AnsiString; const AStart, ACount: SizeInt): AnsiString;inline;
begin
Result:=Copy(AText,AStart,ACount);
end;
Function LeftStr(const AText: WideString; const ACount: SizeInt): WideString;inline;
begin
Result:=Copy(AText,1,ACount);
end;
Function RightStr(const AText: WideString; const ACount: SizeInt): WideString;
var
j,l:SizeInt;
begin
l:=length(atext);
j:=ACount;
if j>l then j:=l;
Result:=Copy(AText,l-j+1,j);
end;
Function MidStr(const AText: WideString; const AStart, ACount: SizeInt): WideString;inline;
begin
Result:=Copy(AText,AStart,ACount);
end;
{ ---------------------------------------------------------------------
Extended search and replace
---------------------------------------------------------------------}
type
TEqualFunction = function (const a,b : char) : boolean;
function EqualWithCase (const a,b : char) : boolean;
begin
result := (a = b);
end;
function EqualWithoutCase (const a,b : char) : boolean;
begin
result := (lowerCase(a) = lowerCase(b));
end;
function IsWholeWord (bufstart, bufend, wordstart, wordend : pchar) : boolean;
begin
// Check start
result := ((wordstart = bufstart) or ((wordstart-1)^ in worddelimiters)) and
// Check end
((wordend = bufend) or ((wordend+1)^ in worddelimiters));
end;
function SearchDown(buf,aStart,endchar:pchar; SearchString:string;
Equals : TEqualFunction; WholeWords:boolean) : pchar;
var Found : boolean;
s, c : pchar;
begin
result := aStart;
Found := false;
while not Found and (result <= endchar) do
begin
// Search first letter
while (result <= endchar) and not Equals(result^,SearchString[1]) do
inc (result);
// Check if following is searchstring
c := result;
s := @(Searchstring[1]);
Found := true;
while (c <= endchar) and (s^ <> #0) and Found do
begin
Found := Equals(c^, s^);
inc (c);
inc (s);
end;
if s^ <> #0 then
Found := false;
// Check if it is a word
if Found and WholeWords then
Found := IsWholeWord(buf,endchar,result,c-1);
if not found then
inc (result);
end;
if not Found then
result := nil;
end;
function SearchUp(buf,aStart,endchar:pchar; SearchString:string;
equals : TEqualFunction; WholeWords:boolean) : pchar;
var Found : boolean;
s, c, l : pchar;
begin
result := aStart;
Found := false;
l := @(SearchString[length(SearchString)]);
while not Found and (result >= buf) do
begin
// Search last letter
while (result >= buf) and not Equals(result^,l^) do
dec (result);
// Check if before is searchstring
c := result;
s := l;
Found := true;
while (c >= buf) and (s >= @SearchString[1]) and Found do
begin
Found := Equals(c^, s^);
dec (c);
dec (s);
end;
if (s >= @(SearchString[1])) then
Found := false;
// Check if it is a word
if Found and WholeWords then
Found := IsWholeWord(buf,endchar,c+1,result);
if found then
result := c+1
else
dec (result);
end;
if not Found then
result := nil;
end;
//function SearchDown(buf,aStart,endchar:pchar; SearchString:string; equal : TEqualFunction; WholeWords:boolean) : pchar;
function SearchBuf(Buf: PChar;BufLen: SizeInt;SelStart: SizeInt;SelLength: SizeInt;
SearchString: String;Options: TStringSearchOptions):PChar;
var
equal : TEqualFunction;
begin
SelStart := SelStart + SelLength;
if (SearchString = '') or (SelStart > BufLen) or (SelStart < 0) then
result := nil
else
begin
if soMatchCase in Options then
Equal := @EqualWithCase
else
Equal := @EqualWithoutCase;
if soDown in Options then
result := SearchDown(buf,buf+SelStart,Buf+(BufLen-1), SearchString, Equal, (soWholeWord in Options))
else
result := SearchUp(buf,buf+SelStart,Buf+(Buflen-1), SearchString, Equal, (soWholeWord in Options));
end;
end;
Function SearchBuf(Buf: PChar; BufLen: SizeInt; SelStart, SelLength: SizeInt; SearchString: String): PChar;inline; // ; Options: TStringSearchOptions = [soDown]
begin
Result:=SearchBuf(Buf,BufLen,SelStart,SelLength,SearchString,[soDown]);
end;
Function PosEx(const SubStr, S: string; Offset: SizeUint): SizeInt;
var
i,MaxLen, SubLen : SizeInt;
SubFirst: Char;
pc : pchar;
begin
PosEx:=0;
SubLen := Length(SubStr);
if (SubLen > 0) and (Offset > 0) and (Offset <= Cardinal(Length(S))) then
begin
MaxLen := Length(S)- SubLen;
SubFirst := SubStr[1];
i := indexbyte(S[Offset],Length(S) - Offset + 1, Byte(SubFirst));
while (i >= 0) and ((i + sizeint(Offset) - 1) <= MaxLen) do
begin
pc := @S[i+SizeInt(Offset)];
//we know now that pc^ = SubFirst, because indexbyte returned a value > -1
if (CompareByte(Substr[1],pc^,SubLen) = 0) then
begin
PosEx := i + SizeInt(Offset);
Exit;
end;
//point Offset to next char in S
Offset := sizeuint(i) + Offset + 1;
i := indexbyte(S[Offset],Length(S) - Offset + 1, Byte(SubFirst));
end;
end;
end;
Function PosEx(c:char; const S: string; Offset: SizeUint): SizeInt;
var
p,Len : SizeInt;
begin
Len := length(S);
if (Offset < 1) or (Offset > SizeUInt(Length(S))) then exit(0);
Len := length(S);
p := indexbyte(S[Offset],Len-offset+1,Byte(c));
if (p < 0) then
PosEx := 0
else
PosEx := p + sizeint(Offset);
end;
Function PosEx(const SubStr, S: string): SizeInt;inline; // Offset: Cardinal = 1
begin
posex:=posex(substr,s,1);
end;
Function PosEx(const SubStr, S: UnicodeString; Offset: SizeUint): SizeInt;
var
i,MaxLen, SubLen : SizeInt;
SubFirst: WideChar;
pc : pwidechar;
begin
PosEx:=0;
SubLen := Length(SubStr);
if (SubLen > 0) and (Offset > 0) and (Offset <= Cardinal(Length(S))) then
begin
MaxLen := Length(S)- SubLen;
SubFirst := SubStr[1];
i := indexword(S[Offset],Length(S) - Offset + 1, Word(SubFirst));
while (i >= 0) and ((i + sizeint(Offset) - 1) <= MaxLen) do
begin
pc := @S[i+SizeInt(Offset)];
//we know now that pc^ = SubFirst, because indexbyte returned a value > -1
if (CompareWord(Substr[1],pc^,SubLen) = 0) then
begin
PosEx := i + SizeInt(Offset);
Exit;
end;
//point Offset to next char in S
Offset := sizeuint(i) + Offset + 1;
i := indexword(S[Offset],Length(S) - Offset + 1, Word(SubFirst));
end;
end;
end;
Function PosEx(c: WideChar; const S: UnicodeString; Offset: SizeUint): SizeInt;
var
Len,p : SizeInt;
begin
Len := length(S);
if (Offset < 1) or (Offset > SizeUInt(Length(S))) then exit(0);
Len := length(S);
p := indexword(S[Offset],Len-offset+1,Word(c));
if (p < 0) then
PosEx := 0
else
PosEx := p + sizeint(Offset);
end;
Function PosEx(const SubStr, S: UnicodeString): SizeInt;inline; // Offset: Cardinal = 1
begin
PosEx:=PosEx(SubStr,S,1);
end;
function StringsReplace(const S: string; OldPattern, NewPattern: array of string; Flags: TReplaceFlags): string;
var pc,pcc,lastpc : pchar;
strcount : integer;
ResStr,
CompStr : string;
Found : Boolean;
sc : sizeint;
begin
sc := length(OldPattern);
if sc <> length(NewPattern) then
raise exception.Create(SErrAmountStrings);
dec(sc);
if rfIgnoreCase in Flags then
begin
CompStr:=AnsiUpperCase(S);
for strcount := 0 to sc do
OldPattern[strcount] := AnsiUpperCase(OldPattern[strcount]);
end
else
CompStr := s;
ResStr := '';
pc := @CompStr[1];
pcc := @s[1];
lastpc := pc+Length(S);
while pc < lastpc do
begin
Found := False;
for strcount := 0 to sc do
begin
if (length(OldPattern[strcount])>0) and
(OldPattern[strcount][1]=pc^) and
(Length(OldPattern[strcount]) <= (lastpc-pc)) and
(CompareByte(OldPattern[strcount][1],pc^,Length(OldPattern[strcount]))=0) then
begin
ResStr := ResStr + NewPattern[strcount];
pc := pc+Length(OldPattern[strcount]);
pcc := pcc+Length(OldPattern[strcount]);
Found := true;
end
end;
if not found then
begin
ResStr := ResStr + pcc^;
inc(pc);
inc(pcc);
end
else if not (rfReplaceAll in Flags) then
begin
ResStr := ResStr + StrPas(pcc);
break;
end;
end;
Result := ResStr;
end;
{ ---------------------------------------------------------------------
Delphi compat
---------------------------------------------------------------------}
Function ReplaceStr(const AText, AFromText, AToText: string): string;inline;
begin
result:=AnsiReplaceStr(AText, AFromText, AToText);
end;
Function ReplaceText(const AText, AFromText, AToText: string): string;inline;
begin
result:=AnsiReplaceText(AText, AFromText, AToText);
end;
{ ---------------------------------------------------------------------
Soundex Functions.
---------------------------------------------------------------------}
Const
SScore : array[1..255] of Char =
('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 1..32
'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 33..64
'0','1','2','3','0','1','2','i','0','2','2','4','5','5','0','1','2','6','2','3','0','1','i','2','i','2', // 65..90
'0','0','0','0','0','0', // 91..96
'0','1','2','3','0','1','2','i','0','2','2','4','5','5','0','1','2','6','2','3','0','1','i','2','i','2', // 97..122
'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 123..154
'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 155..186
'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 187..218
'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', // 219..250
'0','0','0','0','0'); // 251..255
Function Soundex(const AText: string; ALength: TSoundexLength): string;
Var
S,PS : Char;
I,L : SizeInt;
begin
Result:='';
PS:=#0;
If Length(AText)>0 then
begin
Result:=Upcase(AText[1]);
I:=2;
L:=Length(AText);
While (I<=L) and (Length(Result)<ALength) do
begin
S:=SScore[Ord(AText[i])];
If Not (S in ['0','i',PS]) then
Result:=Result+S;
If (S<>'i') then
PS:=S;
Inc(I);
end;
end;
L:=Length(Result);
If (L<ALength) then
Result:=Result+StringOfChar('0',Alength-L);
end;
Function Soundex(const AText: string): string;inline; // ; ALength: TSoundexLength = 4
begin
Result:=Soundex(AText,4);
end;
Const
Ord0 = Ord('0');
OrdA = Ord('A');
Function SoundexInt(const AText: string; ALength: TSoundexIntLength): Integer;
var
SE: string;
I: SizeInt;
begin
Result:=-1;
SE:=Soundex(AText,ALength);
If Length(SE)>0 then
begin
Result:=Ord(SE[1])-OrdA;
if ALength > 1 then
begin
Result:=Result*26+(Ord(SE[2])-Ord0);
for I:=3 to ALength do
Result:=(Ord(SE[I])-Ord0)+Result*7;
end;
Result:=ALength+Result*9;
end;
end;
Function SoundexInt(const AText: string): Integer;inline; //; ALength: TSoundexIntLength = 4
begin
Result:=SoundexInt(AText,4);
end;
Function DecodeSoundexInt(AValue: Integer): string;
var
I, Len: Integer;
begin
Result := '';
Len := AValue mod 9;
AValue := AValue div 9;
for I:=Len downto 3 do
begin
Result:=Chr(Ord0+(AValue mod 7))+Result;
AValue:=AValue div 7;
end;
if Len>1 then
begin
Result:=Chr(Ord0+(AValue mod 26))+Result;
AValue:=AValue div 26;
end;
Result:=Chr(OrdA+AValue)+Result;
end;
Function SoundexWord(const AText: string): Word;
Var
S : String;
begin
S:=SoundEx(Atext,4);
Result:=Ord(S[1])-OrdA;
Result:=Result*26+ord(S[2])-48;
Result:=Result*7+ord(S[3])-48;
Result:=Result*7+ord(S[4])-48;
end;
Function DecodeSoundexWord(AValue: Word): string;
begin
Result := Chr(Ord0+ (AValue mod 7));
AValue := AValue div 7;
Result := Chr(Ord0+ (AValue mod 7)) + Result;
AValue := AValue div 7;
Result := IntToStr(AValue mod 26) + Result;
AValue := AValue div 26;
Result := Chr(OrdA+AValue) + Result;
end;
Function SoundexSimilar(const AText, AOther: string; ALength: TSoundexLength): Boolean;inline;
begin
Result:=Soundex(AText,ALength)=Soundex(AOther,ALength);
end;
Function SoundexSimilar(const AText, AOther: string): Boolean;inline; //; ALength: TSoundexLength = 4
begin
Result:=SoundexSimilar(AText,AOther,4);
end;
Function SoundexCompare(const AText, AOther: string; ALength: TSoundexLength): Integer;inline;
begin
Result:=AnsiCompareStr(Soundex(AText,ALength),Soundex(AOther,ALength));
end;
Function SoundexCompare(const AText, AOther: string): Integer;inline; //; ALength: TSoundexLength = 4
begin
Result:=SoundexCompare(AText,AOther,4);
end;
Function SoundexProc(const AText, AOther: string): Boolean;
begin
Result:=SoundexSimilar(AText,AOther);
end;
{ ---------------------------------------------------------------------
RxStrUtils-like functions.
---------------------------------------------------------------------}
function IsEmptyStr(const S: string; const EmptyChars: TSysCharSet): Boolean;
var
i,l: SizeInt;
begin
l:=Length(S);
i:=1;
Result:=True;
while Result and (i<=l) do
begin
Result:=(S[i] in EmptyChars);
Inc(i);
end;
end;
function DelSpace(const S: String): string;
begin
Result:=DelChars(S,' ');
end;
function DelChars(const S: string; Chr: Char): string;
var
I,J: SizeInt;
begin
Result:=S;
I:=Length(Result);
While I>0 do
begin
if Result[I]=Chr then
begin
J:=I-1;
While (J>0) and (Result[J]=Chr) do
Dec(j);
Delete(Result,J+1,I-J);
I:=J+1;
end;
dec(I);
end;
end;
function DelSpace1(const S: string): string;
var
I : SizeInt;
begin
Result:=S;
for i:=Length(Result) downto 2 do
if (Result[i]=' ') and (Result[I-1]=' ') then
Delete(Result,I,1);
end;
function Tab2Space(const S: string; Numb: Byte): string;
var
I: SizeInt;
begin
I:=1;
Result:=S;
while I <= Length(Result) do
if Result[I]<>Chr(9) then
inc(I)
else
begin
Result[I]:=' ';
If (Numb>1) then
Insert(StringOfChar(' ',Numb-1),Result,I);
Inc(I,Numb);
end;
end;
function NPos(const C: string; S: string; N: Integer): SizeInt;
var
i,p,k: SizeInt;
begin
Result:=0;
if N<1 then
Exit;
k:=0;
i:=1;
Repeat
p:=pos(C,S);
Inc(k,p);
if p>0 then
delete(S,1,p);
Inc(i);
Until (i>n) or (p=0);
If (P>0) then
Result:=K;
end;
function AddChar(C: Char; const S: string; N: Integer): string;
Var
l : SizeInt;
begin
Result:=S;
l:=Length(Result);
if l<N then
Result:=StringOfChar(C,N-l)+Result;
end;
function AddCharR(C: Char; const S: string; N: Integer): string;
Var
l : SizeInt;
begin
Result:=S;
l:=Length(Result);
if l<N then
Result:=Result+StringOfChar(C,N-l);
end;
function PadRight(const S: string; N: Integer): string;inline;
begin
Result:=AddCharR(' ',S,N);
end;
function PadLeft(const S: string; N: Integer): string;inline;
begin
Result:=AddChar(' ',S,N);
end;
function Copy2Symb(const S: string; Symb: Char): string;
var
p: SizeInt;
begin
p:=Pos(Symb,S);
if p=0 then
p:=Length(S)+1;
Result:=Copy(S,1,p-1);
end;
function Copy2SymbDel(var S: string; Symb: Char): string;
var
p: SizeInt;
begin
p:=Pos(Symb,S);
if p=0 then
begin
result:=s;
s:='';
end
else
begin
Result:=Copy(S,1,p-1);
delete(s,1,p);
end;
end;
function Copy2Space(const S: string): string;inline;
begin
Result:=Copy2Symb(S,' ');
end;
function Copy2SpaceDel(var S: string): string;inline;
begin
Result:=Copy2SymbDel(S,' ');
end;
function AnsiProperCase(const S: string; const WordDelims: TSysCharSet): string;
var
P,PE : PChar;
begin
Result:=AnsiLowerCase(S);
P:=PChar(pointer(Result));
PE:=P+Length(Result);
while (P<PE) do
begin
while (P<PE) and (P^ in WordDelims) do
inc(P);
if (P<PE) then
P^:=UpCase(P^);
while (P<PE) and not (P^ in WordDelims) do
inc(P);
end;
end;
function WordCount(const S: string; const WordDelims: TSysCharSet): SizeInt;
var
P,PE : PChar;
begin
Result:=0;
P:=Pchar(pointer(S));
PE:=P+Length(S);
while (P<PE) do
begin
while (P<PE) and (P^ in WordDelims) do
Inc(P);
if (P<PE) then
inc(Result);
while (P<PE) and not (P^ in WordDelims) do
inc(P);
end;
end;
function WordPosition(const N: Integer; const S: string; const WordDelims: TSysCharSet): SizeInt;
var
PS,P,PE : PChar;
Count: Integer;
begin
Result:=0;
Count:=0;
PS:=PChar(pointer(S));
PE:=PS+Length(S);
P:=PS;
while (P<PE) and (Count<>N) do
begin
while (P<PE) and (P^ in WordDelims) do
inc(P);
if (P<PE) then
inc(Count);
if (Count<>N) then
while (P<PE) and not (P^ in WordDelims) do
inc(P)
else
Result:=(P-PS)+1;
end;
end;
function ExtractWord(N: Integer; const S: string; const WordDelims: TSysCharSet): string;inline;
var
i: SizeInt;
begin
Result:=ExtractWordPos(N,S,WordDelims,i);
end;
function ExtractWordPos(N: Integer; const S: string; const WordDelims: TSysCharSet; out Pos: Integer): string;
var
i,j,l: SizeInt;
begin
j:=0;
i:=WordPosition(N, S, WordDelims);
if (I>High(Integer)) then
begin
Result:='';
Pos:=-1;
Exit;
end;
Pos:=i;
if (i<>0) then
begin
j:=i;
l:=Length(S);
while (j<=L) and not (S[j] in WordDelims) do
inc(j);
end;
SetLength(Result,j-i);
If ((j-i)>0) then
Move(S[i],Result[1],j-i);
end;
{$IF SIZEOF(SIZEINT)<>SIZEOF(INTEGER)}
function ExtractWordPos(N: Integer; const S: string; const WordDelims: TSysCharSet; Out Pos: SizeInt): string;
var
i,j,l: SizeInt;
begin
j:=0;
i:=WordPosition(N, S, WordDelims);
Pos:=i;
if (i<>0) then
begin
j:=i;
l:=Length(S);
while (j<=L) and not (S[j] in WordDelims) do
inc(j);
end;
SetLength(Result,j-i);
If ((j-i)>0) then
Move(S[i],Result[1],j-i);
end;
{$ENDIF}
function ExtractDelimited(N: Integer; const S: string; const Delims: TSysCharSet): string;
var
w,i,l,len: SizeInt;
begin
w:=0;
i:=1;
l:=0;
len:=Length(S);
SetLength(Result, 0);
while (i<=len) and (w<>N) do
begin
if s[i] in Delims then
inc(w)
else
begin
if (N-1)=w then
begin
inc(l);
SetLength(Result,l);
Result[L]:=S[i];
end;
end;
inc(i);
end;
end;
{$IF SIZEOF(SIZEINT)<>SIZEOF(INTEGER)}
function ExtractSubstr(const S: string; var Pos: SizeInt; const Delims: TSysCharSet): string;
var
i,l: SizeInt;
begin
i:=Pos;
l:=Length(S);
while (i<=l) and not (S[i] in Delims) do
inc(i);
Result:=Copy(S,Pos,i-Pos);
while (i<=l) and (S[i] in Delims) do
inc(i);
Pos:=i;
end;
{$ENDIF}
function ExtractSubstr(const S: string; var Pos: Integer; const Delims: TSysCharSet): string;
var
i,l: SizeInt;
begin
i:=Pos;
l:=Length(S);
while (i<=l) and not (S[i] in Delims) do
inc(i);
Result:=Copy(S,Pos,i-Pos);
while (i<=l) and (S[i] in Delims) do
inc(i);
if I>MaxInt then
Pos:=MaxInt
else
Pos:=i;
end;
function isWordPresent(const W, S: string; const WordDelims: TSysCharSet): Boolean;
var
i,Count : SizeInt;
begin
Result:=False;
Count:=WordCount(S, WordDelims);
I:=1;
While (Not Result) and (I<=Count) do
begin
Result:=ExtractWord(i,S,WordDelims)=W;
Inc(i);
end;
end;
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i:=Length(S);
Result:=S;
NA:=0;
while (i > 0) do begin
if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then
begin
insert(',', Result, i);
inc(NA);
end;
Dec(i);
end;
end;
function PadCenter(const S: string; Len: SizeInt): string;
begin
if Length(S)<Len then
begin
Result:=StringOfChar(' ',(Len div 2) -(Length(S) div 2))+S;
Result:=Result+StringOfChar(' ',Len-Length(Result));
end
else
Result:=S;
end;
function Dec2Numb(N: Longint; Len, Base: Byte): string;
var
C: Integer;
Number: Longint;
begin
if N=0 then
Result:='0'
else
begin
Number:=N;
Result:='';
while Number>0 do
begin
C:=Number mod Base;
if C>9 then
C:=C+55
else
C:=C+48;
Result:=Chr(C)+Result;
Number:=Number div Base;
end;
end;
if (Result<>'') then
Result:=AddChar('0',Result,Len);
end;
function Numb2Dec(S: string; Base: Byte): Longint;
var
i, P: sizeint;
begin
i:=Length(S);
Result:=0;
S:=UpperCase(S);
P:=1;
while (i>=1) do
begin
if (S[i]>'@') then
Result:=Result+(Ord(S[i])-55)*P
else
Result:=Result+(Ord(S[i])-48)*P;
Dec(i);
P:=P*Base;
end;
end;
function RomanToIntDontCare(const S: String): Longint;
{This was the original implementation of RomanToInt,
it is internally used in TryRomanToInt when Strictness = rcsDontCare}
const
RomanChars = ['C','D','I','L','M','V','X'];
RomanValues : array['C'..'X'] of Word
= (100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10);
var
index, Next: Char;
i,l: SizeInt;
Negative: Boolean;
begin
Result:=0;
i:=0;
Negative:=(Length(S)>0) and (S[1]='-');
if Negative then
inc(i);
l:=Length(S);
while (i<l) do
begin
inc(i);
index:=UpCase(S[i]);
if index in RomanChars then
begin
if Succ(i)<=l then
Next:=UpCase(S[i+1])
else
Next:=#0;
if (Next in RomanChars) and (RomanValues[index]<RomanValues[Next]) then
begin
inc(Result, RomanValues[Next]);
Dec(Result, RomanValues[index]);
inc(i);
end
else
inc(Result, RomanValues[index]);
end
else
begin
Result:=0;
Exit;
end;
end;
if Negative then
Result:=-Result;
end;
{ TryRomanToInt: try to convert a roman numeral to an integer
Parameters:
S: Roman numeral (like: 'MCMXXII')
N: Integer value of S (only meaningfull if the function succeeds)
Stricness: controls how strict the parsing of S is
- rcsStrict:
* Follow common subtraction rules
- only 1 preceding subtraction character allowed: IX = 9, but IIX <> 8
- from M you can only subtract C
- from D you can only subtract C
- from C you can only subtract X
- from L you can only subtract X
- from X you can only subtract I
- from V you can only subtract I
* The numeral is parsed in "groups" (first M's, then D's etc.), the next group to be parsed
must always be of a lower denomination than the previous one.
Example: 'MMDCCXX' is allowed but 'MMCCXXDD' is not
* There can only ever be 3 consecutive M's, C's, X's or I's
* There can only ever be 1 D, 1 L and 1 V
* After IX or IV there can be no more characters
* Negative numbers are not supported
// As a consequence the maximum allowed Roman numeral is MMMCMXCIX = 3999, also N can never become 0 (zero)
- rcsRelaxed: Like rcsStrict but with the following exceptions:
* An infinite number of (leading) M's is allowed
* Up to 4 consecutive M's, C's, X's and I's are allowed
// So this is allowed: 'MMMMMMCXIIII' = 6124
- rcsDontCare:
* no checking on the order of "groups" is done
* there are no restrictions on the number of consecutive chars
* negative numbers are supported
* an empty string as input will return True and N will be 0
* invalid input will return false
// for backwards comatibility: it supports rather ludicrous input like '-IIIMIII' -> -(2+(1000-1)+3)=-1004
}
function TryRomanToInt(S: String; out N: LongInt; Strictness: TRomanConversionStrictness = rcsRelaxed): Boolean;
var
i, Len: SizeInt;
Terminated: Boolean;
begin
Result := (False);
S := UpperCase(S); //don't use AnsiUpperCase please
Len := Length(S);
if (Strictness = rcsDontCare) then
begin
N := RomanToIntDontCare(S);
if (N = 0) then
begin
Result := (Len = 0);
end
else
Result := True;
Exit;
end;
if (Len = 0) then Exit;
i := 1;
N := 0;
Terminated := False;
//leading M's
while (i <= Len) and ((Strictness <> rcsStrict) or (i < 4)) and (S[i] = 'M') do
begin
//writeln('TryRomanToInt: Found 1000');
Inc(i);
N := N + 1000;
end;
//then CM or or CD or D or (C, CC, CCC, CCCC)
if (i <= Len) and (S[i] = 'D') then
begin
//writeln('TryRomanToInt: Found 500');
Inc(i);
N := N + 500;
end
else if (i + 1 <= Len) and (S[i] = 'C') then
begin
if (S[i+1] = 'M') then
begin
//writeln('TryRomanToInt: Found 900');
Inc(i,2);
N := N + 900;
end
else if (S[i+1] = 'D') then
begin
//writeln('TryRomanToInt: Found 400');
Inc(i,2);
N := N + 400;
end;
end ;
//next max 4 or 3 C's, depending on Strictness
if (i <= Len) and (S[i] = 'C') then
begin
//find max 4 C's
//writeln('TryRomanToInt: Found 100');
Inc(i);
N := N + 100;
if (i <= Len) and (S[i] = 'C') then
begin
//writeln('TryRomanToInt: Found 100');
Inc(i);
N := N + 100;
end;
if (i <= Len) and (S[i] = 'C') then
begin
//writeln('TryRomanToInt: Found 100');
Inc(i);
N := N + 100;
end;
if (Strictness <> rcsStrict) and (i <= Len) and (S[i] = 'C') then
begin
//writeln('TryRomanToInt: Found 100');
Inc(i);
N := N + 100;
end;
end;
//then XC or XL
if (i + 1 <= Len) and (S[i] = 'X') then
begin
if (S[i+1] = 'C') then
begin
//writeln('TryRomanToInt: Found 90');
Inc(i,2);
N := N + 90;
end
else if (S[i+1] = 'L') then
begin
//writeln('TryRomanToInt: Found 40');
Inc(i,2);
N := N + 40;
end;
end;
//then L
if (i <= Len) and (S[i] = 'L') then
begin
//writeln('TryRomanToInt: Found 50');
Inc(i);
N := N + 50;
end;
//then (X, xx, xxx, xxxx)
if (i <= Len) and (S[i] = 'X') then
begin
//find max 3 or 4 X's, depending on Strictness
//writeln('TryRomanToInt: Found 10');
Inc(i);
N := N + 10;
if (i <= Len) and (S[i] = 'X') then
begin
//writeln('TryRomanToInt: Found 10');
Inc(i);
N := N + 10;
end;
if (i <= Len) and (S[i] = 'X') then
begin
//writeln('TryRomanToInt: Found 10');
Inc(i);
N := N + 10;
end;
if (Strictness <> rcsStrict) and (i <= Len) and (S[i] = 'X') then
begin
//writeln('TryRomanToInt: Found 10');
Inc(i);
N := N + 10;
end;
end;
//then IX or IV
if (i + 1 <= Len) and (S[i] = 'I') then
begin
if (S[i+1] = 'X') then
begin
Terminated := (True);
//writeln('TryRomanToInt: Found 9');
Inc(i,2);
N := N + 9;
end
else if (S[i+1] = 'V') then
begin
Terminated := (True);
//writeln('TryRomanToInt: Found 4');
Inc(i,2);
N := N + 4;
end;
end;
//then V
if (not Terminated) and (i <= Len) and (S[i] = 'V') then
begin
//writeln('TryRomanToInt: Found 5');
Inc(i);
N := N + 5;
end;
//then I
if (not Terminated) and (i <= Len) and (S[i] = 'I') then
begin
Terminated := (True);
//writeln('TryRomanToInt: Found 1');
Inc(i);
N := N + 1;
//Find max 2 or 3 closing I's, depending on strictness
if (i <= Len) and (S[i] = 'I') then
begin
//writeln('TryRomanToInt: Found 1');
Inc(i);
N := N + 1;
end;
if (i <= Len) and (S[i] = 'I') then
begin
//writeln('TryRomanToInt: Found 1');
Inc(i);
N := N + 1;
end;
if (Strictness <> rcsStrict) and (i <= Len) and (S[i] = 'I') then
begin
//writeln('TryRomanToInt: Found 1');
Inc(i);
N := N + 1;
end;
end;
//writeln('TryRomanToInt: Len = ',Len,' i = ',i);
Result := (i > Len);
//if Result then writeln('TryRomanToInt: N = ',N);
end;
function RomanToInt(const S: string; Strictness: TRomanConversionStrictness = rcsRelaxed): Longint;
begin
if not TryRomanToInt(S, Result, Strictness) then
raise EConvertError.CreateFmt(SInvalidRomanNumeral,[S]);
end;
function RomanToIntDef(const S: String; const ADefault: Longint;
Strictness: TRomanConversionStrictness): Longint;
begin
if not TryRomanToInt(S, Result, Strictness) then
Result := ADefault;
end;
function intToRoman(Value: Longint): string;
const
Arabics : Array[1..13] of Integer
= (1,4,5,9,10,40,50,90,100,400,500,900,1000);
Romans : Array[1..13] of String
= ('I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M');
var
i: Integer;
begin
Result:='';
for i:=13 downto 1 do
while (Value >= Arabics[i]) do
begin
Value:=Value-Arabics[i];
Result:=Result+Romans[i];
end;
end;
function intToBin(Value: Longint; Digits, Spaces: Integer): string;
var endpos : integer;
p,p2:pchar;
k: integer;
begin
Result:='';
if (Digits>32) then
Digits:=32;
if (spaces=0) then
begin
result:=inttobin(value,digits);
exit;
end;
endpos:=digits+ (digits-1) div spaces;
setlength(result,endpos);
p:=@result[endpos];
p2:=@result[1];
k:=spaces;
while (p>=p2) do
begin
if k=0 then
begin
p^:=' ';
dec(p);
k:=spaces;
end;
p^:=chr(48+(cardinal(value) and 1));
value:=cardinal(value) shr 1;
dec(p);
dec(k);
end;
end;
function intToBin(Value: Longint; Digits:integer): string;
var p,p2 : pchar;
begin
result:='';
if digits<=0 then exit;
setlength(result,digits);
p:=pchar(pointer(@result[digits]));
p2:=pchar(pointer(@result[1]));
// typecasts because we want to keep intto* delphi compat and take an integer
while (p>=p2) and (cardinal(value)>0) do
begin
p^:=chr(48+(cardinal(value) and 1));
value:=cardinal(value) shr 1;
dec(p);
end;
digits:=p-p2+1;
if digits>0 then
fillchar(result[1],digits,#48);
end;
function intToBin(Value: int64; Digits:integer): string;
var p,p2 : pchar;
begin
result:='';
if digits<=0 then exit;
setlength(result,digits);
p:=pchar(pointer(@result[digits]));
p2:=pchar(pointer(@result[1]));
// typecasts because we want to keep intto* delphi compat and take a signed val
// and avoid warnings
while (p>=p2) and (qword(value)>0) do
begin
p^:=chr(48+(cardinal(value) and 1));
value:=qword(value) shr 1;
dec(p);
end;
digits:=p-p2+1;
if digits>0 then
fillchar(result[1],digits,#48);
end;
function FindPart(const HelpWilds, inputStr: string): SizeInt;
var
Diff, i, J: SizeInt;
begin
Result:=0;
i:=Pos('?',HelpWilds);
if (i=0) then
Result:=Pos(HelpWilds, inputStr)
else
begin
Diff:=Length(inputStr) - Length(HelpWilds);
for i:=0 to Diff do
begin
for J:=1 to Length(HelpWilds) do
if (inputStr[i + J] = HelpWilds[J]) or (HelpWilds[J] = '?') then
begin
if (J=Length(HelpWilds)) then
begin
Result:=i+1;
Exit;
end;
end
else
Break;
end;
end;
end;
Function isMatch(level : integer;inputstr,wilds : string; CWild, CinputWord: SizeInt;MaxInputword,maxwilds : SizeInt; Out EOS : Boolean) : Boolean;
begin
EOS:=False;
Result:=True;
repeat
if Wilds[CWild] = '*' then { handling of '*' }
begin
inc(CWild);
while Wilds[CWild] = '?' do { equal to '?' }
begin
{ goto next letter }
inc(CWild);
inc(CinputWord);
end;
{ increase until a match }
Repeat
while (inputStr[CinputWord]<>Wilds[CWild]) and (CinputWord <= MaxinputWord) do
inc(CinputWord);
Result:=isMatch(Level+1,inputstr,wilds,CWild, CinputWord,MaxInputword,maxwilds,EOS);
if not Result then
Inc(cInputWord);
Until Result or (CinputWord>=MaxinputWord);
if Result and EOS then
Exit;
Continue;
end;
if Wilds[CWild] = '?' then { equal to '?' }
begin
{ goto next letter }
inc(CWild);
inc(CinputWord);
Continue;
end;
if inputStr[CinputWord] = Wilds[CWild] then { equal letters }
begin
{ goto next letter }
inc(CWild);
inc(CinputWord);
Continue;
end;
Result:=false;
Exit;
until (CinputWord > MaxinputWord) or (CWild > MaxWilds);
{ no completed evaluation, we need to check what happened }
if (CinputWord <= MaxinputWord) or (CWild < MaxWilds) then
Result:=false
else if (CWild>Maxwilds) then
EOS:=False
else
begin
EOS:=Wilds[CWild]='*';
if not EOS then
Result:=False;
end
end;
function isWild(inputStr, Wilds: string; ignoreCase: boolean): boolean;
var
i: SizeInt;
MaxinputWord, MaxWilds: SizeInt; { Length of inputStr and Wilds }
eos : Boolean;
begin
Result:=true;
if Wilds = inputStr then
Exit;
{ delete '**', because '**' = '*' }
i:=Pos('**', Wilds);
while i > 0 do
begin
Delete(Wilds, i, 1);
i:=Pos('**', Wilds);
end;
if Wilds = '*' then { for fast end, if Wilds only '*' }
Exit;
MaxinputWord:=Length(inputStr);
MaxWilds:=Length(Wilds);
if (MaxWilds = 0) or (MaxinputWord = 0) then
begin
Result:=false;
Exit;
end;
if ignoreCase then { upcase all letters }
begin
inputStr:=AnsiUpperCase(inputStr);
Wilds:=AnsiUpperCase(Wilds);
end;
Result:=isMatch(1,inputStr,wilds,1,1,MaxinputWord, MaxWilds,EOS);
end;
function XorString(const Key, Src: ShortString): ShortString;
var
i: SizeInt;
begin
Result:=Src;
if Length(Key) > 0 then
for i:=1 to Length(Src) do
Result[i]:=Chr(Byte(Key[1 + ((i - 1) mod Length(Key))]) xor Ord(Src[i]));
end;
function XorEncode(const Key, Source: string): string;
var
i: Integer;
C: Byte;
begin
Result:='';
for i:=1 to Length(Source) do
begin
if Length(Key) > 0 then
C:=Byte(Key[1 + ((i - 1) mod Length(Key))]) xor Byte(Source[i])
else
C:=Byte(Source[i]);
Result:=Result+AnsiLowerCase(intToHex(C, 2));
end;
end;
function XorDecode(const Key, Source: string): string;
var
i: Integer;
C: Char;
begin
Result:='';
for i:=0 to Length(Source) div 2 - 1 do
begin
C:=Chr(StrTointDef('$' + Copy(Source, (i * 2) + 1, 2), Ord(' ')));
if Length(Key) > 0 then
C:=Chr(Byte(Key[1 + (i mod Length(Key))]) xor Byte(C));
Result:=Result + C;
end;
end;
function GetCmdLineArg(const Switch: string; SwitchChars: TSysCharSet): string;
var
i: Integer;
S: string;
begin
i:=1;
Result:='';
while (Result='') and (i<=ParamCount) do
begin
S:=ParamStr(i);
if (SwitchChars=[]) or ((S[1] in SwitchChars) and (Length(S) > 1)) and
(AnsiCompareText(Copy(S,2,Length(S)-1),Switch)=0) then
begin
inc(i);
if i<=ParamCount then
Result:=ParamStr(i);
end;
inc(i);
end;
end;
Function RPosEX(C:char;const S : AnsiString;offs:cardinal):SizeInt; overload;
var I : SizeUInt;
p,p2: pChar;
Begin
I:=Length(S);
If (I<>0) and (offs<=i) Then
begin
p:=@s[offs];
p2:=@s[1];
while (p2<=p) and (p^<>c) do dec(p);
RPosEx:=(p-p2)+1;
end
else
RPosEX:=0;
End;
Function RPos(c:char;const S : AnsiString):SizeInt; overload;
var I : SizeInt;
p,p2: pChar;
Begin
I:=Length(S);
If I<>0 Then
begin
p:=@s[i];
p2:=@s[1];
while (p2<=p) and (p^<>c) do dec(p);
i:=p-p2+1;
end;
RPos:=i;
End;
Function RPos (Const Substr : AnsiString; Const Source : AnsiString) : SizeInt; overload;
var
MaxLen,llen : SizeInt;
c : char;
pc,pc2 : pchar;
begin
rPos:=0;
llen:=Length(SubStr);
maxlen:=length(source);
if (llen>0) and (maxlen>0) and ( llen<=maxlen) then
begin
// i:=maxlen;
pc:=@source[maxlen];
pc2:=@source[llen-1];
c:=substr[llen];
while pc>=pc2 do
begin
if (c=pc^) and
(CompareChar(Substr[1],pchar(pc-llen+1)^,Length(SubStr))=0) then
begin
rPos:=pchar(pc-llen+1)-pchar(@source[1])+1;
exit;
end;
dec(pc);
end;
end;
end;
Function RPosex (Const Substr : AnsiString; Const Source : AnsiString;offs:cardinal) : SizeInt; overload;
var
MaxLen,llen : SizeInt;
c : char;
pc,pc2 : pchar;
begin
rPosex:=0;
llen:=Length(SubStr);
maxlen:=length(source);
if SizeInt(offs)<maxlen then maxlen:=offs;
if (llen>0) and (maxlen>0) and ( llen<=maxlen) then
begin
// i:=maxlen;
pc:=@source[maxlen];
pc2:=@source[llen-1];
c:=substr[llen];
while pc>=pc2 do
begin
if (c=pc^) and
(CompareChar(Substr[1],pchar(pc-llen+1)^,Length(SubStr))=0) then
begin
rPosex:=pchar(pc-llen+1)-pchar(@source[1])+1;
exit;
end;
dec(pc);
end;
end;
end;
// def from delphi.about.com:
procedure BinToHex(BinValue, HexValue: PChar; BinBufSize: Integer);
Const
HexDigits='0123456789ABCDEF';
var
i : longint;
begin
for i:=0 to binbufsize-1 do
begin
HexValue[0]:=hexdigits[1+((ord(binvalue^) shr 4))];
HexValue[1]:=hexdigits[1+((ord(binvalue^) and 15))];
inc(hexvalue,2);
inc(binvalue);
end;
end;
function HexToBin(HexValue, BinValue: PChar; BinBufSize: Integer): Integer;
// more complex, have to accept more than bintohex
// A..F 1000001
// a..f 1100001
// 0..9 110000
var i,j,h,l : integer;
begin
i:=binbufsize;
while (i>0) do
begin
if hexvalue^ IN ['A'..'F','a'..'f'] then
h:=((ord(hexvalue^)+9) and 15)
else if hexvalue^ IN ['0'..'9'] then
h:=((ord(hexvalue^)) and 15)
else
break;
inc(hexvalue);
if hexvalue^ IN ['A'..'F','a'..'f'] then
l:=(ord(hexvalue^)+9) and 15
else if hexvalue^ IN ['0'..'9'] then
l:=(ord(hexvalue^)) and 15
else
break;
j := l + (h shl 4);
inc(hexvalue);
binvalue^:=chr(j);
inc(binvalue);
dec(i);
end;
result:=binbufsize-i;
end;
function possetex (const c:TSysCharSet;const s : ansistring;count:Integer ):SizeInt;
var i,j:SizeInt;
begin
if pchar(pointer(s))=nil then
j:=0
else
begin
i:=length(s);
j:=count;
if j>i then
begin
result:=0;
exit;
end;
while (j<=i) and (not (s[j] in c)) do inc(j);
if (j>i) then
j:=0; // not found.
end;
result:=j;
end;
function posset (const c:TSysCharSet;const s : ansistring ):SizeInt;
begin
result:=possetex(c,s,1);
end;
function possetex (const c:string;const s : ansistring;count:Integer ):SizeInt;
var cset : TSysCharSet;
i : SizeInt;
begin
cset:=[];
if length(c)>0 then
for i:=1 to length(c) do
include(cset,c[i]);
result:=possetex(cset,s,count);
end;
function posset (const c:string;const s : ansistring ):SizeInt;
var cset : TSysCharSet;
i : SizeInt;
begin
cset:=[];
if length(c)>0 then
for i:=1 to length(c) do
include(cset,c[i]);
result:=possetex(cset,s,1);
end;
Procedure Removeleadingchars(VAR S : AnsiString; Const CSet:TSysCharset);
VAR I,J : Longint;
Begin
I:=Length(S);
IF (I>0) Then
Begin
J:=1;
While (J<=I) And (S[J] IN CSet) DO
INC(J);
IF J>1 Then
Delete(S,1,J-1);
End;
End;
function TrimLeftSet(const S: String;const CSet:TSysCharSet): String;
begin
result:=s;
removeleadingchars(result,cset);
end;
Procedure RemoveTrailingChars(VAR S : AnsiString;Const CSet:TSysCharset);
VAR I,J: LONGINT;
Begin
I:=Length(S);
IF (I>0) Then
Begin
J:=I;
While (j>0) and (S[J] IN CSet) DO DEC(J);
IF J<>I Then
SetLength(S,J);
End;
End;
Function TrimRightSet(const S: String;const CSet:TSysCharSet): String;
begin
result:=s;
RemoveTrailingchars(result,cset);
end;
Procedure RemovePadChars(VAR S : AnsiString;Const CSet:TSysCharset);
VAR I,J,K: LONGINT;
Begin
I:=Length(S);
IF (I>0) Then
Begin
J:=I;
While (j>0) and (S[J] IN CSet) DO DEC(J);
if j=0 Then
begin
s:='';
exit;
end;
k:=1;
While (k<=I) And (S[k] IN CSet) DO
INC(k);
IF k>1 Then
begin
move(s[k],s[1],j-k+1);
setlength(s,j-k+1);
end
else
setlength(s,j);
End;
End;
function TrimSet(const S: String;const CSet:TSysCharSet): String;
begin
result:=s;
RemovePadChars(result,cset);
end;
end.
|
unit ParameterPoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, Parameter, TestInterval, MeasureUnits;
type
TParameterDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TParameterValueDataPoster = class(TImplementedDataPoster)
private
FParameters: TParameters;
public
property AllParameters: TParameters read FParameters write FParameters;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TParameterByWellDataPoster = class(TImplementedDataPoster)
private
FAllMeasureUnits: TMeasureUnits;
procedure SetAllMeasureUnits(const Value: TMeasureUnits);
public
property AllMeasureUnits: TMeasureUnits read FAllMeasureUnits write SetAllMeasureUnits;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TParametersGroupByWellDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TParameterValueByWellDataPoster = class(TImplementedDataPoster)
private
FAllParameters: TParametersByWell;
procedure SetAllParameters(const Value: TParametersByWell);
public
property AllParameters: TParametersByWell read FAllParameters write SetAllParameters;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Facade, SysUtils, Well;
{ TParameterDataPoster }
constructor TParameterDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_TESTING_PARAMETER_DICT';
KeyFieldNames := 'TESTING_PARAMETER_ID';
FieldNames := 'TESTING_PARAMETER_ID, VCH_TESTING_PARAM_NAME, VCH_TESTING_PARAM_SHORT_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_TESTING_PARAM_NAME';
end;
function TParameterDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TParameterDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TParameter;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TParameter;
o.ID := ds.FieldByName('Testing_Parameter_ID').AsInteger;
o.Name := trim(ds.FieldByName('vch_Testing_Param_Name').AsString);
o.ShortName := trim(ds.FieldByName('vch_Testing_Param_Short_Name').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TParameterDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TParameter;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TParameter;
ds.FieldByName('Testing_Parameter_ID').Value := o.ID;
ds.FieldByName('vch_Testing_Param_Name').Value := o.Name;
ds.FieldByName('vch_Testing_Param_Short_Name').Value := o.ShortName;
ds.Post;
o.ID := ds.FieldByName('Testing_Parameter_ID').Value;
end;
{ TParameterValueDataPoster }
constructor TParameterValueDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'tbl_Testing_Parameter_Value';
KeyFieldNames := 'TESTING_PARAMETER_VALUE_ID';
FieldNames := 'TESTING_PARAMETER_VALUE_ID, TESTING_INTERVAL_UIN, TESTING_PARAMETER_ID, num_Testing_Parameter_Value, vch_Testing_Parameter_Value';
AccessoryFieldNames := '';
AutoFillDates := false;
end;
function TParameterValueDataPoster.DeleteFromDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TParameterValueDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
p: TParameterValue;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
p := AObjects.Add as TParameterValue;
p.ID := ds.FieldByName('TESTING_PARAMETER_VALUE_ID').AsInteger;
p.Parameter := AllParameters.ItemsByID[ds.FieldByName('TESTING_PARAMETER_ID').AsInteger] as TParameter;
p.Value := ds.FieldByName('VCH_TESTING_PARAMETER_VALUE').AsString;
p.NumValue := ds.FieldByName('NUM_TESTING_PARAMETER_VALUE').AsFloat;
ds.Next;
end;
ds.First;
end;
end;
function TParameterValueDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
p: TParameterValue;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
p := AObject as TParameterValue;
ds.FieldByName('TESTING_PARAMETER_VALUE_ID').Value := p.ID;
ds.FieldByName('TESTING_PARAMETER_ID').Value := p.Parameter.ID;
ds.FieldByName('VCH_TESTING_PARAMETER_VALUE').Value := p.Value;
ds.FieldByName('NUM_TESTING_PARAMETER_VALUE').Value := p.NumValue;
ds.FieldByName('TESTING_INTERVAL_UIN').Value := p.Collection.Owner.ID;
ds.Post;
if p.ID <= 0 then p.ID := (ds as TCommonServerDataSet).CurrentRecordFilterValues[0];
end;
{ TParameterValueByWellDataPoster }
constructor TParameterValueByWellDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'TBL_PARAMETR_VALUES';
KeyFieldNames := 'PARAMETR_VALUE_ID';
FieldNames := 'PARAMETR_VALUE_ID, WELL_UIN, REASON_CHANGE_ID, INT_VALUE, VCH_VALUE, DTM_VALUE, DICT_VALUE_ID, TABLE_ID, PARAMETR_ID';
AccessoryFieldNames := 'PARAMETR_VALUE_ID, WELL_UIN, REASON_CHANGE_ID, INT_VALUE, VCH_VALUE, DTM_VALUE, DICT_VALUE_ID, TABLE_ID, PARAMETR_ID';
AutoFillDates := false;
Sort := 'PARAMETR_VALUE_ID';
end;
function TParameterValueByWellDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TParameterValueByWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TParameterValueByWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TParameterValueByWell;
o.ID := ds.FieldByName('PARAMETR_VALUE_ID').AsInteger;
o.INTValue := ds.FieldByName('INT_VALUE').AsInteger;
o.VCHValue := ds.FieldByName('VCH_VALUE').AsString;
o.DTMValue := ds.FieldByName('DTM_VALUE').AsDateTime;
//if Assigned ((o.Collection.Owner as TDinamicWell).ReasonChange) then
// ds.FieldByName('REASON_CHANGE_ID').AsInteger := (o.Collection.Owner as TDinamicWell).ReasonChange.ID;
o.ParametrWell := AllParameters.ItemsByID[ds.FieldByName('PARAMETR_ID').AsInteger] as TParameterByWell;
// WELL_UIN,
// REASON_CHANGE_ID,
// DICT_VALUE_ID,
// TABLE_ID
ds.Next;
end;
ds.First;
end;
end;
function TParameterValueByWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TParameterValueByWell;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TParameterValueByWell;
ds.FieldByName('PARAMETR_VALUE_ID').AsInteger := o.ID;
ds.FieldByName('WELL_UIN').AsInteger := o.Collection.Owner.ID;
//if Assigned ((o.Collection.Owner as TDinamicWell).ReasonChange) then
// ds.FieldByName('REASON_CHANGE_ID').AsInteger := (o.Collection.Owner as TDinamicWell).ReasonChange.ID;
ds.FieldByName('INT_VALUE').AsInteger := o.INTValue;
ds.FieldByName('VCH_VALUE').AsString := trim (o.VCHValue);
ds.FieldByName('DTM_VALUE').AsDateTime := o.DTMValue;
ds.FieldByName('PARAMETR_ID').AsInteger := o.ParametrWell.ID;
//DICT_VALUE_ID,
//TABLE_ID,
ds.Post;
if o.ID = 0 then o.ID := ds.FieldByName('PARAMETR_VALUE_ID').Value;
end;
procedure TParameterValueByWellDataPoster.SetAllParameters(
const Value: TParametersByWell);
begin
if FAllParameters <> Value then
FAllParameters := Value;
end;
{ TParameterByWellDataPoster }
constructor TParameterByWellDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'TBL_PARAMETRS_DICT';
KeyFieldNames := 'PARAMETR_ID';
FieldNames := 'PARAMETR_ID, PARAMETR_NAME, PARAMETR_GROUPS_ID, MEASURE_UNIT_ID';
AccessoryFieldNames := 'PARAMETR_ID, PARAMETR_NAME, PARAMETR_GROUPS_ID, MEASURE_UNIT_ID';
AutoFillDates := false;
Sort := 'PARAMETR_ID';
end;
function TParameterByWellDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TParameterByWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TParameterByWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TParameterByWell;
o.ID := ds.FieldByName('PARAMETR_ID').AsInteger;
o.Name := trim(ds.FieldByName('PARAMETR_NAME').AsString);
if ds.FieldByName('MEASURE_UNIT_ID').AsInteger > 0 then
o.MeasureUnit := FAllMeasureUnits.ItemsByID[ds.FieldByName('MEASURE_UNIT_ID').AsInteger] as TMeasureUnit;
ds.Next;
end;
ds.First;
end;
end;
function TParameterByWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TParameterByWell;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TParameterByWell;
ds.FieldByName('PARAMETR_ID').AsInteger := o.ID;
ds.FieldByName('PARAMETR_NAME').AsString := trim (o.Name);
ds.FieldByName('PARAMETR_GROUPS_ID').AsInteger := o.Owner.ID;
if Assigned (o.MeasureUnit) then
ds.FieldByName('MEASURE_UNIT_ID').AsInteger := o.MeasureUnit.ID;
ds.Post;
if o.ID = 0 then o.ID := ds.FieldByName('PARAMETR_ID').Value;
end;
{ TParameterGroupByWellDataPoster }
constructor TParametersGroupByWellDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'TBL_PARAMETR_GROUPS_DICT';
KeyFieldNames := 'PARAMETR_GROUPS_ID';
FieldNames := 'PARAMETR_GROUPS_ID, PARAMETR_GROUPS_NAME';
AccessoryFieldNames := 'PARAMETR_GROUPS_ID, PARAMETR_GROUPS_NAME';
AutoFillDates := false;
Sort := 'PARAMETR_GROUPS_ID';
end;
function TParametersGroupByWellDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TParametersGroupByWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TParametersGroupByWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TParametersGroupByWell;
o.ID := ds.FieldByName('PARAMETR_GROUPS_ID').AsInteger;
o.Name := trim(ds.FieldByName('PARAMETR_GROUPS_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TParametersGroupByWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TParametersGroupByWell;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TParametersGroupByWell;
ds.FieldByName('PARAMETR_GROUPS_ID').AsInteger := o.ID;
ds.FieldByName('PARAMETR_GROUPS_NAME').AsString := trim (o.Name);
ds.Post;
if o.ID = 0 then o.ID := ds.FieldByName('PARAMETR_GROUPS_ID').Value;
end;
procedure TParameterByWellDataPoster.SetAllMeasureUnits(
const Value: TMeasureUnits);
begin
if FAllMeasureUnits <> Value then
FAllMeasureUnits := Value;
end;
end.
|
{==============================================================================|
| Project : Ararat Synapse | 009.009.001 |
|==============================================================================|
| Content: Library base |
|==============================================================================|
| Copyright (c)1999-2013, Lukas Gebauer |
| 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 Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)1999-2013. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{
Special thanks to Gregor Ibic <gregor.ibic@intelicom.si>
(Intelicom d.o.o., http://www.intelicom.si)
for good inspiration about SSL programming.
}
{$DEFINE ONCEWINSOCK}
{Note about define ONCEWINSOCK:
If you remove this compiler directive, then socket interface is loaded and
initialized on constructor of TBlockSocket class for each socket separately.
Socket interface is used only if your need it.
If you leave this directive here, then socket interface is loaded and
initialized only once at start of your program! It boost performace on high
count of created and destroyed sockets. It eliminate possible small resource
leak on Windows systems too.
}
//{$DEFINE RAISEEXCEPT}
{When you enable this define, then is Raiseexcept property is on by default
}
{:@abstract(Synapse's library core)
Core with implementation basic socket classes.
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$IFDEF VER125}
{$DEFINE BCB}
{$ENDIF}
{$IFDEF BCB}
{$ObjExportAll On}
{$ENDIF}
{$Q-}
{$H+}
{$M+}
{$TYPEDADDRESS OFF}
//old Delphi does not have MSWINDOWS define.
{$IFDEF WIN32}
{$IFNDEF MSWINDOWS}
{$DEFINE MSWINDOWS}
{$ENDIF}
{$ENDIF}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit blcksock;
interface
uses
SysUtils, Classes,
synafpc,
synsock, synautil, synacode, synaip
{$IFDEF CIL}
,System.Net
,System.Net.Sockets
,System.Text
{$ENDIF}
;
const
SynapseRelease = '40';
cLocalhost = '127.0.0.1';
cAnyHost = '0.0.0.0';
cBroadcast = '255.255.255.255';
c6Localhost = '::1';
c6AnyHost = '::0';
c6Broadcast = 'ffff::1';
cAnyPort = '0';
CR = #$0d;
LF = #$0a;
CRLF = CR + LF;
c64k = 65536;
type
{:@abstract(Exception clas used by Synapse)
When you enable generating of exceptions, this exception is raised by
Synapse's units.}
ESynapseError = class(Exception)
private
FErrorCode: Integer;
FErrorMessage: string;
published
{:Code of error. Value depending on used operating system}
property ErrorCode: Integer read FErrorCode Write FErrorCode;
{:Human readable description of error.}
property ErrorMessage: string read FErrorMessage Write FErrorMessage;
end;
{:Types of OnStatus events}
THookSocketReason = (
{:Resolving is begin. Resolved IP and port is in parameter in format like:
'localhost.somewhere.com:25'.}
HR_ResolvingBegin,
{:Resolving is done. Resolved IP and port is in parameter in format like:
'localhost.somewhere.com:25'. It is always same as in HR_ResolvingBegin!}
HR_ResolvingEnd,
{:Socket created by CreateSocket method. It reporting Family of created
socket too!}
HR_SocketCreate,
{:Socket closed by CloseSocket method.}
HR_SocketClose,
{:Socket binded to IP and Port. Binded IP and Port is in parameter in format
like: 'localhost.somewhere.com:25'.}
HR_Bind,
{:Socket connected to IP and Port. Connected IP and Port is in parameter in
format like: 'localhost.somewhere.com:25'.}
HR_Connect,
{:Called when CanRead method is used with @True result.}
HR_CanRead,
{:Called when CanWrite method is used with @True result.}
HR_CanWrite,
{:Socket is swithed to Listen mode. (TCP socket only)}
HR_Listen,
{:Socket Accepting client connection. (TCP socket only)}
HR_Accept,
{:report count of bytes readed from socket. Number is in parameter string.
If you need is in integer, you must use StrToInt function!}
HR_ReadCount,
{:report count of bytes writed to socket. Number is in parameter string. If
you need is in integer, you must use StrToInt function!}
HR_WriteCount,
{:If is limiting of bandwidth on, then this reason is called when sending or
receiving is stopped for satisfy bandwidth limit. Parameter is count of
waiting milliseconds.}
HR_Wait,
{:report situation where communication error occured. When raiseexcept is
@true, then exception is called after this Hook reason.}
HR_Error
);
{:Procedural type for OnStatus event. Sender is calling TBlockSocket object,
Reason is one of set Status events and value is optional data.}
THookSocketStatus = procedure(Sender: TObject; Reason: THookSocketReason;
const Value: String) of object;
{:This procedural type is used for DataFilter hooks.}
THookDataFilter = procedure(Sender: TObject; var Value: AnsiString) of object;
{:This procedural type is used for hook OnCreateSocket. By this hook you can
insert your code after initialisation of socket. (you can set special socket
options, etc.)}
THookCreateSocket = procedure(Sender: TObject) of object;
{:This procedural type is used for monitoring of communication.}
THookMonitor = procedure(Sender: TObject; Writing: Boolean;
const Buffer: TMemory; Len: Integer) of object;
{:This procedural type is used for hook OnAfterConnect. By this hook you can
insert your code after TCP socket has been sucessfully connected.}
THookAfterConnect = procedure(Sender: TObject) of object;
{:This procedural type is used for hook OnVerifyCert. By this hook you can
insert your additional certificate verification code. Usefull to verify server
CN against URL. }
THookVerifyCert = function(Sender: TObject):boolean of object;
{:This procedural type is used for hook OnHeartbeat. By this hook you can
call your code repeately during long socket operations.
You must enable heartbeats by @Link(HeartbeatRate) property!}
THookHeartbeat = procedure(Sender: TObject) of object;
{:Specify family of socket.}
TSocketFamily = (
{:Default mode. Socket family is defined by target address for connection.
It allows instant access to IPv4 and IPv6 nodes. When you need IPv6 address
as destination, then is used IPv6 mode. othervise is used IPv4 mode.
However this mode not working properly with preliminary IPv6 supports!}
SF_Any,
{:Turn this class to pure IPv4 mode. This mode is totally compatible with
previous Synapse releases.}
SF_IP4,
{:Turn to only IPv6 mode.}
SF_IP6
);
{:specify possible values of SOCKS modes.}
TSocksType = (
ST_Socks5,
ST_Socks4
);
{:Specify requested SSL/TLS version for secure connection.}
TSSLType = (
LT_all,
LT_SSLv2,
LT_SSLv3,
LT_TLSv1,
LT_TLSv1_1,
LT_TLSv1_2,
LT_SSHv2
);
{:Specify type of socket delayed option.}
TSynaOptionType = (
SOT_Linger,
SOT_RecvBuff,
SOT_SendBuff,
SOT_NonBlock,
SOT_RecvTimeout,
SOT_SendTimeout,
SOT_Reuse,
SOT_TTL,
SOT_Broadcast,
SOT_MulticastTTL,
SOT_MulticastLoop
);
{:@abstract(this object is used for remember delayed socket option set.)}
TSynaOption = class(TObject)
public
Option: TSynaOptionType;
Enabled: Boolean;
Value: Integer;
end;
TCustomSSL = class;
TSSLClass = class of TCustomSSL;
{:@abstract(Basic IP object.)
This is parent class for other class with protocol implementations. Do not
use this class directly! Use @link(TICMPBlockSocket), @link(TRAWBlockSocket),
@link(TTCPBlockSocket) or @link(TUDPBlockSocket) instead.}
TBlockSocket = class(TObject)
private
FOnStatus: THookSocketStatus;
FOnReadFilter: THookDataFilter;
FOnCreateSocket: THookCreateSocket;
FOnMonitor: THookMonitor;
FOnHeartbeat: THookHeartbeat;
FLocalSin: TVarSin;
FRemoteSin: TVarSin;
FTag: integer;
FBuffer: AnsiString;
FRaiseExcept: Boolean;
FNonBlockMode: Boolean;
FMaxLineLength: Integer;
FMaxSendBandwidth: Integer;
FNextSend: LongWord;
FMaxRecvBandwidth: Integer;
FNextRecv: LongWord;
FConvertLineEnd: Boolean;
FLastCR: Boolean;
FLastLF: Boolean;
FBinded: Boolean;
FFamily: TSocketFamily;
FFamilySave: TSocketFamily;
FIP6used: Boolean;
FPreferIP4: Boolean;
FDelayedOptions: TList;
FInterPacketTimeout: Boolean;
{$IFNDEF CIL}
FFDSet: TFDSet;
{$ENDIF}
FRecvCounter: Integer;
FSendCounter: Integer;
FSendMaxChunk: Integer;
FStopFlag: Boolean;
FNonblockSendTimeout: Integer;
FHeartbeatRate: integer;
FConnectionTimeout: integer;
{$IFNDEF ONCEWINSOCK}
FWsaDataOnce: TWSADATA;
{$ENDIF}
function GetSizeRecvBuffer: Integer;
procedure SetSizeRecvBuffer(Size: Integer);
function GetSizeSendBuffer: Integer;
procedure SetSizeSendBuffer(Size: Integer);
procedure SetNonBlockMode(Value: Boolean);
procedure SetTTL(TTL: integer);
function GetTTL:integer;
procedure SetFamily(Value: TSocketFamily); virtual;
procedure SetSocket(Value: TSocket); virtual;
function GetWsaData: TWSAData;
function FamilyToAF(f: TSocketFamily): TAddrFamily;
protected
FSocket: TSocket;
FLastError: Integer;
FLastErrorDesc: string;
FOwner: TObject;
procedure SetDelayedOption(const Value: TSynaOption);
procedure DelayedOption(const Value: TSynaOption);
procedure ProcessDelayedOptions;
procedure InternalCreateSocket(Sin: TVarSin);
procedure SetSin(var Sin: TVarSin; IP, Port: string);
function GetSinIP(Sin: TVarSin): string;
function GetSinPort(Sin: TVarSin): Integer;
procedure DoStatus(Reason: THookSocketReason; const Value: string);
procedure DoReadFilter(Buffer: TMemory; var Len: Integer);
procedure DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
procedure DoCreateSocket;
procedure DoHeartbeat;
procedure LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
procedure SetBandwidth(Value: Integer);
function TestStopFlag: Boolean;
procedure InternalSendStream(const Stream: TStream; WithSize, Indy: boolean); virtual;
function InternalCanRead(Timeout: Integer): Boolean; virtual;
public
constructor Create;
{:Create object and load all necessary socket library. What library is
loaded is described by STUB parameter. If STUB is empty string, then is
loaded default libraries.}
constructor CreateAlternate(Stub: string);
destructor Destroy; override;
{:If @link(family) is not SF_Any, then create socket with type defined in
@link(Family) property. If family is SF_Any, then do nothing! (socket is
created automaticly when you know what type of socket you need to create.
(i.e. inside @link(Connect) or @link(Bind) call.) When socket is created,
then is aplyed all stored delayed socket options.}
procedure CreateSocket;
{:It create socket. Address resolving of Value tells what type of socket is
created. If Value is resolved as IPv4 IP, then is created IPv4 socket. If
value is resolved as IPv6 address, then is created IPv6 socket.}
procedure CreateSocketByName(const Value: String);
{:Destroy socket in use. This method is also automatically called from
object destructor.}
procedure CloseSocket; virtual;
{:Abort any work on Socket and destroy them.}
procedure AbortSocket; virtual;
{:Connects socket to local IP address and PORT. IP address may be numeric or
symbolic ('192.168.74.50', 'cosi.nekde.cz', 'ff08::1'). The same for PORT
- it may be number or mnemonic port ('23', 'telnet').
If port value is '0', system chooses itself and conects unused port in the
range 1024 to 4096 (this depending by operating system!). Structure
LocalSin is filled after calling this method.
Note: If you call this on non-created socket, then socket is created
automaticly.
Warning: when you call : Bind('0.0.0.0','0'); then is nothing done! In this
case is used implicit system bind instead.}
procedure Bind(IP, Port: string);
{:Connects socket to remote IP address and PORT. The same rules as with
@link(BIND) method are valid. The only exception is that PORT with 0 value
will not be connected!
Structures LocalSin and RemoteSin will be filled with valid values.
When you call this on non-created socket, then socket is created
automaticly. Type of created socket is by @link(Family) property. If is
used SF_IP4, then is created socket for IPv4. If is used SF_IP6, then is
created socket for IPv6. When you have family on SF_Any (default!), then
type of created socket is determined by address resolving of destination
address. (Not work properly on prilimitary winsock IPv6 support!)}
procedure Connect(IP, Port: string); virtual;
{:Sets socket to receive mode for new incoming connections. It is necessary
to use @link(TBlockSocket.BIND) function call before this method to select
receiving port!}
procedure Listen; virtual;
{:Waits until new incoming connection comes. After it comes a new socket is
automatically created (socket handler is returned by this function as
result).}
function Accept: TSocket; virtual;
{:Sends data of LENGTH from BUFFER address via connected socket. System
automatically splits data to packets.}
function SendBuffer(Buffer: Tmemory; Length: Integer): Integer; virtual;
{:One data BYTE is sent via connected socket.}
procedure SendByte(Data: Byte); virtual;
{:Send data string via connected socket. Any terminator is not added! If you
need send true string with CR-LF termination, you must add CR-LF characters
to sended string! Because any termination is not added automaticly, you can
use this function for sending any binary data in binary string.}
procedure SendString(Data: AnsiString); virtual;
{:Send integer as four bytes to socket.}
procedure SendInteger(Data: integer); virtual;
{:Send data as one block to socket. Each block begin with 4 bytes with
length of data in block. This 4 bytes is added automaticly by this
function.}
procedure SendBlock(const Data: AnsiString); virtual;
{:Send data from stream to socket.}
procedure SendStreamRaw(const Stream: TStream); virtual;
{:Send content of stream to socket. It using @link(SendBlock) method}
procedure SendStream(const Stream: TStream); virtual;
{:Send content of stream to socket. It using @link(SendBlock) method and
this is compatible with streams in Indy library.}
procedure SendStreamIndy(const Stream: TStream); virtual;
{:Note: This is low-level receive function. You must be sure if data is
waiting for read before call this function for avoid deadlock!
Waits until allocated buffer is filled by received data. Returns number of
data received, which equals to LENGTH value under normal operation. If it
is not equal the communication channel is possibly broken.
On stream oriented sockets if is received 0 bytes, it mean 'socket is
closed!"
On datagram socket is readed first waiting datagram.}
function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions!
Method waits until data is received. If no data is received within TIMEOUT
(in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT. Methods
serves for reading any size of data (i.e. one megabyte...). This method is
preffered for reading from stream sockets (like TCP).}
function RecvBufferEx(Buffer: Tmemory; Len: Integer;
Timeout: Integer): Integer; virtual;
{:Similar to @link(RecvBufferEx), but readed data is stored in binary
string, not in memory buffer.}
function RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions.
Waits until one data byte is received which is also returned as function
result. If no data is received within TIMEOUT (in milliseconds)period,
@link(LastError) is set to WSAETIMEDOUT and result have value 0.}
function RecvByte(Timeout: Integer): Byte; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions.
Waits until one four bytes are received and return it as one Ineger Value.
If no data is received within TIMEOUT (in milliseconds)period,
@link(LastError) is set to WSAETIMEDOUT and result have value 0.}
function RecvInteger(Timeout: Integer): Integer; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions.
Method waits until data string is received. This string is terminated by
CR-LF characters. The resulting string is returned without this termination
(CR-LF)! If @link(ConvertLineEnd) is used, then CR-LF sequence may not be
exactly CR-LF. See @link(ConvertLineEnd) description. If no data is
received within TIMEOUT (in milliseconds) period, @link(LastError) is set
to WSAETIMEDOUT. You may also specify maximum length of reading data by
@link(MaxLineLength) property.}
function RecvString(Timeout: Integer): AnsiString; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions.
Method waits until data string is received. This string is terminated by
Terminator string. The resulting string is returned without this
termination. If no data is received within TIMEOUT (in milliseconds)
period, @link(LastError) is set to WSAETIMEDOUT. You may also specify
maximum length of reading data by @link(MaxLineLength) property.}
function RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString; virtual;
{:Note: This is high-level receive function. It using internal
@link(LineBuffer) and you can combine this function freely with other
high-level functions.
Method reads all data waiting for read. If no data is received within
TIMEOUT (in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT.
Methods serves for reading unknown size of data. Because before call this
function you don't know size of received data, returned data is stored in
dynamic size binary string. This method is preffered for reading from
stream sockets (like TCP). It is very goot for receiving datagrams too!
(UDP protocol)}
function RecvPacket(Timeout: Integer): AnsiString; virtual;
{:Read one block of data from socket. Each block begin with 4 bytes with
length of data in block. This function read first 4 bytes for get lenght,
then it wait for reported count of bytes.}
function RecvBlock(Timeout: Integer): AnsiString; virtual;
{:Read all data from socket to stream until socket is closed (or any error
occured.)}
procedure RecvStreamRaw(const Stream: TStream; Timeout: Integer); virtual;
{:Read requested count of bytes from socket to stream.}
procedure RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer);
{:Receive data to stream. It using @link(RecvBlock) method.}
procedure RecvStream(const Stream: TStream; Timeout: Integer); virtual;
{:Receive data to stream. This function is compatible with similar function
in Indy library. It using @link(RecvBlock) method.}
procedure RecvStreamIndy(const Stream: TStream; Timeout: Integer); virtual;
{:Same as @link(RecvBuffer), but readed data stays in system input buffer.
Warning: this function not respect data in @link(LineBuffer)! Is not
recommended to use this function!}
function PeekBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
{:Same as @link(RecvByte), but readed data stays in input system buffer.
Warning: this function not respect data in @link(LineBuffer)! Is not
recommended to use this function!}
function PeekByte(Timeout: Integer): Byte; virtual;
{:On stream sockets it returns number of received bytes waiting for picking.
0 is returned when there is no such data. On datagram socket it returns
length of the first waiting datagram. Returns 0 if no datagram is waiting.}
function WaitingData: Integer; virtual;
{:Same as @link(WaitingData), but if exists some of data in @link(Linebuffer),
return their length instead.}
function WaitingDataEx: Integer;
{:Clear all waiting data for read from buffers.}
procedure Purge;
{:Sets linger. Enabled linger means that the system waits another LINGER
(in milliseconds) time for delivery of sent data. This function is only for
stream type of socket! (TCP)}
procedure SetLinger(Enable: Boolean; Linger: Integer);
{:Actualize values in @link(LocalSin).}
procedure GetSinLocal;
{:Actualize values in @link(RemoteSin).}
procedure GetSinRemote;
{:Actualize values in @link(LocalSin) and @link(RemoteSin).}
procedure GetSins;
{:Reset @link(LastError) and @link(LastErrorDesc) to non-error state.}
procedure ResetLastError;
{:If you "manually" call Socket API functions, forward their return code as
parameter to this function, which evaluates it, eventually calls
GetLastError and found error code returns and stores to @link(LastError).}
function SockCheck(SockResult: Integer): Integer; virtual;
{:If @link(LastError) contains some error code and @link(RaiseExcept)
property is @true, raise adequate exception.}
procedure ExceptCheck;
{:Returns local computer name as numerical or symbolic value. It try get
fully qualified domain name. Name is returned in the format acceptable by
functions demanding IP as input parameter.}
function LocalName: string;
{:Try resolve name to all possible IP address. i.e. If you pass as name
result of @link(LocalName) method, you get all IP addresses used by local
system.}
procedure ResolveNameToIP(Name: string; const IPList: TStrings);
{:Try resolve name to primary IP address. i.e. If you pass as name result of
@link(LocalName) method, you get primary IP addresses used by local system.}
function ResolveName(Name: string): string;
{:Try resolve IP to their primary domain name. If IP not have domain name,
then is returned original IP.}
function ResolveIPToName(IP: string): string;
{:Try resolve symbolic port name to port number. (i.e. 'Echo' to 8)}
function ResolvePort(Port: string): Word;
{:Set information about remote side socket. It is good for seting remote
side for sending UDP packet, etc.}
procedure SetRemoteSin(IP, Port: string);
{:Picks IP socket address from @link(LocalSin).}
function GetLocalSinIP: string; virtual;
{:Picks IP socket address from @link(RemoteSin).}
function GetRemoteSinIP: string; virtual;
{:Picks socket PORT number from @link(LocalSin).}
function GetLocalSinPort: Integer; virtual;
{:Picks socket PORT number from @link(RemoteSin).}
function GetRemoteSinPort: Integer; virtual;
{:Return @TRUE, if you can read any data from socket or is incoming
connection on TCP based socket. Status is tested for time Timeout (in
milliseconds). If value in Timeout is 0, status is only tested and
continue. If value in Timeout is -1, run is breaked and waiting for read
data maybe forever.
This function is need only on special cases, when you need use
@link(RecvBuffer) function directly! read functioms what have timeout as
calling parameter, calling this function internally.}
function CanRead(Timeout: Integer): Boolean; virtual;
{:Same as @link(CanRead), but additionally return @TRUE if is some data in
@link(LineBuffer).}
function CanReadEx(Timeout: Integer): Boolean; virtual;
{:Return @TRUE, if you can to socket write any data (not full sending
buffer). Status is tested for time Timeout (in milliseconds). If value in
Timeout is 0, status is only tested and continue. If value in Timeout is
-1, run is breaked and waiting for write data maybe forever.
This function is need only on special cases!}
function CanWrite(Timeout: Integer): Boolean; virtual;
{:Same as @link(SendBuffer), but send datagram to address from
@link(RemoteSin). Usefull for sending reply to datagram received by
function @link(RecvBufferFrom).}
function SendBufferTo(Buffer: TMemory; Length: Integer): Integer; virtual;
{:Note: This is low-lever receive function. You must be sure if data is
waiting for read before call this function for avoid deadlock!
Receives first waiting datagram to allocated buffer. If there is no waiting
one, then waits until one comes. Returns length of datagram stored in
BUFFER. If length exceeds buffer datagram is truncated. After this
@link(RemoteSin) structure contains information about sender of UDP packet.}
function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; virtual;
{$IFNDEF CIL}
{:This function is for check for incoming data on set of sockets. Whitch
sockets is checked is decribed by SocketList Tlist with TBlockSocket
objects. TList may have maximal number of objects defined by FD_SETSIZE
constant. Return @TRUE, if you can from some socket read any data or is
incoming connection on TCP based socket. Status is tested for time Timeout
(in milliseconds). If value in Timeout is 0, status is only tested and
continue. If value in Timeout is -1, run is breaked and waiting for read
data maybe forever. If is returned @TRUE, CanReadList TList is filled by all
TBlockSocket objects what waiting for read.}
function GroupCanRead(const SocketList: TList; Timeout: Integer;
const CanReadList: TList): Boolean;
{$ENDIF}
{:By this method you may turn address reuse mode for local @link(bind). It
is good specially for UDP protocol. Using this with TCP protocol is
hazardous!}
procedure EnableReuse(Value: Boolean);
{:Try set timeout for all sending and receiving operations, if socket
provider can do it. (It not supported by all socket providers!)}
procedure SetTimeout(Timeout: Integer);
{:Try set timeout for all sending operations, if socket provider can do it.
(It not supported by all socket providers!)}
procedure SetSendTimeout(Timeout: Integer);
{:Try set timeout for all receiving operations, if socket provider can do
it. (It not supported by all socket providers!)}
procedure SetRecvTimeout(Timeout: Integer);
{:Return value of socket type.}
function GetSocketType: integer; Virtual;
{:Return value of protocol type for socket creation.}
function GetSocketProtocol: integer; Virtual;
{:WSA structure with information about socket provider. On non-windows
platforms this structure is simulated!}
property WSAData: TWSADATA read GetWsaData;
{:FDset structure prepared for usage with this socket.}
property FDset: TFDSet read FFDset;
{:Structure describing local socket side.}
property LocalSin: TVarSin read FLocalSin write FLocalSin;
{:Structure describing remote socket side.}
property RemoteSin: TVarSin read FRemoteSin write FRemoteSin;
{:Socket handler. Suitable for "manual" calls to socket API or manual
connection of socket to a previously created socket (i.e by Accept method
on TCP socket)}
property Socket: TSocket read FSocket write SetSocket;
{:Last socket operation error code. Error codes are described in socket
documentation. Human readable error description is stored in
@link(LastErrorDesc) property.}
property LastError: Integer read FLastError;
{:Human readable error description of @link(LastError) code.}
property LastErrorDesc: string read FLastErrorDesc;
{:Buffer used by all high-level receiving functions. This buffer is used for
optimized reading of data from socket. In normal cases you not need access
to this buffer directly!}
property LineBuffer: AnsiString read FBuffer write FBuffer;
{:Size of Winsock receive buffer. If it is not supported by socket provider,
it return as size one kilobyte.}
property SizeRecvBuffer: Integer read GetSizeRecvBuffer write SetSizeRecvBuffer;
{:Size of Winsock send buffer. If it is not supported by socket provider, it
return as size one kilobyte.}
property SizeSendBuffer: Integer read GetSizeSendBuffer write SetSizeSendBuffer;
{:If @True, turn class to non-blocking mode. Not all functions are working
properly in this mode, you must know exactly what you are doing! However
when you have big experience with non-blocking programming, then you can
optimise your program by non-block mode!}
property NonBlockMode: Boolean read FNonBlockMode Write SetNonBlockMode;
{:Set Time-to-live value. (if system supporting it!)}
property TTL: Integer read GetTTL Write SetTTL;
{:If is @true, then class in in IPv6 mode.}
property IP6used: Boolean read FIP6used;
{:Return count of received bytes on this socket from begin of current
connection.}
property RecvCounter: Integer read FRecvCounter;
{:Return count of sended bytes on this socket from begin of current
connection.}
property SendCounter: Integer read FSendCounter;
published
{:Return descriptive string for given error code. This is class function.
You may call it without created object!}
class function GetErrorDesc(ErrorCode: Integer): string;
{:Return descriptive string for @link(LastError).}
function GetErrorDescEx: string; virtual;
{:this value is for free use.}
property Tag: Integer read FTag write FTag;
{:If @true, winsock errors raises exception. Otherwise is setted
@link(LastError) value only and you must check it from your program! Default
value is @false.}
property RaiseExcept: Boolean read FRaiseExcept write FRaiseExcept;
{:Define maximum length in bytes of @link(LineBuffer) for high-level
receiving functions. If this functions try to read more data then this
limit, error is returned! If value is 0 (default), no limitation is used.
This is very good protection for stupid attacks to your server by sending
lot of data without proper terminator... until all your memory is allocated
by LineBuffer!
Note: This maximum length is checked only in functions, what read unknown
number of bytes! (like @link(RecvString) or @link(RecvTerminated))}
property MaxLineLength: Integer read FMaxLineLength Write FMaxLineLength;
{:Define maximal bandwidth for all sending operations in bytes per second.
If value is 0 (default), bandwidth limitation is not used.}
property MaxSendBandwidth: Integer read FMaxSendBandwidth Write FMaxSendBandwidth;
{:Define maximal bandwidth for all receiving operations in bytes per second.
If value is 0 (default), bandwidth limitation is not used.}
property MaxRecvBandwidth: Integer read FMaxRecvBandwidth Write FMaxRecvBandwidth;
{:Define maximal bandwidth for all sending and receiving operations in bytes
per second. If value is 0 (default), bandwidth limitation is not used.}
property MaxBandwidth: Integer Write SetBandwidth;
{:Do a conversion of non-standard line terminators to CRLF. (Off by default)
If @True, then terminators like sigle CR, single LF or LFCR are converted
to CRLF internally. This have effect only in @link(RecvString) method!}
property ConvertLineEnd: Boolean read FConvertLineEnd Write FConvertLineEnd;
{:Specified Family of this socket. When you are using Windows preliminary
support for IPv6, then I recommend to set this property!}
property Family: TSocketFamily read FFamily Write SetFamily;
{:When resolving of domain name return both IPv4 and IPv6 addresses, then
specify if is used IPv4 (dafault - @true) or IPv6.}
property PreferIP4: Boolean read FPreferIP4 Write FPreferIP4;
{:By default (@true) is all timeouts used as timeout between two packets in
reading operations. If you set this to @false, then Timeouts is for overall
reading operation!}
property InterPacketTimeout: Boolean read FInterPacketTimeout Write FInterPacketTimeout;
{:All sended datas was splitted by this value.}
property SendMaxChunk: Integer read FSendMaxChunk Write FSendMaxChunk;
{:By setting this property to @true you can stop any communication. You can
use this property for soft abort of communication.}
property StopFlag: Boolean read FStopFlag Write FStopFlag;
{:Timeout for data sending by non-blocking socket mode.}
property NonblockSendTimeout: Integer read FNonblockSendTimeout Write FNonblockSendTimeout;
{:Timeout for @link(Connect) call. Default value 0 means default system timeout.
Non-zero value means timeout in millisecond.}
property ConnectionTimeout: Integer read FConnectionTimeout write FConnectionTimeout;
{:This event is called by various reasons. It is good for monitoring socket,
create gauges for data transfers, etc.}
property OnStatus: THookSocketStatus read FOnStatus write FOnStatus;
{:this event is good for some internal thinks about filtering readed datas.
It is used by telnet client by example.}
property OnReadFilter: THookDataFilter read FOnReadFilter write FOnReadFilter;
{:This event is called after real socket creation for setting special socket
options, because you not know when socket is created. (it is depended on
Ipv4, IPv6 or automatic mode)}
property OnCreateSocket: THookCreateSocket read FOnCreateSocket write FOnCreateSocket;
{:This event is good for monitoring content of readed or writed datas.}
property OnMonitor: THookMonitor read FOnMonitor write FOnMonitor;
{:This event is good for calling your code during long socket operations.
(Example, for refresing UI if class in not called within the thread.)
Rate of heartbeats can be modified by @link(HeartbeatRate) property.}
property OnHeartbeat: THookHeartbeat read FOnHeartbeat write FOnHeartbeat;
{:Specify typical rate of @link(OnHeartbeat) event and @link(StopFlag) testing.
Default value 0 disabling heartbeats! Value is in milliseconds.
Real rate can be higher or smaller then this value, because it depending
on real socket operations too!
Note: Each heartbeat slowing socket processing.}
property HeartbeatRate: integer read FHeartbeatRate Write FHeartbeatRate;
{:What class own this socket? Used by protocol implementation classes.}
property Owner: TObject read FOwner Write FOwner;
end;
{:@abstract(Support for SOCKS4 and SOCKS5 proxy)
Layer with definition all necessary properties and functions for
implementation SOCKS proxy client. Do not use this class directly.}
TSocksBlockSocket = class(TBlockSocket)
protected
FSocksIP: string;
FSocksPort: string;
FSocksTimeout: integer;
FSocksUsername: string;
FSocksPassword: string;
FUsingSocks: Boolean;
FSocksResolver: Boolean;
FSocksLastError: integer;
FSocksResponseIP: string;
FSocksResponsePort: string;
FSocksLocalIP: string;
FSocksLocalPort: string;
FSocksRemoteIP: string;
FSocksRemotePort: string;
FBypassFlag: Boolean;
FSocksType: TSocksType;
function SocksCode(IP, Port: string): Ansistring;
function SocksDecode(Value: Ansistring): integer;
public
constructor Create;
{:Open connection to SOCKS proxy and if @link(SocksUsername) is set, do
authorisation to proxy. This is needed only in special cases! (it is called
internally!)}
function SocksOpen: Boolean;
{:Send specified request to SOCKS proxy. This is needed only in special
cases! (it is called internally!)}
function SocksRequest(Cmd: Byte; const IP, Port: string): Boolean;
{:Receive response to previosly sended request. This is needed only in
special cases! (it is called internally!)}
function SocksResponse: Boolean;
{:Is @True when class is using SOCKS proxy.}
property UsingSocks: Boolean read FUsingSocks;
{:If SOCKS proxy failed, here is error code returned from SOCKS proxy.}
property SocksLastError: integer read FSocksLastError;
published
{:Address of SOCKS server. If value is empty string, SOCKS support is
disabled. Assingning any value to this property enable SOCKS mode.
Warning: You cannot combine this mode with HTTP-tunneling mode!}
property SocksIP: string read FSocksIP write FSocksIP;
{:Port of SOCKS server. Default value is '1080'.}
property SocksPort: string read FSocksPort write FSocksPort;
{:If you need authorisation on SOCKS server, set username here.}
property SocksUsername: string read FSocksUsername write FSocksUsername;
{:If you need authorisation on SOCKS server, set password here.}
property SocksPassword: string read FSocksPassword write FSocksPassword;
{:Specify timeout for communicatin with SOCKS server. Default is one minute.}
property SocksTimeout: integer read FSocksTimeout write FSocksTimeout;
{:If @True, all symbolic names of target hosts is not translated to IP's
locally, but resolving is by SOCKS proxy. Default is @True.}
property SocksResolver: Boolean read FSocksResolver write FSocksResolver;
{:Specify SOCKS type. By default is used SOCKS5, but you can use SOCKS4 too.
When you select SOCKS4, then if @link(SOCKSResolver) is enabled, then is
used SOCKS4a. Othervise is used pure SOCKS4.}
property SocksType: TSocksType read FSocksType write FSocksType;
end;
{:@abstract(Implementation of TCP socket.)
Supported features: IPv4, IPv6, SSL/TLS or SSH (depending on used plugin),
SOCKS5 proxy (outgoing connections and limited incomming), SOCKS4/4a proxy
(outgoing connections and limited incomming), TCP through HTTP proxy tunnel.}
TTCPBlockSocket = class(TSocksBlockSocket)
protected
FOnAfterConnect: THookAfterConnect;
FSSL: TCustomSSL;
FHTTPTunnelIP: string;
FHTTPTunnelPort: string;
FHTTPTunnel: Boolean;
FHTTPTunnelRemoteIP: string;
FHTTPTunnelRemotePort: string;
FHTTPTunnelUser: string;
FHTTPTunnelPass: string;
FHTTPTunnelTimeout: integer;
procedure SocksDoConnect(IP, Port: string);
procedure HTTPTunnelDoConnect(IP, Port: string);
procedure DoAfterConnect;
public
{:Create TCP socket class with default plugin for SSL/TSL/SSH implementation
(see @link(SSLImplementation))}
constructor Create;
{:Create TCP socket class with desired plugin for SSL/TSL/SSH implementation}
constructor CreateWithSSL(SSLPlugin: TSSLClass);
destructor Destroy; override;
{:See @link(TBlockSocket.CloseSocket)}
procedure CloseSocket; override;
{:See @link(TBlockSocket.WaitingData)}
function WaitingData: Integer; override;
{:Sets socket to receive mode for new incoming connections. It is necessary
to use @link(TBlockSocket.BIND) function call before this method to select
receiving port!
If you use SOCKS, activate incoming TCP connection by this proxy. (By BIND
method of SOCKS.)}
procedure Listen; override;
{:Waits until new incoming connection comes. After it comes a new socket is
automatically created (socket handler is returned by this function as
result).
If you use SOCKS, new socket is not created! In this case is used same
socket as socket for listening! So, you can accept only one connection in
SOCKS mode.}
function Accept: TSocket; override;
{:Connects socket to remote IP address and PORT. The same rules as with
@link(TBlockSocket.BIND) method are valid. The only exception is that PORT
with 0 value will not be connected. After call to this method
a communication channel between local and remote socket is created. Local
socket is assigned automatically if not controlled by previous call to
@link(TBlockSocket.BIND) method. Structures @link(TBlockSocket.LocalSin)
and @link(TBlockSocket.RemoteSin) will be filled with valid values.
If you use SOCKS, activate outgoing TCP connection by SOCKS proxy specified
in @link(TSocksBlockSocket.SocksIP). (By CONNECT method of SOCKS.)
If you use HTTP-tunnel mode, activate outgoing TCP connection by HTTP
tunnel specified in @link(HTTPTunnelIP). (By CONNECT method of HTTP
protocol.)
Note: If you call this on non-created socket, then socket is created
automaticly.}
procedure Connect(IP, Port: string); override;
{:If you need upgrade existing TCP connection to SSL/TLS (or SSH2, if plugin
allows it) mode, then call this method. This method switch this class to
SSL mode and do SSL/TSL handshake.}
procedure SSLDoConnect;
{:By this method you can downgrade existing SSL/TLS connection to normal TCP
connection.}
procedure SSLDoShutdown;
{:If you need use this component as SSL/TLS TCP server, then after accepting
of inbound connection you need start SSL/TLS session by this method. Before
call this function, you must have assigned all neeeded certificates and
keys!}
function SSLAcceptConnection: Boolean;
{:See @link(TBlockSocket.GetLocalSinIP)}
function GetLocalSinIP: string; override;
{:See @link(TBlockSocket.GetRemoteSinIP)}
function GetRemoteSinIP: string; override;
{:See @link(TBlockSocket.GetLocalSinPort)}
function GetLocalSinPort: Integer; override;
{:See @link(TBlockSocket.GetRemoteSinPort)}
function GetRemoteSinPort: Integer; override;
{:See @link(TBlockSocket.SendBuffer)}
function SendBuffer(Buffer: TMemory; Length: Integer): Integer; override;
{:See @link(TBlockSocket.RecvBuffer)}
function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override;
{:Return value of socket type. For TCP return SOCK_STREAM.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For TCP return
IPPROTO_TCP.}
function GetSocketProtocol: integer; override;
{:Class implementing SSL/TLS support. It is allways some descendant
of @link(TCustomSSL) class. When programmer not select some SSL plugin
class, then is used @link(TSSLNone)}
property SSL: TCustomSSL read FSSL;
{:@True if is used HTTP tunnel mode.}
property HTTPTunnel: Boolean read FHTTPTunnel;
published
{:Return descriptive string for @link(LastError). On case of error
in SSL/TLS subsystem, it returns right error description.}
function GetErrorDescEx: string; override;
{:Specify IP address of HTTP proxy. Assingning non-empty value to this
property enable HTTP-tunnel mode. This mode is for tunnelling any outgoing
TCP connection through HTTP proxy server. (If policy on HTTP proxy server
allow this!) Warning: You cannot combine this mode with SOCK5 mode!}
property HTTPTunnelIP: string read FHTTPTunnelIP Write FHTTPTunnelIP;
{:Specify port of HTTP proxy for HTTP-tunneling.}
property HTTPTunnelPort: string read FHTTPTunnelPort Write FHTTPTunnelPort;
{:Specify authorisation username for access to HTTP proxy in HTTP-tunnel
mode. If you not need authorisation, then let this property empty.}
property HTTPTunnelUser: string read FHTTPTunnelUser Write FHTTPTunnelUser;
{:Specify authorisation password for access to HTTP proxy in HTTP-tunnel
mode.}
property HTTPTunnelPass: string read FHTTPTunnelPass Write FHTTPTunnelPass;
{:Specify timeout for communication with HTTP proxy in HTTPtunnel mode.}
property HTTPTunnelTimeout: integer read FHTTPTunnelTimeout Write FHTTPTunnelTimeout;
{:This event is called after sucessful TCP socket connection.}
property OnAfterConnect: THookAfterConnect read FOnAfterConnect write FOnAfterConnect;
end;
{:@abstract(Datagram based communication)
This class implementing datagram based communication instead default stream
based communication style.}
TDgramBlockSocket = class(TSocksBlockSocket)
public
{:Fill @link(TBlockSocket.RemoteSin) structure. This address is used for
sending data.}
procedure Connect(IP, Port: string); override;
{:Silently redirected to @link(TBlockSocket.SendBufferTo).}
function SendBuffer(Buffer: TMemory; Length: Integer): Integer; override;
{:Silently redirected to @link(TBlockSocket.RecvBufferFrom).}
function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; override;
end;
{:@abstract(Implementation of UDP socket.)
NOTE: in this class is all receiving redirected to RecvBufferFrom. You can
use for reading any receive function. Preffered is RecvPacket! Similary all
sending is redirected to SendbufferTo. You can use for sending UDP packet any
sending function, like SendString.
Supported features: IPv4, IPv6, unicasts, broadcasts, multicasts, SOCKS5
proxy (only unicasts! Outgoing and incomming.)}
TUDPBlockSocket = class(TDgramBlockSocket)
protected
FSocksControlSock: TTCPBlockSocket;
function UdpAssociation: Boolean;
procedure SetMulticastTTL(TTL: integer);
function GetMulticastTTL:integer;
public
destructor Destroy; override;
{:Enable or disable sending of broadcasts. If seting OK, result is @true.
This method is not supported in SOCKS5 mode! IPv6 does not support
broadcasts! In this case you must use Multicasts instead.}
procedure EnableBroadcast(Value: Boolean);
{:See @link(TBlockSocket.SendBufferTo)}
function SendBufferTo(Buffer: TMemory; Length: Integer): Integer; override;
{:See @link(TBlockSocket.RecvBufferFrom)}
function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; override;
{$IFNDEF CIL}
{:Add this socket to given multicast group. You cannot use Multicasts in
SOCKS mode!}
procedure AddMulticast(MCastIP:string);
{:Remove this socket from given multicast group.}
procedure DropMulticast(MCastIP:string);
{$ENDIF}
{:All sended multicast datagrams is loopbacked to your interface too. (you
can read your sended datas.) You can disable this feature by this function.
This function not working on some Windows systems!}
procedure EnableMulticastLoop(Value: Boolean);
{:Return value of socket type. For UDP return SOCK_DGRAM.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For UDP return
IPPROTO_UDP.}
function GetSocketProtocol: integer; override;
{:Set Time-to-live value for multicasts packets. It define number of routers
for transfer of datas. If you set this to 1 (dafault system value), then
multicasts packet goes only to you local network. If you need transport
multicast packet to worldwide, then increase this value, but be carefull,
lot of routers on internet does not transport multicasts packets!}
property MulticastTTL: Integer read GetMulticastTTL Write SetMulticastTTL;
end;
{:@abstract(Implementation of RAW ICMP socket.)
For this object you must have rights for creating RAW sockets!}
TICMPBlockSocket = class(TDgramBlockSocket)
public
{:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For ICMP returns
IPPROTO_ICMP or IPPROTO_ICMPV6}
function GetSocketProtocol: integer; override;
end;
{:@abstract(Implementation of RAW socket.)
For this object you must have rights for creating RAW sockets!}
TRAWBlockSocket = class(TBlockSocket)
public
{:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For RAW returns
IPPROTO_RAW.}
function GetSocketProtocol: integer; override;
end;
{:@abstract(Implementation of PGM-message socket.)
Not all systems supports this protocol!}
TPGMMessageBlockSocket = class(TBlockSocket)
public
{:Return value of socket type. For PGM-message return SOCK_RDM.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For PGM-message returns
IPPROTO_RM.}
function GetSocketProtocol: integer; override;
end;
{:@abstract(Implementation of PGM-stream socket.)
Not all systems supports this protocol!}
TPGMStreamBlockSocket = class(TBlockSocket)
public
{:Return value of socket type. For PGM-stream return SOCK_STREAM.}
function GetSocketType: integer; override;
{:Return value of protocol type for socket creation. For PGM-stream returns
IPPROTO_RM.}
function GetSocketProtocol: integer; override;
end;
{:@abstract(Parent class for all SSL plugins.)
This is abstract class defining interface for other SSL plugins.
Instance of this class will be created for each @link(TTCPBlockSocket).
Warning: not all methods and propertis can work in all existing SSL plugins!
Please, read documentation of used SSL plugin.}
TCustomSSL = class(TObject)
private
protected
FOnVerifyCert: THookVerifyCert;
FSocket: TTCPBlockSocket;
FSSLEnabled: Boolean;
FLastError: integer;
FLastErrorDesc: string;
FSSLType: TSSLType;
FKeyPassword: string;
FCiphers: string;
FCertificateFile: string;
FPrivateKeyFile: string;
FCertificate: Ansistring;
FPrivateKey: Ansistring;
FPFX: Ansistring;
FPFXfile: string;
FCertCA: Ansistring;
FCertCAFile: string;
FTrustCertificate: Ansistring;
FTrustCertificateFile: string;
FVerifyCert: Boolean;
FUsername: string;
FPassword: string;
FSSHChannelType: string;
FSSHChannelArg1: string;
FSSHChannelArg2: string;
FCertComplianceLevel: integer;
FSNIHost: string;
procedure ReturnError;
procedure SetCertCAFile(const Value: string); virtual;
function DoVerifyCert:boolean;
function CreateSelfSignedCert(Host: string): Boolean; virtual;
public
{: Create plugin class. it is called internally from @link(TTCPBlockSocket)}
constructor Create(const Value: TTCPBlockSocket); virtual;
{: Assign settings (certificates and configuration) from another SSL plugin
class.}
procedure Assign(const Value: TCustomSSL); virtual;
{: return description of used plugin. It usually return name and version
of used SSL library.}
function LibVersion: String; virtual;
{: return name of used plugin.}
function LibName: String; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for start SSL connection.}
function Connect: boolean; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for acept new SSL connection.}
function Accept: boolean; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for hard shutdown of SSL connection. (for example,
before socket is closed)}
function Shutdown: boolean; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for soft shutdown of SSL connection. (for example,
when you need to continue with unprotected connection.)}
function BiShutdown: boolean; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for sending some datas by SSL connection.}
function SendBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for receiving some datas by SSL connection.}
function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
{: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
Here is needed code for getting count of datas what waiting for read.
If SSL plugin not allows this, then it should return 0.}
function WaitingData: Integer; virtual;
{:Return string with identificator of SSL/TLS version of existing
connection.}
function GetSSLVersion: string; virtual;
{:Return subject of remote SSL peer.}
function GetPeerSubject: string; virtual;
{:Return Serial number if remote X509 certificate.}
function GetPeerSerialNo: integer; virtual;
{:Return issuer certificate of remote SSL peer.}
function GetPeerIssuer: string; virtual;
{:Return peer name from remote side certificate. This is good for verify,
if certificate is generated for remote side IP name.}
function GetPeerName: string; virtual;
{:Returns has of peer name from remote side certificate. This is good
for fast remote side authentication.}
function GetPeerNameHash: cardinal; virtual;
{:Return fingerprint of remote SSL peer.}
function GetPeerFingerprint: string; virtual;
{:Return all detailed information about certificate from remote side of
SSL/TLS connection. Result string can be multilined! Each plugin can return
this informations in different format!}
function GetCertInfo: string; virtual;
{:Return currently used Cipher.}
function GetCipherName: string; virtual;
{:Return currently used number of bits in current Cipher algorythm.}
function GetCipherBits: integer; virtual;
{:Return number of bits in current Cipher algorythm.}
function GetCipherAlgBits: integer; virtual;
{:Return result value of verify remote side certificate. Look to OpenSSL
documentation for possible values. For example 0 is successfuly verified
certificate, or 18 is self-signed certificate.}
function GetVerifyCert: integer; virtual;
{: Resurn @true if SSL mode is enabled on existing cvonnection.}
property SSLEnabled: Boolean read FSSLEnabled;
{:Return error code of last SSL operation. 0 is OK.}
property LastError: integer read FLastError;
{:Return error description of last SSL operation.}
property LastErrorDesc: string read FLastErrorDesc;
published
{:Here you can specify requested SSL/TLS mode. Default is autodetection, but
on some servers autodetection not working properly. In this case you must
specify requested SSL/TLS mode by your hand!}
property SSLType: TSSLType read FSSLType write FSSLType;
{:Password for decrypting of encoded certificate or key.}
property KeyPassword: string read FKeyPassword write FKeyPassword;
{:Username for possible credentials.}
property Username: string read FUsername write FUsername;
{:password for possible credentials.}
property Password: string read FPassword write FPassword;
{:By this property you can modify default set of SSL/TLS ciphers.}
property Ciphers: string read FCiphers write FCiphers;
{:Used for loading certificate from disk file. See to plugin documentation
if this method is supported and how!}
property CertificateFile: string read FCertificateFile write FCertificateFile;
{:Used for loading private key from disk file. See to plugin documentation
if this method is supported and how!}
property PrivateKeyFile: string read FPrivateKeyFile write FPrivateKeyFile;
{:Used for loading certificate from binary string. See to plugin documentation
if this method is supported and how!}
property Certificate: Ansistring read FCertificate write FCertificate;
{:Used for loading private key from binary string. See to plugin documentation
if this method is supported and how!}
property PrivateKey: Ansistring read FPrivateKey write FPrivateKey;
{:Used for loading PFX from binary string. See to plugin documentation
if this method is supported and how!}
property PFX: Ansistring read FPFX write FPFX;
{:Used for loading PFX from disk file. See to plugin documentation
if this method is supported and how!}
property PFXfile: string read FPFXfile write FPFXfile;
{:Used for loading trusted certificates from disk file. See to plugin documentation
if this method is supported and how!}
property TrustCertificateFile: string read FTrustCertificateFile write FTrustCertificateFile;
{:Used for loading trusted certificates from binary string. See to plugin documentation
if this method is supported and how!}
property TrustCertificate: Ansistring read FTrustCertificate write FTrustCertificate;
{:Used for loading CA certificates from binary string. See to plugin documentation
if this method is supported and how!}
property CertCA: Ansistring read FCertCA write FCertCA;
{:Used for loading CA certificates from disk file. See to plugin documentation
if this method is supported and how!}
property CertCAFile: string read FCertCAFile write SetCertCAFile;
{:If @true, then is verified client certificate. (it is good for writing
SSL/TLS servers.) When you are not server, but you are client, then if this
property is @true, verify servers certificate.}
property VerifyCert: Boolean read FVerifyCert write FVerifyCert;
{:channel type for possible SSH connections}
property SSHChannelType: string read FSSHChannelType write FSSHChannelType;
{:First argument of channel type for possible SSH connections}
property SSHChannelArg1: string read FSSHChannelArg1 write FSSHChannelArg1;
{:Second argument of channel type for possible SSH connections}
property SSHChannelArg2: string read FSSHChannelArg2 write FSSHChannelArg2;
{: Level of standards compliance level
(CryptLib: values in cryptlib.pas, -1: use default value ) }
property CertComplianceLevel:integer read FCertComplianceLevel write FCertComplianceLevel;
{:This event is called when verifying the server certificate immediatally after
a successfull verification in the ssl library.}
property OnVerifyCert: THookVerifyCert read FOnVerifyCert write FOnVerifyCert;
{: Server Name Identification. Host name to send to server. If empty the host name
found in URL will be used, which should be the normal use (http Header Host = SNI Host).
The value is cleared after the connection is established.
(SNI support requires OpenSSL 0.9.8k or later. Cryptlib not supported, yet ) }
property SNIHost:string read FSNIHost write FSNIHost;
end;
{:@abstract(Default SSL plugin with no SSL support.)
Dummy SSL plugin implementation for applications without SSL/TLS support.}
TSSLNone = class (TCustomSSL)
public
{:See @inherited}
function LibVersion: String; override;
{:See @inherited}
function LibName: String; override;
end;
{:@abstract(Record with definition of IP packet header.)
For reading data from ICMP or RAW sockets.}
TIPHeader = record
VerLen: Byte;
TOS: Byte;
TotalLen: Word;
Identifer: Word;
FragOffsets: Word;
TTL: Byte;
Protocol: Byte;
CheckSum: Word;
SourceIp: LongWord;
DestIp: LongWord;
Options: LongWord;
end;
{:@abstract(Parent class of application protocol implementations.)
By this class is defined common properties.}
TSynaClient = Class(TObject)
protected
FTargetHost: string;
FTargetPort: string;
FIPInterface: string;
FTimeout: integer;
FUserName: string;
FPassword: string;
public
constructor Create;
published
{:Specify terget server IP (or symbolic name). Default is 'localhost'.}
property TargetHost: string read FTargetHost Write FTargetHost;
{:Specify terget server port (or symbolic name).}
property TargetPort: string read FTargetPort Write FTargetPort;
{:Defined local socket address. (outgoing IP address). By default is used
'0.0.0.0' as wildcard for default IP.}
property IPInterface: string read FIPInterface Write FIPInterface;
{:Specify default timeout for socket operations.}
property Timeout: integer read FTimeout Write FTimeout;
{:If protocol need user authorization, then fill here username.}
property UserName: string read FUserName Write FUserName;
{:If protocol need user authorization, then fill here password.}
property Password: string read FPassword Write FPassword;
end;
var
{:Selected SSL plugin. Default is @link(TSSLNone).
Do not change this value directly!!!
Just add your plugin unit to your project uses instead. Each plugin unit have
initialization code what modify this variable.}
SSLImplementation: TSSLClass = TSSLNone;
implementation
{$IFDEF ONCEWINSOCK}
var
WsaDataOnce: TWSADATA;
e: ESynapseError;
{$ENDIF}
constructor TBlockSocket.Create;
begin
CreateAlternate('');
end;
constructor TBlockSocket.CreateAlternate(Stub: string);
{$IFNDEF ONCEWINSOCK}
var
e: ESynapseError;
{$ENDIF}
begin
inherited Create;
FDelayedOptions := TList.Create;
FRaiseExcept := False;
{$IFDEF RAISEEXCEPT}
FRaiseExcept := True;
{$ENDIF}
FSocket := INVALID_SOCKET;
FBuffer := '';
FLastCR := False;
FLastLF := False;
FBinded := False;
FNonBlockMode := False;
FMaxLineLength := 0;
FMaxSendBandwidth := 0;
FNextSend := 0;
FMaxRecvBandwidth := 0;
FNextRecv := 0;
FConvertLineEnd := False;
FFamily := SF_Any;
FFamilySave := SF_Any;
FIP6used := False;
FPreferIP4 := True;
FInterPacketTimeout := True;
FRecvCounter := 0;
FSendCounter := 0;
FSendMaxChunk := c64k;
FStopFlag := False;
FNonblockSendTimeout := 15000;
FHeartbeatRate := 0;
FConnectionTimeout := 0;
FOwner := nil;
{$IFNDEF ONCEWINSOCK}
if Stub = '' then
Stub := DLLStackName;
if not InitSocketInterface(Stub) then
begin
e := ESynapseError.Create('Error loading Socket interface (' + Stub + ')!');
e.ErrorCode := 0;
e.ErrorMessage := 'Error loading Socket interface (' + Stub + ')!';
raise e;
end;
SockCheck(synsock.WSAStartup(WinsockLevel, FWsaDataOnce));
ExceptCheck;
{$ENDIF}
end;
destructor TBlockSocket.Destroy;
var
n: integer;
p: TSynaOption;
begin
CloseSocket;
{$IFNDEF ONCEWINSOCK}
synsock.WSACleanup;
DestroySocketInterface;
{$ENDIF}
for n := FDelayedOptions.Count - 1 downto 0 do
begin
p := TSynaOption(FDelayedOptions[n]);
p.Free;
end;
FDelayedOptions.Free;
inherited Destroy;
end;
function TBlockSocket.FamilyToAF(f: TSocketFamily): TAddrFamily;
begin
case f of
SF_ip4:
Result := AF_INET;
SF_ip6:
Result := AF_INET6;
else
Result := AF_UNSPEC;
end;
end;
procedure TBlockSocket.SetDelayedOption(const Value: TSynaOption);
var
li: TLinger;
x: integer;
buf: TMemory;
{$IFNDEF MSWINDOWS}
timeval: TTimeval;
{$ENDIF}
begin
case value.Option of
SOT_Linger:
begin
{$IFDEF CIL}
li := TLinger.Create(Value.Enabled, Value.Value div 1000);
synsock.SetSockOptObj(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), li);
{$ELSE}
li.l_onoff := Ord(Value.Enabled);
li.l_linger := Value.Value div 1000;
buf := @li;
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), buf, SizeOf(li));
{$ENDIF}
end;
SOT_RecvBuff:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
{$ELSE}
buf := @Value.Value;
{$ENDIF}
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF),
buf, SizeOf(Value.Value));
end;
SOT_SendBuff:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
{$ELSE}
buf := @Value.Value;
{$ENDIF}
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF),
buf, SizeOf(Value.Value));
end;
SOT_NonBlock:
begin
FNonBlockMode := Value.Enabled;
x := Ord(FNonBlockMode);
synsock.IoctlSocket(FSocket, FIONBIO, x);
end;
SOT_RecvTimeout:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
buf, SizeOf(Value.Value));
{$ELSE}
{$IFDEF MSWINDOWS}
buf := @Value.Value;
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
buf, SizeOf(Value.Value));
{$ELSE}
timeval.tv_sec:=Value.Value div 1000;
timeval.tv_usec:=(Value.Value mod 1000) * 1000;
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
@timeval, SizeOf(timeval));
{$ENDIF}
{$ENDIF}
end;
SOT_SendTimeout:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
{$ELSE}
{$IFDEF MSWINDOWS}
buf := @Value.Value;
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
buf, SizeOf(Value.Value));
{$ELSE}
timeval.tv_sec:=Value.Value div 1000;
timeval.tv_usec:=(Value.Value mod 1000) * 1000;
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
@timeval, SizeOf(timeval));
{$ENDIF}
{$ENDIF}
end;
SOT_Reuse:
begin
x := Ord(Value.Enabled);
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(x);
{$ELSE}
buf := @x;
{$ENDIF}
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_REUSEADDR), buf, SizeOf(x));
end;
SOT_TTL:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
{$ELSE}
buf := @Value.Value;
{$ENDIF}
if FIP6Used then
synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_UNICAST_HOPS),
buf, SizeOf(Value.Value))
else
synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_TTL),
buf, SizeOf(Value.Value));
end;
SOT_Broadcast:
begin
//#todo1 broadcasty na IP6
x := Ord(Value.Enabled);
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(x);
{$ELSE}
buf := @x;
{$ENDIF}
synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_BROADCAST), buf, SizeOf(x));
end;
SOT_MulticastTTL:
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(value.Value);
{$ELSE}
buf := @Value.Value;
{$ENDIF}
if FIP6Used then
synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_HOPS),
buf, SizeOf(Value.Value))
else
synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_TTL),
buf, SizeOf(Value.Value));
end;
SOT_MulticastLoop:
begin
x := Ord(Value.Enabled);
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(x);
{$ELSE}
buf := @x;
{$ENDIF}
if FIP6Used then
synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_LOOP), buf, SizeOf(x))
else
synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_LOOP), buf, SizeOf(x));
end;
end;
Value.free;
end;
procedure TBlockSocket.DelayedOption(const Value: TSynaOption);
begin
if FSocket = INVALID_SOCKET then
begin
FDelayedOptions.Insert(0, Value);
end
else
SetDelayedOption(Value);
end;
procedure TBlockSocket.ProcessDelayedOptions;
var
n: integer;
d: TSynaOption;
begin
for n := FDelayedOptions.Count - 1 downto 0 do
begin
d := TSynaOption(FDelayedOptions[n]);
SetDelayedOption(d);
end;
FDelayedOptions.Clear;
end;
procedure TBlockSocket.SetSin(var Sin: TVarSin; IP, Port: string);
var
f: TSocketFamily;
begin
DoStatus(HR_ResolvingBegin, IP + ':' + Port);
ResetLastError;
//if socket exists, then use their type, else use users selection
f := SF_Any;
if (FSocket = INVALID_SOCKET) and (FFamily = SF_any) then
begin
if IsIP(IP) then
f := SF_IP4
else
if IsIP6(IP) then
f := SF_IP6;
end
else
f := FFamily;
FLastError := synsock.SetVarSin(sin, ip, port, FamilyToAF(f),
GetSocketprotocol, GetSocketType, FPreferIP4);
DoStatus(HR_ResolvingEnd, GetSinIP(sin) + ':' + IntTostr(GetSinPort(sin)));
end;
function TBlockSocket.GetSinIP(Sin: TVarSin): string;
begin
Result := synsock.GetSinIP(sin);
end;
function TBlockSocket.GetSinPort(Sin: TVarSin): Integer;
begin
Result := synsock.GetSinPort(sin);
end;
procedure TBlockSocket.CreateSocket;
var
sin: TVarSin;
begin
//dummy for SF_Any Family mode
ResetLastError;
if (FFamily <> SF_Any) and (FSocket = INVALID_SOCKET) then
begin
{$IFDEF CIL}
if FFamily = SF_IP6 then
sin := TVarSin.Create(IPAddress.Parse('::0'), 0)
else
sin := TVarSin.Create(IPAddress.Parse('0.0.0.0'), 0);
{$ELSE}
FillChar(Sin, Sizeof(Sin), 0);
if FFamily = SF_IP6 then
sin.sin_family := AF_INET6
else
sin.sin_family := AF_INET;
{$ENDIF}
InternalCreateSocket(Sin);
end;
end;
procedure TBlockSocket.CreateSocketByName(const Value: String);
var
sin: TVarSin;
begin
ResetLastError;
if FSocket = INVALID_SOCKET then
begin
SetSin(sin, value, '0');
if FLastError = 0 then
InternalCreateSocket(Sin);
end;
end;
procedure TBlockSocket.InternalCreateSocket(Sin: TVarSin);
begin
FStopFlag := False;
FRecvCounter := 0;
FSendCounter := 0;
ResetLastError;
if FSocket = INVALID_SOCKET then
begin
FBuffer := '';
FBinded := False;
FIP6Used := Sin.AddressFamily = AF_INET6;
FSocket := synsock.Socket(integer(Sin.AddressFamily), GetSocketType, GetSocketProtocol);
if FSocket = INVALID_SOCKET then
FLastError := synsock.WSAGetLastError;
{$IFNDEF CIL}
FD_ZERO(FFDSet);
FD_SET(FSocket, FFDSet);
{$ENDIF}
ExceptCheck;
if FIP6used then
DoStatus(HR_SocketCreate, 'IPv6')
else
DoStatus(HR_SocketCreate, 'IPv4');
ProcessDelayedOptions;
DoCreateSocket;
end;
end;
procedure TBlockSocket.CloseSocket;
begin
AbortSocket;
end;
procedure TBlockSocket.AbortSocket;
var
n: integer;
p: TSynaOption;
begin
if FSocket <> INVALID_SOCKET then
synsock.CloseSocket(FSocket);
FSocket := INVALID_SOCKET;
for n := FDelayedOptions.Count - 1 downto 0 do
begin
p := TSynaOption(FDelayedOptions[n]);
p.Free;
end;
FDelayedOptions.Clear;
FFamily := FFamilySave;
DoStatus(HR_SocketClose, '');
end;
procedure TBlockSocket.Bind(IP, Port: string);
var
Sin: TVarSin;
begin
ResetLastError;
if (FSocket <> INVALID_SOCKET)
or not((FFamily = SF_ANY) and (IP = cAnyHost) and (Port = cAnyPort)) then
begin
SetSin(Sin, IP, Port);
if FLastError = 0 then
begin
if FSocket = INVALID_SOCKET then
InternalCreateSocket(Sin);
SockCheck(synsock.Bind(FSocket, Sin));
GetSinLocal;
FBuffer := '';
FBinded := True;
end;
ExceptCheck;
DoStatus(HR_Bind, IP + ':' + Port);
end;
end;
procedure TBlockSocket.Connect(IP, Port: string);
var
Sin: TVarSin;
b: boolean;
begin
SetSin(Sin, IP, Port);
if FLastError = 0 then
begin
if FSocket = INVALID_SOCKET then
InternalCreateSocket(Sin);
if FConnectionTimeout > 0 then
begin
// connect in non-blocking mode
b := NonBlockMode;
NonBlockMode := true;
SockCheck(synsock.Connect(FSocket, Sin));
if (FLastError = WSAEINPROGRESS) OR (FLastError = WSAEWOULDBLOCK) then
if not CanWrite(FConnectionTimeout) then
FLastError := WSAETIMEDOUT;
NonBlockMode := b;
end
else
SockCheck(synsock.Connect(FSocket, Sin));
if FLastError = 0 then
GetSins;
FBuffer := '';
FLastCR := False;
FLastLF := False;
end;
ExceptCheck;
DoStatus(HR_Connect, IP + ':' + Port);
end;
procedure TBlockSocket.Listen;
begin
SockCheck(synsock.Listen(FSocket, SOMAXCONN));
GetSins;
ExceptCheck;
DoStatus(HR_Listen, '');
end;
function TBlockSocket.Accept: TSocket;
begin
Result := synsock.Accept(FSocket, FRemoteSin);
/// SockCheck(Result);
ExceptCheck;
DoStatus(HR_Accept, '');
end;
procedure TBlockSocket.GetSinLocal;
begin
synsock.GetSockName(FSocket, FLocalSin);
end;
procedure TBlockSocket.GetSinRemote;
begin
synsock.GetPeerName(FSocket, FRemoteSin);
end;
procedure TBlockSocket.GetSins;
begin
GetSinLocal;
GetSinRemote;
end;
procedure TBlockSocket.SetBandwidth(Value: Integer);
begin
MaxSendBandwidth := Value;
MaxRecvBandwidth := Value;
end;
procedure TBlockSocket.LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
var
x: LongWord;
y: LongWord;
n: integer;
begin
if FStopFlag then
exit;
if MaxB > 0 then
begin
y := GetTick;
if Next > y then
begin
x := Next - y;
if x > 0 then
begin
DoStatus(HR_Wait, IntToStr(x));
sleep(x mod 250);
for n := 1 to x div 250 do
if FStopFlag then
Break
else
sleep(250);
end;
end;
Next := GetTick + Trunc((Length / MaxB) * 1000);
end;
end;
function TBlockSocket.TestStopFlag: Boolean;
begin
DoHeartbeat;
Result := FStopFlag;
if Result then
begin
FStopFlag := False;
FLastError := WSAECONNABORTED;
ExceptCheck;
end;
end;
function TBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
{$IFNDEF CIL}
var
x, y: integer;
l, r: integer;
p: Pointer;
{$ENDIF}
begin
Result := 0;
if TestStopFlag then
Exit;
DoMonitor(True, Buffer, Length);
{$IFDEF CIL}
Result := synsock.Send(FSocket, Buffer, Length, 0);
{$ELSE}
l := Length;
x := 0;
while x < l do
begin
y := l - x;
if y > FSendMaxChunk then
y := FSendMaxChunk;
if y > 0 then
begin
LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
p := IncPoint(Buffer, x);
r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
SockCheck(r);
if FLastError = WSAEWOULDBLOCK then
begin
if CanWrite(FNonblockSendTimeout) then
begin
r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
SockCheck(r);
end
else
FLastError := WSAETIMEDOUT;
end;
if FLastError <> 0 then
Break;
Inc(x, r);
Inc(Result, r);
Inc(FSendCounter, r);
DoStatus(HR_WriteCount, IntToStr(r));
end
else
break;
end;
{$ENDIF}
ExceptCheck;
end;
procedure TBlockSocket.SendByte(Data: Byte);
{$IFDEF CIL}
var
buf: TMemory;
{$ENDIF}
begin
{$IFDEF CIL}
setlength(buf, 1);
buf[0] := Data;
SendBuffer(buf, 1);
{$ELSE}
SendBuffer(@Data, 1);
{$ENDIF}
end;
procedure TBlockSocket.SendString(Data: AnsiString);
var
buf: TMemory;
begin
{$IFDEF CIL}
buf := BytesOf(Data);
{$ELSE}
buf := Pointer(data);
{$ENDIF}
SendBuffer(buf, Length(Data));
end;
procedure TBlockSocket.SendInteger(Data: integer);
var
buf: TMemory;
begin
{$IFDEF CIL}
buf := System.BitConverter.GetBytes(Data);
{$ELSE}
buf := @Data;
{$ENDIF}
SendBuffer(buf, SizeOf(Data));
end;
procedure TBlockSocket.SendBlock(const Data: AnsiString);
var
i: integer;
begin
i := SwapBytes(Length(data));
SendString(Codelongint(i) + Data);
end;
procedure TBlockSocket.InternalSendStream(const Stream: TStream; WithSize, Indy: boolean);
var
l: integer;
yr: integer;
s: AnsiString;
b: boolean;
{$IFDEF CIL}
buf: TMemory;
{$ENDIF}
begin
b := true;
l := 0;
if WithSize then
begin
l := Stream.Size - Stream.Position;;
if not Indy then
l := synsock.HToNL(l);
end;
repeat
{$IFDEF CIL}
Setlength(buf, FSendMaxChunk);
yr := Stream.read(buf, FSendMaxChunk);
if yr > 0 then
begin
if WithSize and b then
begin
b := false;
SendString(CodeLongInt(l));
end;
SendBuffer(buf, yr);
if FLastError <> 0 then
break;
end
{$ELSE}
Setlength(s, FSendMaxChunk);
yr := Stream.read(Pointer(s)^, FSendMaxChunk);
if yr > 0 then
begin
SetLength(s, yr);
if WithSize and b then
begin
b := false;
SendString(CodeLongInt(l) + s);
end
else
SendString(s);
if FLastError <> 0 then
break;
end
{$ENDIF}
until yr <= 0;
end;
procedure TBlockSocket.SendStreamRaw(const Stream: TStream);
begin
InternalSendStream(Stream, false, false);
end;
procedure TBlockSocket.SendStreamIndy(const Stream: TStream);
begin
InternalSendStream(Stream, true, true);
end;
procedure TBlockSocket.SendStream(const Stream: TStream);
begin
InternalSendStream(Stream, true, false);
end;
function TBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
begin
Result := 0;
if TestStopFlag then
Exit;
LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
// Result := synsock.Recv(FSocket, Buffer^, Length, MSG_NOSIGNAL);
Result := synsock.Recv(FSocket, Buffer, Length, MSG_NOSIGNAL);
if Result = 0 then
FLastError := WSAECONNRESET
else
SockCheck(Result);
ExceptCheck;
if Result > 0 then
begin
Inc(FRecvCounter, Result);
DoStatus(HR_ReadCount, IntToStr(Result));
DoMonitor(False, Buffer, Result);
DoReadFilter(Buffer, Result);
end;
end;
function TBlockSocket.RecvBufferEx(Buffer: TMemory; Len: Integer;
Timeout: Integer): Integer;
var
s: AnsiString;
rl, l: integer;
ti: LongWord;
{$IFDEF CIL}
n: integer;
b: TMemory;
{$ENDIF}
begin
ResetLastError;
Result := 0;
if Len > 0 then
begin
rl := 0;
repeat
ti := GetTick;
s := RecvPacket(Timeout);
l := Length(s);
if (rl + l) > Len then
l := Len - rl;
{$IFDEF CIL}
b := BytesOf(s);
for n := 0 to l do
Buffer[rl + n] := b[n];
{$ELSE}
Move(Pointer(s)^, IncPoint(Buffer, rl)^, l);
{$ENDIF}
rl := rl + l;
if FLastError <> 0 then
Break;
if rl >= Len then
Break;
if not FInterPacketTimeout then
begin
Timeout := Timeout - integer(TickDelta(ti, GetTick));
if Timeout <= 0 then
begin
FLastError := WSAETIMEDOUT;
Break;
end;
end;
until False;
delete(s, 1, l);
FBuffer := s;
Result := rl;
end;
end;
function TBlockSocket.RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString;
var
x: integer;
{$IFDEF CIL}
buf: Tmemory;
{$ENDIF}
begin
Result := '';
if Len > 0 then
begin
{$IFDEF CIL}
Setlength(Buf, Len);
x := RecvBufferEx(buf, Len , Timeout);
if FLastError = 0 then
begin
SetLength(Buf, x);
Result := StringOf(buf);
end
else
Result := '';
{$ELSE}
Setlength(Result, Len);
x := RecvBufferEx(Pointer(Result), Len , Timeout);
if FLastError = 0 then
SetLength(Result, x)
else
Result := '';
{$ENDIF}
end;
end;
function TBlockSocket.RecvPacket(Timeout: Integer): AnsiString;
var
x: integer;
{$IFDEF CIL}
buf: TMemory;
{$ENDIF}
begin
Result := '';
ResetLastError;
if FBuffer <> '' then
begin
Result := FBuffer;
FBuffer := '';
end
else
begin
{$IFDEF MSWINDOWS}
//not drain CPU on large downloads...
Sleep(0);
{$ENDIF}
x := WaitingData;
if x > 0 then
begin
{$IFDEF CIL}
SetLength(Buf, x);
x := RecvBuffer(Buf, x);
if x >= 0 then
begin
SetLength(Buf, x);
Result := StringOf(Buf);
end;
{$ELSE}
SetLength(Result, x);
x := RecvBuffer(Pointer(Result), x);
if x >= 0 then
SetLength(Result, x);
{$ENDIF}
end
else
begin
if CanRead(Timeout) then
begin
x := WaitingData;
if x = 0 then
FLastError := WSAECONNRESET;
if x > 0 then
begin
{$IFDEF CIL}
SetLength(Buf, x);
x := RecvBuffer(Buf, x);
if x >= 0 then
begin
SetLength(Buf, x);
result := StringOf(Buf);
end;
{$ELSE}
SetLength(Result, x);
x := RecvBuffer(Pointer(Result), x);
if x >= 0 then
SetLength(Result, x);
{$ENDIF}
end;
end
else
FLastError := WSAETIMEDOUT;
end;
end;
if FConvertLineEnd and (Result <> '') then
begin
if FLastCR and (Result[1] = LF) then
Delete(Result, 1, 1);
if FLastLF and (Result[1] = CR) then
Delete(Result, 1, 1);
FLastCR := False;
FLastLF := False;
end;
ExceptCheck;
end;
function TBlockSocket.RecvByte(Timeout: Integer): Byte;
begin
Result := 0;
ResetLastError;
if FBuffer = '' then
FBuffer := RecvPacket(Timeout);
if (FLastError = 0) and (FBuffer <> '') then
begin
Result := Ord(FBuffer[1]);
Delete(FBuffer, 1, 1);
end;
ExceptCheck;
end;
function TBlockSocket.RecvInteger(Timeout: Integer): Integer;
var
s: AnsiString;
begin
Result := 0;
s := RecvBufferStr(4, Timeout);
if FLastError = 0 then
Result := (ord(s[1]) + ord(s[2]) * 256) + (ord(s[3]) + ord(s[4]) * 256) * 65536;
end;
function TBlockSocket.RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString;
var
x: Integer;
s: AnsiString;
l: Integer;
CorCRLF: Boolean;
t: AnsiString;
tl: integer;
ti: LongWord;
begin
ResetLastError;
Result := '';
l := Length(Terminator);
if l = 0 then
Exit;
tl := l;
CorCRLF := FConvertLineEnd and (Terminator = CRLF);
s := '';
x := 0;
repeat
//get rest of FBuffer or incomming new data...
ti := GetTick;
s := s + RecvPacket(Timeout);
if FLastError <> 0 then
Break;
x := 0;
if Length(s) > 0 then
if CorCRLF then
begin
t := '';
x := PosCRLF(s, t);
tl := Length(t);
if t = CR then
FLastCR := True;
if t = LF then
FLastLF := True;
end
else
begin
x := pos(Terminator, s);
tl := l;
end;
if (FMaxLineLength <> 0) and (Length(s) > FMaxLineLength) then
begin
FLastError := WSAENOBUFS;
Break;
end;
if x > 0 then
Break;
if not FInterPacketTimeout then
begin
Timeout := Timeout - integer(TickDelta(ti, GetTick));
if Timeout <= 0 then
begin
FLastError := WSAETIMEDOUT;
Break;
end;
end;
until False;
if x > 0 then
begin
Result := Copy(s, 1, x - 1);
Delete(s, 1, x + tl - 1);
end;
FBuffer := s;
ExceptCheck;
end;
function TBlockSocket.RecvString(Timeout: Integer): AnsiString;
var
s: AnsiString;
begin
Result := '';
s := RecvTerminated(Timeout, CRLF);
if FLastError = 0 then
Result := s;
end;
function TBlockSocket.RecvBlock(Timeout: Integer): AnsiString;
var
x: integer;
begin
Result := '';
x := RecvInteger(Timeout);
if FLastError = 0 then
Result := RecvBufferStr(x, Timeout);
end;
procedure TBlockSocket.RecvStreamRaw(const Stream: TStream; Timeout: Integer);
var
s: AnsiString;
begin
repeat
s := RecvPacket(Timeout);
if FLastError = 0 then
WriteStrToStream(Stream, s);
until FLastError <> 0;
end;
procedure TBlockSocket.RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer);
var
s: AnsiString;
n: integer;
{$IFDEF CIL}
buf: TMemory;
{$ENDIF}
begin
for n := 1 to (Size div FSendMaxChunk) do
begin
{$IFDEF CIL}
SetLength(buf, FSendMaxChunk);
RecvBufferEx(buf, FSendMaxChunk, Timeout);
if FLastError <> 0 then
Exit;
Stream.Write(buf, FSendMaxChunk);
{$ELSE}
s := RecvBufferStr(FSendMaxChunk, Timeout);
if FLastError <> 0 then
Exit;
WriteStrToStream(Stream, s);
{$ENDIF}
end;
n := Size mod FSendMaxChunk;
if n > 0 then
begin
{$IFDEF CIL}
SetLength(buf, n);
RecvBufferEx(buf, n, Timeout);
if FLastError <> 0 then
Exit;
Stream.Write(buf, n);
{$ELSE}
s := RecvBufferStr(n, Timeout);
if FLastError <> 0 then
Exit;
WriteStrToStream(Stream, s);
{$ENDIF}
end;
end;
procedure TBlockSocket.RecvStreamIndy(const Stream: TStream; Timeout: Integer);
var
x: integer;
begin
x := RecvInteger(Timeout);
x := synsock.NToHL(x);
if FLastError = 0 then
RecvStreamSize(Stream, Timeout, x);
end;
procedure TBlockSocket.RecvStream(const Stream: TStream; Timeout: Integer);
var
x: integer;
begin
x := RecvInteger(Timeout);
if FLastError = 0 then
RecvStreamSize(Stream, Timeout, x);
end;
function TBlockSocket.PeekBuffer(Buffer: TMemory; Length: Integer): Integer;
begin
{$IFNDEF CIL}
// Result := synsock.Recv(FSocket, Buffer^, Length, MSG_PEEK + MSG_NOSIGNAL);
Result := synsock.Recv(FSocket, Buffer, Length, MSG_PEEK + MSG_NOSIGNAL);
SockCheck(Result);
ExceptCheck;
{$ENDIF}
end;
function TBlockSocket.PeekByte(Timeout: Integer): Byte;
var
s: string;
begin
{$IFNDEF CIL}
Result := 0;
if CanRead(Timeout) then
begin
SetLength(s, 1);
PeekBuffer(Pointer(s), 1);
if s <> '' then
Result := Ord(s[1]);
end
else
FLastError := WSAETIMEDOUT;
ExceptCheck;
{$ENDIF}
end;
procedure TBlockSocket.ResetLastError;
begin
FLastError := 0;
FLastErrorDesc := '';
end;
function TBlockSocket.SockCheck(SockResult: Integer): Integer;
begin
ResetLastError;
if SockResult = integer(SOCKET_ERROR) then
begin
FLastError := synsock.WSAGetLastError;
FLastErrorDesc := GetErrorDescEx;
end;
Result := FLastError;
end;
procedure TBlockSocket.ExceptCheck;
var
e: ESynapseError;
begin
FLastErrorDesc := GetErrorDescEx;
if (LastError <> 0) and (LastError <> WSAEINPROGRESS)
and (LastError <> WSAEWOULDBLOCK) then
begin
DoStatus(HR_Error, IntToStr(FLastError) + ',' + FLastErrorDesc);
if FRaiseExcept then
begin
e := ESynapseError.Create(Format('Synapse TCP/IP Socket error %d: %s',
[FLastError, FLastErrorDesc]));
e.ErrorCode := FLastError;
e.ErrorMessage := FLastErrorDesc;
raise e;
end;
end;
end;
function TBlockSocket.WaitingData: Integer;
var
x: Integer;
begin
Result := 0;
if synsock.IoctlSocket(FSocket, FIONREAD, x) = 0 then
Result := x;
if Result > c64k then
Result := c64k;
end;
function TBlockSocket.WaitingDataEx: Integer;
begin
if FBuffer <> '' then
Result := Length(FBuffer)
else
Result := WaitingData;
end;
procedure TBlockSocket.Purge;
begin
Sleep(1);
try
while (Length(FBuffer) > 0) or (WaitingData > 0) do
begin
RecvPacket(0);
if FLastError <> 0 then
break;
end;
except
on exception do;
end;
ResetLastError;
end;
procedure TBlockSocket.SetLinger(Enable: Boolean; Linger: Integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_Linger;
d.Enabled := Enable;
d.Value := Linger;
DelayedOption(d);
end;
function TBlockSocket.LocalName: string;
begin
Result := synsock.GetHostName;
if Result = '' then
Result := '127.0.0.1';
end;
procedure TBlockSocket.ResolveNameToIP(Name: string; const IPList: TStrings);
begin
IPList.Clear;
synsock.ResolveNameToIP(Name, FamilyToAF(FFamily), GetSocketprotocol, GetSocketType, IPList);
if IPList.Count = 0 then
IPList.Add(cAnyHost);
end;
function TBlockSocket.ResolveName(Name: string): string;
var
l: TStringList;
begin
l := TStringList.Create;
try
ResolveNameToIP(Name, l);
Result := l[0];
finally
l.Free;
end;
end;
function TBlockSocket.ResolvePort(Port: string): Word;
begin
Result := synsock.ResolvePort(Port, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
end;
function TBlockSocket.ResolveIPToName(IP: string): string;
begin
if not IsIP(IP) and not IsIp6(IP) then
IP := ResolveName(IP);
Result := synsock.ResolveIPToName(IP, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
end;
procedure TBlockSocket.SetRemoteSin(IP, Port: string);
begin
SetSin(FRemoteSin, IP, Port);
end;
function TBlockSocket.GetLocalSinIP: string;
begin
Result := GetSinIP(FLocalSin);
end;
function TBlockSocket.GetRemoteSinIP: string;
begin
Result := GetSinIP(FRemoteSin);
end;
function TBlockSocket.GetLocalSinPort: Integer;
begin
Result := GetSinPort(FLocalSin);
end;
function TBlockSocket.GetRemoteSinPort: Integer;
begin
Result := GetSinPort(FRemoteSin);
end;
function TBlockSocket.InternalCanRead(Timeout: Integer): Boolean;
{$IFDEF CIL}
begin
Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectRead);
{$ELSE}
var
TimeVal: PTimeVal;
TimeV: TTimeVal;
x: Integer;
FDSet: TFDSet;
begin
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
TimeVal := @TimeV;
if Timeout = -1 then
TimeVal := nil;
FDSet := FFdSet;
x := synsock.Select(FSocket + 1, @FDSet, nil, nil, TimeVal);
SockCheck(x);
if FLastError <> 0 then
x := 0;
Result := x > 0;
{$ENDIF}
end;
function TBlockSocket.CanRead(Timeout: Integer): Boolean;
var
ti, tr: Integer;
n: integer;
begin
if (FHeartbeatRate <> 0) and (Timeout <> -1) then
begin
ti := Timeout div FHeartbeatRate;
tr := Timeout mod FHeartbeatRate;
end
else
begin
ti := 0;
tr := Timeout;
end;
Result := InternalCanRead(tr);
if not Result then
for n := 0 to ti do
begin
DoHeartbeat;
if FStopFlag then
begin
Result := False;
FStopFlag := False;
Break;
end;
Result := InternalCanRead(FHeartbeatRate);
if Result then
break;
end;
ExceptCheck;
if Result then
DoStatus(HR_CanRead, '');
end;
function TBlockSocket.CanWrite(Timeout: Integer): Boolean;
{$IFDEF CIL}
begin
Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectWrite);
{$ELSE}
var
TimeVal: PTimeVal;
TimeV: TTimeVal;
x: Integer;
FDSet: TFDSet;
begin
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
TimeVal := @TimeV;
if Timeout = -1 then
TimeVal := nil;
FDSet := FFdSet;
x := synsock.Select(FSocket + 1, nil, @FDSet, nil, TimeVal);
SockCheck(x);
if FLastError <> 0 then
x := 0;
Result := x > 0;
{$ENDIF}
ExceptCheck;
if Result then
DoStatus(HR_CanWrite, '');
end;
function TBlockSocket.CanReadEx(Timeout: Integer): Boolean;
begin
if FBuffer <> '' then
Result := True
else
Result := CanRead(Timeout);
end;
function TBlockSocket.SendBufferTo(Buffer: TMemory; Length: Integer): Integer;
begin
Result := 0;
if TestStopFlag then
Exit;
DoMonitor(True, Buffer, Length);
LimitBandwidth(Length, FMaxSendBandwidth, FNextsend);
Result := synsock.SendTo(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
SockCheck(Result);
ExceptCheck;
Inc(FSendCounter, Result);
DoStatus(HR_WriteCount, IntToStr(Result));
end;
function TBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
begin
Result := 0;
if TestStopFlag then
Exit;
LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
Result := synsock.RecvFrom(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
SockCheck(Result);
ExceptCheck;
Inc(FRecvCounter, Result);
DoStatus(HR_ReadCount, IntToStr(Result));
DoMonitor(False, Buffer, Result);
end;
function TBlockSocket.GetSizeRecvBuffer: Integer;
var
l: Integer;
{$IFDEF CIL}
buf: TMemory;
{$ENDIF}
begin
{$IFDEF CIL}
setlength(buf, 4);
SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF), buf, l));
Result := System.BitConverter.ToInt32(buf,0);
{$ELSE}
l := SizeOf(Result);
SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_RCVBUF, @Result, l));
if FLastError <> 0 then
Result := 1024;
ExceptCheck;
{$ENDIF}
end;
procedure TBlockSocket.SetSizeRecvBuffer(Size: Integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_RecvBuff;
d.Value := Size;
DelayedOption(d);
end;
function TBlockSocket.GetSizeSendBuffer: Integer;
var
l: Integer;
{$IFDEF CIL}
buf: TMemory;
{$ENDIF}
begin
{$IFDEF CIL}
setlength(buf, 4);
SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF), buf, l));
Result := System.BitConverter.ToInt32(buf,0);
{$ELSE}
l := SizeOf(Result);
SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_SNDBUF, @Result, l));
if FLastError <> 0 then
Result := 1024;
ExceptCheck;
{$ENDIF}
end;
procedure TBlockSocket.SetSizeSendBuffer(Size: Integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_SendBuff;
d.Value := Size;
DelayedOption(d);
end;
procedure TBlockSocket.SetNonBlockMode(Value: Boolean);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_nonblock;
d.Enabled := Value;
DelayedOption(d);
end;
procedure TBlockSocket.SetTimeout(Timeout: Integer);
begin
SetSendTimeout(Timeout);
SetRecvTimeout(Timeout);
end;
procedure TBlockSocket.SetSendTimeout(Timeout: Integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_sendtimeout;
d.Value := Timeout;
DelayedOption(d);
end;
procedure TBlockSocket.SetRecvTimeout(Timeout: Integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_recvtimeout;
d.Value := Timeout;
DelayedOption(d);
end;
{$IFNDEF CIL}
function TBlockSocket.GroupCanRead(const SocketList: TList; Timeout: Integer;
const CanReadList: TList): boolean;
var
FDSet: TFDSet;
TimeVal: PTimeVal;
TimeV: TTimeVal;
x, n: Integer;
Max: Integer;
begin
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
TimeVal := @TimeV;
if Timeout = -1 then
TimeVal := nil;
FD_ZERO(FDSet);
Max := 0;
for n := 0 to SocketList.Count - 1 do
if TObject(SocketList.Items[n]) is TBlockSocket then
begin
if TBlockSocket(SocketList.Items[n]).Socket > Max then
Max := TBlockSocket(SocketList.Items[n]).Socket;
FD_SET(TBlockSocket(SocketList.Items[n]).Socket, FDSet);
end;
x := synsock.Select(Max + 1, @FDSet, nil, nil, TimeVal);
SockCheck(x);
ExceptCheck;
if FLastError <> 0 then
x := 0;
Result := x > 0;
CanReadList.Clear;
if Result then
for n := 0 to SocketList.Count - 1 do
if TObject(SocketList.Items[n]) is TBlockSocket then
if FD_ISSET(TBlockSocket(SocketList.Items[n]).Socket, FDSet) then
CanReadList.Add(TBlockSocket(SocketList.Items[n]));
end;
{$ENDIF}
procedure TBlockSocket.EnableReuse(Value: Boolean);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_reuse;
d.Enabled := Value;
DelayedOption(d);
end;
procedure TBlockSocket.SetTTL(TTL: integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_TTL;
d.Value := TTL;
DelayedOption(d);
end;
function TBlockSocket.GetTTL:integer;
var
l: Integer;
begin
{$IFNDEF CIL}
l := SizeOf(Result);
if FIP6Used then
synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, @Result, l)
else
synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_TTL, @Result, l);
{$ENDIF}
end;
procedure TBlockSocket.SetFamily(Value: TSocketFamily);
begin
FFamily := Value;
FFamilySave := Value;
end;
procedure TBlockSocket.SetSocket(Value: TSocket);
begin
FRecvCounter := 0;
FSendCounter := 0;
FSocket := Value;
{$IFNDEF CIL}
FD_ZERO(FFDSet);
FD_SET(FSocket, FFDSet);
{$ENDIF}
GetSins;
FIP6Used := FRemoteSin.AddressFamily = AF_INET6;
end;
function TBlockSocket.GetWsaData: TWSAData;
begin
{$IFDEF ONCEWINSOCK}
Result := WsaDataOnce;
{$ELSE}
Result := FWsaDataOnce;
{$ENDIF}
end;
function TBlockSocket.GetSocketType: integer;
begin
Result := 0;
end;
function TBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_IP);
end;
procedure TBlockSocket.DoStatus(Reason: THookSocketReason; const Value: string);
begin
if assigned(OnStatus) then
OnStatus(Self, Reason, Value);
end;
procedure TBlockSocket.DoReadFilter(Buffer: TMemory; var Len: Integer);
var
s: AnsiString;
begin
if assigned(OnReadFilter) then
if Len > 0 then
begin
{$IFDEF CIL}
s := StringOf(Buffer);
{$ELSE}
SetLength(s, Len);
Move(Buffer^, Pointer(s)^, Len);
{$ENDIF}
OnReadFilter(Self, s);
if Length(s) > Len then
SetLength(s, Len);
Len := Length(s);
{$IFDEF CIL}
Buffer := BytesOf(s);
{$ELSE}
Move(Pointer(s)^, Buffer^, Len);
{$ENDIF}
end;
end;
procedure TBlockSocket.DoCreateSocket;
begin
if assigned(OnCreateSocket) then
OnCreateSocket(Self);
end;
procedure TBlockSocket.DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
begin
if assigned(OnMonitor) then
begin
OnMonitor(Self, Writing, Buffer, Len);
end;
end;
procedure TBlockSocket.DoHeartbeat;
begin
if assigned(OnHeartbeat) and (FHeartbeatRate <> 0) then
begin
OnHeartbeat(Self);
end;
end;
function TBlockSocket.GetErrorDescEx: string;
begin
Result := GetErrorDesc(FLastError);
end;
class function TBlockSocket.GetErrorDesc(ErrorCode: Integer): string;
begin
{$IFDEF CIL}
if ErrorCode = 0 then
Result := ''
else
begin
Result := WSAGetLastErrorDesc;
if Result = '' then
Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
end;
{$ELSE}
case ErrorCode of
0:
Result := '';
WSAEINTR: {10004}
Result := 'Interrupted system call';
WSAEBADF: {10009}
Result := 'Bad file number';
WSAEACCES: {10013}
Result := 'Permission denied';
WSAEFAULT: {10014}
Result := 'Bad address';
WSAEINVAL: {10022}
Result := 'Invalid argument';
WSAEMFILE: {10024}
Result := 'Too many open files';
WSAEWOULDBLOCK: {10035}
Result := 'Operation would block';
WSAEINPROGRESS: {10036}
Result := 'Operation now in progress';
WSAEALREADY: {10037}
Result := 'Operation already in progress';
WSAENOTSOCK: {10038}
Result := 'Socket operation on nonsocket';
WSAEDESTADDRREQ: {10039}
Result := 'Destination address required';
WSAEMSGSIZE: {10040}
Result := 'Message too long';
WSAEPROTOTYPE: {10041}
Result := 'Protocol wrong type for Socket';
WSAENOPROTOOPT: {10042}
Result := 'Protocol not available';
WSAEPROTONOSUPPORT: {10043}
Result := 'Protocol not supported';
WSAESOCKTNOSUPPORT: {10044}
Result := 'Socket not supported';
WSAEOPNOTSUPP: {10045}
Result := 'Operation not supported on Socket';
WSAEPFNOSUPPORT: {10046}
Result := 'Protocol family not supported';
WSAEAFNOSUPPORT: {10047}
Result := 'Address family not supported';
WSAEADDRINUSE: {10048}
Result := 'Address already in use';
WSAEADDRNOTAVAIL: {10049}
Result := 'Can''t assign requested address';
WSAENETDOWN: {10050}
Result := 'Network is down';
WSAENETUNREACH: {10051}
Result := 'Network is unreachable';
WSAENETRESET: {10052}
Result := 'Network dropped connection on reset';
WSAECONNABORTED: {10053}
Result := 'Software caused connection abort';
WSAECONNRESET: {10054}
Result := 'Connection reset by peer';
WSAENOBUFS: {10055}
Result := 'No Buffer space available';
WSAEISCONN: {10056}
Result := 'Socket is already connected';
WSAENOTCONN: {10057}
Result := 'Socket is not connected';
WSAESHUTDOWN: {10058}
Result := 'Can''t send after Socket shutdown';
WSAETOOMANYREFS: {10059}
Result := 'Too many references:can''t splice';
WSAETIMEDOUT: {10060}
Result := 'Connection timed out';
WSAECONNREFUSED: {10061}
Result := 'Connection refused';
WSAELOOP: {10062}
Result := 'Too many levels of symbolic links';
WSAENAMETOOLONG: {10063}
Result := 'File name is too long';
WSAEHOSTDOWN: {10064}
Result := 'Host is down';
WSAEHOSTUNREACH: {10065}
Result := 'No route to host';
WSAENOTEMPTY: {10066}
Result := 'Directory is not empty';
WSAEPROCLIM: {10067}
Result := 'Too many processes';
WSAEUSERS: {10068}
Result := 'Too many users';
WSAEDQUOT: {10069}
Result := 'Disk quota exceeded';
WSAESTALE: {10070}
Result := 'Stale NFS file handle';
WSAEREMOTE: {10071}
Result := 'Too many levels of remote in path';
WSASYSNOTREADY: {10091}
Result := 'Network subsystem is unusable';
WSAVERNOTSUPPORTED: {10092}
Result := 'Winsock DLL cannot support this application';
WSANOTINITIALISED: {10093}
Result := 'Winsock not initialized';
WSAEDISCON: {10101}
Result := 'Disconnect';
WSAHOST_NOT_FOUND: {11001}
Result := 'Host not found';
WSATRY_AGAIN: {11002}
Result := 'Non authoritative - host not found';
WSANO_RECOVERY: {11003}
Result := 'Non recoverable error';
WSANO_DATA: {11004}
Result := 'Valid name, no data record of requested type'
else
Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
end;
{$ENDIF}
end;
{======================================================================}
constructor TSocksBlockSocket.Create;
begin
inherited Create;
FSocksIP:= '';
FSocksPort:= '1080';
FSocksTimeout:= 60000;
FSocksUsername:= '';
FSocksPassword:= '';
FUsingSocks := False;
FSocksResolver := True;
FSocksLastError := 0;
FSocksResponseIP := '';
FSocksResponsePort := '';
FSocksLocalIP := '';
FSocksLocalPort := '';
FSocksRemoteIP := '';
FSocksRemotePort := '';
FBypassFlag := False;
FSocksType := ST_Socks5;
end;
function TSocksBlockSocket.SocksOpen: boolean;
var
Buf: AnsiString;
n: integer;
begin
Result := False;
FUsingSocks := False;
if FSocksType <> ST_Socks5 then
begin
FUsingSocks := True;
Result := True;
end
else
begin
FBypassFlag := True;
try
if FSocksUsername = '' then
Buf := #5 + #1 + #0
else
Buf := #5 + #2 + #2 +#0;
SendString(Buf);
Buf := RecvBufferStr(2, FSocksTimeout);
if Length(Buf) < 2 then
Exit;
if Buf[1] <> #5 then
Exit;
n := Ord(Buf[2]);
case n of
0: //not need authorisation
;
2:
begin
Buf := #1 + AnsiChar(Length(FSocksUsername)) + FSocksUsername
+ AnsiChar(Length(FSocksPassword)) + FSocksPassword;
SendString(Buf);
Buf := RecvBufferStr(2, FSocksTimeout);
if Length(Buf) < 2 then
Exit;
if Buf[2] <> #0 then
Exit;
end;
else
//other authorisation is not supported!
Exit;
end;
FUsingSocks := True;
Result := True;
finally
FBypassFlag := False;
end;
end;
end;
function TSocksBlockSocket.SocksRequest(Cmd: Byte;
const IP, Port: string): Boolean;
var
Buf: AnsiString;
begin
FBypassFlag := True;
try
if FSocksType <> ST_Socks5 then
Buf := #4 + AnsiChar(Cmd) + SocksCode(IP, Port)
else
Buf := #5 + AnsiChar(Cmd) + #0 + SocksCode(IP, Port);
SendString(Buf);
Result := FLastError = 0;
finally
FBypassFlag := False;
end;
end;
function TSocksBlockSocket.SocksResponse: Boolean;
var
Buf, s: AnsiString;
x: integer;
begin
Result := False;
FBypassFlag := True;
try
FSocksResponseIP := '';
FSocksResponsePort := '';
FSocksLastError := -1;
if FSocksType <> ST_Socks5 then
begin
Buf := RecvBufferStr(8, FSocksTimeout);
if FLastError <> 0 then
Exit;
if Buf[1] <> #0 then
Exit;
FSocksLastError := Ord(Buf[2]);
end
else
begin
Buf := RecvBufferStr(4, FSocksTimeout);
if FLastError <> 0 then
Exit;
if Buf[1] <> #5 then
Exit;
case Ord(Buf[4]) of
1:
s := RecvBufferStr(4, FSocksTimeout);
3:
begin
x := RecvByte(FSocksTimeout);
if FLastError <> 0 then
Exit;
s := AnsiChar(x) + RecvBufferStr(x, FSocksTimeout);
end;
4:
s := RecvBufferStr(16, FSocksTimeout);
else
Exit;
end;
Buf := Buf + s + RecvBufferStr(2, FSocksTimeout);
if FLastError <> 0 then
Exit;
FSocksLastError := Ord(Buf[2]);
end;
if ((FSocksLastError <> 0) and (FSocksLastError <> 90)) then
Exit;
SocksDecode(Buf);
Result := True;
finally
FBypassFlag := False;
end;
end;
function TSocksBlockSocket.SocksCode(IP, Port: string): Ansistring;
var
ip6: TIp6Bytes;
n: integer;
begin
if FSocksType <> ST_Socks5 then
begin
Result := CodeInt(ResolvePort(Port));
if not FSocksResolver then
IP := ResolveName(IP);
if IsIP(IP) then
begin
Result := Result + IPToID(IP);
Result := Result + FSocksUsername + #0;
end
else
begin
Result := Result + IPToID('0.0.0.1');
Result := Result + FSocksUsername + #0;
Result := Result + IP + #0;
end;
end
else
begin
if not FSocksResolver then
IP := ResolveName(IP);
if IsIP(IP) then
Result := #1 + IPToID(IP)
else
if IsIP6(IP) then
begin
ip6 := StrToIP6(IP);
Result := #4;
for n := 0 to 15 do
Result := Result + AnsiChar(ip6[n]);
end
else
Result := #3 + AnsiChar(Length(IP)) + IP;
Result := Result + CodeInt(ResolvePort(Port));
end;
end;
function TSocksBlockSocket.SocksDecode(Value: Ansistring): integer;
var
Atyp: Byte;
y, n: integer;
w: Word;
ip6: TIp6Bytes;
begin
FSocksResponsePort := '0';
Result := 0;
if FSocksType <> ST_Socks5 then
begin
if Length(Value) < 8 then
Exit;
Result := 3;
w := DecodeInt(Value, Result);
FSocksResponsePort := IntToStr(w);
FSocksResponseIP := Format('%d.%d.%d.%d',
[Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
Result := 9;
end
else
begin
if Length(Value) < 4 then
Exit;
Atyp := Ord(Value[4]);
Result := 5;
case Atyp of
1:
begin
if Length(Value) < 10 then
Exit;
FSocksResponseIP := Format('%d.%d.%d.%d',
[Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
Result := 9;
end;
3:
begin
y := Ord(Value[5]);
if Length(Value) < (5 + y + 2) then
Exit;
for n := 6 to 6 + y - 1 do
FSocksResponseIP := FSocksResponseIP + Value[n];
Result := 5 + y + 1;
end;
4:
begin
if Length(Value) < 22 then
Exit;
for n := 0 to 15 do
ip6[n] := ord(Value[n + 5]);
FSocksResponseIP := IP6ToStr(ip6);
Result := 21;
end;
else
Exit;
end;
w := DecodeInt(Value, Result);
FSocksResponsePort := IntToStr(w);
Result := Result + 2;
end;
end;
{======================================================================}
procedure TDgramBlockSocket.Connect(IP, Port: string);
begin
SetRemoteSin(IP, Port);
InternalCreateSocket(FRemoteSin);
FBuffer := '';
DoStatus(HR_Connect, IP + ':' + Port);
end;
function TDgramBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
begin
Result := RecvBufferFrom(Buffer, Length);
end;
function TDgramBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
begin
Result := SendBufferTo(Buffer, Length);
end;
{======================================================================}
destructor TUDPBlockSocket.Destroy;
begin
if Assigned(FSocksControlSock) then
FSocksControlSock.Free;
inherited;
end;
procedure TUDPBlockSocket.EnableBroadcast(Value: Boolean);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_Broadcast;
d.Enabled := Value;
DelayedOption(d);
end;
function TUDPBlockSocket.UdpAssociation: Boolean;
var
b: Boolean;
begin
Result := True;
FUsingSocks := False;
if FSocksIP <> '' then
begin
Result := False;
if not Assigned(FSocksControlSock) then
FSocksControlSock := TTCPBlockSocket.Create;
FSocksControlSock.CloseSocket;
FSocksControlSock.CreateSocketByName(FSocksIP);
FSocksControlSock.Connect(FSocksIP, FSocksPort);
if FSocksControlSock.LastError <> 0 then
Exit;
// if not assigned local port, assign it!
if not FBinded then
Bind(cAnyHost, cAnyPort);
//open control TCP connection to SOCKS
FSocksControlSock.FSocksUsername := FSocksUsername;
FSocksControlSock.FSocksPassword := FSocksPassword;
b := FSocksControlSock.SocksOpen;
if b then
b := FSocksControlSock.SocksRequest(3, GetLocalSinIP, IntToStr(GetLocalSinPort));
if b then
b := FSocksControlSock.SocksResponse;
if not b and (FLastError = 0) then
FLastError := WSANO_RECOVERY;
FUsingSocks :=FSocksControlSock.UsingSocks;
FSocksRemoteIP := FSocksControlSock.FSocksResponseIP;
FSocksRemotePort := FSocksControlSock.FSocksResponsePort;
Result := b and (FLastError = 0);
end;
end;
function TUDPBlockSocket.SendBufferTo(Buffer: TMemory; Length: Integer): Integer;
var
SIp: string;
SPort: integer;
Buf: Ansistring;
begin
Result := 0;
FUsingSocks := False;
if (FSocksIP <> '') and (not UdpAssociation) then
FLastError := WSANO_RECOVERY
else
begin
if FUsingSocks then
begin
{$IFNDEF CIL}
Sip := GetRemoteSinIp;
SPort := GetRemoteSinPort;
SetRemoteSin(FSocksRemoteIP, FSocksRemotePort);
SetLength(Buf,Length);
Move(Buffer^, Pointer(Buf)^, Length);
Buf := #0 + #0 + #0 + SocksCode(Sip, IntToStr(SPort)) + Buf;
Result := inherited SendBufferTo(Pointer(Buf), System.Length(buf));
SetRemoteSin(Sip, IntToStr(SPort));
{$ENDIF}
end
else
Result := inherited SendBufferTo(Buffer, Length);
end;
end;
function TUDPBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
var
Buf: Ansistring;
x: integer;
begin
Result := inherited RecvBufferFrom(Buffer, Length);
if FUsingSocks then
begin
{$IFNDEF CIL}
SetLength(Buf, Result);
Move(Buffer^, Pointer(Buf)^, Result);
x := SocksDecode(Buf);
Result := Result - x + 1;
Buf := Copy(Buf, x, Result);
Move(Pointer(Buf)^, Buffer^, Result);
SetRemoteSin(FSocksResponseIP, FSocksResponsePort);
{$ENDIF}
end;
end;
{$IFNDEF CIL}
procedure TUDPBlockSocket.AddMulticast(MCastIP: string);
var
Multicast: TIP_mreq;
Multicast6: TIPv6_mreq;
n: integer;
ip6: Tip6bytes;
begin
if FIP6Used then
begin
ip6 := StrToIp6(MCastIP);
for n := 0 to 15 do
Multicast6.ipv6mr_multiaddr.u6_addr8[n] := Ip6[n];
Multicast6.ipv6mr_interface := 0;
SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_JOIN_GROUP,
PAnsiChar(@Multicast6), SizeOf(Multicast6)));
end
else
begin
Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
// Multicast.imr_interface.S_addr := INADDR_ANY;
Multicast.imr_interface.S_addr := FLocalSin.sin_addr.S_addr;
SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
PAnsiChar(@Multicast), SizeOf(Multicast)));
end;
ExceptCheck;
end;
procedure TUDPBlockSocket.DropMulticast(MCastIP: string);
var
Multicast: TIP_mreq;
Multicast6: TIPv6_mreq;
n: integer;
ip6: Tip6bytes;
begin
if FIP6Used then
begin
ip6 := StrToIp6(MCastIP);
for n := 0 to 15 do
Multicast6.ipv6mr_multiaddr.u6_addr8[n] := Ip6[n];
Multicast6.ipv6mr_interface := 0;
SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
PAnsiChar(@Multicast6), SizeOf(Multicast6)));
end
else
begin
Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
// Multicast.imr_interface.S_addr := INADDR_ANY;
Multicast.imr_interface.S_addr := FLocalSin.sin_addr.S_addr;
SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
PAnsiChar(@Multicast), SizeOf(Multicast)));
end;
ExceptCheck;
end;
{$ENDIF}
procedure TUDPBlockSocket.SetMulticastTTL(TTL: integer);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_MulticastTTL;
d.Value := TTL;
DelayedOption(d);
end;
function TUDPBlockSocket.GetMulticastTTL:integer;
var
l: Integer;
begin
{$IFNDEF CIL}
l := SizeOf(Result);
if FIP6Used then
synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, @Result, l)
else
synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_MULTICAST_TTL, @Result, l);
{$ENDIF}
end;
procedure TUDPBlockSocket.EnableMulticastLoop(Value: Boolean);
var
d: TSynaOption;
begin
d := TSynaOption.Create;
d.Option := SOT_MulticastLoop;
d.Enabled := Value;
DelayedOption(d);
end;
function TUDPBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_DGRAM);
end;
function TUDPBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_UDP);
end;
{======================================================================}
constructor TTCPBlockSocket.CreateWithSSL(SSLPlugin: TSSLClass);
begin
inherited Create;
FSSL := SSLPlugin.Create(self);
FHTTPTunnelIP := '';
FHTTPTunnelPort := '';
FHTTPTunnel := False;
FHTTPTunnelRemoteIP := '';
FHTTPTunnelRemotePort := '';
FHTTPTunnelUser := '';
FHTTPTunnelPass := '';
FHTTPTunnelTimeout := 30000;
end;
constructor TTCPBlockSocket.Create;
begin
CreateWithSSL(SSLImplementation);
end;
destructor TTCPBlockSocket.Destroy;
begin
inherited Destroy;
FSSL.Free;
end;
function TTCPBlockSocket.GetErrorDescEx: string;
begin
Result := inherited GetErrorDescEx;
if (FLastError = WSASYSNOTREADY) and (self.SSL.LastError <> 0) then
begin
Result := self.SSL.LastErrorDesc;
end;
end;
procedure TTCPBlockSocket.CloseSocket;
begin
if FSSL.SSLEnabled then
FSSL.Shutdown;
if (FSocket <> INVALID_SOCKET) and (FLastError = 0) then
begin
Synsock.Shutdown(FSocket, 1);
Purge;
end;
inherited CloseSocket;
end;
procedure TTCPBlockSocket.DoAfterConnect;
begin
if assigned(OnAfterConnect) then
begin
OnAfterConnect(Self);
end;
end;
function TTCPBlockSocket.WaitingData: Integer;
begin
Result := 0;
if FSSL.SSLEnabled and (FSocket <> INVALID_SOCKET) then
Result := FSSL.WaitingData;
if Result = 0 then
Result := inherited WaitingData;
end;
procedure TTCPBlockSocket.Listen;
var
b: Boolean;
Sip,SPort: string;
begin
if FSocksIP = '' then
begin
inherited Listen;
end
else
begin
Sip := GetLocalSinIP;
if Sip = cAnyHost then
Sip := LocalName;
SPort := IntToStr(GetLocalSinPort);
inherited Connect(FSocksIP, FSocksPort);
b := SocksOpen;
if b then
b := SocksRequest(2, Sip, SPort);
if b then
b := SocksResponse;
if not b and (FLastError = 0) then
FLastError := WSANO_RECOVERY;
FSocksLocalIP := FSocksResponseIP;
if FSocksLocalIP = cAnyHost then
FSocksLocalIP := FSocksIP;
FSocksLocalPort := FSocksResponsePort;
FSocksRemoteIP := '';
FSocksRemotePort := '';
ExceptCheck;
DoStatus(HR_Listen, '');
end;
end;
function TTCPBlockSocket.Accept: TSocket;
begin
if FUsingSocks then
begin
if not SocksResponse and (FLastError = 0) then
FLastError := WSANO_RECOVERY;
FSocksRemoteIP := FSocksResponseIP;
FSocksRemotePort := FSocksResponsePort;
Result := FSocket;
ExceptCheck;
DoStatus(HR_Accept, '');
end
else
begin
result := inherited Accept;
end;
end;
procedure TTCPBlockSocket.Connect(IP, Port: string);
begin
if FSocksIP <> '' then
SocksDoConnect(IP, Port)
else
if FHTTPTunnelIP <> '' then
HTTPTunnelDoConnect(IP, Port)
else
inherited Connect(IP, Port);
if FLasterror = 0 then
DoAfterConnect;
end;
procedure TTCPBlockSocket.SocksDoConnect(IP, Port: string);
var
b: Boolean;
begin
inherited Connect(FSocksIP, FSocksPort);
if FLastError = 0 then
begin
b := SocksOpen;
if b then
b := SocksRequest(1, IP, Port);
if b then
b := SocksResponse;
if not b and (FLastError = 0) then
FLastError := WSASYSNOTREADY;
FSocksLocalIP := FSocksResponseIP;
FSocksLocalPort := FSocksResponsePort;
FSocksRemoteIP := IP;
FSocksRemotePort := Port;
end;
ExceptCheck;
DoStatus(HR_Connect, IP + ':' + Port);
end;
procedure TTCPBlockSocket.HTTPTunnelDoConnect(IP, Port: string);
//bugfixed by Mike Green (mgreen@emixode.com)
var
s: string;
begin
Port := IntToStr(ResolvePort(Port));
inherited Connect(FHTTPTunnelIP, FHTTPTunnelPort);
if FLastError <> 0 then
Exit;
FHTTPTunnel := False;
if IsIP6(IP) then
IP := '[' + IP + ']';
SendString('CONNECT ' + IP + ':' + Port + ' HTTP/1.0' + CRLF);
if FHTTPTunnelUser <> '' then
Sendstring('Proxy-Authorization: Basic ' +
EncodeBase64(FHTTPTunnelUser + ':' + FHTTPTunnelPass) + CRLF);
SendString(CRLF);
repeat
s := RecvTerminated(FHTTPTunnelTimeout, #$0a);
if FLastError <> 0 then
Break;
if (Pos('HTTP/', s) = 1) and (Length(s) > 11) then
FHTTPTunnel := s[10] = '2';
until (s = '') or (s = #$0d);
if (FLasterror = 0) and not FHTTPTunnel then
FLastError := WSAECONNREFUSED;
FHTTPTunnelRemoteIP := IP;
FHTTPTunnelRemotePort := Port;
ExceptCheck;
end;
procedure TTCPBlockSocket.SSLDoConnect;
begin
ResetLastError;
if not FSSL.Connect then
FLastError := WSASYSNOTREADY;
ExceptCheck;
end;
procedure TTCPBlockSocket.SSLDoShutdown;
begin
ResetLastError;
FSSL.BiShutdown;
end;
function TTCPBlockSocket.GetLocalSinIP: string;
begin
if FUsingSocks then
Result := FSocksLocalIP
else
Result := inherited GetLocalSinIP;
end;
function TTCPBlockSocket.GetRemoteSinIP: string;
begin
if FUsingSocks then
Result := FSocksRemoteIP
else
if FHTTPTunnel then
Result := FHTTPTunnelRemoteIP
else
Result := inherited GetRemoteSinIP;
end;
function TTCPBlockSocket.GetLocalSinPort: Integer;
begin
if FUsingSocks then
Result := StrToIntDef(FSocksLocalPort, 0)
else
Result := inherited GetLocalSinPort;
end;
function TTCPBlockSocket.GetRemoteSinPort: Integer;
begin
if FUsingSocks then
Result := ResolvePort(FSocksRemotePort)
else
if FHTTPTunnel then
Result := StrToIntDef(FHTTPTunnelRemotePort, 0)
else
Result := inherited GetRemoteSinPort;
end;
function TTCPBlockSocket.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
begin
if FSSL.SSLEnabled then
begin
Result := 0;
if TestStopFlag then
Exit;
ResetLastError;
LimitBandwidth(Len, FMaxRecvBandwidth, FNextRecv);
Result := FSSL.RecvBuffer(Buffer, Len);
if FSSL.LastError <> 0 then
FLastError := WSASYSNOTREADY;
ExceptCheck;
Inc(FRecvCounter, Result);
DoStatus(HR_ReadCount, IntToStr(Result));
DoMonitor(False, Buffer, Result);
DoReadFilter(Buffer, Result);
end
else
Result := inherited RecvBuffer(Buffer, Len);
end;
function TTCPBlockSocket.SendBuffer(Buffer: TMemory; Length: Integer): Integer;
var
x, y: integer;
l, r: integer;
{$IFNDEF CIL}
p: Pointer;
{$ENDIF}
begin
if FSSL.SSLEnabled then
begin
Result := 0;
if TestStopFlag then
Exit;
ResetLastError;
DoMonitor(True, Buffer, Length);
{$IFDEF CIL}
Result := FSSL.SendBuffer(Buffer, Length);
if FSSL.LastError <> 0 then
FLastError := WSASYSNOTREADY;
Inc(FSendCounter, Result);
DoStatus(HR_WriteCount, IntToStr(Result));
{$ELSE}
l := Length;
x := 0;
while x < l do
begin
y := l - x;
if y > FSendMaxChunk then
y := FSendMaxChunk;
if y > 0 then
begin
LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
p := IncPoint(Buffer, x);
r := FSSL.SendBuffer(p, y);
if FSSL.LastError <> 0 then
FLastError := WSASYSNOTREADY;
if Flasterror <> 0 then
Break;
Inc(x, r);
Inc(Result, r);
Inc(FSendCounter, r);
DoStatus(HR_WriteCount, IntToStr(r));
end
else
break;
end;
{$ENDIF}
ExceptCheck;
end
else
Result := inherited SendBuffer(Buffer, Length);
end;
function TTCPBlockSocket.SSLAcceptConnection: Boolean;
begin
ResetLastError;
if not FSSL.Accept then
FLastError := WSASYSNOTREADY;
ExceptCheck;
Result := FLastError = 0;
end;
function TTCPBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_STREAM);
end;
function TTCPBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_TCP);
end;
{======================================================================}
function TICMPBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_RAW);
end;
function TICMPBlockSocket.GetSocketProtocol: integer;
begin
if FIP6Used then
Result := integer(IPPROTO_ICMPV6)
else
Result := integer(IPPROTO_ICMP);
end;
{======================================================================}
function TRAWBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_RAW);
end;
function TRAWBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_RAW);
end;
{======================================================================}
function TPGMmessageBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_RDM);
end;
function TPGMmessageBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_RM);
end;
{======================================================================}
function TPGMstreamBlockSocket.GetSocketType: integer;
begin
Result := integer(SOCK_STREAM);
end;
function TPGMstreamBlockSocket.GetSocketProtocol: integer;
begin
Result := integer(IPPROTO_RM);
end;
{======================================================================}
constructor TSynaClient.Create;
begin
inherited Create;
FIPInterface := cAnyHost;
FTargetHost := cLocalhost;
FTargetPort := cAnyPort;
FTimeout := 5000;
FUsername := '';
FPassword := '';
end;
{======================================================================}
constructor TCustomSSL.Create(const Value: TTCPBlockSocket);
begin
inherited Create;
FSocket := Value;
FSSLEnabled := False;
FUsername := '';
FPassword := '';
FLastError := 0;
FLastErrorDesc := '';
FVerifyCert := False;
FSSLType := LT_all;
FKeyPassword := '';
FCiphers := '';
FCertificateFile := '';
FPrivateKeyFile := '';
FCertCAFile := '';
FCertCA := '';
FTrustCertificate := '';
FTrustCertificateFile := '';
FCertificate := '';
FPrivateKey := '';
FPFX := '';
FPFXfile := '';
FSSHChannelType := '';
FSSHChannelArg1 := '';
FSSHChannelArg2 := '';
FCertComplianceLevel := -1; //default
FSNIHost := '';
end;
procedure TCustomSSL.Assign(const Value: TCustomSSL);
begin
FUsername := Value.Username;
FPassword := Value.Password;
FVerifyCert := Value.VerifyCert;
FSSLType := Value.SSLType;
FKeyPassword := Value.KeyPassword;
FCiphers := Value.Ciphers;
FCertificateFile := Value.CertificateFile;
FPrivateKeyFile := Value.PrivateKeyFile;
FCertCAFile := Value.CertCAFile;
FCertCA := Value.CertCA;
FTrustCertificate := Value.TrustCertificate;
FTrustCertificateFile := Value.TrustCertificateFile;
FCertificate := Value.Certificate;
FPrivateKey := Value.PrivateKey;
FPFX := Value.PFX;
FPFXfile := Value.PFXfile;
FCertComplianceLevel := Value.CertComplianceLevel;
FSNIHost := Value.FSNIHost;
end;
procedure TCustomSSL.ReturnError;
begin
FLastError := -1;
FLastErrorDesc := 'SSL/TLS support is not compiled!';
end;
function TCustomSSL.LibVersion: String;
begin
Result := '';
end;
function TCustomSSL.LibName: String;
begin
Result := '';
end;
function TCustomSSL.CreateSelfSignedCert(Host: string): Boolean;
begin
Result := False;
end;
function TCustomSSL.Connect: boolean;
begin
ReturnError;
Result := False;
end;
function TCustomSSL.Accept: boolean;
begin
ReturnError;
Result := False;
end;
function TCustomSSL.Shutdown: boolean;
begin
ReturnError;
Result := False;
end;
function TCustomSSL.BiShutdown: boolean;
begin
ReturnError;
Result := False;
end;
function TCustomSSL.SendBuffer(Buffer: TMemory; Len: Integer): Integer;
begin
ReturnError;
Result := integer(SOCKET_ERROR);
end;
procedure TCustomSSL.SetCertCAFile(const Value: string);
begin
FCertCAFile := Value;
end;
function TCustomSSL.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
begin
ReturnError;
Result := integer(SOCKET_ERROR);
end;
function TCustomSSL.WaitingData: Integer;
begin
ReturnError;
Result := 0;
end;
function TCustomSSL.GetSSLVersion: string;
begin
Result := '';
end;
function TCustomSSL.GetPeerSubject: string;
begin
Result := '';
end;
function TCustomSSL.GetPeerSerialNo: integer;
begin
Result := -1;
end;
function TCustomSSL.GetPeerName: string;
begin
Result := '';
end;
function TCustomSSL.GetPeerNameHash: cardinal;
begin
Result := 0;
end;
function TCustomSSL.GetPeerIssuer: string;
begin
Result := '';
end;
function TCustomSSL.GetPeerFingerprint: string;
begin
Result := '';
end;
function TCustomSSL.GetCertInfo: string;
begin
Result := '';
end;
function TCustomSSL.GetCipherName: string;
begin
Result := '';
end;
function TCustomSSL.GetCipherBits: integer;
begin
Result := 0;
end;
function TCustomSSL.GetCipherAlgBits: integer;
begin
Result := 0;
end;
function TCustomSSL.GetVerifyCert: integer;
begin
Result := 1;
end;
function TCustomSSL.DoVerifyCert:boolean;
begin
if assigned(OnVerifyCert) then
begin
result:=OnVerifyCert(Self);
end
else
result:=true;
end;
{======================================================================}
function TSSLNone.LibVersion: String;
begin
Result := 'Without SSL support';
end;
function TSSLNone.LibName: String;
begin
Result := 'ssl_none';
end;
{======================================================================}
initialization
begin
{$IFDEF ONCEWINSOCK}
if not InitSocketInterface(DLLStackName) then
begin
e := ESynapseError.Create('Error loading Socket interface (' + DLLStackName + ')!');
e.ErrorCode := 0;
e.ErrorMessage := 'Error loading Socket interface (' + DLLStackName + ')!';
raise e;
end;
synsock.WSAStartup(WinsockLevel, WsaDataOnce);
{$ENDIF}
end;
finalization
begin
{$IFDEF ONCEWINSOCK}
synsock.WSACleanup;
DestroySocketInterface;
{$ENDIF}
end;
end.
|
program JoyTest;
procedure ReadJoystick; Assembler;
asm
djrr: lda $dc00 ; get input from port 2 only
djrrb: ldy #0 ; this routine reads and decodes the
ldx #0 ; joystick/firebutton input data in
lsr ; the accumulator. this least significant
bcs djr0 ; 5 bits contain the switch closure
dey ; information. if a switch is closed then it
djr0: lsr ; produces a zero bit. if a switch is open then
bcs djr1 ; it produces a one bit. The joystick dir-
iny ; ections are right, left, forward, backward
djr1: lsr ; bit3=right, bit2=left, bit1=backward,
bcs djr2 ; bit0=forward and bit4=fire button.
dex ; at rts time dx and dy contain 2's compliment
djr2: lsr ; direction numbers i.e. $ff=-1, $00=0, $01=1.
bcs djr3 ; dx=1 (move right), dx=-1 (move left),
inx ; dx=0 (no x change). dy=-1 (move up screen),
djr3: lsr ; dy=0 (move down screen), dy=0 (no y change).
stx dx ; the forward joystick position corresponds
sty dy ; to move up the screen and the backward
dx: .byte 0
dy: .byte 0
end;
begin
Init;
end.
|
unit tracerIgnore;
{$mode delphi}
interface
uses
Classes, SysUtils, symbolhandler, symbolhandlerstructs, cefuncproc, globals;
type
TTracerIgnore=class
private
ignoredtracerregions: array of record
start: ptruint;
stop: ptruint;
end;
public
function InIgnoredModuleRange(address: ptruint): boolean;
procedure loadIgnoredModules;
end;
var IgnoredModuleListHandler: TTracerIgnore;
implementation
procedure TTracerIgnore.loadIgnoredModules;
var
s: string;
i,j: integer;
donottrace: tstringlist;
mi: tmoduleinfo;
begin
//parse the donottrace.txt file and find the range
setlength(ignoredtracerregions, 0);
s:=cheatenginedir+'donottrace.txt';
if FileExists(s) then //if the list exists
begin
donottrace:=tstringlist.create;
try
donottrace.LoadFromFile(s{$if FPC_FULLVERSION>=030200}, true{$endif});
i:=0;
while i<donottrace.Count do
begin
j:=pos('#', donottrace[i]);
if j>0 then
donottrace[i]:=trim(copy(donottrace[i], 1, j-1));
donottrace[i]:=lowercase(donottrace[i]);
if donottrace[i]='' then
donottrace.Delete(i)
else
begin
if symhandler.getmodulebyname(donottrace[i], mi) then
begin
//found it
setlength(ignoredtracerregions, length(ignoredtracerregions)+1);
ignoredtracerregions[length(ignoredtracerregions)-1].start:=mi.baseaddress;
ignoredtracerregions[length(ignoredtracerregions)-1].stop:=mi.baseaddress+mi.basesize;
end;
inc(i);
end;
end;
except
//don't care if file can't be loaded anyhow
end;
end;
end;
function TTracerIgnore.InIgnoredModuleRange(address: ptruint): boolean;
var i: integer;
begin
result:=false;
for i:=0 to length(ignoredtracerregions)-1 do
if InRangeX(address, ignoredtracerregions[i].start, ignoredtracerregions[i].stop) then
exit(true);
end;
initialization
IgnoredModuleListHandler:=TTracerIgnore.create;
end.
|
unit unit_penambahan_buku;
{unit untuk melakukan penambahan buku, baik buku itu sendiri ataupun jumlahnya}
interface
uses
unit_csv, unit_type;
{prosedur untuk menambahkan buku}
procedure tambah_buku(var buku : textfile; var tabelbuku : tabel_data);
{prosedur untuk menambahkan jumlah buku tertentu}
procedure tambah_jumlah_buku(var buku : textfile; var tabelbuku : tabel_data);
implementation
procedure tambah_buku(var buku : textfile; var tabelbuku : tabel_data);
var
banyakbuku : integer;
arraybuku : array_of_buku;
begin
arraybuku := buat_array_buku(tabelbuku);
banyakbuku := length(arraybuku);
setLength(arraybuku, banyakbuku + 1);
writeln('Masukkan Informasi buku yang ditambahkan: ');
write('Masukkan id buku: ');
readln(arraybuku[banyakbuku].id_buku);
write('Masukkan judul buku: ');
readln(arraybuku[banyakbuku].judul_buku);
write('Masukkan pengarang buku: ');
readln(arraybuku[banyakbuku].author);
write('Masukkan jumlah buku: ');
readln(arraybuku[banyakbuku].jumlah_buku);
write('Masukkan tahun terbit buku: ');
readln(arraybuku[banyakbuku].tahun_penerbit);
write('Masukkan kategori buku: ');
readln(arraybuku[banyakbuku].kategori);
masukkan_array_buku(arraybuku, tabelbuku);
writeln('Buku berhasil ditambahkan ke dalam sistem!');
end;
procedure tambah_jumlah_buku(var buku : textfile; var tabelbuku : tabel_data);
{KAMUS LOKAL}
var
id, i : integer;
jmlh_buku : integer;
arraybuku : array_of_buku;
found : boolean; {variabel untuk mengecek apakah ada buku atau tidak}
{ALGORITMA}
begin
arraybuku := buat_array_buku(tabelbuku);
write('Masukkan ID Buku: ');
readln(id);
write('Masukkan jumlah buku yang ditambahkan: ');
readln(jmlh_buku);
found := false;
for i := 1 to length(arraybuku) - 1 do begin
if(arraybuku[i].id_buku = id) then begin
found := true;
arraybuku[i].jumlah_buku := arraybuku[i].jumlah_buku + jmlh_buku;
writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ',arraybuku[i].judul_buku,' di perpustakaan menjadi ',
arraybuku[i].jumlah_buku);
masukkan_array_buku(arraybuku, tabelbuku);
end;
end;
if not found then begin
writeln('ID buku tidak ditemukan');
end;
end;
end.
|
{
This script checkes to see if an EDID is present in the selected record.
If not present it will add an EDID record.
Assign 'Position' to the first space found in NAME
Assign the EDID value to be the Prefix, plus the NAME of the reference up to the first space, and a suffix.
}
unit AddPrefixPlusNameToEDID;
{
Change Prefix to the desired value for your plugin.
}
Const
Prefix = 'Reserve';
Var
Count: Integer;
NavCount: Integer;
Sig: string;
function Process(e: IInterface): integer;
var
elEditorID: IInterface;
s, s1: String;
Position: Integer;
ESPFlags, SkipIt, NavMesh: Boolean;
ZPos: Integer;
begin
Sig := Signature(e);
Result := 0;
s1:= '';
// if (Sig = 'CELL') or (Sig = 'WRLD') then begin
AddMessage('Processing: ' + Name(e));
elEditorID := ElementByName(e, 'EDID - Editor ID');
s := GetElementEditValues(e, 'NAME');
Position:= pos(' ', s);
ZPos:= GetElementNativeValues(e, 'DATA\Position\Z');
ESPFlags:= GetIsInitiallyDisabled(e);
SkipIt:= False;
NavMesh:= False;
if (ZPos = -30000) and ESPFlags then SkipIt:= True;
if Position > 0 then s1 := Copy(s, 0, (Position - 1));
if Sig = 'NAVM' then NavMesh:= True;
if NavMesh then s1 := 'Navigation Mesh';
if Assigned(elEditorID) then Begin
if SkipIt then elEditorID := RemoveElement(e, 'EDID');
End;
if Not Assigned(elEditorID) then Begin
if not SkipIt then elEditorID := Add(e, 'EDID', True);
End;
if (not SkipIt) and Assigned(elEditorID) then Begin
if NavMesh then SetEditValue(elEditorID, s1 + '_' + IntToStr(NavCount));
if Not NavMesh then SetEditValue(elEditorID, Prefix + s1 + '_' + IntToStr(Count));
if NavMesh then Inc(NavCount);
if Not NavMesh then Inc(Count)
End;
// End;
end;
end.
|
unit JsonTests;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
Uses
SysUtils, Classes, Soap.EncdDecd, System.NetEncoding,
StringSupport, GuidSupport, BytesSupport,
AdvObjects, AdvJson,
DUnitX.TestFramework;
Type
[TextFixture]
TJsonTests = Class (TObject)
Private
Published
[TestCase]
procedure TestResource;
[TestCase]
procedure TestCustomDoc2;
End;
JsonPatchTestCaseAttribute = class (CustomTestCaseSourceAttribute)
protected
function GetCaseInfoArray : TestCaseInfoArray; override;
end;
[TextFixture]
TJsonPatchTests = Class (TObject)
Private
tests : TJsonArray;
engine : TJsonPatchEngine;
Published
[SetupFixture] procedure setup;
[TearDownFixture] procedure teardown;
[JsonPatchTestCase]
procedure PatchTest(Name : String);
End;
function CheckJsonIsSame(filename1, filename2 : String; var msg : string) : boolean;
implementation
uses
IdGlobalProtocols, TextUtilities, ShellSupport, XmlTests;
{ TJsonTests }
procedure TJsonTests.TestCustomDoc2;
var
json : TJsonObject;
f : TFileStream;
begin
f := TFileStream.Create('C:\work\fhirserver\tests\test.json', fmopenRead + fmShareDenyWrite);
try
json := TJSONParser.Parse(f);
try
assert.IsNotNull(json);
finally
json.Free;
end;
finally
f.Free;
end;
end;
procedure TJsonTests.TestResource;
var
json : TJsonObject;
f : TFileStream;
begin
f := TFileStream.Create('C:\work\org.hl7.fhir\build\publish\account-example.json', fmopenRead + fmShareDenyWrite);
try
json := TJSONParser.Parse(f);
try
assert.IsNotNull(json);
finally
json.Free;
end;
finally
f.Free;
end;
end;
{ JsonPatchTestCaseAttribute }
function JsonPatchTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray;
var
tests : TJsonArray;
test : TJsonNode;
i : integer;
s : String;
begin
tests := TJSONParser.ParseNode(FileToBytes('C:\work\fhirserver\tests\json-patch-tests.json')) as TJsonArray;
try
SetLength(result, tests.Count);
i := 0;
for test in tests do
begin
s := (test as TJsonObject)['comment'];
s := s.Substring(0, s.IndexOf(' '));
result[i].Name := s;
SetLength(result[i].Values, 1);
result[i].Values[0] := s;
inc(i);
end;
finally
tests.free;
end;
end;
{ TJsonPatchTests }
procedure TJsonPatchTests.PatchTest(Name: String);
var
t : TJsonNode;
test, outcome : TJsonObject;
s : String;
begin
for t in tests do
begin
test := t as TJsonObject;
s := test['comment'];
if s.StartsWith(Name) then
begin
if test.has('error') then
begin
Assert.WillRaise(
procedure begin
engine.applyPatch(test.obj['doc'], test.arr['patch']).Free;
end, Exception);
end
else
begin
outcome := engine.applyPatch(test.obj['doc'], test.arr['patch']);
try
Assert.IsTrue(TJsonNode.compare(outcome, test.obj['expected']))
finally
outcome.Free;
end;
end;
end;
end;
end;
procedure TJsonPatchTests.setup;
begin
tests := TJSONParser.ParseNode(FileToBytes('C:\work\fhirserver\tests\json-patch-tests.json')) as TJsonArray;
engine := TJsonPatchEngine.Create;
end;
procedure TJsonPatchTests.teardown;
begin
engine.Free;
tests.Free;
end;
function unbase64(text : String) : TBytes;
begin
result := DecodeBase64(AnsiString(text));
end;
function CompareObjects(path : String; o1, o2 : TJsonObject) : String; forward;
function CompareNodes(path : String; n1, n2 : TJsonNode) : String;
var
s, s1, s2 : String;
i : integer;
begin
if n1.ClassName <> n2.ClassName then
exit('properties differ at '+path+': type '+n1.ClassName+'/'+n2.ClassName)
else if (n1 is TJsonBoolean) then
begin
if ((n1 as TJsonBoolean).value <> (n2 as TJsonBoolean).value) then
exit('boolean property values differ at '+path+': type '+booltoStr((n1 as TJsonBoolean).value)+'/'+boolToStr((n2 as TJsonBoolean).value))
end
else if (n1 is TJsonString) then
begin
s1 := (n1 as TJsonString).value;
s2 := (n2 as TJsonString).value;
if not (s1.contains('<div') and s2.contains('<div')) then
if s1 <> s2 then
if not SameBytes(unbase64(s1), unbase64(s2)) then
exit('string property values differ at '+path+': type '+s1+'/'+s2)
end
else if (n1 is TJsonNumber) then
begin
if ((n1 as TJsonNumber).value <> (n2 as TJsonNumber).value) then
exit('number property values differ at '+path+': type '+(n1 as TJsonNumber).value+'/'+(n2 as TJsonNumber).value)
end
else if (n1 is TJsonObject) then
begin
s := CompareObjects(path, (n1 as TJsonObject), (n2 as TJsonObject));
if s <> '' then
exit(s)
end
else if (n1 is TJsonArray) then
begin
if ((n1 as TJsonArray).Count <> (n2 as TJsonArray).Count) then
exit('array properties differ at '+path+': count '+inttostr((n1 as TJsonArray).Count)+'/'+inttostr((n2 as TJsonArray).Count))
else
for I := 0 to (n1 as TJsonArray).Count - 1 do
begin
s := compareNodes(path+'['+inttostr(i)+']', (n1 as TJsonArray).Item[i], (n2 as TJsonArray).Item[i]);
if s <> '' then
exit(s)
end;
end
else if (n1 is TJsonNull) then
begin
// nothing to compare
end
else
exit('unhandled property '+n1.className);
end;
function CompareObjects(path : String; o1, o2 : TJsonObject) : String;
var
n : String;
n1: TJsonNode;
s : string;
begin
for n in o1.properties.Keys do
if (n <> 'fhir_comments') then
begin
n1 := o1.properties[n];
if o2.properties.ContainsKey(n) then
begin
s := compareNodes(path+'.'+n, n1, o2.properties[n]);
if (s <> '') then
exit(s);
end
else
exit('properties differ at '+path+': missing property '+n);
end;
for n in o2.properties.Keys do
if (n <> 'fhir_comments') then
if not o1.properties.ContainsKey(n) then
exit('properties differ at '+path+': missing property '+n);
end;
function CompareJson(filename1, filename2 : String; var msg : string) : boolean;
var
j1, j2 : TJsonObject;
begin
j1 := TJSONParser.ParseFile(filename1);
try
j2 := TJSONParser.ParseFile(filename2);
try
msg := CompareObjects('$', j1, j2);
result := msg = '';
finally
j2.free;
end;
finally
j1.Free;
end;
end;
function CheckJsonIsSame(filename1, filename2 : String; var msg : string) : boolean;
{$IFDEF DIFF}
var
j1, j2 : TJsonObject;
f1, f2, cmd : String;
{$ENDIF}
begin
result := compareJson(filename1, filename2, msg);
{$IFDEF DIFF}
if not result and showdiff then
begin
showdiff := false;
j1 := TJSONParser.ParseFile(filename1);
j2 := TJSONParser.ParseFile(filename2);
try
f1 := MakeTempFilename +'-source.xml';
f2 := MakeTempFilename +'-dest.xml';
StringToFile(TJsonWriter.writeObjectStr(j1, true), f1, TEncoding.UTF8);
StringToFile(TJsonWriter.writeObjectStr(j2, true), f2, TEncoding.UTF8);
cmd := f1+' '+f2;
ExecuteLaunch('open', '"C:\Program Files (x86)\WinMerge\WinMergeU.exe"', PChar(cmd), true);
finally
j2.Free;
j1.Free;
end;
end;
{$ENDIF}
end;
initialization
TDUnitX.RegisterTestFixture(TJsonTests);
TDUnitX.RegisterTestFixture(TJsonPatchTests);
end.
|
unit RGFileutil;
{
Scooby's magic file utilities.
Last modified : 16/7/97
In Win32 you might want to use API FileCopy rather than the
included CopyFile.
}
interface
uses SysUtils, LZExpand, Dialogs, WinProcs, WinTypes, forms, classes;
const
NL = #10;
type
ELZCopyError = class(exception);
EWinExecError = class(exception);
function CopyFile(PFromFileName, PToFileName : PChar): Boolean;
function CatFiles(const SourceFile, DestFile: string): boolean;
function FileLen(f_name: string): Longint;
function DeleteFileSpec(filespec: string): integer;
procedure Log_Report(log_OutputName, log_InputName: string);
function ReadFlatKeyString(Filename, KeyName: string): string;
function ReadFirstHTMLTag(sHTMLFile, sTagName: string): string;
function FindFiles(
FileSpec: string;
var lstHits: TStringList;
KeepPath: Boolean
): integer;
implementation
function CopyFile(PFromFileName, PToFileName : PChar): Boolean;
{ Corresponds to Delphi2 CopyAFile function ? }
var FromFile,ToFile: File;
FromFileName, ToFileName: String;
Begin
CopyFile := False;
try
FromFileName := StrPas(PFromFileName);
ToFileName := StrPas(PToFileName);
AssignFile(FromFile, FromFileName);
AssignFile(ToFile, ToFileName);
Reset(FromFile);
except
On E: EInOutError do begin
{ShowMessage('Error Copying!');}
CopyFile := False;
exit;
end;
end;
try
try
ReWrite(ToFile);
except
On E: EInOutError do begin
// ShowMessage('Disk I/O error! ' + E.message);
CopyFile := False;
exit;
end;
end;
try
if LZCopy(TFileRec(FromFile).Handle, TFileRec(ToFile).Handle) < 0 then
begin
raise ELZCopyError.Create('Error copying file with LZCopy');
end else begin
CopyFile := True;
end;
finally
CloseFile(ToFile);
end;
finally
CloseFile(FromFile);
end;
End;
function CatFiles(const SourceFile, DestFile: string): boolean;
{
Appends SourceFile to DestFile.
}
const
BUF_SIZE = 4096;
var
strmSource, strmDest: TFileStream;
Buffer: array[0..BUF_SIZE] of char;
bytesRead: LongInt;
begin
try
strmSource := TFileStream.Create(SourceFile, fmOpenRead);
if FileExists(DestFile) then
strmDest := TFileStream.Create(DestFile, fmOpenWrite)
else
strmDest := TFileStream.Create(DestFile, fmCreate);
strmDest.Seek(0, soFromEnd);
try
repeat
bytesRead := strmSource.Read(Buffer, BUF_SIZE);
strmDest.Write(Buffer, bytesRead);
until bytesRead < Sizeof(Buffer);
result := true;
finally
strmSource.Free;
strmDest.Free;
end;
except
On E: EInOutError do result := false;
end;
end;
function FileLen(f_name: string): Integer;
{ Returns the size of a file given by a fully-qualified filename }
begin
with TFileStream.Create(f_name, fmOpenRead) do try
result := Size;
finally free; end;
end;
procedure Log_Report(log_OutputName, log_InputName: string);
{
Write to a report file using the entire contents of log_InputName.
Where log_InputName begins with '*', this indicates verbatim text
to be written to the log file. When writing a new log file, attention
is paid to the first letter of the filename and a header written accordingly.
}
const
HDR_VIRUS = '--- One day Abnormal Virus Scan Log ---';
HDR_HEADER = '--- One day HEADER.INI log ---';
HDR_PROGRAM = '--- One day program operation log ---';
HDR_REPORT = '--- One day REPORT.DAT log ---';
var
Log_Out, Log_In: Textfile;
buf: String;
begin
try
try
{
Open log for append if exists, otherwise create with
default text.
}
AssignFile(Log_Out, log_OutputName);
If FileExists(log_OutputName) then
Append(Log_Out)
else begin
{ New file }
ReWrite(Log_Out);
{ Write report header }
buf := lowercase(copy(ExtractFileName(log_OutputName), 1, 1));
if buf = 'v' then
Writeln(Log_Out, HDR_VIRUS)
else if buf = 'h' then
Writeln(Log_Out, HDR_HEADER)
else if buf = 'p' then
Writeln(Log_Out, HDR_PROGRAM)
else if buf = 'r' then
Writeln(Log_Out, HDR_REPORT);
writeln(Log_Out);
end;
{
Append the entire input file (header, virus log, REPORT.DAT,
(or take literal text from the '*'-prefixed Log_InputName)
to the output file specified in Log_OutputName
}
writeln(Log_Out, FormatDateTime('hh:mm:ss :', now));
if Copy(Log_InputName, 1, 1) <> '*' then begin
AssignFile(Log_In, log_InputName);
Reset(Log_In);
writeln(Log_Out);
try
while not EOF(Log_In) do begin
readln(Log_In, buf);
writeln(Log_Out, buf);
end;
finally
CloseFile(Log_In);
end;
end else begin
buf := copy(Log_InputName, 2, length(Log_InputName));
writeln(Log_Out, buf);
end;
finally
CloseFile(Log_Out);
end;
except
On exception do ; // Keep quiet, this is non-essential
end;
end;
function DeleteFileSpec(filespec: string): integer;
{
Delete all files matching a given fully-qualified filespec.
*** USE WITH CAUTION. ***
^^^ You're intelligent. You didn't need to know this.
}
var
srHits: TSearchRec;
sPath: string;
begin
result := 0;
try
sPath := ExtractFilePath(filespec);
if FindFirst(filespec, faAnyFile, srHits) = 0 then begin
try
repeat
if DeleteFile(PChar(sPath + srHits.Name)) then
inc(result);
until FindNext(srHits) <> 0;
finally
Sysutils.FindClose(srHits);
end;
end;
except
on exception do ;
end;
end;
function FindFiles(
FileSpec: string;
var lstHits: TStringList;
KeepPath: Boolean
): integer;
{
Returns a stringlist of files found using the supplied filespec.
Does only one directory, for now, but may be expanded for recursion
later.
}
var
srHits: TSearchRec;
sPath: string;
begin
result := 0;
lstHits.Clear;
try
sPath := ExtractFilePath(filespec);
if FindFirst(filespec, faAnyFile, srHits) = 0 then begin
try
repeat
If KeepPath then
lstHits.Add(sPath + srHits.Name)
else
lstHits.Add(srHits.Name);
inc(result);
until FindNext(srHits) <> 0;
finally
Sysutils.FindClose(srHits);
end;
end;
except
on exception do ;
end;
end;
function ReadFlatKeyString(Filename, KeyName: string): string;
{
Will read an INI-style string value from a flat, sectionless (e.g. html)
file.
}
var
KeyFile: TextFile;
buf: string;
iPos: Integer;
begin
result := '';
try
try
AssignFile(KeyFile, FileName);
Reset(KeyFile);
While not(EOF(KeyFile)) do begin
{ Read line by line til EOF }
readln(KeyFile, buf);
{ Look for key }
iPos := pos(lowercase(KeyName), lowercase(buf));
if iPos <> 0 then begin
buf := Trim(Copy(buf, iPos + 1, Length(buf)));
iPos := pos('=', buf);
If iPos <> 0 then result := Trim(copy(buf, iPos + 1, Length(buf)));
break;
end;
end;
finally
CloseFile(KeyFile);
end;
except
On E: Exception do begin
result := '';
{$ifdef DEBUG}
Log_Report('C:\WINDOWS\DESKTOP\HAHA.LOG',
'*FlatKey Exception: ' + E.Message);
{$endif}
end;
end;
end;
function ReadFirstHTMLTag(sHTMLFile, sTagName: string): string;
{
Read first value occurrence of a given HTML tag (e.g. H1, TITLE)
}
const
TAG_START = '<';
TAG_START_END = '</';
TAG_END = '>';
var
lSize: Longint;
pStart, pEnd: PChar;
Buffer, Target: PChar;
HTML: TFileStream;
bytesRead: Longint;
begin
result := '';
try
If not FileExists(sHTMLFile) then exit;
lSize := FileLen(sHTMLFile);
Buffer := StrAlloc(Succ(lSize));
Target := StrAlloc(Succ(Length(TAG_START_END) + Length(TAG_END)
+ Length(sTagName)));
HTML := nil;
try
StrCopy(Target, PChar(TAG_START + sTagName + TAG_END));
HTML := TFileStream.Create(sHTMLFile, fmOpenRead);
bytesRead := HTML.Read(Buffer[0], lSize);
if bytesRead = 0 then
exit;
Buffer[lSize] := #0;
pStart := StrPos(Buffer, Target);
If pStart <> nil then
pStart := pStart + StrLen(Target)
else
exit;
StrCopy(Target, PChar(TAG_START_END + sTagName + TAG_END));
pEnd := StrPos(Buffer, Target);
if pEnd = nil then exit;
pEnd[0] := #0;
result := StrPas(pStart);
pEnd[0] := TAG_START;
finally
StrDispose(Buffer);
StrDispose(Target);
HTML.Free;
end;
except
on Exception do result := '';
end;
end;
end.
|
{SWAG=OOP.SWG,LARRY HADLEY,OOP-STRG.PAS,OOP,STRG,PAS}
{
LARRY HADLEY
>Right now, I have an Array of Pointers that point to the beginning
>of each page. The entire File is loaded into memory using BlockRead.
>To jump to a page, it checks the current page number, jumps to that
>offset (as specified by the Page Array) and dumps the contents
>to the screen Until it reaches the bottom.
I think I see. You have a monolithic block of memory...problem!
> There are a lot of ways to do it. One way would be to store the
> File as Arrays of *Pointers* to Strings...this would allow 64k of
> *sentences*, not just 64k of Text. It's a Variation on the old
Actually, this is wrong. Since TP use 4 Byte Pointers, you can
only store 16k of sentences in a single Array, but even
though that should still be plenty, you can use linked lists to
overcome that limitation!
>I have an Array of Pointers to the offset of each page. Could you
>provide a short code fragment?
Instead of treating the Pointers as offsets, you should be using
them as actual data collections.
{
*****************************************************************
Strings Unit With StrArray Object. Manage linked lists of Strings
transparently.
By Larry Hadley - May be used freely, provided credit is given
wherever this code is used.
*****************************************************************
}
Unit StrArray;
Interface
Type
PString = ^String;
PStringList = ^StringList;
StringList = Record
P : PString;
Next : PStringList;
end;
pStrArray = ^oStrArray;
oStrArray = Object
Root : PStringList;
total : Word;
eolist : Boolean; {end of list - only valid after calling At,
AtInsert, and AtDelete}
Constructor Init;
Destructor Done;
Procedure Insert(s : String);
Procedure Delete;
Function At(item : Word) : PString;
Procedure AtInsert(item : Word; s : String);
Procedure AtDelete(item : Word);
Function First : PString;
Function Last : PString;
Private
Procedure NewNode(N : PStringList);
Function AllocateS(s : String) : PString;
Procedure DeallocateS(Var P : PString);
end;
Implementation
Constructor oStrArray.Init;
begin
Root := NIL;
total := 0;
eolist := False;
end;
Destructor oStrArray.Done;
Var
T : PStringList;
begin
While Root <> NIL do
begin
T := Root^.Next;
if Root^.P <> NIL then
DeallocateS(Root^.P);
Dispose(Root);
Root := T;
end;
end;
Procedure oStrArray.Insert(s : String);
Var
T, T1 : PStringList;
begin
NewNode(T1);
T1^.P := AllocateS(s);
Inc(total);
if Root <> NIL then
begin
T := Root;
While T^.Next <> NIL do
T := T^.Next;
T^.Next := T1;
end
else
Root := T1;
end;
Procedure oStrArray.Delete;
Var
T, T1 : PStringList;
begin
T := Root;
if T <> NIL then
While T^.Next <> NIL do
begin
T1 := T;
T := T^.Next;
end;
T1^.Next := T^.Next;
if T^.P <> NIL then
DeallocateS(T^.P);
Dispose(T);
Dec(total);
end;
Function oStrArray.At(item : Word) : PString;
Var
count : Word;
T : PStringList;
begin
if item>total then
eolist := True
else
eolist := False;
count := 1; {1 based offset}
T := Root;
While (count < item) and (T^.Next <> NIL) do
begin
T := T^.Next;
Inc(count);
end;
At := T^.P;
end;
Procedure oStrArray.AtInsert(item : Word; s : String);
Var
count : Word;
T, T1 : PStringList;
begin
if item > total then
eolist := True
else
eolist := False;
NewNode(T1);
T1^.P := AllocateS(s);
Inc(total);
count := 1;
if Root <> NIL then
begin
T := Root;
While (count < Item) and (T^.Next <> NIL) do
begin
T := T^.Next;
Inc(count);
end;
T1^.Next := T^.Next;
T^.Next := T1;
end
else
Root := T1;
end;
Procedure oStrArray.AtDelete(item : Word);
Var
count : Word;
T, T1 : PStringList;
begin
if item > total then { don't delete if item bigger than list total -
explicit only! }
begin
eolist := True;
Exit;
end
else
eolist := False;
count := 1;
T := Root;
T1 := NIL;
While (count < item) and (T^.Next <> NIL) do
begin
T1 := T;
T := T^.Next;
Inc(count);
end;
if T1 = NIL then
Root := Root^.Next
else
T1^.Next := T^.Next;
DeallocateS(T^.P);
Dispose(T);
Dec(total);
end;
Function oStrArray.First : PString;
begin
First := Root^.P;
end;
Function oStrArray.Last : PString;
Var
T : PStringList;
begin
T := Root;
if T <> NIL then
While T^.Next <> NIL do
T := T^.Next;
Last := T^.P;
end;
Procedure oStrArray.NewNode(N : PStringList);
Var
T : PStringList;
begin
New(T);
T^.Next := NIL;
T^.P := NIL;
if N = NIL then
N := T
else
begin
T^.Next := N^.Next;
N^.Next := T;
end;
end;
Function oStrArray.AllocateS(s : String) : PString;
Var
P : PString;
begin
GetMem(P, Ord(s[0]) + 1);
P^ := s;
AllocateS := P;
end;
Procedure oStrArray.DeallocateS(Var P : PString);
begin
FreeMem(P, Ord(P^[0]) + 1);
P := NIL; {for error checking}
end;
end. {Unit StringS}
{
Code fragment :
Var
TextList : pStrArray;
...
New(TextList, Init);
...
Repeat
ReadLn(TextFile, s);
TextList^.Insert(s);
Until Eof(TextFile) or LowMemory;
...
For Loop := 1 to PageLen do
if Not(TextList^.eolist) then
Writeln(TextList^At(PageTop + Loop)^);
...
etc.
} |
unit GameUnit;
interface
uses
AvL, avlUtils, avlMath, avlVectors, OpenGL, VSEPrimitiveModel, VSETerrain;
type
TUnit=class(TObject)
private
FPos: TVector3D;
FDir, FBaseRoll, FBasePitch: Single;
FModel: TPriModel;
FTerrain: TTerrain;
FUpdateCount: Cardinal;
procedure SetPos(Pos: TVector3D);
procedure SetDir(Dir: Single);
public
constructor Create;
destructor Destroy; override;
procedure Draw;
procedure Update;
property Pos: TVector3D read FPos write SetPos;
property Dir: Single read FDir write SetDir;
end;
implementation
uses
VSECore, StateGame;
constructor TUnit.Create;
begin
inherited Create;
FModel:=TPriModel.Create(Core.GetFile('Tank.vpm'), true);
FTerrain:=TStateGame(Core.GetState(Core.FindState('Game'))).Terrain;
Pos:=Vector3D(68);
end;
destructor TUnit.Destroy;
begin
FAN(FModel);
inherited Destroy;
end;
procedure TUnit.Draw;
begin
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
with FPos do glTranslate(X, Y, Z);
glRotate(FDir, 0, 1, 0);
glRotate(FBaseRoll, -1, 0, 0);
glRotate(FBasePitch, 0, 0, 1);
FModel.Draw;
glPopMatrix;
end;
procedure TUnit.Update;
const
Speed=0.1;
begin
FPos.X:=FPos.X+Speed*cos(DegToRad(Dir));
FPos.Z:=FPos.Z-Speed*sin(DegToRad(Dir));
Pos:=FPos;
Dir:=Dir+0.15;
Inc(FUpdateCount);
if FUpdateCount>10 then
begin
FUpdateCount:=0;
Dir:=Dir+(2*Random-1);
end;
end;
procedure TUnit.SetPos(Pos: TVector3D);
const
dV1: TVector3D = (X: 3; Y: 0; Z: 2.25);
dV2: TVector3D = (X: 3; Y: 0; Z: -2.25);
var
V1, V2: TVector3D;
H1, H2, H3, H4, H14, H23, H: Single;
begin
FPos:=Pos;
with Pos do
begin
V1:=dV1;
VectorRotateY(-FDir, V1);
V2:=dV2;
VectorRotateY(-FDir, V2);
H1:=FTerrain.Altitude(X-V1.X, Z-V1.Z);
H2:=FTerrain.Altitude(X+V2.X, Z+V2.Z);
H3:=FTerrain.Altitude(X-V2.X, Z-V2.Z);
H4:=FTerrain.Altitude(X+V1.X, Z+V1.Z);
end;
H14:=(H1+H4)/2;
H23:=(H2+H3)/2;
H:=(H14+H23)/2;
FPos.Y:=3+H;
H14:=H-H14;
H23:=H-H23;
FBaseRoll:=RadToDeg(arctan((H3+H23-H1+H14)/4.5));
FBasePitch:=RadToDeg(arctan((H2+H23-H1+H14)/6));
end;
procedure TUnit.SetDir(Dir: Single);
begin
if (Dir>360) or (Dir<0)
then FDir:=Dir-360*Floor(Dir/360)
else FDir:=Dir;
end;
end. |
unit UTools;
interface
uses
Windows, Math, Controls, Classes, Graphics, ClipBrd, UObjectFile, ULevelFile,
types;
const
TOOLS_NUMBER = 3;
STATE_IDLE = 0;
STATE_MOVING = 1;
STATE_PASTED = 2;
STATE_DRAWING = 4;
type
TSelectionProps = record
R: TRect;
procedure Clear();
function Width(): Integer;
function Height(): Integer;
procedure SetRect(x0, y0, x1, y1: Integer);
end;
TTool = class
private
x1, x2 : Integer;
y1, y2 : Integer;
State : Integer;
isDrawing: Boolean;
Objects : TObjectFilePropsArr;
Level : TLevelFile;
xpos : PInteger;
ypos : PInteger;
public
constructor Create(vObjects: TObjectFilePropsArr;
vLevel: TLevelFile); virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); virtual;
procedure AssignCoords(x, y: PInteger); virtual;
procedure Draw(x, y: Integer); virtual;
procedure Paint(canvas: TCanvas); virtual;
procedure SetState(NewState: Integer);
function GetCursor():TCursor; virtual;
procedure Clear(); virtual; abstract;
end;
TBasicSelectionTool = class(TTool)
public
procedure Paste; virtual; abstract;
procedure Cut; virtual; abstract;
procedure Copy; virtual; abstract;
end;
TToolArr = array of TTool;
procedure CreateTools(var dest: TToolArr; vObjects: TObjectFilePropsArr;
vLevel: TLevelFile);
implementation
type
TPenTool = class(TTool)
private
SelectedObj: PObjectPropsNode;
SelRect: TRect;
dx, dy: Integer;
public
constructor Create(vObjects: TObjectFilePropsArr;
vLevel: TLevelFile); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Draw(x, y: Integer); override;
procedure Paint(canvas: TCanvas); override;
function GetCursor():TCursor; override;
procedure Clear(); override;
end;
THandTool = class(TTool)
public
constructor Create(vObjects: TObjectFilePropsArr;
vLevel: TLevelFile); override;
procedure Draw(x, y: Integer); override;
end;
TSelectionTool = class(TBasicSelectionTool)
public
dx, dy: Integer;
constructor Create(vObjects: TObjectFilePropsArr;
vLevel: TLevelFile); override;
procedure Paint(canvas: TCanvas); override;
procedure Draw(x, y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
function GetCursor():TCursor; override;
procedure Copy(); override;
procedure Paste(); override;
procedure Cut(); override;
end;
type
TToolClassIndex = (ttPen, ttHand, ttSelection);
TToolClass = class of TTool;
const
aTools: array [TToolClassIndex] of TToolClass = (TPenTool, THandTool,
TSelectionTool);
{ TTool }
procedure TTool.AssignCoords(x, y: PInteger);
begin
xpos := x;
ypos := y;
end;
constructor TTool.Create(vObjects: TObjectFilePropsArr; vLevel: TLevelFile);
begin
Objects := vObjects;
Level := vLevel;
x1 := 0;
x2 := 0;
y1 := 0;
y2 := 0;
isDrawing := false;
end;
procedure TTool.Paint(canvas: TCanvas);
begin
//..
end;
procedure TTool.SetState(NewState: Integer);
begin
State := NewState;
end;
procedure TTool.Draw;
begin
end;
function TTool.GetCursor: TCursor;
begin
result := crArrow;
end;
procedure TTool.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
isDrawing := true;
x1 := x;
y1 := y;
x2 := x;
y2 := y;
end;
end;
procedure TTool.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
isDrawing := false;
x2 := x;
y2 := y;
end;
end;
procedure TTool.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if not isDrawing then
Exit;
x2 := x;
y2 := y;
Draw(x,y);
end;
{ TPenTool }
procedure TPenTool.Clear;
begin
SelectedObj := nil;
with SelRect do
begin
left := 0;
Right := 0;
Top := 0;
Bottom := 0;
end;
end;
constructor TPenTool.Create(vObjects: TObjectFilePropsArr; vLevel: TLevelFile);
begin
inherited;
SetState(STATE_IDLE);
dx := 0;
dy := 0;
end;
procedure TPenTool.Draw(x, y: Integer);
begin
if state <> STATE_MOVING then
Exit;
dx := x - dx;
dy := y - dy;
SelectedObj.SetX(SelectedObj.x + dx);
SelectedObj.SetY(SelectedObj.y + dy);
SelRect := Level.GetObjectRect(SelectedObj^);
dx := x;
dy := y;
end;
function TPenTool.GetCursor: TCursor;
begin
case state of
STATE_IDLE:
Result := crCross;
STATE_MOVING:
Result := crSizeAll;
end;
end;
procedure TPenTool.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
dx := x1;
dy := y1;
case state of
STATE_IDLE:
begin
Level.ClearSelection;
SelectedObj := Level.AddObject(x, y);
SelRect := Level.GetObjectRect(SelectedObj^);
SelectedObj.selected := true;
state := STATE_MOVING;
end;
STATE_MOVING:
begin
if not ptinrect(SelRect, Point(x, y)) then
begin
state := STATE_IDLE;
MouseDown(Button, Shift, x, y);
Exit;
end;
end;
end;
end;
procedure TPenTool.Paint(canvas: TCanvas);
begin
canvas.Pen.width := 1;
canvas.Pen.Style := psDot;
canvas.Brush.Style := bsClear;
canvas.Pen.Color := RGB(180, 0, 30);
OffsetRect(SelRect, xpos^, ypos^);
canvas.Rectangle(SelRect);
OffsetRect(SelRect, -xpos^, -ypos^);
end;
{ THandTool }
constructor THandTool.Create(vObjects: TObjectFilePropsArr; vLevel: TLevelFile);
begin
inherited;
end;
procedure THandTool.Draw(x, y: Integer);
var
oxpos, oypos: Integer;
begin
oxpos := xpos^;
oypos := ypos^;
xpos^ := xpos^ + x2 - x1;
ypos^ := ypos^ + y2 - y1;
end;
{ TSelectionTool }
procedure TSelectionTool.Copy;
begin
end;
constructor TSelectionTool.Create(vObjects: TObjectFilePropsArr; vLevel: TLevelFile);
begin
inherited ;
State := STATE_IDLE;
end;
procedure TSelectionTool.Cut;
begin
end;
procedure TSelectionTool.Draw(x, y: Integer);
begin
Inherited;
end;
function TSelectionTool.GetCursor: TCursor;
begin
case state of
STATE_IDLE:
Result := crCross;
STATE_MOVING:
Result := crSizeAll;
end;
end;
procedure TSelectionTool.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
rct: TRect;
begin
Inherited;
if mbRight = Button then
Level.ClearSelection;
dx := x;
dy := y;
if Level.PtInSelection(x, y) then
state := STATE_MOVING
else
begin
state := STATE_IDLE;
with rct do
begin
Left := x1;
Right := x1+1;
Top := y1;
Bottom := y1+1;
Level.ClearSelection;
Level.SelectObjects(left, top, right, bottom);
end;
end;
end;
procedure TSelectionTool.MouseMove(Shift: TShiftState; X, Y: Integer);
var
rct: TRect;
begin
inherited;
if not isDrawing then
Exit;
case state of
STATE_IDLE:
begin
with rct do
begin
Left := Min(x1, x2);
Right := Max(x1, x2);
Top := Min(y1, y2);
Bottom := Max(y1, y2);
begin
if ssCtrl in Shift then
Level.AddToSelection(left, top, right, bottom)
else
begin
if not (ssShift in Shift) then
Level.ClearSelection;
Level.SelectObjects(left, top, right, bottom);
end;
end;
end;
end;
STATE_MOVING:
begin
if not isDrawing then
Exit;
dx := x - dx;
dy := y - dy;
// snapping будет приблизительно в этом месте, и еще там ^
Level.OffsetSelected(dx, dy);
Level.TrySnap;
dx := x;
dy := y;
end;
end;
end;
procedure TSelectionTool.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
// Level.ClearSelection;
// Level.SelectObjects(x1, y1, x2, y2);
// state := STATE_IDLE;
x1 := -1;
y1 := -1;
x2 := -1;
y1 := -1;
end;
procedure TSelectionTool.Paint(canvas: TCanvas);
begin
if state <> STATE_IDLE then
Exit;
canvas.Pen.width := 1;
canvas.Pen.Style := psDash;
canvas.Brush.Style := bsClear;
canvas.Pen.Color := RGB(125, 0, 90);
canvas.Rectangle(x1 + xpos^ , y1 + ypos^, x2 + xpos^ , y2 + ypos^);
end;
procedure TSelectionTool.Paste;
begin
end;
{ TSelectionProps }
function TSelectionProps.Width: Integer;
begin
Result := abs(R.Right - R.Left);
end;
function TSelectionProps.Height: Integer;
begin
Result := abs(R.Bottom - R.Top);
end;
procedure TSelectionProps.Clear;
begin
R := Rect(0, 0, 0, 0);
end;
procedure TSelectionProps.SetRect(x0, y0, x1, y1: Integer);
begin
R.Left := Min(x0, x1);
R.Right := Max(x0, x1);
R.Top := Min(y0, y1);
R.Bottom := Max(y0, y1);
end;
procedure CreateTools(var dest: TToolArr; vObjects: TObjectFilePropsArr;
vLevel: TLevelFile);
var
i: Integer;
begin
SetLength(dest, TOOLS_NUMBER);
for i := 0 to TOOLS_NUMBER-1 do
dest[i] := aTools[TToolClassIndex(i)].Create(vObjects, vLevel);
end;
end.
|
unit StringLib;
{*******************************************************************************
* Unit StringLib (for use with gds2txt) *
* Copyright (c) 2018 Coenrad Fourie *
* *
* 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. *
********************************************************************************}
interface
uses
SysUtils, Math;
type
TByteFile = file of Byte;
procedure ExitWithHaltCode(EText : string; HCode : integer);
function Read8Real(var r8File : TByteFile) : double;
function Read4Int(var r4File : TByteFile) : integer;
function Read2Bytes(var rrFile : TByteFile) : integer;
function ReadASCIIString(var raFile : TByteFile; raBytes : integer) : string;
procedure SkipRecord(var rrFile : TByteFile; srBytes : integer);
implementation
{ ---------------------------- ExitWithHaltCode ------------------------------ }
procedure ExitWithHaltCode(EText : string; HCode : integer);
// Writes text to screen and halts
begin
WriteLn('('+IntToStr(HCode)+') '+EText);
Halt(HCode);
end; // ExitWithHaltCode
// GDS2 Routines //
{ ------------------------------- Read8Real ---------------------------------- }
function Read8Real(var r8File : TByteFile) : double;
type
TEightByte = array[1..8] of byte;
var
eightByte : ^TEightByte;
r8Value : double;
r8Mantissa : Int64;
r8Exponent : integer;
r8i : shortint;
begin
r8Mantissa := 0;
r8Value := 0;
eightByte := @r8Value; // point eightByte to r8Value
for r8i := 1 to 8 do
Read(r8File,eightByte^[r8i]);
r8Exponent := eightByte^[1];
for r8i := 2 to 8 do
r8Mantissa := (r8Mantissa shl 8) or eightByte^[r8i];
if r8Exponent = 0 then // Special case - zero
begin
Read8Real := 0;
exit;
end;
if r8Exponent > 127 then
begin
dec(r8Exponent, 128);
r8Value := -1*(r8Mantissa/IntPower(2,56))*IntPower(16,(r8Exponent-64));
end
else
r8Value := 1.0*(r8Mantissa/IntPower(2,56))*IntPower(16,(r8Exponent-64));
Read8Real := r8Value;
end; // Read8Real
{ -------------------------------- Read4Int ---------------------------------- }
function Read4Int(var r4File : TByteFile) : integer;
var
r4Value, r4i : integer;
r8Byte : byte;
begin
r4Value := 0;
for r4i := 1 to 4 do
begin
Read(r4File, r8Byte);
r4Value := (r4Value shl 8) or r8Byte;
end;
Read4Int := r4Value;
end; // Read4Int
{ ------------------------------- Read2Bytes --------------------------------- }
function Read2Bytes(var rrFile : TByteFile) : integer;
var
rrByte : byte;
rrInt : integer;
begin
Read(rrFile,rrByte);
rrInt := rrByte;
Read(rrFile,rrByte);
rrInt := (rrInt shl 8) or rrByte;
Read2Bytes := rrInt;
end; // Read2Bytes
{ ---------------------------- ReadASCIIString ------------------------------- }
function ReadASCIIString(var raFile : TByteFile; raBytes : integer) : string;
var
raByte : byte;
rai : integer;
raStr : string;
begin
raStr := '';
for rai := 1 to raBytes do
begin
Read(raFile,raByte);
if raByte <> 0 then // Ignore null character
raStr := raStr + chr(raByte);
end;
ReadASCIIString := '"'+raStr+'"';
end; // ReadASCIIString
{ ------------------------------- SkipRecord --------------------------------- }
procedure SkipRecord(var rrFile : TByteFile; srBytes : integer);
var
sri : integer;
srEmptyByte : byte;
begin
for sri := 1 to srBytes do
Read(rrFile, srEmptyByte);
end;
end.
|
unit ftDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
ImgList, ActnList, ftForm, ftButtons, AdvShapeButton, ftAdvShapeButton;
type
TfrmDialog = class(TftForm)
btOK: TftOKButton;
btCancel: TftCancelButton;
alDialogActions: TActionList;
actOk: TAction;
actCancel: TAction;
procedure actCancelExecute(Sender: TObject);
procedure actOkExecute(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
private
public
procedure CreateParams(var Params: TCreateParams); override;
end;
implementation
{$R *.dfm}
procedure TfrmDialog.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or WS_POPUP;
if assigned(Owner) then
Params.WndParent := (Owner as TWinControl).Handle;
end;
procedure TfrmDialog.actCancelExecute(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmDialog.actOkExecute(Sender: TObject);
begin
//switch focus to another WinControl to ensure the current focused editor updates it's Subject
SelectNext(ActiveControl as TWinControl,True,True);
ModalResult := mrOK;
end;
procedure TfrmDialog.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Ord(Key) = VK_RETURN) and
((ActiveControl <> nil) and (ActiveControl.ClassType <> TMemo)) or
(ActiveControl = nil) then
begin
Key := #0;
actOk.Execute;
end
else
if (Ord(Key) = VK_ESCAPE) then
begin
Key := #0; //don't forward it on for processing
actCancel.Execute;
end;
end;
procedure TfrmDialog.FormActivate(Sender: TObject);
begin
inherited;
//keep method
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2010-5-19
描述: 数据持久化
*******************************************************************************}
unit UDataSaved;
interface
uses
Windows, Classes, Controls, Graphics, SysUtils, NativeXML, USysConst,
UMovedControl, UMovedItems, UBoderControl;
type
TScreensData = array of TScreenItem;
TMoviesData = array of TZnBorderControl;
TDataManager = class(TObject)
private
FXML: TNativeXml;
//数据对象
FDataFile: string;
//数据文件
FMovieParent: TWinControl;
//节目容器
FScreens: TScreensData;
FMovies: TMoviesData;
//屏幕&节目
public
constructor Create;
destructor Destroy; override;
//创建释放
function SaveToFile(const nFile: string): Boolean;
function LoadFromFile(const nFile: string): Boolean;
//保存载入
procedure ResetBlank(const nAll: Boolean);
//空文件名
property DataFile: string read FDataFile;
property Screens: TScreensData read FScreens;
property Movies: TMoviesData read FMovies;
property MovieParent: TWinControl read FMovieParent write FMovieParent;
end;
var
gDataManager: TDataManager = nil;
//全局使用
implementation
constructor TDataManager.Create;
begin
ResetBlank(True);
FMovieParent := nil;
FXML := TNativeXml.Create;
end;
destructor TDataManager.Destroy;
begin
FXML.Free;
inherited;
end;
procedure TDataManager.ResetBlank(const nAll: Boolean);
begin
SetLength(FMovies, 0);
SetLength(FScreens, 0);
if nAll then FDataFile := '';
end;
//------------------------------------------------------------------------------
//Desc: 读取或保存字体
procedure NodeFont(const nNode: TXmlNode; const nFont: TFont; nSave: Boolean);
begin
if nSave then
begin
nNode.NodeNew('Name').ValueAsString := EncodeBase64(nFont.Name);
nNode.NodeNew('Size').ValueAsInteger := nFont.Size;
nNode.NodeNew('Color').ValueAsInteger := nFont.Color;
nNode.NodeNew('Charset').ValueAsInteger := nFont.Charset;
nNode.NodeNew('fsBold').ValueAsBool := fsBold in nFont.Style;
nNode.NodeNew('fsItalic').ValueAsBool := fsItalic in nFont.Style;
nNode.NodeNew('fsUnderline').ValueAsBool := fsUnderline in nFont.Style;
nNode.NodeNew('fsStrikeOut').ValueAsBool := fsStrikeOut in nFont.Style;
end else
begin
nFont.Name := DecodeBase64(nNode.NodeByName('Name').ValueAsString);
nFont.Size := nNode.NodeByName('Size').ValueAsInteger;
nFont.Color := nNode.NodeByName('Color').ValueAsInteger;
nFont.Charset := nNode.NodeByName('Charset').ValueAsInteger;
nFont.Style := [];
if nNode.NodeByName('fsBold').ValueAsBool then
nFont.Style := [fsBold];
if nNode.NodeByName('fsItalic').ValueAsBool then
nFont.Style := nFont.Style + [fsItalic];
if nNode.NodeByName('fsUnderline').ValueAsBool then
nFont.Style := nFont.Style + [fsUnderline];
if nNode.NodeByName('fsStrikeOut').ValueAsBool then
nFont.Style := nFont.Style + [fsStrikeOut];
end;
end;
//Desc: 读取或保存nNode节点里nItem的属性
procedure NodeZnMovedControl(const nNode: TXmlNode; const nItem: TZnMovedControl;
const nSave: Boolean);
begin
if nSave then
begin
nNode.NodeNew('ShortName').ValueAsString := EncodeBase64(nItem.ShortName);
nNode.NodeNew('Byte_LTWH').ValueAsBool := nItem.Byte_LTWH;
nNode.NodeNew('ModeEnter').ValueAsInteger := nItem.ModeEnter;
nNode.NodeNew('ModeExit').ValueAsInteger := nItem.ModeExit;
nNode.NodeNew('SpeedEnter').ValueAsInteger := nItem.SpeedEnter;
nNode.NodeNew('SpeedExit').ValueAsInteger := nItem.SpeedExit;
nNode.NodeNew('KeedTime').ValueAsInteger := nItem.KeedTime;
nNode.NodeNew('ModeSerial').ValueAsInteger := nItem.ModeSerial;
NodeFont(nNode.NodeNew('Font'), nItem.Font, True);
nNode.NodeNew('ParentFont').ValueAsBool := nItem.ParentFont;
nNode.NodeNew('Color').ValueAsInteger := nItem.Color;
end else
begin
nItem.ShortName := DecodeBase64(nNode.NodeByName('ShortName').ValueAsString);
nItem.Byte_LTWH := nNode.NodeByName('Byte_LTWH').ValueAsBool;
nItem.ModeEnter := nNode.NodeByName('ModeEnter').ValueAsInteger;
nItem.ModeExit := nNode.NodeByName('ModeExit').ValueAsInteger;
nItem.SpeedEnter := nNode.NodeByName('SpeedEnter').ValueAsInteger;
nItem.SpeedExit := nNode.NodeByName('SpeedExit').ValueAsInteger;
nItem.KeedTime := nNode.NodeByName('KeedTime').ValueAsInteger;
nItem.ModeSerial := nNode.NodeByName('ModeSerial').ValueAsInteger;
NodeFont(nNode.NodeByName('Font'), nItem.Font, False);
nItem.ParentFont := nNode.NodeByName('ParentFont').ValueAsBool;
nItem.Color := nNode.NodeByName('Color').ValueAsInteger;
end;
end;
//Desc: 读取或保存nItem文本项
procedure NodeTextMovedItem(const nNode: TXmlNode; const nItem: TTextMovedItem;
const nSave: Boolean);
begin
if nSave then
begin
nNode.NodeNew('Text').ValueAsString := EncodeBase64(nItem.Text);
end else
begin
nItem.Text := DecodeBase64(nNode.NodeByName('Text').ValueAsString);
end;
end;
//Desc: 读取或保存nItem图文项
procedure NodePictureMovedItem(const nNode: TXmlNode; const nItem: TPictureMovedItem;
const nSave: Boolean);
var nStr: string;
nTop,nTmp: TXmlNode;
i,nLen,nIdx: Integer;
begin
if nSave then
begin
nNode.NodeNew('Text').ValueAsString := EncodeBase64(nItem.Text);
nNode.NodeNew('Stretch').ValueAsBool := nItem.Stretch;
nTop := nNode.NodeNew('Images');
nLen := nItem.DataList.Count - 1;
for i:=0 to nLen do
with PPictureData(nItem.DataList[i])^ do
begin
nTmp := nTop.NodeNew('Image');
nTmp.NodeNew('File').ValueAsString := EncodeBase64(FFile);
nTmp.NodeNew('Type').ValueAsInteger := Ord(FType);
nTmp.NodeNew('SingleLine').ValueAsBool := FSingleLine;
nTmp.NodeNew('ModeEnter').ValueAsInteger := FModeEnter;
nTmp.NodeNew('ModeExit').ValueAsInteger := FModeExit;
nTmp.NodeNew('SpeedEnter').ValueAsInteger := FSpeedEnter;
nTmp.NodeNew('SpeedExit').ValueAsInteger := FSpeedExit;
nTmp.NodeNew('KeedTime').ValueAsInteger := FKeedTime;
nTmp.NodeNew('ModeSerial').ValueAsInteger := FModeSerial;
end;
end else
begin
nItem.Text := DecodeBase64(nNode.NodeByName('Text').ValueAsString);
nItem.Stretch := nNode.NodeByName('Stretch').ValueAsBool;
nTop := nNode.NodeByName('Images');
nLen := nTop.NodeCount - 1;
for i:=0 to nLen do
begin
nTmp := nTop.Nodes[i];
if nTmp.Name <> 'Image' then Continue;
nStr := DecodeBase64(nTmp.NodeByName('File').ValueAsString);
nIdx := nTmp.NodeByName('Type').ValueAsInteger;
nIdx := nItem.AddData(nStr, TPictureDataType(nIdx));
with PPictureData(nItem.DataList[nIdx])^ do
begin
FSingleLine := nTmp.NodeByName('SingleLine').ValueAsBool;
FModeEnter := nTmp.NodeByName('ModeEnter').ValueAsInteger;
FModeExit := nTmp.NodeByName('ModeExit').ValueAsInteger;
FSpeedEnter := nTmp.NodeByName('SpeedEnter').ValueAsInteger;
FSpeedExit := nTmp.NodeByName('SpeedExit').ValueAsInteger;
FKeedTime := nTmp.NodeByName('KeedTime').ValueAsInteger;
FModeSerial := nTmp.NodeByName('ModeSerial').ValueAsInteger;
end;
end;
end;
end;
//Desc: 读取或保存nItem动画
procedure NodeAnimateMovedItem(const nNode: TXmlNode; const nItem: TAnimateMovedItem;
const nSave: Boolean);
var nStr: string;
begin
if nSave then
begin
nNode.NodeNew('Text').ValueAsString := EncodeBase64(nItem.Text);
nNode.NodeNew('ImageFile').ValueAsString := EncodeBase64(nItem.ImageFile);
nNode.NodeNew('Speed').ValueAsInteger := nItem.Speed;
nNode.NodeNew('Reverse').ValueAsBool := nItem.Reverse;
nNode.NodeNew('Stretch').ValueAsBool := nItem.Stretch;
end else
begin
nItem.Text := DecodeBase64(nNode.NodeByName('Text').ValueAsString);
nStr := DecodeBase64(nNode.NodeByName('ImageFile').ValueAsString);
if FileExists(nStr) then nItem.ImageFile := nStr;
nItem.Speed := nNode.NodeByName('Speed').ValueAsInteger;
nItem.Reverse := nNode.NodeByName('Reverse').ValueAsBool;
nItem.Stretch := nNode.NodeByName('Stretch').ValueAsBool;
end;
end;
//Desc: 读取或保存nItem时钟
procedure NodeTimeMovedItem(const nNode: TXmlNode; const nItem: TTimeMovedItem;
const nSave: Boolean);
begin
if nSave then
begin
nNode.NodeNew('FixText').ValueAsString := EncodeBase64(nItem.FixText);
nNode.NodeNew('DateText').ValueAsString := EncodeBase64(nItem.DateText);
nNode.NodeNew('WeekText').ValueAsString := EncodeBase64(nItem.WeekText);
nNode.NodeNew('TimeText').ValueAsString := EncodeBase64(nItem.TimeText);
nNode.NodeNew('FixColor').ValueAsInteger := nItem.FixColor;
nNode.NodeNew('DateColor').ValueAsInteger := nItem.DateColor;
nNode.NodeNew('WeekColor').ValueAsInteger := nItem.WeekColor;
nNode.NodeNew('TimeColor').ValueAsInteger := nItem.TimeColor;
nNode.NodeNew('ModeChar').ValueAsInteger := nItem.ModeChar;
nNode.NodeNew('ModeLine').ValueAsInteger := nItem.ModeLine;
nNode.NodeNew('ModeDate').ValueAsInteger := nItem.ModeDate;
nNode.NodeNew('ModeWeek').ValueAsInteger := nItem.ModeWeek;
nNode.NodeNew('ModeTime').ValueAsInteger := nItem.ModeTime;
end else
begin
nItem.FixText := DecodeBase64(nNode.NodeByName('FixText').ValueAsString);
nItem.DateText := DecodeBase64(nNode.NodeByName('DateText').ValueAsString);
nItem.WeekText := DecodeBase64(nNode.NodeByName('WeekText').ValueAsString);
nItem.TimeText := DecodeBase64(nNode.NodeByName('TimeText').ValueAsString);
nItem.FixColor := nNode.NodeByName('FixColor').ValueAsInteger;
nItem.DateColor := nNode.NodeByName('DateColor').ValueAsInteger;
nItem.WeekColor := nNode.NodeByName('WeekColor').ValueAsInteger;
nItem.TimeColor := nNode.NodeByName('TimeColor').ValueAsInteger;
nItem.ModeChar := nNode.NodeByName('ModeChar').ValueAsInteger;
nItem.ModeLine := nNode.NodeByName('ModeLine').ValueAsInteger;
nItem.ModeDate := nNode.NodeByName('ModeDate').ValueAsInteger;
nItem.ModeWeek := nNode.NodeByName('ModeWeek').ValueAsInteger;
nItem.ModeTime := nNode.NodeByName('ModeTime').ValueAsInteger;
end;
end;
//Desc: 读取或保存nItem表盘
procedure NodeClockMovedItem(const nNode: TXmlNode; const nItem: TClockMovedItem;
const nSave: Boolean);
var nTmp: TXmlNode;
nStream: TStringStream;
begin
if nSave then
begin
nNode.NodeNew('Text').ValueAsString := EncodeBase64(nItem.Text);
nNode.NodeNew('AutoDot').ValueAsBool := nItem.AutoDot;
nNode.NodeNew('DotX').ValueAsInteger := nItem.DotPoint.X;
nNode.NodeNew('DotY').ValueAsInteger := nItem.DotPoint.Y;
nNode.NodeNew('ColorHour').ValueAsInteger := nItem.ColorHour;
nNode.NodeNew('ColorMin').ValueAsInteger := nItem.ColorMin;
nNode.NodeNew('ColorSec').ValueAsInteger := nItem.ColorSec;
if Assigned(nItem.Image.Graphic) then
begin
nStream := TStringStream.Create('');
nItem.Image.Bitmap.SaveToStream(nStream);
nNode.NodeNew('Image').ValueAsString := EncodeBinHex(nStream.DataString);
nStream.Free;
end;
end else
begin
nItem.Text := DecodeBase64(nNode.NodeNew('Text').ValueAsString);
nItem.AutoDot := nNode.NodeByName('AutoDot').ValueAsBool;
nItem.DotPoint := Point(nNode.NodeByName('DotX').ValueAsInteger,
nNode.NodeByName('DotY').ValueAsInteger);
nItem.ColorHour := nNode.NodeByName('ColorHour').ValueAsInteger;
nItem.ColorMin := nNode.NodeByName('ColorMin').ValueAsInteger;
nItem.ColorSec := nNode.NodeByName('ColorSec').ValueAsInteger;
nTmp := nNode.FindNode('Image');
if Assigned(nTmp) then
begin
nStream := TStringStream.Create(DecodeBinHex(nTmp.ValueAsString));
nItem.Image.Bitmap.LoadFromStream(nStream);
nStream.Free;
end;
end;
end;
//Desc: 读取或保存nItem屏幕项
procedure NodeScreenItem(const nNode: TXmlNode; const nItem: PScreenItem;
const nSave: Boolean);
var nTmp: TXmlNode;
i,nLen: Integer;
begin
if nSave then
begin
nNode.NodeNew('ID').ValueAsInteger := nItem.FID;
nNode.NodeNew('Name').ValueAsString := EncodeBase64(nItem.FName);
nNode.NodeNew('Card').ValueAsInteger := nItem.FCard;
nNode.NodeNew('LenX').ValueAsInteger := nItem.FLenX;
nNode.NodeNew('LenY').ValueAsInteger := nItem.FLenY;
nNode.NodeNew('Type').ValueAsInteger := Ord(nItem.FType);
nNode.NodeNew('Port').ValueAsString := nItem.FPort;
nNode.NodeNew('Bote').ValueAsInteger := nItem.FBote;
nTmp := nNode.NodeNew('Devices');
nLen := High(nItem.FDevice);
for i:=Low(nItem.FDevice) to nLen do
with nTmp.NodeNew('Device') do
begin
AttributeAdd('ID', nItem.FDevice[i].FID);
AttributeAdd('Name', EncodeBase64(nItem.FDevice[i].FName));
end;
end else
begin
nItem.FID := nNode.NodeByName('ID').ValueAsInteger;
nItem.FName := DecodeBase64(nNode.NodeByName('Name').ValueAsString);
nItem.FCard := nNode.NodeByName('Card').ValueAsInteger;
nItem.FLenX := nNode.NodeByName('LenX').ValueAsInteger;
nItem.FLenY := nNode.NodeByName('LenY').ValueAsInteger;
nItem.FType := TScreenType(nNode.NodeByName('Type').ValueAsInteger);
nItem.FPort := nNode.NodeByName('Port').ValueAsString;
nItem.FBote := nNode.NodeByName('Bote').ValueAsInteger;
nTmp := nNode.NodeByName('Devices');
SetLength(nItem.FDevice, nTmp.NodeCount);
nLen := nTmp.NodeCount - 1;
for i:=0 to nLen do
begin
nItem.FDevice[i].FID := StrToInt(nTmp.Nodes[i].AttributeByName['ID']);
nItem.FDevice[i].FName := DecodeBase64(nTmp.Nodes[i].AttributeByName['Name']);
end;
end;
end;
//Desc: 读取或保存nItem的内容
procedure NodeMovieItem(const nNode: TXmlNode; var nItem: TControl;
const nSave: Boolean);
var nStr: string;
nPCtrl: TWinControl;
begin
if nSave then
begin
nNode.AttributeAdd('Name', nItem.Name);
nNode.AttributeAdd('Class', nItem.ClassName);
nNode.NodeNew('Left').ValueAsInteger := nItem.Left;
nNode.NodeNew('Top').ValueAsInteger := nItem.Top;
nNode.NodeNew('Width').ValueAsInteger := nItem.Width;
nNode.NodeNew('Height').ValueAsInteger := nItem.Height;
end else
begin
nPCtrl := TWinControl(nItem);
nItem := nil;
nStr := nNode.AttributeByName['Class'];
if nStr = TTextMovedItem.ClassName then
nItem := TTextMovedItem.Create(nPCtrl) else
//文本
if nStr = TPictureMovedItem.ClassName then
nItem := TPictureMovedItem.Create(nPCtrl) else
//图文
if nStr = TAnimateMovedItem.ClassName then
nItem := TAnimateMovedItem.Create(nPCtrl) else
//动画
if nStr = TTimeMovedItem.ClassName then
nItem := TTimeMovedItem.Create(nPCtrl) else
//时钟
if nStr = TClockMovedItem.ClassName then
nItem := TClockMovedItem.Create(nPCtrl) else Exit;
//表盘
nItem.Parent := nPCtrl;
nItem.Left := nNode.NodeByName('Left').ValueAsInteger;
nItem.Top := nNode.NodeByName('Top').ValueAsInteger;
nItem.Width := nNode.NodeByName('Width').ValueAsInteger;
nItem.Height := nNode.NodeByName('Height').ValueAsInteger;
end;
if nItem is TZnMovedControl then
NodeZnMovedControl(nNode, TZnMovedControl(nItem), nSave);
//基类属性
if nItem is TTextMovedItem then
NodeTextMovedItem(nNode, TTextMovedItem(nItem), nSave);
//文本
if nItem is TPictureMovedItem then
NodePictureMovedItem(nNode, TPictureMovedItem(nItem), nSave);
//图文
if nItem is TAnimateMovedItem then
NodeAnimateMovedItem(nNode, TAnimateMovedItem(nItem), nSave);
//动画
if nItem is TTimeMovedItem then
NodeTimeMovedItem(nNode, TTimeMovedItem(nItem), nSave);
//时钟
if nItem is TClockMovedItem then
NodeClockMovedItem(nNode, TClockMovedItem(nItem), nSave);
//表盘
end;
//Desc: 载入nFile文件
function TDataManager.LoadFromFile(const nFile: string): Boolean;
var nCtrl: TControl;
i,nIdx,nLen: Integer;
nNode,nTmp: TXmlNode;
begin
Result := False;
if not FileExists(nFile) then Exit;
try
FXML.LoadFromFile(nFile);
nNode := FXML.Root.NodeByName('Screens');
SetLength(FScreens, nNode.NodeCount);
nLen := nNode.NodeCount - 1;
for i:=0 to nLen do
NodeScreenItem(nNode.Nodes[i], @FScreens[i], False);
//屏幕列表
nNode := FXML.Root.NodeByName('Movies');
SetLength(FMovies, nNode.NodeCount);
nLen := nNode.NodeCount - 1;
for i:=0 to nLen do
with nNode.Nodes[i] do
begin
FMovies[i] := TZnBorderControl.Create(FMovieParent);
with FMovies[i] do
begin
Parent := FMovieParent;
Tag := NodeByName('Screen').ValueAsInteger;
Width := NodeByName('Width').ValueAsInteger;
Height := NodeByName('Height').ValueAsInteger;
HasBorder := NodeByName('HasBorder').ValueAsBool;
BorderSpeed := NodeByName('BorderSpeed').ValueAsInteger;
BorderWidth := NodeByName('BorderWidth').ValueAsInteger;
BorderColor := NodeByName('BorderColor').ValueAsInteger;
BorderEffect := NodeByName('BorderEffect').ValueAsInteger;
end;
nIdx := 0;
nTmp := NodeByName('Items');
while nIdx < nTmp.NodeCount do
begin
nCtrl := FMovies[i];
NodeMovieItem(nTmp.Nodes[nIdx], nCtrl, False);
Inc(nIdx);
end;
end;
Result := True;
FDataFile := nFile;
except
//ignor any error
end;
end;
//Date: 2010-5-20
//Parm: 文件名
//Desc: 将屏幕和节目数据存入nFile
function TDataManager.SaveToFile(const nFile: string): Boolean;
var nCtrl: TControl;
i,nIdx,nLen: Integer;
nNode,nTmp: TXmlNode;
begin
Result := False;
if FileExists(nFile) and (not DeleteFile(nFile)) then Exit;
FXML.Clear;
FXML.Utf8Encoded := True;
FXML.EncodingString := 'utf-8';
FXML.XmlFormat := xfReadable;
FXML.Root.Name := 'HBMData';
nNode := FXML.Root.NodeNew('Screens');
nLen := gScreenList.Count - 1;
for i:=0 to nLen do
begin
nTmp := nNode.NodeNew('Screen');
NodeScreenItem(nTmp, PScreenItem(gScreenList[i]), True);
end;
nNode := FXML.Root.NodeNew('Movies');
nLen := FMovieParent.ControlCount - 1;
for i:=0 to nLen do
if FMovieParent.Controls[i] is TZnBorderControl then
with TZnBorderControl(FMovieParent.Controls[i]) do
begin
nTmp := nNode.NodeNew('Movie');
nTmp.NodeNew('Screen').ValueAsInteger := Tag;
nTmp.NodeNew('Width').ValueAsInteger := Width;
nTmp.NodeNew('Height').ValueAsInteger := Height;
nTmp.NodeNew('HasBorder').ValueAsBool := HasBorder;
nTmp.NodeNew('BorderSpeed').ValueAsInteger := BorderSpeed;
nTmp.NodeNew('BorderWidth').ValueAsInteger := BorderWidth;
nTmp.NodeNew('BorderColor').ValueAsInteger := BorderColor;
nTmp.NodeNew('BorderEffect').ValueAsInteger := Ord(BorderEffect);
nIdx := 0;
nTmp := nTmp.NodeNew('Items');
while nIdx < ControlCount do
begin
nCtrl := Controls[nIdx];
NodeMovieItem(nTmp.NodeNew('Item'), nCtrl, True);
Inc(nIdx);
end;
end;
FXML.SaveToFile(nFile);
Result := True;
end;
initialization
gDataManager := TDataManager.Create;
finalization
FreeAndNil(gDataManager);
end.
|
unit dguiapp_main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Button3: TButton;
Button4: TButton;
Button5: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
protected
procedure Log(const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function AttachConsole(dwProcessID: Integer): Boolean; stdcall; external 'kernel32.dll';
const
ATTACH_PARENT_PROCESS = -1;
procedure TForm1.Log(const msg: string);
begin
Memo1.Lines.Add(msg);
end;
procedure TForm1.Button3Click(Sender: TObject);
var hStdIn, hStdOut, hStdErr: THandle;
begin
hStdIn := GetStdHandle(STD_INPUT_HANDLE);
hStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
hStdErr := GetStdHandle(STD_ERROR_HANDLE);
Log('In='+IntToStr(hStdIn)+', out='+IntToStr(hStdOut)+', err='+IntToStr(hStdErr));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if not AttachConsole(ATTACH_PARENT_PROCESS) then
RaiseLastOsError();
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Log('Handle: '+IntToStr(TTextRec(Output).Handle));
writeln('Yo dawg');
Log('Handle: '+IntToStr(TTextRec(Output).Handle));
end;
procedure TForm1.Button5Click(Sender: TObject);
var hStdOut: THandle;
str: string;
written: cardinal;
begin
str := 'Yo dawg';
hStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
if not WriteFile(hStdOut, str[1], Length(str)*SizeOf(char), written, nil) then
Log('Failed: error '+IntToStr(GetLastError));
end;
procedure TForm1.Button4Click(Sender: TObject);
var s: string;
begin
readln(s);
Log('Read: '+s);
end;
end.
|
{
Copyright (c) 2018, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit RGBConvert_test;
interface
uses
SysUtils,
Graphics,
RGB, RGBConvert,
{$IFDEF FPC}
fpcunit, testregistry
{$ELSE}
TestFramework
{$ENDIF};
type
TRGBTColorTest = class sealed(TTestCase)
published
procedure ToValueReturnPurple;
procedure FromValuePurple;
end;
implementation
procedure TRGBTColorTest.FromValuePurple;
var
RGB: IRGB;
begin
RGB := TRGBTColor.New.FromValue(clPurple);
CheckEquals(128, RGB.Red);
CheckEquals(0, RGB.Green);
CheckEquals(128, RGB.Blue);
end;
procedure TRGBTColorTest.ToValueReturnPurple;
var
RGB: IRGB;
Value: TColor;
begin
RGB := TRGB.New(128, 0, 128);
Value := TRGBTColor.New.ToValue(RGB);
CheckTrue(Value = clPurple);
end;
initialization
RegisterTest(TRGBTColorTest {$IFNDEF FPC}.Suite {$ENDIF});
end.
|
unit ZhSocketTransferImpl;
interface
uses
Windows, Classes, Forms, ScktComp, SysUtils, WinSock, ZhFileTreeImpl, Contnrs,
SyncObjs;
const
{ 数据包长度 }
PACKET_SIZE = 1024;
{ 定义消息 }
FILE_LIST = $00000001;
FILE_INFO = $00000002;
FILE_DOWNLOAD = $00000003;
{ 网络超时 }
G_TIMEOUT = 60000;
{ 代理信息 }
SOCKS_VER5 = $05;
CMD_CONNECT = $01;
RSV_DEFAULT = $00;
ATYP_DN = $03;
REP_SUCCESS = $00;
ATYP_IPV4 = $01;
type
TAuthenType = (atNone, atUserPass);
TDownloadStatus = (dsBegin, dsFileBegin, dsFileData, dsFileEnd, dsEnd, dsError);
TDownloadCallback = procedure(Sender: TObject; DownloadStatus: TDownloadStatus;
const WorkCount: Integer) of object;
//下载进度
TDownloadProgress = procedure(DownloadStatus: TDownloadStatus; FileName: string;
WorkCount: Integer);
{ 代理服务器属性 }
TProxyInfo = record
Enabled: Boolean;
IP: string;
Port: Integer;
Username: string;
Password: string;
end;
PSocksInfo = ^TSocksInfo;
TSocksInfo = record
ProxyIP: PChar; //代理服务器IP
ProxyPort: Integer; //代理服务器端口
ProxyUser: PChar; //代理服务器用户名
ProxyPass: PChar; //代理服务器密码
end;
{ 项目 }
TProjectItem = class(TCollectionItem)
private
FDescription: string;
FProjectName: string;
FResTree: TResTree;
FRootDir: string;
function GetResTreeFileName: string;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure RemoveResTree;
procedure SaveResTree;
procedure LoadResTree;
property ProjectName: string read FProjectName write FProjectName;
property Description: string read FDescription write FDescription;
property RootDir: string read FRootDir write FRootDir;
property ResTree: TResTree read FResTree;
end;
{ 项目管理器 }
TProjectCollection = class(TCollection)
private
FFileName: string;
FOwner: TPersistent;
procedure SaveToFile;
procedure LoadFromFile;
function GetItem(Index: Integer): TProjectItem;
public
constructor Create(AOwner: TPersistent; FileName: string);
destructor Destroy; override;
function Add(ProjectName, Descripton, RootDir: string): TProjectItem;
procedure Delete(Index: Integer);
procedure Clear;
function IndexOf(const ProjectName: string): Integer;
property Items[Index: Integer]: TProjectItem read GetItem; default;
end;
TMyServerClientThread = class(TServerClientThread)
private
procedure SendFileList(ProjectName: string);
procedure SendFile(ProjectName, FileName: string);
protected
procedure ClientExecute; override;
public
constructor Create(CreateSuspended: Boolean; ASocket: TServerClientWinSocket);
destructor Destroy; override;
end;
ThxUpdateServer = class(TObject)
private
FServerSocket: TServerSocket;
procedure FServerSocketGetThread(Sender: TObject; ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
procedure FServerSocketThreadStart(Sender: TObject; Thread: TServerClientThread);
procedure FServerSocketThreadEnd(Sender: TObject; Thread: TServerClientThread);
procedure FServerSocketListen(Sender: TObject; Socket: TCustomWinSocket);
function GetActive: Boolean;
public
constructor Create(APort: Integer);
destructor Destroy; override;
procedure StartService;
procedure StopServerice;
property Active: Boolean read GetActive;
end;
{ 下载文件列表,共用一个连接,下载完毕后连接不断开}
TDownloadFileListThread = class(TThread)
private
FClientSocket: TClientSocket;
FResTree: TResTree;
FProjectName: string;
FDownloadCallback: TDownloadCallback;
FDownloadStatus: TDownloadStatus;
FWorkCount: Integer;
procedure DoDownloadCallback;
procedure SyncDownloadCallback(DownloadStatus: TDownloadStatus; WorkCount: Integer);
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean; ClientSocket: TClientSocket;
ProjectName: string; ResTree: TResTree; DownloadCallback: TDownloadCallback);
property ResTree: TResTree read FResTree;
end;
ThxUpdateClient = class;
{ 下载多个文件,共用一个连接,下载完毕后连接不断开 }
TDownloadFilesThread = class(TThread)
private
FClientSocket: TClientSocket;
FFileNames: TStrings;
FDownloadCallback: TDownloadCallback;
FUpdateClient: ThxUpdateClient;
FProjectName: string;
FDownloadFileName: string;
FDownloadStatus: TDownloadStatus;
FWorkCount: Integer;
procedure DoDownloadCallback;
procedure SyncDownloadCallback(DownloadStatus: TDownloadStatus; WorkCount: Integer);
procedure DownloadAFile(AFileName: string);
protected
procedure Execute; override;
public
constructor Create(UpdateClient: ThxUpdateClient; CreateSuspended: Boolean; ClientSocket: TClientSocket;
ProjectName: string; FileNames: TStrings; DownloadCallback: TDownloadCallback);
destructor Destroy; override;
property DownloadFileName: string read FDownloadFileName;
end;
ThxUpdateClient = class(TObject)
private
FClientSocket: TClientSocket;
FResTree: TResTree;
FProjectName: string;
FProxyInfo: TProxyInfo;
function GetActive: Boolean;
function Handclasp(Socket: TSocket; AuthenType: TAuthenType): Boolean;
function ConnectByProxy(Socket: TSocket; RemoteIP: string; RemotePort: Integer): Boolean;
public
constructor Create(ProjectName: string);
destructor Destroy; override;
procedure Open(ServerIP: string; Port: Integer);
procedure Close;
procedure DownloadFileList(DownloadCallback: TDownloadCallback);
procedure DownloadFiles(FileNames: TStrings; DownloadCallback: TDownloadCallback);
property Active: Boolean read GetActive;
property ProxyInfo: TProxyInfo read FProxyInfo write FProxyInfo;
end;
function GetProjectCollection: TProjectCollection;
implementation
uses
ZhPubUtils, TypInfo;
var
G_ProjectCollection: TProjectCollection = nil;
function GetProjectCollection: TProjectCollection;
begin
if G_ProjectCollection = nil then
G_ProjectCollection:= TProjectCollection.Create(nil, ExtractFilePath(ParamStr(0)) + 'myprjs.dat');
Result:= G_ProjectCollection;
end;
{ TMyServerClientThread }
procedure TMyServerClientThread.ClientExecute;
var
Stream: TWinSocketStream;
CMD: Cardinal;
ProjectName, FileName: string;
begin
while (not Terminated) and ClientSocket.Connected do
begin
try
Stream := TWinSocketStream.Create(ClientSocket, G_TIMEOUT);
try
if Stream.WaitForData(G_TIMEOUT) then
begin
if ClientSocket.ReceiveLength = 0 then
begin
ClientSocket.Close;
Break;
end;
try
CMD:= StreamReadInteger(Stream);
ProjectName:= StreamReadString(Stream);
if GetProjectCollection.IndexOf(ProjectName) = -1 then
ClientSocket.Close;
case CMD of
// 下载文件列表
FILE_LIST:
begin
SendFileList(ProjectName);
end;
// 下载文件
FILE_DOWNLOAD:
begin
FileName:= StreamReadString(Stream);
SendFile(ProjectName, FileName);
end;
end;
except
ClientSocket.Close;
end;
end
else
ClientSocket.Close;
finally
Stream.Free;
end;
except
HandleException;
end;
end;
Terminate;
end;
constructor TMyServerClientThread.Create(CreateSuspended: Boolean; ASocket: TServerClientWinSocket);
begin
inherited Create(CreateSuspended, ASocket);
FreeOnTerminate:= True;
end;
destructor TMyServerClientThread.Destroy;
begin
inherited Destroy;
end;
procedure TMyServerClientThread.SendFile(ProjectName, FileName: string);
var
fs: TFileStream;
wss: TWinSocketStream;
Buf: array[0..PACKET_SIZE - 1] of char;
ReadCount: Integer;
Index: Integer;
RootDir: string;
begin
wss:= TWinSocketStream.Create(ClientSocket, G_TIMEOUT);
try
Index:= GetProjectCollection.IndexOf(ProjectName);
RootDir:= FormatDirectoryName(GetProjectCollection.Items[Index].RootDir);
fs:= TFileStream.Create(RootDir + FileName, fmOpenRead);
try
StreamWriteInteger(wss, FILE_DOWNLOAD);
StreamWriteString(wss, FileName);
StreamWriteInteger(wss, fs.Size);
while fs.Position < fs.Size do
begin
ReadCount:= fs.Read(Buf, PACKET_SIZE);
wss.WriteBuffer(Buf, ReadCount);
end;
finally
fs.Free;
end;
finally
wss.Free;
end;
end;
procedure TMyServerClientThread.SendFileList(ProjectName: string);
var
Index: Integer;
wss: TWinSocketStream;
begin
Index:= GetProjectCollection.IndexOf(ProjectName);
wss:= TWinSocketStream.Create(ClientSocket, G_TIMEOUT);
try
StreamWriteInteger(wss, FILE_LIST);
// 需要时才加载,可以节约资源
with GetProjectCollection.Items[Index] do
begin
LoadResTree;
ResTree.SaveToStream(wss);
//ResTree.Clear;
end;
finally
wss.Free;
end;
end;
{ ThxUpdateServer }
constructor ThxUpdateServer.Create(APort: Integer);
begin
FServerSocket:= TServerSocket.Create(nil);
FServerSocket.ServerType:= stThreadBlocking;
FServerSocket.ThreadCacheSize:= 0;
FServerSocket.Port:= APort;
FServerSocket.OnGetThread:= FServerSocketGetThread;
FServerSocket.OnThreadStart:= FServerSocketThreadStart;
FServerSocket.OnThreadEnd:= FServerSocketThreadEnd;
FServerSocket.OnListen:= FServerSocketListen;
end;
destructor ThxUpdateServer.Destroy;
begin
FServerSocket.Free;
inherited Destroy;
end;
procedure ThxUpdateServer.FServerSocketGetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket; var SocketThread: TServerClientThread);
begin
Assert(ClientSocket.Connected);
SocketThread:= TMyServerClientThread.Create(False, ClientSocket);
end;
procedure ThxUpdateServer.FServerSocketListen(Sender: TObject; Socket: TCustomWinSocket);
begin
end;
procedure ThxUpdateServer.FServerSocketThreadEnd(Sender: TObject; Thread: TServerClientThread);
begin
end;
procedure ThxUpdateServer.FServerSocketThreadStart(Sender: TObject; Thread: TServerClientThread);
begin
end;
function ThxUpdateServer.GetActive: Boolean;
begin
Result:= FServerSocket.Active;
end;
procedure ThxUpdateServer.StartService;
begin
FServerSocket.Open;
end;
procedure ThxUpdateServer.StopServerice;
begin
FServerSocket.Close;
end;
{ TDownloadFileListThread }
constructor TDownloadFileListThread.Create(CreateSuspended: Boolean; ClientSocket: TClientSocket;
ProjectName: string; ResTree: TResTree; DownloadCallback: TDownloadCallback);
begin
inherited Create(CreateSuspended);
FreeOnTerminate:= True;
FClientSocket:= ClientSocket;
FProjectName:= ProjectName;
FResTree:= ResTree;
FDownloadCallback:= DownloadCallback;
end;
procedure TDownloadFileListThread.DoDownloadCallback;
begin
if Assigned(FDownloadCallback) then
FDownloadCallback(Self, FDownloadStatus, FWorkCount);
end;
procedure TDownloadFileListThread.Execute;
var
wss: TWinSocketStream;
CMD: Cardinal;
begin
// 下载文件列表
if (not Terminated) and (FClientSocket.Socket.Connected) then
begin
wss:= TWinSocketStream.Create(FClientSocket.Socket, G_TIMEOUT);
try
// 请求下载文件列表
StreamWriteInteger(wss, FILE_LIST);
StreamWriteString(wss, FProjectName);
SyncDownloadCallback(dsBegin, 0);
// 等待下载文件列表
if wss.WaitForData(G_TIMEOUT) then
begin
CMD:= StreamReadInteger(wss);
Assert(CMD = FILE_LIST);
FResTree.LoadFromStream(wss);
SyncDownloadCallback(dsEnd, wss.Size);
Terminate;
end
else
FClientSocket.Close;
finally
wss.Free;
end;
end;
end;
{ TDownloadFiles }
constructor TDownloadFilesThread.Create(UpdateClient: ThxUpdateClient; CreateSuspended: Boolean; ClientSocket: TClientSocket;
ProjectName: string; FileNames: TStrings; DownloadCallback: TDownloadCallback);
begin
inherited Create(CreateSuspended);
FUpdateClient:= UpdateClient;
FreeOnTerminate:= True;
FClientSocket:= ClientSocket;
FProjectName:= ProjectName;
FDownloadCallback:= DownloadCallback;
FFileNames:= TStringList.Create;
FFileNames.Assign(FileNames);
FDownloadFileName:= '';
Assert(FClientSocket.Socket.Connected = True);
end;
destructor TDownloadFilesThread.Destroy;
begin
FFileNames.Free;
inherited Destroy;
end;
procedure TDownloadFilesThread.DownloadAFile(AFileName: string);
var
CMD: Cardinal;
wss: TWinSocketStream;
fs: TFileStream;
FileName: string;
FileSize: Integer;
Buf: array[0..PACKET_SIZE - 1] of char;
WriteCount: Integer;
szDir: string;
begin
Assert(FClientSocket.Socket.Connected = True);
wss:= TWinSocketStream.Create(FClientSocket.Socket, G_TIMEOUT);
try
// 请求下载文件列表
StreamWriteInteger(wss, FILE_DOWNLOAD);
StreamWriteString(wss, FProjectName);
StreamWriteString(wss, AFileName);
// 等待下载文件列表
if wss.WaitForData(G_TIMEOUT) then
begin
CMD:= StreamReadInteger(wss);
Assert(CMD = FILE_DOWNLOAD);
FileName:= StreamReadString(wss);
FileSize:= StreamReadInteger(wss);
FDownloadFileName:= FileName;
//开始下载
SyncDownloadCallback(dsFileBegin, FileSize);
//下载指定文件
FileName:= ExtractFilePath(Application.ExeName) + FDownloadFileName;
szDir:= ExtractFilePath(FileName);
if not ForceDirectories(szDir) then
raise Exception.Create('创建目录失败!');
fs:= TFileStream.Create(FileName, fmCreate);
try
while fs.Size < FileSize do
begin
FillChar(Buf, PACKET_SIZE, #0);
WriteCount:= wss.Read(Buf, PACKET_SIZE);
fs.WriteBuffer(Buf, WriteCount);
//下载中....
SyncDownloadCallback(dsFileData, WriteCount);
end;
//下载完毕
SyncDownloadCallback(dsFileEnd, fs.Size);
finally
fs.Free;
end;
end
else
FClientSocket.Close;
finally
wss.Free;
end;
end;
procedure TDownloadFilesThread.DoDownloadCallback;
begin
if Assigned(FDownloadCallback) then
FDownloadCallback(Self, FDownloadStatus, FWorkCount);
end;
procedure TDownloadFilesThread.Execute;
var
I: Integer;
begin
Assert(FClientSocket.Socket.Connected = True);
// 下载指定文件
for I:= 0 to FFileNames.Count - 1 do
begin
if (not Terminated) and (FClientSocket.Socket.Connected) then
DownloadAFile(FFileNames[I])
else
Break;
end;
FDownloadFileName:= '';
SyncDownloadCallback(dsEnd, 0);
Terminate;
end;
procedure TDownloadFileListThread.SyncDownloadCallback(
DownloadStatus: TDownloadStatus; WorkCount: Integer);
begin
FDownloadStatus:= DownloadStatus;
FWorkCount:= WorkCount;
if Application.Handle = 0 then
DoDownloadCallback
else
Synchronize(Self, DoDownloadCallback);
end;
{ ThxUpdateClient }
procedure ThxUpdateClient.Close;
begin
FClientSocket.Close;
end;
function ThxUpdateClient.ConnectByProxy(Socket: TSocket; RemoteIP: string;
RemotePort: Integer): Boolean;
var
Buf: array[0..1023] of Byte;
Ret: Integer;
saRemote: TSockAddr;
begin
Result:= False;
FillChar(saRemote, SizeOf(saRemote), #0);
saRemote.sin_family:= AF_INET;
saRemote.sin_addr.S_addr:= inet_addr(PChar(RemoteIP));
saRemote.sin_port:= htons(RemotePort);
Buf[0]:= SOCKS_VER5; // 代理协议版本号(Socks5)
Buf[1]:= CMD_CONNECT; // Reply
Buf[2]:= RSV_DEFAULT; // 保留字段
Buf[3]:= ATYP_IPV4; // 地址类型(IPV4)
CopyMemory(@Buf[4], @saRemote.sin_addr, 4); // 目标地址
CopyMemory(@Buf[8], @saRemote.sin_port, 2); // 目标端口号
Ret:= send(Socket, Buf, 10, 0);
if Ret = -1 then Exit;
Ret:= recv(Socket, Buf, 1023, 0);
if Ret = -1 then Exit;
if Buf[1] <> REP_SUCCESS then Exit;
Result:= True;
end;
constructor ThxUpdateClient.Create(ProjectName: string);
var
wsData: TWSAData;
begin
FProjectName:= ProjectName;
FResTree:= TResTree.Create;
Assert(WSAStartup(MAKEWORD(1, 1), wsData) = 0);
FClientSocket:= TClientSocket.Create(nil);
FClientSocket.ClientType:= ctBlocking;
end;
destructor ThxUpdateClient.Destroy;
begin
if FClientSocket.Socket.Connected then
FClientSocket.Close;
FreeAndNil(FClientSocket);
FreeAndNil(FResTree);
WSACleanup;
inherited Destroy;
end;
procedure ThxUpdateClient.DownloadFileList(DownloadCallback: TDownloadCallback);
begin
FResTree.Clear;
TDownloadFileListThread.Create(False, FClientSocket, FProjectName, FResTree, DownloadCallback);
end;
procedure ThxUpdateClient.DownloadFiles(FileNames: TStrings; DownloadCallback: TDownloadCallback);
begin
TDownloadFilesThread.Create(Self, False, FClientSocket, FProjectName, FileNames, DownloadCallback);
end;
function ThxUpdateClient.GetActive: Boolean;
begin
Result:= FClientSocket.Socket.Connected;
end;
function ThxUpdateClient.Handclasp(Socket: TSocket; AuthenType: TAuthenType): Boolean;
var
Buf: array[0..254] of Byte;
I, Ret: Integer;
Username, Password: string;
begin
Result:= False;
case AuthenType of
// 无需验证
atNone:
begin
Buf[0]:= SOCKS_VER5;
Buf[1]:= $01;
Buf[2]:= $00;
Ret:= send(Socket, Buf, 3, 0);
if Ret = -1 then Exit;
Ret:= recv(Socket, Buf, 255, 0);
if Ret < 2 then Exit;
if Buf[1] <> $00 then Exit;
Result:= True;
end;
// 用户名密码验证
atUserPass:
begin
Buf[0]:= SOCKS_VER5;
Buf[1]:= $02;
Buf[2]:= $00;
Buf[3]:= $02;
Ret:= send(Socket, Buf, 4, 0);
if Ret = -1 then Exit;
FillChar(Buf, 255, #0);
Ret:= recv(Socket, Buf, 255, 0);
if Ret < 2 then Exit;
if Buf[1] <> $02 then Exit;
Username:= FProxyInfo.Username;
Password:= FProxyInfo.Password;
FillChar(Buf, 255, #0);
Buf[0]:= $01;
Buf[1]:= Length(Username);
for I:= 0 to Buf[1] - 1 do
Buf[2 + I]:= Ord(Username[I + 1]);
Buf[2 + Length(Username)]:= Length(Password);
for I:= 0 to Buf[2 + Length(Username)] - 1 do
Buf[3 + Length(Username) + I]:= Ord(Password[I + 1]);
Ret:= send(Socket, Buf, Length(Username) + Length(Password) + 3, 0);
if Ret = -1 then Exit;
Ret:= recv(Socket, Buf, 255, 0);
if Ret = -1 then Exit;
if Buf[1] <> $00 then Exit;
Result:= True;
end;
end;
end;
procedure ThxUpdateClient.Open(ServerIP: string; Port: Integer);
begin
Assert(FClientSocket.Socket.Connected = False);
try
if not FProxyInfo.Enabled then
begin
FClientSocket.Host:= ServerIP;
FClientSocket.Port:= Port;
FClientSocket.Open;
end
else begin { 使用代理服务器 }
// 连接到Socks服务器
FClientSocket.Host:= FProxyInfo.IP;
FClientSocket.Port:= FProxyInfo.Port;
FClientSocket.Open;
if Trim(FProxyInfo.Username) <> '' then
Handclasp(FClientSocket.Socket.SocketHandle, atUserPass)
else
Handclasp(FClientSocket.Socket.SocketHandle, atNone);
// 连接到目标地址
ConnectByProxy(FClientSocket.Socket.SocketHandle, ServerIP, Port);
end;
except
raise Exception.Create('无法连接到LiveUpdate服务器,请检查网络配置!');
end;
end;
{ TProjectMgr }
function TProjectCollection.Add(ProjectName, Descripton, RootDir: string): TProjectItem;
begin
Result:= TProjectItem(inherited Add);
Result.ProjectName:= ProjectName;
Result.Description:= Descripton;
Result.RootDir:= RootDir;
end;
procedure TProjectCollection.Clear;
begin
inherited Clear;
end;
constructor TProjectCollection.Create(AOwner: TPersistent; FileName: string);
begin
inherited Create(TProjectItem);
FOwner:= AOwner;
FFileName:= FileName;
LoadFromFile;
end;
procedure TProjectCollection.Delete(Index: Integer);
begin
inherited Delete(Index);
end;
destructor TProjectCollection.Destroy;
begin
SaveToFile;
Clear;
inherited Destroy;
end;
function TProjectCollection.GetItem(Index: Integer): TProjectItem;
begin
Result:= TProjectItem(inherited GetItem(Index));
end;
function TProjectCollection.IndexOf(const ProjectName: string): Integer;
var
I: Integer;
begin
Result:= -1;
for I:= 0 to Count - 1 do
if SameText(TProjectItem(Items[I]).ProjectName, ProjectName) then
begin
Result:= I;
Break;
end;
end;
procedure TProjectCollection.LoadFromFile;
var
I, C: Integer;
Stream: TStream;
szProjectName, szRootDir, szDescription: string;
begin
Clear;
if not FileExists(FFileName) then Exit;
Stream:= TFileStream.Create(FFileName, fmOpenRead);
try
C:= StreamReadInteger(Stream);
for I:= 0 to C - 1 do
begin
szProjectName:= StreamReadString(Stream);
szRootDir:= StreamReadString(Stream);
szDescription:= StreamReadString(Stream);;
Add(szProjectName, szDescription, szRootDir);
end;
finally
Stream.Free;
end;
end;
procedure TProjectCollection.SaveToFile;
var
I: Integer;
Stream: TFileStream;
begin
Stream:= TFileStream.Create(FFileName, fmCreate);
try
StreamWriteInteger(Stream, Count);
for I:= 0 to Count - 1 do
with Items[I] do
begin
StreamWriteString(Stream, ProjectName);
StreamWriteString(Stream, RootDir);
StreamWriteString(Stream, Description);
end;
finally
Stream.Free;
end;
end;
{ TProjectItem }
constructor TProjectItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FResTree:= TResTree.Create;
end;
destructor TProjectItem.Destroy;
begin
FResTree.Free;
inherited Destroy;
end;
function TProjectItem.GetResTreeFileName: string;
begin
Result:= ExtractFilePath(ParamStr(0)) + 'Projects\' + FProjectName + '.vf';
end;
procedure TProjectItem.LoadResTree;
begin
if FileExists(GetResTreeFileName) then
FResTree.LoadFromFile(GetResTreeFileName);
end;
procedure TProjectItem.RemoveResTree;
var
ResFileName: string;
begin
ResFileName:= GetResTreeFileName;
if FileExists(ResFileName) then
DeleteFile(ResFileName);
end;
procedure TProjectItem.SaveResTree;
var
ResFilePath, ResFileName: string;
begin
ResFileName:= GetResTreeFileName;
ResFilePath:= ExtractFilePath(ResFileName);
if not DirectoryExists(ResFilePath) then
ForceDirectories(ResFilePath);
FResTree.SaveToFile(ResFileName);
end;
procedure TDownloadFilesThread.SyncDownloadCallback(
DownloadStatus: TDownloadStatus; WorkCount: Integer);
begin
FDownloadStatus:= DownloadStatus;
FWorkCount:= WorkCount;
{
if Application.Handle = 0 then
DoDownloadCallback
else
Synchronize(Self, DoDownloadCallback);
}
DoDownloadCallback;
end;
end.
|
unit FreeOTFEfrmVolProperties;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
OTFEFreeOTFEBase_U,
OTFEFreeOTFE_U,
SDUForms;
type
TfrmFreeOTFEVolProperties = class(TSDUForm)
pbOK: TButton;
Label15: TLabel;
Label22: TLabel;
Label5: TLabel;
Label7: TLabel;
Label6: TLabel;
edDrive: TEdit;
edDeviceName: TEdit;
edVolumeFile: TEdit;
edReadOnly: TEdit;
edMainCypher: TEdit;
pbInfoMainCypher: TButton;
pbInfoIVHash: TButton;
lblIVHash: TLabel;
edIVHash: TEdit;
Label2: TLabel;
edSectorIVGenMethod: TEdit;
pbInfoIVCypher: TButton;
edIVCypher: TEdit;
lblIVCypher: TLabel;
procedure FormShow(Sender: TObject);
procedure pbInfoIVHashClick(Sender: TObject);
procedure pbInfoMainCypherClick(Sender: TObject);
procedure pbInfoIVCypherClick(Sender: TObject);
private
{ Private declarations }
public
DriveLetter: char;
OTFEFreeOTFE: TOTFEFreeOTFE;
end;
implementation
{$R *.DFM}
uses
ActiveX, // Required for IsEqualGUID
ComObj, // Required for StringToGUID
SDUi18n,
SDUDialogs,
SDUGeneral,
OTFEFreeOTFE_DriverAPI; // Required for NULL_GUID
procedure TfrmFreeOTFEVolProperties.FormShow(Sender: TObject);
var
volumeInfo: TOTFEFreeOTFEVolumeInfo;
hashDetails: TFreeOTFEHash;
cypherDetails: TFreeOTFECypher_v3;
begin
edDrive.text := DriveLetter+':';
edVolumeFile.text := RS_UNKNOWN;
edReadOnly.text := RS_UNKNOWN;
edIVHash.text := RS_UNKNOWN;
edIVCypher.text := RS_UNKNOWN;
edMainCypher.text := RS_UNKNOWN;
edDeviceName.text := RS_UNKNOWN;
edSectorIVGenMethod.Text := RS_UNKNOWN;
lblIVHash.Enabled := FALSE;
edIVHash.Enabled := FALSE;
pbInfoIVHash.Enabled := FALSE;
lblIVCypher.Enabled := FALSE;
edIVCypher.Enabled := FALSE;
pbInfoIVCypher.Enabled := FALSE;
if OTFEFreeOTFE.GetVolumeInfo(DriveLetter, volumeInfo) then
begin
edVolumeFile.text := volumeInfo.Filename;
if volumeInfo.ReadOnly then
begin
edReadOnly.text := _('Readonly');
end
else
begin
edReadOnly.text := _('Read/write');
end;
edSectorIVGenMethod.Text := FreeOTFESectorIVGenMethodTitle[volumeInfo.SectorIVGenMethod];
if (
(volumeInfo.IVHashDevice = '') and
IsEqualGUID(volumeInfo.IVHashGUID, StringToGUID(NULL_GUID))
) then
begin
edIVHash.Text := _('n/a');
end
else
begin
lblIVHash.Enabled := TRUE;
edIVHash.Enabled := TRUE;
pbInfoIVHash.Enabled := TRUE;
if OTFEFreeOTFE.GetSpecificHashDetails(
volumeInfo.IVHashDevice,
volumeInfo.IVHashGUID,
hashDetails
) then
begin
edIVHash.Text := OTFEFreeOTFE.GetHashDisplayTitle(hashDetails);
end;
end;
if (
(volumeInfo.IVCypherDevice = '') and
IsEqualGUID(volumeInfo.IVCypherGUID, StringToGUID(NULL_GUID))
) then
begin
edIVCypher.Text := _('n/a');
end
else
begin
lblIVCypher.Enabled := TRUE;
edIVCypher.Enabled := TRUE;
pbInfoIVCypher.Enabled := TRUE;
if OTFEFreeOTFE.GetSpecificCypherDetails(
volumeInfo.IVCypherDevice,
volumeInfo.IVCypherGUID,
cypherDetails
) then
begin
edIVCypher.Text := OTFEFreeOTFE.GetCypherDisplayTitle(cypherDetails);
end;
end;
if OTFEFreeOTFE.GetSpecificCypherDetails(
volumeInfo.MainCypherDevice,
volumeInfo.MainCypherGUID,
cypherDetails
) then
begin
edMainCypher.Text := OTFEFreeOTFE.GetCypherDisplayTitle(cypherDetails);
end;
edDeviceName.text := volumeInfo.DeviceName;
end
else
begin
SDUMessageDlg(
SDUParamSubstitute(_('Unable to get drive properties for drive %1:'), [DriveLetter]),
mtError
);
end;
end;
procedure TfrmFreeOTFEVolProperties.pbInfoIVHashClick(Sender: TObject);
var
volumeInfo: TOTFEFreeOTFEVolumeInfo;
begin
if OTFEFreeOTFE.GetVolumeInfo(DriveLetter, volumeInfo) then
begin
OTFEFreeOTFE.ShowHashDetailsDlg(volumeInfo.IVHashDevice, volumeInfo.IVHashGUID);
end;
end;
procedure TfrmFreeOTFEVolProperties.pbInfoMainCypherClick(Sender: TObject);
var
volumeInfo: TOTFEFreeOTFEVolumeInfo;
begin
if OTFEFreeOTFE.GetVolumeInfo(DriveLetter, volumeInfo) then
begin
OTFEFreeOTFE.ShowCypherDetailsDlg(volumeInfo.MainCypherDevice, volumeInfo.MainCypherGUID);
end;
end;
procedure TfrmFreeOTFEVolProperties.pbInfoIVCypherClick(Sender: TObject);
var
volumeInfo: TOTFEFreeOTFEVolumeInfo;
begin
if OTFEFreeOTFE.GetVolumeInfo(DriveLetter, volumeInfo) then
begin
OTFEFreeOTFE.ShowCypherDetailsDlg(volumeInfo.IVCypherDevice, volumeInfo.IVCypherGUID);
end;
end;
END.
|
unit EF.Mapping.Base;
interface
uses
System.TypInfo, RTTI, SysUtils, System.Classes,System.Contnrs,
EF.Mapping.Atributes, EF.Core.Types,REST.JSON, JsonDataObjects;
type
//TCollate = Class;
TEntityBase = class(TPersistent)
private
FId: TInteger;
procedure ValidateFieldNotNull(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
procedure ValidateRange(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
procedure ValidateLengthMin(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
protected
// FDataCadastro: TEntityDatetime;
public
constructor Create; overload; virtual;
destructor Destroy;override;
procedure Validate; virtual;
function ToJson(UsingRestJson:boolean = false): string;
procedure FromJson{<T: class, constructor>}(const AJson: String);
published
[Column('ID', 'integer', false, true, true)]
property Id: TInteger read FId write FId;
// property DataCadastro: TEntityDatetime read FDataCadastro write FDataCadastro;
end;
implementation
{ TEntityBase }
uses EF.Mapping.AutoMapper;
constructor TEntityBase.Create;
begin
TAutoMapper.ToMapping(self, true, false);
inherited Create;
end;
destructor TEntityBase.Destroy;
begin
inherited;
FreeAndNilProperties(self);
end;
function TEntityBase.ToJson(UsingRestJson:boolean = false): string;
var
json: TJsonObject;
ListField, ListValues: TStringList;
I: integer;
begin
if UsingRestJson then
result:= TJson.ObjectToJsonString(self)
else
begin
try
json := TJsonObject.Create;
ListField := TAutoMapper.GetFieldsList(self, false, true);
ListValues := TAutoMapper.GetValuesFieldsList(self, true);
for I := 0 to ListField.Count - 1 do
begin
json.S[ListField.Strings[I]] := ListValues.Strings[I];
end;
result := json.ToJson;
finally
ListField.Free;
ListValues.Free;
json.Free;
end;
end;
end;
procedure TEntityBase.FromJson{<T>}(const AJson: String);
var
Contexto: TRttiContext;
TipoRtti: TRttiType;
PropRtti: TRttiProperty;
joJSON: TJsonObject;
begin
//self := TJson.JsonToObject<T>( AJson ) as TEntityBase;
Contexto := TRttiContext.Create;
try
joJSON := TJsonObject.Create;
joJSON.FromJson(AJson);
TipoRtti := Contexto.GetType(self.ClassType);
for PropRtti in TipoRtti.GetProperties do
begin
if PropRtti.IsWritable then
begin
if (joJSON.Contains(upperCase(PropRtti.Name))) then
begin
if (PropRtti.PropertyType.ToString = 'TDate') then
begin
if (joJSON.S[upperCase(PropRtti.Name)] <> '') then
TAutoMapper.SetAtribute( self, PropRtti.Name, joJSON.S[upperCase(PropRtti.Name)], false )
end
else
TAutoMapper.SetAtribute( self, PropRtti.Name, joJSON.S[upperCase(PropRtti.Name)], false );
end;
end;
end;
finally
Contexto.Free;
FreeAndNil(joJSON);
end;
end;
procedure TEntityBase.ValidateLengthMin(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
var
mensagem: string;
begin
mensagem := 'Valor "' + PropRtti.Name + '" é inválido para o mínimo requerido !';
if not (atrbRtti as Validator).IsValid(TAutoMapper.GetValueProperty(self, PropRtti.Name), mensagem) then
begin
abort;
end;
end;
procedure TEntityBase.ValidateRange(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
var
mensagem: string;
begin
mensagem := 'Valor "' + PropRtti.Name + '" inválido para o intervalor!';
if not (atrbRtti as Validator).IsValid(TAutoMapper.GetValueProperty(self, PropRtti.Name).ToInteger, mensagem) then
begin
abort;
end;
end;
procedure TEntityBase.ValidateFieldNotNull(PropRtti: TRttiProperty; atrbRtti: TCustomAttribute);
var
mensagem: string;
begin
mensagem := 'Campo "' + PropRtti.Name + '" Requerido!';
if not (atrbRtti as Validator).IsValid(TAutoMapper.GetValueProperty(self, PropRtti.Name), mensagem) then
begin
abort;
end;
end;
procedure TEntityBase.Validate;
var
ctx: TRttiContext;
typeRtti: TRttiType;
PropRtti: TRttiProperty;
atrbRtti: TCustomAttribute;
begin
try
ctx := TRttiContext.Create;
typeRtti := ctx.GetType(self.ClassType);
for PropRtti in typeRtti.GetProperties do
begin
for atrbRtti in PropRtti.GetAttributes do
begin
if atrbRtti is NotNull then
begin
ValidateFieldNotNull(PropRtti, atrbRtti);
end
else if atrbRtti is LengthMin then
begin
ValidateLengthMin(PropRtti, atrbRtti);
end
else if atrbRtti is Range then
begin
ValidateRange(PropRtti, atrbRtti);
end;
end;
end;
finally
ctx.Free;
end;
end;
end.
|
(*
Copyright 2016 Michael Justin
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 djLogAPI;
interface
uses
SysUtils;
type
ILogger = interface ['{58764670-2414-477F-8CE6-02A418D4CF09}']
procedure Debug(const AMsg: string); overload;
procedure Debug(const AFormat: string; const AArgs: array of const); overload;
procedure Debug(const AMsg: string; const AException: Exception); overload;
procedure Error(const AMsg: string); overload;
procedure Error(const AFormat: string; const AArgs: array of const); overload;
procedure Error(const AMsg: string; const AException: Exception); overload;
procedure Info(const AMsg: string); overload;
procedure Info(const AFormat: string; const AArgs: array of const); overload;
procedure Info(const AMsg: string; const AException: Exception); overload;
procedure Warn(const AMsg: string); overload;
procedure Warn(const AFormat: string; const AArgs: array of const); overload;
procedure Warn(const AMsg: string; const AException: Exception); overload;
procedure Trace(const AMsg: string); overload;
procedure Trace(const AFormat: string; const AArgs: array of const); overload;
procedure Trace(const AMsg: string; const AException: Exception); overload;
function IsDebugEnabled: Boolean;
function IsErrorEnabled: Boolean;
function IsInfoEnabled: Boolean;
function IsWarnEnabled: Boolean;
function IsTraceEnabled: Boolean;
function Name: string;
end;
ILoggerFactory = interface ['{B5EC64AC-85D6-40F1-88CC-EC045D9ED653}']
function GetLogger(const AName: string): ILogger;
end;
implementation
end.
|
{------------------------------------
功能说明:注册菜单接口
创建日期:2010/04/23
作者:wzw
版权:wzw
-------------------------------------}
unit MenuRegIntf;
{$weakpackageunit on}
interface
type
IMenuReg = interface
['{89934683-EC0C-4DE8-ABA8-057C9DF63599}']
procedure RegMenu(const Key, Path: WideString);
procedure UnRegMenu(const Key: WideString);
procedure RegToolItem(const Key, aCaption, aHint: WideString);
procedure UnRegToolItem(const Key: WideString);
end;
implementation
end.
|
Unit AdvPointers;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
MemorySupport, StringSupport,
AdvItems, AdvIterators;
Type
TPointerItem = Pointer;
TPointerItems = Array[0..(MaxInt Div SizeOf(TPointerItem)) - 1] Of TPointerItem;
PPointerItems = ^TPointerItems;
TAdvPointerList = Class(TAdvItems)
Private
FPointerArray : PPointerItems;
Function GetPointerByIndex(iIndex: Integer): TPointerItem;
Procedure SetPointerByIndex(iIndex: Integer; Const pValue: TPointerItem);
Protected
Function GetItem(iIndex : Integer) : Pointer; Override;
Procedure SetItem(iIndex : Integer; pValue: Pointer); Override;
Procedure AssignItem(oItems : TAdvItems; iIndex : Integer); Override;
Procedure InternalResize(iValue : Integer); Override;
Procedure InternalCopy(iSource, iTarget, iCount : Integer); Override;
Procedure InternalEmpty(iIndex, iLength : Integer); Override;
Procedure InternalInsert(iIndex : Integer); Overload; Override;
Procedure InternalExchange(iA, iB : Integer); Override;
Function CapacityLimit : Integer; Override;
Public
Function Iterator : TAdvIterator; Override;
Function IndexByValue(pValue : TPointerItem) : Integer;
Function ExistsByValue(pValue : TPointerItem) : Boolean;
Function Add(pValue : TPointerItem) : Integer;
Procedure Insert(iIndex : Integer; pValue : TPointerItem);
Procedure DeleteByValue(pValue : TPointerItem);
Function RemoveFirst : TPointerItem;
Function RemoveLast : TPointerItem;
Property PointerByIndex[iIndex : Integer] : Pointer Read GetPointerByIndex Write SetPointerByIndex; Default;
End;
TAdvPointerListIterator = Class(TAdvPointerIterator)
Private
FPointerArray : TAdvPointerList;
FIndex : Integer;
Procedure SetPointers(Const Value: TAdvPointerList);
Public
Constructor Create; Override;
Destructor Destroy; Override;
Procedure First; Override;
Procedure Last; Override;
Procedure Next; Override;
Procedure Back; Override;
Function More : Boolean; Override;
Function Current : Pointer; Override;
Property Pointers : TAdvPointerList Read FPointerArray Write SetPointers;
End;
TAdvPointers = TAdvPointerList;
Implementation
Procedure TAdvPointerList.AssignItem(oItems : TAdvItems; iIndex : Integer);
Begin
FPointerArray^[iIndex] := TAdvPointerList(oItems).FPointerArray^[iIndex];
End;
Procedure TAdvPointerList.InternalResize(iValue : Integer);
Begin
Inherited;
MemoryResize(FPointerArray, Capacity * SizeOf(TPointerItem), iValue * SizeOf(TPointerItem));
End;
Procedure TAdvPointerList.InternalEmpty(iIndex, iLength: Integer);
Begin
Inherited;
MemoryZero(Pointer(NativeUInt(FPointerArray) + (iIndex * SizeOf(TPointerItem))), (iLength * SizeOf(TPointerItem)));
End;
Procedure TAdvPointerList.InternalCopy(iSource, iTarget, iCount: Integer);
Begin
Inherited;
MemoryMove(@FPointerArray^[iSource], @FPointerArray^[iTarget], iCount * SizeOf(TPointerItem));
End;
Function TAdvPointerList.IndexByValue(pValue : TPointerItem): Integer;
Begin
If Not Find(pValue, Result) Then
Result := -1;
End;
Function TAdvPointerList.ExistsByValue(pValue : TPointerItem): Boolean;
Begin
Result := ExistsByIndex(IndexByValue(pValue));
End;
Function TAdvPointerList.Add(pValue : TPointerItem): Integer;
Begin
Result := -1;
If Not IsAllowDuplicates And Find(pValue, Result) Then
Begin
If IsPreventDuplicates Then
RaiseError('Add', StringFormat('Item already exists in list ($%x)', [Integer(pValue)]));
End
Else
Begin
If Not IsSorted Then
Result := Count
Else If (Result < 0) Then
Find(pValue, Result);
Insert(Result, pValue);
End;
End;
Procedure TAdvPointerList.Insert(iIndex : Integer; pValue: TPointerItem);
Begin
InternalInsert(iIndex);
FPointerArray^[iIndex] := pValue;
End;
Procedure TAdvPointerList.InternalInsert(iIndex : Integer);
Begin
Inherited;
FPointerArray^[iIndex] := Nil;
End;
Procedure TAdvPointerList.DeleteByValue(pValue : TPointerItem);
Var
iIndex : Integer;
Begin
If Not Find(pValue, iIndex) Then
RaiseError('DeleteByValue', 'Pointer not found in list');
DeleteByIndex(iIndex);
End;
Function TAdvPointerList.RemoveFirst : TPointerItem;
Begin
If Count <= 0 Then
Result := Nil
Else
Begin
Result := FPointerArray^[0];
DeleteByIndex(0);
End;
End;
Function TAdvPointerList.RemoveLast : TPointerItem;
Begin
If Count <= 0 Then
Result := Nil
Else
Begin
Result := FPointerArray^[Count - 1];
DeleteByIndex(Count - 1);
End;
End;
Procedure TAdvPointerList.InternalExchange(iA, iB : Integer);
Var
iTemp : Integer;
ptrA : Pointer;
ptrB : Pointer;
Begin
ptrA := @FPointerArray^[iA];
ptrB := @FPointerArray^[iB];
iTemp := Integer(ptrA^);
Integer(ptrA^) := Integer(ptrB^);
Integer(ptrB^) := iTemp;
End;
Function TAdvPointerList.GetItem(iIndex: Integer): Pointer;
Begin
Assert(ValidateIndex('GetItem', iIndex));
Result := FPointerArray^[iIndex];
End;
Procedure TAdvPointerList.SetItem(iIndex : Integer; pValue: Pointer);
Begin
Assert(ValidateIndex('SetItem', iIndex));
FPointerArray^[iIndex] := pValue;
End;
Function TAdvPointerList.GetPointerByIndex(iIndex : Integer): TPointerItem;
Begin
Assert(ValidateIndex('GetPointerByIndex', iIndex));
Result := FPointerArray^[iIndex];
End;
Procedure TAdvPointerList.SetPointerByIndex(iIndex : Integer; Const pValue : TPointerItem);
Begin
Assert(ValidateIndex('SetPointerByIndex', iIndex));
FPointerArray^[iIndex] := pValue;
End;
Function TAdvPointerList.CapacityLimit : Integer;
Begin
Result := High(TPointerItems);
End;
Function TAdvPointerList.Iterator : TAdvIterator;
Begin
Result := TAdvPointerListIterator.Create;
TAdvPointerListIterator(Result).Pointers := TAdvPointerList(Self.Link);
End;
Constructor TAdvPointerListIterator.Create;
Begin
Inherited;
FPointerArray := Nil;
End;
Destructor TAdvPointerListIterator.Destroy;
Begin
FPointerArray.Free;
Inherited;
End;
Procedure TAdvPointerListIterator.First;
Begin
Inherited;
FIndex := 0;
End;
Procedure TAdvPointerListIterator.Last;
Begin
Inherited;
FIndex := FPointerArray.Count - 1;
End;
Procedure TAdvPointerListIterator.Next;
Begin
Inherited;
Inc(FIndex);
End;
Procedure TAdvPointerListIterator.Back;
Begin
Inherited;
Dec(FIndex);
End;
Function TAdvPointerListIterator.Current : Pointer;
Begin
Result := FPointerArray[FIndex];
End;
Function TAdvPointerListIterator.More : Boolean;
Begin
Result := FPointerArray.ExistsByIndex(FIndex);
End;
Procedure TAdvPointerListIterator.SetPointers(Const Value: TAdvPointerList);
Begin
FPointerArray.Free;
FPointerArray := Value;
End;
End. // AdvPointers //
|
{$A+,B-,D-,E-,F-,G+,I-,L-,N-,O-,R-,S-,V-,X+}
{$M 16384,0,0}
PROGRAM COM_TO_PAS;
{
Программа для преобразования COM-файлов (или любых двоичных
файлов размером до 64K) в типизированную константу PASCAL.
Обращение: COM2PAS двоичный_файл
Создаваемый программой файл имеет имя исходного и расширение
.PAS
Автор: Блашкин И.И.
}
uses dos;
const header:string[200] = '{ -------------------------- File: -------------------------- }'#13#10#13#10+
'const _len = ;'#13#10+
'type = array [0.._len] of byte;'#13#10+
'const _code: = (';
com_file:word = 0;
file_len:word = 0;
var file_name:string[72];
fnlen:byte absolute file_name;
d_str:string[64];
n_str:string[8];
e_str:string[4];
count:word;
procedure write_byte(var b:byte;cnd:boolean);
const hexl:string[16] = '0123456789ABCDEF';
begin
write(input,'$'+hexl[((b shr 4) and 15)+1]+hexl[(b and 15)+1]);
if cnd then writeln(input,');')
else write(input,',');
end;
procedure fail;far;
begin
exitproc := nil;
if textrec(input).mode <> fmClosed then close(input);
case exitcode of
0:writeln(#13'Done.');
254:writeln('Usage: COM2PAS binary_file_name');
255:writeln(#13'User break.');
else writeln(#13'Aborted due to internal error no.',exitcode);
end;
halt(exitcode);
end;
begin
exitproc := @fail;
writeln('COM2PAS version 1.0, Copyright (C) by Blashkin I.I., 1992');
if paramcount = 1
then file_name := fexpand(paramstr(1)) + #0
else runerror(254);
asm
mov ah,48h
mov bx,4096
int 21h
jc @err
mov word ptr com_file,ax
mov ax,3D00h
mov dx,offset file_name[1]
int 21h
jc @err
mov bx,ax
mov ax,word ptr com_file
push ds
mov ds,ax
mov ah,3Fh
mov cx,0FFFFh
sub dx,dx
int 21h
pop ds
jc @err
dec ax
mov word ptr file_len,ax
mov ah,3Eh
int 21h
sub ax,ax
@err: mov word ptr exitcode,ax
end;
if exitcode <> 0 then runerror(hi(exitcode));
dec(fnlen);
fsplit(file_name,d_str,n_str,e_str);
d_str := d_str + n_str + '.PAS';
assign(input,d_str);
asm
mov ah,48h
mov bx,$FFFF
int 21h
mov ah,48h
mov word ptr textrec(input).bufsize,bx
int 21h
mov word ptr exitcode,ax
end;
textrec(input).bufptr := ptr(exitcode,0);
rewrite(input);
if inoutres <> 0 then runerror(inoutres);
writeln('Converting "',file_name,'" into "',d_str+'"');
str(file_len,d_str);
insert(n_str,header,135);
insert(n_str,header,129);
insert(n_str,header,106);
insert(n_str,header,93);
insert(d_str,header,83);
insert(n_str,header,76);
insert(n_str+e_str,header,35);
write(input,header);
exitcode := pos('(',header)-(pos('_code',header)-7-length(n_str))+1;
fillchar(file_name[1],exitcode,32);
fnlen := lo(exitcode);
insert(#13#10,file_name,1);
for count := 0 to file_len do
begin
if (count <> 0) and ((count mod 10) = 0)
then write(input,file_name);
write_byte(mem[com_file:count],count = file_len);
end;
writeln(input,#13#10#9'{ --------------------- The End --------------------- }');
end. |
{ Subroutines that manage the hash tables.
}
module string_hash_subs;
define string_hash_create;
define string_hash_ent_add;
define string_hash_ent_atpos;
define string_hash_ent_del;
define string_hash_ent_lookup;
define string_hash_delete;
define string_hash_pos_first;
define string_hash_pos_lookup;
define string_hash_pos_next;
define string_hash_mem_alloc_del;
define string_hash_mem_alloc_ndel;
define string_hash_mem_dealloc;
%include 'string2.ins.pas';
%include 'math.ins.pas';
const
int_size = sizeof(sys_int_machine_t);
{
********************************************************************************
*
* Subrotuine STRING_HASH_CREATE (HASH_H, N_BUCK, NAME_LEN, DATA_SIZE, MEM)
*
* Initialize a hash table. HASH_H is the user handle for this hash table. It
* is only valid after this call. The remaining call arguments are parameters
* that are used to configure the hash table. These can not be changed once
* the hash table has been created. A hash table remains valid until it is
* deleted with a call to STRING_HASH_DELETE. Configuration arguments are:
*
* N_BUCK - Number of buckets in hash table. This number will be rounded up
* to the nearest power of two. Actual entries are stored in the buckets.
* The particular bucket an entry is in can be computed quickly from the entry
* name using a hashing function (hence the name "hash table"). The time
* to compute the bucket number is independent of the number of buckets.
* Making this number large increases speed but also memory useage.
*
* NAME_LEN - The maximum number of characters an entry name may have in this
* hash table. This number may be from 1 to STRING_HASH_MAX_NAME_LEN_K.
*
* DATA_SIZE - The size of the user data area. The application can get a
* pointer to this area for each entry. The area will be aligned on a
* machine integer boundary, and the size will be rounded up to the nearest
* whole multiple of machine integers.
*
* FLAGS - Set of additional configuration modifier flags. Flags are:
*
* STRING_HASHCRE_MEMDIR_K - Use parent memory context directly. No
* separate memory context will be created for the hash table data
* structures.
*
* STRING_HASHCRE_NODEL_K - It is OK to allocate dynamic memory such that
* it can't be individually deallocated. This saves memory, but reduces
* flexibility.
*
* MEM - Parent memory context to use. A subordinate memory context will be
* created for this hash table, and all dynamic memory will be allocated under
* it. All memory allocated under that context will be released when the
* hash table is deleted.
}
procedure string_hash_create ( {create a hash table}
out hash_h: string_hash_handle_t; {hash table to initialize}
in n_buck: sys_int_machine_t; {number of entries in table, (power of 2)}
in name_len: sys_int_machine_t; {max allowed size of any entry name}
in data_size: sys_int_adr_t; {amount of user data for each entry}
in flags: string_hashcre_t; {additional modifier flags}
in out mem: util_mem_context_t); {parent memory context to use for this table}
val_param;
const
max_msg_parms = 2; {max parameters we can pass to a message}
var
ent: string_hash_entry_t; {just for finding adr offsets}
sz: sys_int_adr_t; {scratch memory size}
hash_p: string_hash_p_t; {pointer to hash table admin data structure}
nb: sys_int_machine_t; {actual number of buckets in hash table}
mem_p: util_mem_context_p_t; {pointer to mem context for hash table}
seed: math_rand_seed_t; {random number seed}
date: string_var80_t; {date/time string}
i: sys_int_machine_t; {loop counter}
idel: boolean; {TRUE if alloc mem to individually dealloc}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
date.max := sizeof(date.str); {init local var string}
if name_len > string_hash_max_name_len_k then begin {requested name size too big ?}
sys_msg_parm_int (msg_parm[1], name_len);
sys_msg_parm_int (msg_parm[2], string_hash_max_name_len_k);
sys_message_bomb ('string', 'hash_max_name_too_long', msg_parm, 2);
end;
nb := 1; {init to minimum number of buckets}
while nb < n_buck do begin {too small, make next power of two ?}
nb := nb * 2;
end;
idel := {alloc to allow individual dealloc ?}
not (string_hashcre_nodel_k in flags);
if string_hashcre_memdir_k in flags
then begin {use parent memory context directly}
mem_p := addr(mem);
end
else begin {create our own memory context}
util_mem_context_get ( {allocate memory context for this hash table}
mem, {parent memory context}
mem_p); {returned pointer to new subordinate context}
end
;
sz := {make size of top hash table structure}
sizeof(string_hash_t) + {raw size as declared}
((nb - 1) * sizeof(string_hash_bucket_t)); {additional buckets than declared}
util_mem_grab (sz, mem_p^, idel, hash_p); {allocate hash table admin block}
hash_h := hash_p; {pass back handle to new hash table}
with hash_p^: hash do begin {HASH is abbrev for hash table admin block}
hash.n_buckets := nb; {number of hash buckets, is 2**n}
hash.mask := hash.n_buckets - 1; {for masking in bucket number}
hash.max_name_len := name_len; {save max size for entry names}
hash.data_offset := {size of our part of each entry}
sizeof(ent) - {raw size as declared}
sizeof(ent.name.str) + {minus characters already declared}
hash.max_name_len; {plus number of characters actually used}
hash.data_offset := {number of whole machine integers needed}
(hash.data_offset + int_size - 1) div int_size;
hash.data_offset := {final size of our part of an entry}
hash.data_offset * int_size;
sz := {whole machine integers for user data}
(data_size + int_size - 1) div int_size;
hash.entry_size := {size of an entire entry}
hash.data_offset + {amount of memory for our internal part}
(sz * int_size); {amount of private user data}
hash.free_p := nil; {init to no free chain exists}
hash.mem_p := mem_p; {pointer to our memory context}
hash.flags := flags; {save configuration flags}
sys_date_time1 (date); {get date string for random number seed}
seed.str := date.str; {init random number seed}
for i := 0 to 255 do begin {once for each hash function entry}
hash.func[i] := math_rand_int32(seed); {function is table of random values}
end;
for i := 0 to hash.n_buckets-1 do begin {once for each bucket descriptor}
hash.bucket[i].first_p := nil; {init this bucket descriptor to empty}
hash.bucket[i].mid_p := nil;
hash.bucket[i].last_p := nil;
hash.bucket[i].n := 0;
hash.bucket[i].n_after := 0;
end;
end; {done with HASH abbreviation}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_DELETE (HASH_H)
*
* Delete a hash table. HASH_H is the user handle to the hash table. All
* dynamic memory allocated under this hash table will be release. HASH_H
* will be returned as invalid.
}
procedure string_hash_delete ( {delete hash table, deallocate resources}
in out hash_h: string_hash_handle_t); {hash table to delete, returned invalid}
val_param;
var
mem_p: util_mem_context_p_t; {points to memory context for this hash table}
hash_p: string_hash_p_t; {points to top data block for this hash table}
begin
hash_p := hash_h; {get pointer to hash table admin block}
if not (string_hashcre_memdir_k in hash_p^.flags) then begin {mem is ours ?}
mem_p := hash_p^.mem_p; {get pointer to memory context for this table}
util_mem_context_del (mem_p); {deallocate all memory for this hash table}
end;
hash_h := nil; {return hash table handle as invalid}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_POS_LOOKUP (HASH_H, NAME, POS, FOUND)
*
* Look up a name in a hash table. HASH_H is the user handle to the hash table.
* NAME is the name to look up. POS is returned as the user position handle to
* the entry. FOUND is set to TRUE if the entry is found. In that case, POS
* indicates the position of the entry itself. If no entry exists of name NAME,
* then FOUND is set to FALSE, and POS indicates the position where the entry
* would go. POS may then be passed to STRING_HASH_ENT_ADD to create the entry.
}
procedure string_hash_pos_lookup ( {return position handle from entry name}
in hash_h: string_hash_handle_t; {handle to hash table}
in name: univ string_var_arg_t; {name to find position for}
out pos: string_hash_pos_t; {handle to position for this name}
out found: boolean); {TRUE if entry existed}
val_param;
var
hash_p: string_hash_p_t; {pointer to this hash table}
buck: sys_int_machine_t; {bucket number accumulator}
i, j: sys_int_machine_t; {loop counters and scratch integers}
char_p: ^char; {pointer for saving name chars}
forward, backward: boolean; {search direction flags}
label
search_loop, search_forward, search_backward;
begin
hash_p := hash_h; {get pointer to hash table master block}
pos.hash_p := hash_p; {save pointer to this hash table}
with hash_p^: hash do begin {HASH is abbrev for top hash table block}
{
* The hash function resulting in the bucket number for this name will be
* computed at the same time that the name characters are copied into the
* position handle. This is because both require a loop over all the name
* characters. The name in the position handle will be zero padded to the
* next whole number of machine integers. This will allow comparing and
* copying the name by using integer operations.
}
buck := 0; {init bucket number hash accumulator}
pos.name_len := name.len; {save number of chars in entry name}
pos.namei_len := {number of whole machine integers in name}
(pos.name_len + int_size - 1) div int_size;
pos.namei[pos.namei_len] := 0; {make sure odd chars filled with zeros}
char_p := univ_ptr( {point to first destination name char}
addr(pos.namei[1]));
for i := 1 to name.len do begin {once for each character in name}
j := 255 & buck; {make hash function index value}
buck := buck + hash.func[j] + ord(name.str[i]); {update hash accumulator}
char_p^ := name.str[i]; {copy this character}
char_p := univ_ptr( {advance destination copy pointer}
sys_int_adr_t(char_p) + sizeof(char_p^));
end;
buck := buck & hash.mask; {make final bucket number for this name}
pos.bucket := buck; {save bucket number in position handle}
pos.after := true; {init to entry is at or after bucket midpoint}
found := false; {init to entry of this name not found}
{
* All fields in POS are set except the ones pointing to a particular entry.
* Start at the middle entry for this bucket and then search in either direction.
}
pos.entry_p := hash.bucket[buck].mid_p; {init current entry to middle entry}
if pos.entry_p = nil then begin {whole bucket is empty ?}
pos.prev_p := nil; {there is no previous entry}
pos.next_p := nil; {there is no successor entry}
return;
end;
{
* The middle bucket entry exists. Now determine which direction to search
* from here.
}
forward := false; {init to search direction not committed yet}
backward := false;
search_loop: {back here to test each new entry}
if pos.namei_len > pos.entry_p^.namei_len {entry is after here ?}
then goto search_forward;
if pos.namei_len < pos.entry_p^.namei_len {entry is before here ?}
then goto search_backward;
for i := 1 to pos.namei_len do begin {once for each name word}
if pos.namei[i] > pos.entry_p^.namei[i] {entry is after here ?}
then goto search_forward;
if pos.namei[i] < pos.entry_p^.namei[i] {entry is before here ?}
then goto search_backward;
end; {back and compare next name char}
{
* NAME matches the current entry. This is the entry pointed to by
* POS.ENTRY_P.
}
pos.prev_p := pos.entry_p^.prev_p; {save pointer to previous entry}
pos.next_p := pos.entry_p^.next_p; {save pointer to next entry}
found := true; {indicate that requested entry was found}
return;
{
* NAME would come after the name of the current entry.
}
search_forward:
if backward or {NAME fits between current entry and next ?}
(pos.entry_p^.next_p = nil) {hit end of chain ?}
then begin
pos.prev_p := pos.entry_p; {current entry is right before this position}
pos.next_p := pos.entry_p^.next_p; {set pointer entry after this position}
pos.entry_p := nil;
return;
end;
pos.entry_p := pos.entry_p^.next_p; {advance current entry one forward}
forward := true; {search direction is definately forward}
goto search_loop; {back and compare NAME to new entry}
{
* NAME would come before the name of the current entry.
}
search_backward:
if forward or {NAME fits between curr entry and previous ?}
(pos.entry_p^.prev_p = nil) {hit start of chain ?}
then begin
pos.prev_p := pos.entry_p^.prev_p; {set pointer to entry before this position}
pos.next_p := pos.entry_p; {current entry is right after this position}
pos.entry_p := nil;
return;
end;
pos.entry_p := pos.entry_p^.prev_p; {advance current entry one backward}
backward := true; {search direction is definately backward}
pos.after := false; {entry will be before bucket midpoint}
goto search_loop; {back and compare NAME to new entry}
end; {done with HASH abbreviation}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_ENT_LOOKUP (HASH_H, NAME, NAME_P, DATA_P)
*
* Return data about an entry in a hash table. HASH_H is the user handle to
* the hash table. NAME is the name of the entry to look up. NAME_P will
* be returned pointing to the var string name stored in the entry descriptor.
* DATA_P will be pointing to the start of the user data area in the entry.
*
* Both NAME_P and DATA_P will be returned NIL if the entry was not found.
}
procedure string_hash_ent_lookup ( {get entry data given name}
in hash_h: string_hash_handle_t; {handle to hash table}
in name: univ string_var_arg_t; {name of entry to get data for}
out name_p: univ_ptr; {pointer to var string hash table entry name}
out data_p: univ_ptr); {pointer to user data area, NIL if not found}
val_param;
var
pos: string_hash_pos_t; {position handle within hash table}
found: boolean; {TRUE if entry of name NAME found}
begin
string_hash_pos_lookup (hash_h, name, pos, found); {get position handle to entry}
if not found then begin {entry of this name doesn't exist ?}
name_p := nil;
data_p := nil;
return;
end;
name_p := addr(pos.entry_p^.name); {pass back pointer to entry name}
data_p := univ_ptr( {pass back pointer to user data area}
sys_int_adr_t(pos.entry_p) + pos.hash_p^.data_offset);
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_ENT_ADD (POS, NAME_P, DATA_P)
*
* Add an entry to a hash table. POS must have been previously set by a call
* to STRING_HASH_POS_LOOKUP. POS must not be pointing to an entry (FOUND
* must have been FALSE in call to STRING_HASH_POS_LOOKUP). NAME_P is
* returned pointing to where the entry name var string is stored, and DATA_P
* will be pointing to the start of the user data area.
}
procedure string_hash_ent_add ( {create new entry at given position}
in out pos: string_hash_pos_t; {handle to position in hash table}
out name_p: univ_ptr; {pointer to var string hash table entry name}
out data_p: univ_ptr); {pointer to hash table entry user data area}
val_param;
var
i: sys_int_machine_t; {loop counter}
n_after: sys_int_machine_t; {correct N_AFTER value in bucket}
begin
with
pos.hash_p^: hash, {HASH is hash table admin block}
pos.hash_p^.bucket[pos.bucket]: buck {BUCK is descriptor for this bucket}
do begin
if hash.free_p = nil
then begin {there are no free entries to re-use}
util_mem_grab ( {allocate memory for new entry}
hash.entry_size, hash.mem_p^, false, pos.entry_p);
end
else begin {re-use an entry from the free chain}
pos.entry_p := hash.free_p; {get pointer to entry block}
hash.free_p := hash.free_p^.next_p; {unlink this entry from free chain}
end
; {POS.ENTRY_P is pointing to new entry block}
with pos.entry_p^: ent do begin {ENT is entry descriptor}
{
* The data block for the new entry is pointed to by POS.ENTRY_P. Abbreviations
* in effect are:
*
* HASH - Hash table admin data structure.
* BUCK - Bucket descriptor for bucket new entry is in.
* ENT - Data structure for new entry.
*
* Link new entry into chain for this bucket.
}
ent.prev_p := pos.prev_p; {point new entry to its neighbors}
ent.next_p := pos.next_p;
if pos.prev_p = nil
then begin {new entry is at start of chain}
buck.first_p := pos.entry_p;
end
else begin {new entry is not at start of chain}
pos.prev_p^.next_p := pos.entry_p;
end
;
if pos.next_p = nil
then begin {new entry is at end of chain}
buck.last_p := pos.entry_p;
end
else begin {new entry is not at end of chain}
pos.next_p^.prev_p := pos.entry_p;
end
;
{
* Copy name into entry.
}
ent.namei_len := pos.namei_len;
ent.name.len := pos.name_len;
ent.name.max := hash.max_name_len;
for i := 1 to pos.namei_len do begin {copy the characters using whole words}
ent.namei[i] := pos.namei[i];
end;
{
* All done with entry. Now update bucket data.
}
buck.n := buck.n + 1; {one more entry in this bucket}
if pos.after then begin {new entry was at or after midpoint ?}
buck.n_after := buck.n_after + 1; {one more entry at or after midpoint}
end;
n_after := buck.n - (buck.n div 2); {desired N_AFTER value in bucket}
if buck.n <= 2
then begin {few enough entries, set midpoint explicitly}
buck.mid_p := buck.last_p;
buck.n_after := n_after;
end
else begin {midpoint may need adjustment}
while buck.n_after <> n_after do begin {need to adjust midpoint ?}
if buck.n_after > n_after
then begin {move midpoint forward}
buck.mid_p := buck.mid_p^.next_p;
buck.n_after := buck.n_after - 1; {one less entry after midpoint}
end
else begin {move midpoint backward}
buck.mid_p := buck.mid_p^.prev_p;
buck.n_after := buck.n_after + 1; {one more entry after midpoint}
end
;
end; {back and check for midpoint adjust needed}
end;
; {bucket midpoint is all set}
name_p := addr(pos.entry_p^.name); {pass back pointer to entry name}
data_p := univ_ptr( {pass back pointer to user data area}
sys_int_adr_t(pos.entry_p) + hash.data_offset);
end; {done with ENT abbreviation}
end; {done with HASH and BUCK abbreviations}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_ENT_ATPOS (POS, NAME_P, DATA_P)
*
* Get data about the hash table entry indicated by the position handle POS.
* NAME_P will be returned pointing to the var string entry name that is
* stored as part of the entry. DATA_P will point to the start of the user
* data area for the entry.
}
procedure string_hash_ent_atpos ( {get entry data from position handle}
in pos: string_hash_pos_t; {position handle, must be at an entry}
out name_p: univ_ptr; {pointer to var string hash table entry name}
out data_p: univ_ptr); {pointer to hash table entry user data area}
val_param;
begin
name_p := addr(pos.entry_p^.name); {pass back pointer to entry name}
data_p := univ_ptr( {pass back pointer to user data area}
sys_int_adr_t(pos.entry_p) + pos.hash_p^.data_offset);
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_ENT_DEL (POS)
*
* Delete the hash table entry indicated by the position handle POS.
}
procedure string_hash_ent_del ( {delete hash table entry at given position}
in out pos: string_hash_pos_t); {handle to entry position in hash table}
val_param;
var
n_after: sys_int_machine_t; {correct N_AFTER value in bucket}
begin
with
pos.hash_p^: hash, {HASH is hash table admin block}
pos.entry_p^: ent, {ENT is entry descriptor}
pos.hash_p^.bucket[pos.bucket]: buck {BUCK is bucket that entry is in}
do begin
if ent.prev_p = nil
then begin {entry is at start of chain}
buck.first_p := ent.next_p;
end
else begin {entry is not at start of chain}
ent.prev_p^.next_p := ent.next_p;
end
;
if ent.next_p = nil
then begin {entry is at end of chain}
buck.last_p := ent.prev_p;
end
else begin {entry is not at end of chain}
ent.next_p^.prev_p := ent.prev_p;
end
; {entry is now unlinked from chain}
if buck.mid_p = addr(ent) then begin {entry was at midpoint ?}
buck.mid_p := ent.next_p; {update midpoint pointer to a real entry}
end;
buck.n := buck.n - 1; {one less entry in this bucket}
if pos.after then begin {entry was at or after midpoint ?}
buck.n_after := buck.n_after - 1;
end;
n_after := buck.n - (buck.n div 2); {desired N_AFTER value in bucket}
if buck.n <= 2
then begin {few enough entries, set midpoint explicitly}
buck.mid_p := buck.last_p;
buck.n_after := n_after;
end
else begin {midpoint may need adjustment}
while buck.n_after <> n_after do begin {need to adjust midpoint ?}
if buck.n_after > n_after
then begin {move midpoint forward}
buck.mid_p := buck.mid_p^.next_p;
buck.n_after := buck.n_after - 1; {one less entry after midpoint}
end
else begin {move midpoint backward}
buck.mid_p := buck.mid_p^.prev_p;
buck.n_after := buck.n_after + 1; {one more entry after midpoint}
end
;
end; {back and check for midpoint adjust needed}
end;
; {bucket midpoint is all set}
ent.next_p := hash.free_p; {link entry to free chain}
hash.free_p := addr(ent);
end; {done with HASH, ENT, and BUCK abbreviations}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_POS_FIRST (HASH_H, POS, FOUND)
*
* Return a position handle to the first entry in the hash table. Entries
* are not in any particular order that is relevant to the user, and the
* "first" entry is only meaningful as a start for traversing all the entries.
}
procedure string_hash_pos_first ( {return position handle to first entry}
in hash_h: string_hash_handle_t; {handle to hash table}
out pos: string_hash_pos_t; {handle to position for this name}
out found: boolean); {TRUE if entry existed}
val_param;
begin
pos.hash_p := hash_h; {save pointer to hash table admin block}
pos.bucket := 0; {init current bucket}
pos.entry_p := pos.hash_p^.bucket[0].first_p; {init current entry}
if pos.entry_p = nil then begin {first bucket is empty}
string_hash_pos_next (pos, found); {advance to first entry, wherever it is}
return;
end;
found := true; {first entry definately existed}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_POS_NEXT (POS, FOUND)
*
* Advance to the next position following the current entry in the hash table.
* The entry order should be considered arbitrary from the user's point of
* view. The only guarantee is that it each entry will be returned exactly once
* if POS is first initialized with STRING_HASH_POS_FIRST, then advanced to the
* end with this subroutine. FOUND is set to false as a result of trying to
* advance forward from the last entry.
}
procedure string_hash_pos_next ( {advance position to next entry in hash table}
in out pos: string_hash_pos_t; {handle to position for this name}
out found: boolean); {TRUE if entry existed}
val_param;
begin
if pos.entry_p <> nil then begin {we are at a current entry ?}
pos.entry_p := pos.entry_p^.next_p; {advance to following entry}
end;
while pos.entry_p = nil do begin {loop back here for each new bucket}
pos.bucket := pos.bucket + 1; {advance to next bucket in list}
if pos.bucket >= pos.hash_p^.n_buckets then begin {past last bucket ?}
found := false;
return;
end;
pos.entry_p := pos.hash_p^.bucket[pos.bucket].first_p; {pnt to first bucket ent}
end; {back and make sure there is an entry here}
found := true; {yes, we found an entry}
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_MEM_ALLOC_DEL (HASH_H, SIZE, P)
*
* Allocate dynamic memory from the same context as the hash table indicated
* by the handle HASH_H. It WILL be possible to deallocate this block of
* memory individually with STRING_HASH_MEM_DEALLOC. SIZE is the amount of
* memory to allocate. P is returned pointing to the start of the new memory
}
procedure string_hash_mem_alloc_del ( {allocate mem from hash context, can dealloc}
in hash_h: string_hash_handle_t; {handle to hash table}
in size: sys_int_adr_t; {amount of memory to allocate}
out p: univ_ptr); {pointer to start of new mem}
val_param;
var
hash_p: string_hash_p_t; {points to hash table admin block}
begin
hash_p := hash_h;
util_mem_grab (size, hash_p^.mem_p^, true, p);
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_MEM_ALLOC_NDEL (HASH_H, SIZE, P)
*
* Allocate dynamic memory from the same context as the hash table indicated
* by the handle HASH_H. It will NOT be possible to deallocate this block of
* memory individually with STRING_HASH_MEM_DEALLOC. SIZE is the amount of
* memory to allocate. P is returned pointing to the start of the new memory
}
procedure string_hash_mem_alloc_ndel ( {allocate mem from hash context, no dealloc}
in hash_h: string_hash_handle_t; {handle to hash table}
in size: sys_int_adr_t; {amount of memory to allocate}
out p: univ_ptr); {pointer to start of new mem}
val_param;
var
hash_p: string_hash_p_t; {points to hash table admin block}
begin
hash_p := hash_h;
util_mem_grab (size, hash_p^.mem_p^, false, p);
end;
{
**************************************************************************
*
* Subroutine STRING_HASH_MEM_DEALLOC (HASH_H, P)
*
* Deallocate memory allocated with STRING_HASH_MEM_ALLOC_DEL.
}
procedure string_hash_mem_dealloc ( {deallocate mem allocated under hash context}
in hash_h: string_hash_handle_t; {handle to hash table}
in out p: univ_ptr); {pointer to start of mem, returned NIL}
val_param;
var
hash_p: string_hash_p_t; {points to hash table admin block}
begin
hash_p := hash_h;
util_mem_ungrab (p, hash_p^.mem_p^);
end;
|
unit Panelmes;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, Timerpnl;
type
TPanelMessage = class(TTimerPanel)
private
{ Private declarations }
fDisplayString: String;
protected
{ Protected declarations }
procedure DisplayString(Sender: TObject); virtual;
procedure SetDisplayString(Value: String); virtual;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
property Display: String read fDisplayString write SetDisplayString;
end;
implementation
procedure TPanelMessage.DisplayString(Sender: TObject);
var
TempString: string;
begin
if Enabled then
begin
if length(fDisplayString) > 0 then
begin
TempString:=Copy(fDisplayString,2,Length(fDisplayString))+fDisplayString[1];
fDisplayString:=TempString;
Caption:=TempString;
end
else
begin
Caption := '';
end;
end;
end;
procedure TPanelMessage.SetDisplayString(Value: String);
begin
fDisplayString := Value;
end;
constructor TPanelMessage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fDisplayString:=Name;
ClockDriver.OnTimer := DisplayString;
end;
end.
|
unit VarMapping;
interface
uses
Classes, Types, SysUtils, LineMapping;
type
TVarMapping = class(TLineMapping)
private
FElementName: string;
FTypeName: string;
protected
function GetText(): string; override;
public
constructor Create(); reintroduce;
procedure ReadFromLine(ALine: string); override;
property ElementName: string read FElementName write FElementName;
property TypeName: string read FTypeName write FTypeName;
end;
implementation
uses
StrUtils;
{ TVarMapping }
constructor TVarMapping.Create;
begin
inherited;
FIsPossibleBreakPoint := False;
end;
function TVarMapping.GetText: string;
begin
Result := inherited + '#' + ElementName + ',' + TypeName;
end;
procedure TVarMapping.ReadFromLine(ALine: string);
var
LLines: TStringDynArray;
LElements: TStringDynArray;
begin
LLines := SplitString(ALine, '#');
if Length(LLines) = 2 then
begin
inherited ReadFromLine(LLines[0]);
LElements := SplitString(LLines[1], ',');
FElementName := LElements[0];
FTypeName := LElements[1];
end
else
begin
raise Exception.Create('Expected 2 LineElements in TVarMapping but found ' + IntToStr(Length(LLines)));
end;
end;
end.
|
{********************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 22/05/2010 10:39:00 }
{ Generated from: C:\REP\WMS\Merge Service\Source\MergeServiceParams.xml }
{ Settings stored in: C:\REP\WMS\Merge Service\Source\MergeServiceParams.xdb }
{ }
{********************************************************************************}
unit MergeServiceParams;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLREPType = interface;
IXMLWMSMergeServiceType = interface;
IXMLLayersType = interface;
IXMLLayerType = interface;
IXMLSourcesType = interface;
IXMLSourceType = interface;
{ IXMLREPType }
IXMLREPType = interface(IXMLNode)
['{63445E9A-46AC-4EFA-ABFC-05E52001375D}']
{ Property Accessors }
function Get_WMSMergeService: IXMLWMSMergeServiceType;
{ Methods & Properties }
property WMSMergeService: IXMLWMSMergeServiceType read Get_WMSMergeService;
end;
{ IXMLWMSMergeServiceType }
IXMLWMSMergeServiceType = interface(IXMLNode)
['{2D8454BC-E135-4FAD-B192-F0B5A5DC27E0}']
{ Property Accessors }
function Get_Layers: IXMLLayersType;
{ Methods & Properties }
property Layers: IXMLLayersType read Get_Layers;
end;
{ IXMLLayersType }
IXMLLayersType = interface(IXMLNodeCollection)
['{FE2B3F6E-1E9E-4295-BACE-42649E4850A4}']
{ Property Accessors }
function Get_Layer(Index: Integer): IXMLLayerType;
{ Methods & Properties }
function Add: IXMLLayerType;
function Insert(const Index: Integer): IXMLLayerType;
property Layer[Index: Integer]: IXMLLayerType read Get_Layer; default;
end;
{ IXMLLayerType }
IXMLLayerType = interface(IXMLNode)
['{58DEB3DD-0A12-4EB4-B227-2D1E4FA75AE2}']
{ Property Accessors }
function Get_Name: WideString;
function Get_Title: WideString;
function Get_SRS: WideString;
function Get_Abstract: WideString;
function Get_Sources: IXMLSourcesType;
procedure Set_Name(Value: WideString);
procedure Set_Title(Value: WideString);
procedure Set_SRS(Value: WideString);
procedure Set_Abstract(Value: WideString);
{ Methods & Properties }
property Name: WideString read Get_Name write Set_Name;
property Title: WideString read Get_Title write Set_Title;
property SRS: WideString read Get_SRS write Set_SRS;
property Abstract: WideString read Get_Abstract write Set_Abstract;
property Sources: IXMLSourcesType read Get_Sources;
end;
{ IXMLSourcesType }
IXMLSourcesType = interface(IXMLNodeCollection)
['{FA30627B-B210-447C-9A8D-03D285262BCE}']
{ Property Accessors }
function Get_Source(Index: Integer): IXMLSourceType;
{ Methods & Properties }
function Add: IXMLSourceType;
function Insert(const Index: Integer): IXMLSourceType;
property Source[Index: Integer]: IXMLSourceType read Get_Source; default;
end;
{ IXMLSourceType }
IXMLSourceType = interface(IXMLNode)
['{AD681124-EBEF-4D8E-8CE8-6AEA0B0217B3}']
{ Property Accessors }
function Get_ServerURL: WideString;
function Get_Layers: WideString;
function Get_Styles: WideString;
procedure Set_ServerURL(Value: WideString);
procedure Set_Layers(Value: WideString);
procedure Set_Styles(Value: WideString);
{ Methods & Properties }
property ServerURL: WideString read Get_ServerURL write Set_ServerURL;
property Layers: WideString read Get_Layers write Set_Layers;
property Styles: WideString read Get_Styles write Set_Styles;
end;
{ Forward Decls }
TXMLREPType = class;
TXMLWMSMergeServiceType = class;
TXMLLayersType = class;
TXMLLayerType = class;
TXMLSourcesType = class;
TXMLSourceType = class;
{ TXMLREPType }
TXMLREPType = class(TXMLNode, IXMLREPType)
protected
{ IXMLREPType }
function Get_WMSMergeService: IXMLWMSMergeServiceType;
public
procedure AfterConstruction; override;
end;
{ TXMLWMSMergeServiceType }
TXMLWMSMergeServiceType = class(TXMLNode, IXMLWMSMergeServiceType)
protected
{ IXMLWMSMergeServiceType }
function Get_Layers: IXMLLayersType;
public
procedure AfterConstruction; override;
end;
{ TXMLLayersType }
TXMLLayersType = class(TXMLNodeCollection, IXMLLayersType)
protected
{ IXMLLayersType }
function Get_Layer(Index: Integer): IXMLLayerType;
function Add: IXMLLayerType;
function Insert(const Index: Integer): IXMLLayerType;
public
procedure AfterConstruction; override;
end;
{ TXMLLayerType }
TXMLLayerType = class(TXMLNode, IXMLLayerType)
protected
{ IXMLLayerType }
function Get_Name: WideString;
function Get_Title: WideString;
function Get_SRS: WideString;
function Get_Abstract: WideString;
function Get_Sources: IXMLSourcesType;
procedure Set_Name(Value: WideString);
procedure Set_Title(Value: WideString);
procedure Set_SRS(Value: WideString);
procedure Set_Abstract(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLSourcesType }
TXMLSourcesType = class(TXMLNodeCollection, IXMLSourcesType)
protected
{ IXMLSourcesType }
function Get_Source(Index: Integer): IXMLSourceType;
function Add: IXMLSourceType;
function Insert(const Index: Integer): IXMLSourceType;
public
procedure AfterConstruction; override;
end;
{ TXMLSourceType }
TXMLSourceType = class(TXMLNode, IXMLSourceType)
protected
{ IXMLSourceType }
function Get_ServerURL: WideString;
function Get_Layers: WideString;
function Get_Styles: WideString;
procedure Set_ServerURL(Value: WideString);
procedure Set_Layers(Value: WideString);
procedure Set_Styles(Value: WideString);
end;
{ Global Functions }
function GetREP(Doc: IXMLDocument): IXMLREPType;
function LoadREP(const FileName: WideString): IXMLREPType;
function NewREP: IXMLREPType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetREP(Doc: IXMLDocument): IXMLREPType;
begin
Result := Doc.GetDocBinding('REP', TXMLREPType, TargetNamespace) as IXMLREPType;
end;
function LoadREP(const FileName: WideString): IXMLREPType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('REP', TXMLREPType, TargetNamespace) as IXMLREPType;
end;
function NewREP: IXMLREPType;
begin
Result := NewXMLDocument.GetDocBinding('REP', TXMLREPType, TargetNamespace) as IXMLREPType;
end;
{ TXMLREPType }
procedure TXMLREPType.AfterConstruction;
begin
RegisterChildNode('WMSMergeService', TXMLWMSMergeServiceType);
inherited;
end;
function TXMLREPType.Get_WMSMergeService: IXMLWMSMergeServiceType;
begin
Result := ChildNodes['WMSMergeService'] as IXMLWMSMergeServiceType;
end;
{ TXMLWMSMergeServiceType }
procedure TXMLWMSMergeServiceType.AfterConstruction;
begin
RegisterChildNode('Layers', TXMLLayersType);
inherited;
end;
function TXMLWMSMergeServiceType.Get_Layers: IXMLLayersType;
begin
Result := ChildNodes['Layers'] as IXMLLayersType;
end;
{ TXMLLayersType }
procedure TXMLLayersType.AfterConstruction;
begin
RegisterChildNode('Layer', TXMLLayerType);
ItemTag := 'Layer';
ItemInterface := IXMLLayerType;
inherited;
end;
function TXMLLayersType.Get_Layer(Index: Integer): IXMLLayerType;
begin
Result := List[Index] as IXMLLayerType;
end;
function TXMLLayersType.Add: IXMLLayerType;
begin
Result := AddItem(-1) as IXMLLayerType;
end;
function TXMLLayersType.Insert(const Index: Integer): IXMLLayerType;
begin
Result := AddItem(Index) as IXMLLayerType;
end;
{ TXMLLayerType }
procedure TXMLLayerType.AfterConstruction;
begin
RegisterChildNode('Sources', TXMLSourcesType);
inherited;
end;
function TXMLLayerType.Get_Name: WideString;
begin
Result := ChildNodes['Name'].Text;
end;
procedure TXMLLayerType.Set_Name(Value: WideString);
begin
ChildNodes['Name'].NodeValue := Value;
end;
function TXMLLayerType.Get_Title: WideString;
begin
Result := ChildNodes['Title'].Text;
end;
procedure TXMLLayerType.Set_Title(Value: WideString);
begin
ChildNodes['Title'].NodeValue := Value;
end;
function TXMLLayerType.Get_SRS: WideString;
begin
Result := ChildNodes['SRS'].Text;
end;
procedure TXMLLayerType.Set_SRS(Value: WideString);
begin
ChildNodes['SRS'].NodeValue := Value;
end;
function TXMLLayerType.Get_Abstract: WideString;
begin
Result := ChildNodes['Abstract'].Text;
end;
procedure TXMLLayerType.Set_Abstract(Value: WideString);
begin
ChildNodes['Abstract'].NodeValue := Value;
end;
function TXMLLayerType.Get_Sources: IXMLSourcesType;
begin
Result := ChildNodes['Sources'] as IXMLSourcesType;
end;
{ TXMLSourcesType }
procedure TXMLSourcesType.AfterConstruction;
begin
RegisterChildNode('Source', TXMLSourceType);
ItemTag := 'Source';
ItemInterface := IXMLSourceType;
inherited;
end;
function TXMLSourcesType.Get_Source(Index: Integer): IXMLSourceType;
begin
Result := List[Index] as IXMLSourceType;
end;
function TXMLSourcesType.Add: IXMLSourceType;
begin
Result := AddItem(-1) as IXMLSourceType;
end;
function TXMLSourcesType.Insert(const Index: Integer): IXMLSourceType;
begin
Result := AddItem(Index) as IXMLSourceType;
end;
{ TXMLSourceType }
function TXMLSourceType.Get_ServerURL: WideString;
begin
Result := ChildNodes['ServerURL'].Text;
end;
procedure TXMLSourceType.Set_ServerURL(Value: WideString);
begin
ChildNodes['ServerURL'].NodeValue := Value;
end;
function TXMLSourceType.Get_Layers: WideString;
begin
Result := ChildNodes['Layers'].Text;
end;
procedure TXMLSourceType.Set_Layers(Value: WideString);
begin
ChildNodes['Layers'].NodeValue := Value;
end;
function TXMLSourceType.Get_Styles: WideString;
begin
Result := ChildNodes['Styles'].Text;
end;
procedure TXMLSourceType.Set_Styles(Value: WideString);
begin
ChildNodes['Styles'].NodeValue := Value;
end;
end.
|
unit newButton;
{$mode objfpc}{$H+}
interface
uses
windows, UxTheme, Classes, SysUtils, StdCtrls, LCLType, Graphics, LMessages, Controls;
type
TNewButton=class(StdCtrls.TButton)
private
painted: boolean;
MouseIsDown: boolean;
fCanvas: TCanvas;
fCustomDraw: boolean;
fOnPaint: TNotifyEvent;
fFaceColorDisabled: TColor;
fFaceColorUp: TColor;
fFaceColorDown: TColor;
fFaceColorHover: TColor;
fBorderColor: TColor;
fInactiveBorderColor: TColor;
fInactiveFontColor: TColor;
fPenColorHover: TColor;
fDarkMode: boolean;
function getColor: TColor;
protected
procedure SetColor(c: TColor); override;
procedure DefaultCustomPaint;
procedure CreateParams(var Params: TCreateParams); override;
procedure WMPaint(var Msg: TLMPaint); message LM_PAINT;
procedure PaintWindow(DC: HDC); override;
procedure FontChanged(Sender: TObject); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure ChildHandlesCreated; override;
published
{ property CustomDraw: boolean read fCustomDraw write fCustomDraw;
property OnPaint: TNotifyEvent read fOnPaint write fOnPaint;
property Canvas: TCanvas read fCanvas;
property Color: TColor read getColor write setColor;
property FaceColorUp: TColor read fFaceColorUp write fFaceColorDown;
property FaceColorDown: TColor read fFaceColorDown write fFaceColorDown;
property FaceColorHover: TColor read fFaceColorHover write fFaceColorHover;
property FaceColorDisabled: TColor read fFaceColorDisabled write fFaceColorDisabled;
property BorderColor: TColor read fBorderColor write fBorderColor;
property InactiveBorderColor: TColor read fInactiveBorderColor write fInactiveBorderColor;
property InactiveFontColor: TColor read fInactiveFontColor write fInactiveFontColor; }
end;
implementation
uses betterControls;
procedure TNewButton.ChildHandlesCreated;
begin
inherited ChildHandlesCreated;
if ShouldAppsUseDarkMode and (Parent<>nil) then
begin
AllowDarkModeForWindow(handle, 1);
SetWindowTheme(handle, 'EXPLORER', nil);
end;
end;
function TNewButton.getColor: Tcolor;
begin
result:=inherited color;
end;
procedure TNewButton.setColor(c: TColor);
var
newc: longint;
r,g,b: byte;
begin
inherited setColor(c);
if ShouldAppsUseDarkMode then
begin
//setting color means default display
fFaceColorUp:=c;
;
fFaceColorDisabled:=clDkGray; //cldark;
fBorderColor:=clActiveBorder;
fPenColorHover:=clBlue;
fInactiveBorderColor:=clInactiveBorder;
fInactiveFontColor:=clInactiveCaption;
if (c=clDefault) or (c=0) then
begin
//default color
fFaceColorDown:=c;
fFaceColorHover:=clBtnHiLight;
end
else
begin
fFaceColorDown:=DecColor(c,14);
//there is no incColor, and -14 is not the same
newc:=ColorToRGB(c);
r:=Red(newc);
g:=Green(newc);
b:=Blue(newc);
if r<255 then inc(r,14) else r:=255;
if g<255 then inc(g,14) else g:=255;
if b<255 then inc(b,14) else b:=255;
fFaceColorHover:=RGBToColor(r,g,b);
end;
end;
end;
procedure TNewButton.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
painted:=false;
inherited MouseMove(shift, x,y);
if ShouldAppsUseDarkMode and (not painted) then
repaint;
end;
procedure TNewButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited mousedown(button, shift, x,y);
MouseIsDown:=true;
end;
procedure TNewButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseUp(Button, shift, x,y);
MouseIsDown:=false;
end;
procedure TNewButton.FontChanged(Sender: TObject);
begin
if ShouldAppsUseDarkMode then
begin
if self=nil then exit;
if fcanvas<>nil then
begin
fCanvas.Font.BeginUpdate;
try
fCanvas.Font.PixelsPerInch := Font.PixelsPerInch;
fCanvas.Font := Font;
finally
fCanvas.Font.EndUpdate;
end;
end;
end;
inherited FontChanged(Sender);
end;
procedure TNewButton.PaintWindow(DC: HDC);
var
DCChanged: boolean;
begin
if ShouldAppsUseDarkMode then
begin
DCChanged := (not FCanvas.HandleAllocated) or (FCanvas.Handle <> DC);
if DCChanged then
FCanvas.Handle := DC;
try
DefaultCustomPaint;
finally
if DCChanged then FCanvas.Handle := 0;
end;
painted:=true;
end
else inherited paintwindow(dc);
end;
procedure TNewButton.DefaultCustomPaint;
var
ts: TTextStyle;
faceColor: TColor;
GKS: TShiftState;
begin
if fcanvas.Handle<>0 then
begin
if enabled then
begin
if self.MouseInClient then
begin
fborderColor:=fpenColorHover;
if MouseIsDown then
facecolor:=fFaceColorDown
else
facecolor:=fFaceColorHover;
end
else
facecolor:=fFaceColorUp;
end
else
begin
facecolor:=fFaceColorDisabled;
end;
fcanvas.brush.style:=bsSolid;
fcanvas.brush.color:=facecolor;
fcanvas.Clear;
fcanvas.pen.Width:=1;
if enabled then
fcanvas.pen.color:=fBorderColor
else
fcanvas.pen.color:=fInactiveBorderColor;
fcanvas.Rectangle(0,0,clientwidth,clientheight);
if enabled then
fcanvas.font.color:=font.color
else
fcanvas.font.color:=fInactiveFontcolor;
ts:=fcanvas.TextStyle;
ts.Alignment:=taCenter;
fcanvas.TextRect(rect(0,0,width,height),0,(height div 2)-(fcanvas.TextHeight(caption) div 2),caption, ts);
if self.Focused then
begin
// fcanvas.pen.color:=
fcanvas.DrawFocusRect(rect(2,2,width-2,height-2));
end;
end;
end;
procedure TNewButton.WMPaint(var Msg: TLMPaint);
begin
if ShouldAppsUseDarkMode then
begin
if (csDestroying in ComponentState) or (not HandleAllocated) then exit;
if (not fdarkmode) and (fCustomDraw or globalCustomDraw) then Include(FControlState, csCustomPaint);
inherited WMPaint(msg);
if (not fdarkmode) and (fCustomDraw or globalCustomDraw) then Exclude(FControlState, csCustomPaint);
end
else
inherited WMPaint(msg);
end;
procedure TNewButton.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
if ShouldAppsUseDarkMode then
begin
fcanvas:=TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FDoubleBuffered:=true;
setcolor(clDefault);
end;
end;
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Angus Robertson, Magenta Systems Ltd
Description: Forward and Reverse SSL HTTP Proxy
Creation: May 2017
Updated: May 2017
Version: 8.48
Sponsor: This component was sponsored in part by Avenir Health and
Banxia Software Ltd. http://www.avenirhealth.org
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Legal issues: Copyright (C) 1997-2017 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium.
<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.
Overview
--------
TIcsProxy is protocol agnostic and may be used to proxy any TCP protocol,
the sample includes SMTP, POP3, NNTP and telnet. It may be used to allow
non-SSL news readers to access forums.embarcadero.com or other similar old
applications and protocols.
TIcsHttpProxy is a full forward and reverse HTTP/HTTPS proxy with header
and body parsing and processing host names and URLs to match the source and
destination. Could potentially be used as a caching proxy, but needs more
events. Can be used to monitor HTTP connections. Reverse proxy targets
may be selected according to partial paths, or using an event for more
complex selection such as load sharing to multiple targets. Or it can
be used to add SSL support to non-SSL servers. The HTTP proxy will
uncompress received pages and/or compress pages returned by the proxy.
These components require USE_SSL to be set, there is no non-SSL version,
but SSL is optional for source and targets. The components support multiple
sources and targets, with multiple ports and IP addresses. To an extent,
data may be intercepted and changed by the proxy, provided the protocols
are not broken. SSL server name identification is supported so multiple
hosts can share the same server address and port.
A forward proxy generally runs on a client or gateway server, and browsers
are configured to redirect all traffic to the proxy, which forwards it to
the remote target in the URL, typically logging or examining that target
and perhaps rejecting it. The browser may specify authentication login
and password, which the proxy sends to the onHttpPxyAuth event. For
non-SSL traffic, the proxy processes requests and responses which may be
checked and manipulated if necessary. But the browser will send SSL
traffic using the CONNECT method which opens a direct connection to the
remote server and the proxy behaves as a transparent tunnel passing
encrypted data back and forward, so requests and responses can not be
seen.
A reverse proxy generally runs in front of the remote web server, perhaps to
provide SSL access to a non-SSL server, for load sharing between multiple
servers, or to direct different URLs to different servers. Potentially,
the proxy can cache static pages, but this is not implemented yet.
Proxy configuration is based on a concept of multiple sources and targets:
Source - TSslWSocketServer listening for incoming source connections, part
of TIcsProxy, defined as a collection of IcsHosts. Each source can listen
on two different IP addresses BindIpAddr and BindIpAddr2 (perhaps IPv4
and IPv6) each with non-SSL BindNonPort and/or SSL BindSslPort. Multiple
source clients can connect to each listening socket. Each source needs
a unique HostTag alphabetic name, and one or more HostNames that match
DNS and SSL certificate names. Each source should define Proto as HTTP
or other, and ForwardProxy as true if that behaviour is required otherwise
reverse proxy is assumed. If SSL is used, an SSL certificate must also
be specified that matches the HostNames, see below. Note IcsHosts is
part of TSslWSocketServer and is used for other server components such
as the web server.
Target - TSslWSocket that connects to a remote target destination, Part
of TProxyClient, at least one for each source client (unless ForwardProxy
is defined), defined as a collection of ProxyTargets, each with a HostTag
alphabetic name that must match a source in the IcsHosts collection, but
for HTTP the request path may be examined and there may be multiple
ProxyTargets. Each target specifies TarHost, TarPort and TarSsl as the
remote target. If the target is SSL, the remote SSL certificate chain may
be validated and reported according to the TCertVerMethod setting. The
OnSetTarget event is called immediately before each remote target connection
is started and may be used for logging or TarHost, TarPort and TarSsl may be
changed to alter the target for this connection only.
Once source and target are connected, traffic from source is sent to target,
and vice versa. The proxy receives data in a temporary TBytes buffer of size
RxBuffSize (default 64K). For HTTP, entire request and response headers are
saved into a String for ease of processing and each line parsed into
THttpProxyClient RequestXX and ResponseXX properties. The event handlers
onHttpReqHdr and onHttpRespHdr allow the complete headers to be logged or
changed, with care because changes may break the proxy or protocol.
If the target specifies UpdateHttp, the proxy may modify the Location, Host
and Referrer headers from and to the source and target host names, ports
and http/https, so the HTTP protocol works correctly.
If UpdateHtml is specified, textual body content also has absolute URLs
modified similarly, with the header page length modified if the content
length changes. To modify bodies, the proxy needs to read the entire body
first which has required local memory and also delays response to the
source that might cause a timeout, so body size is restricted by the
HttpMaxBody setting, defaulting to 10MB, the assumption being larger
textual bodies will not contain absolute server links. If the
onHttpRespBody event is set, it will be called with the body, but note
only for textual bodies smaller than HttpMaxBody.
To support SSL sources, the SslCert property should ideally be set the
SSL certificate bundle file name in PEM, PFX or P12 format that also
includes the private key and any intermediate certificates required.
But SslCert also accepts a bundle as Base64 encoded ASCII. SslPassword
should be set to the private key password, if required. If SslCert only
specifies a PEM, DER or PK7 certificate, SslKey and SslInter may be used
to specify the private key and intermediate bundle file names (or ASCII
versions). SslSrvSecurity sets TSslSrvSecurity which may stop low security
protocols or certificates being used.
There is an ICS sample application OverbyteIcsProxySslServer that illustrates
the use of TIcsHttpProxy. It reads all it's settings from an INI file, using
three functions in the main ICS components, IcsLoadIcsHostsFromIni in
OverbyteIcsWSocketS.pas, and IcsLoadProxyTargetsFromIni and
IcsLoadTIcsHttpProxyFromIni in this proxy unit. The sample INI file is
OverbyteIcsProxySslServer.ini with several source and target sections.
So the application just needs to open an INI file and these three functions
will read all necessary settings. This is all optional, the application
could keep settings in XML or the registry and set-up the proxy collection
properties directly. nut using the same INI settings will ease adding future
functionality to the proxy with minimal application changes.
Updates:
28 May 2017 - 8.48 baseline
pending...
Convert TByte buffers to UTF8 instead of ANSI
Test Transfer-Encoding: gzip, chunked
Proxy generated error page if target connection fails
Proxy statistics
}
unit OverbyteIcsProxy;
{$I Include\OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$IFDEF BCB}
{$ObjExportAll On}
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
{$IFDEF RTL_NAMESPACES}Winapi.Messages{$ELSE}Messages{$ENDIF},
{$IFDEF RTL_NAMESPACES}Winapi.Windows{$ELSE}Windows{$ENDIF},
{$IFDEF RTL_NAMESPACES}System.IniFiles{$ELSE}IniFiles{$ENDIF},
{$ENDIF}
{$IFDEF POSIX}
Posix.Time,
Ics.Posix.WinTypes,
Ics.Posix.Messages,
{$ENDIF}
{$Ifdef Rtl_Namespaces}System.Classes{$Else}Classes{$Endif},
{$Ifdef Rtl_Namespaces}System.Sysutils{$Else}Sysutils{$Endif},
{$IFDEF Rtl_Namespaces}System.StrUtils{$ELSE}StrUtils{$ENDIF},
Overbyteicsssleay, Overbyteicslibeay,
OverbyteIcsSslSessionCache,
OverbyteIcsMsSslUtils, OverbyteIcsWinCrypt,
{$I Include\OverbyteIcsZlib.inc}
OverbyteIcsZlibHigh,
{$IFDEF USE_ZLIB_OBJ}
OverbyteIcsZLibObj, {interface to access ZLIB C OBJ files}
{$ELSE}
OverbyteIcsZLibDll, {interface to access zLib1.dll}
{$ENDIF}
OverbyteIcsLogger,
// OverbyteIcsStreams,
{$IFDEF FMX}
Ics.Fmx.OverbyteIcsWndControl,
Ics.Fmx.OverbyteIcsWSocket,
Ics.Fmx.OverbyteIcsWSocketS,
{$ELSE}
OverbyteIcsWndControl,
OverbyteIcsWSocket,
OverbyteIcsWSocketS,
{$ENDIF FMX}
OverbyteIcsTypes,
OverbyteIcsMimeUtils,
OverbyteIcsURL,
OverbyteIcsUtils;
{ NOTE - these components only build with SSL, there is no non-SSL option }
{$IFDEF USE_SSL}
const
THttpServerVersion = 848;
CopyRight : String = ' TIcsHttpProxy (c) 2017 F. Piette V8.48 ';
DefServerHeader : string = 'Server: ICS-Proxy-8.48';
CompressMinSize = 5000; // 5K minimum to make it worth compressing a page
CompressMaxSize = 5000000; // 5M bigger takes too long
DefRxBuffSize = 65536;
DefMaxBodySize = 1000000; // 10M general maximum length of body to buffer and process
MaxBodyDumpSize = 200000; // 200K maximum length of body to log
Ssl_Session_ID_Context = 'IcsProxy';
MaxPipelineReqs = 10;
cLF = #10;
cFF = #12;
cCR = #13;
cCRLF: PChar = cCR+cLF;
cCRLF_ = cCR+cLF;
cDoubleCRLF = cCR+cLF+cCR+cLF;
FlushSslCacheMins = 120; // how often to clear SSL domain cache
type
{ forware declarations }
TIcsProxy = class;
TIcsHttpProxy = class;
TProxyClient = Class;
THttpProxyClient = Class;
{ event handlers }
TProxyProgEvent = procedure (Sender: TObject; LogOption: TLogOption; const Msg: string) of object;
TProxyDataEvent = procedure (Sender: TObject; ProxyClient: TProxyClient; DataPtr: Pointer; var DataLen: Integer) of object;
TProxyTarEvent = procedure (Sender: TObject; ProxyClient: TProxyClient) of object;
TProxyHttpEvent = procedure (Sender: TObject; ProxyClient: THttpProxyClient; var Arg: String) of object;
{ property and state types }
TPxyTarState = (PxyClosed, PxyHdrFind, PxyLenEnd, PxyCnkEnd, PxyGetBody, PxyNoBody, PxySendBody);
TPxyChunkState = (PxyChunkGetSize, PxyChunkGetExt, PxyChunkGetData, PxyChunkSkipDataEnd, PxyChunkDone);
TCertVerMethod = (CertVerNone, CertVerBundle, CertVerWinStore);
TDebugLevel = (DebugNone, DebugConn, DebugSsl, DebugHttpHdr, DebugHttpBody, DebugChunks, DebugAll);
THttpReqMethod = (httpMethodNone, httpMethodGet, httpMethodPost, httpMethodHead, httpMethodOptions,
httpMethodPut, httpMethodDelete, httpMethodTrace, httpMethodPatch, httpMethodConnect);
THttpReqState = (httpStNone, httpStReqStart, httpStReqHdrWait, httpStWaitResp, httpStRespStart,
httpStRespHdrWait, httpStRespBody, httpStRespSend, httpStRespDone);
{ used for pipelining, all information about one request for when we process the response }
{ we may receive two or three requests together, then all the responses }
THttpInfo = record
HttpReqState: THttpReqState; // HTTP State, doing request and response
HttpReqMethod: THttpReqMethod; // HTTP request type only
ReqContentLen: Integer; // expected request content length according to header
ReqStartLine: String; // request method, path and version
ReqAcceptEnc: String; // request accept-encoding
TickReqStart: LongWord; // when request started
TickReqSend: LongWord; // when request was forwarded
TickWaitResp: LongWord; // when request finished. wait response
TickRespStart: LongWord; // when response started
TickRespBody: LongWord; // when response body started
TickRespSend: LongWord; // when response forwarding started
TickRespDone: LongWord; // when response forwarding finished
TickRespEnd: LongWord; // when response all forwarded
end;
{ TProxyTarget defines the reverse proxy target, or act as forward proxy }
TProxyTarget = class(TCollectionItem)
private
FHostTag: String;
FHostEnabled: Boolean;
FDescr: String;
FSrcPath: String;
FTarHost: String;
FTarPort: Integer;
FTarSsl: Boolean;
FIdleTimeout: Integer;
FUpdateHttp: Boolean;
FUpdateHtml: Boolean;
protected
function GetDisplayName: string; override;
published
constructor Create (Collection: TCollection); Override ;
property HostTag: String read FHostTag
write FHostTag;
property HostEnabled : boolean read FHostEnabled
write FHostEnabled;
property Descr : String read FDescr
write FDescr;
property SrcPath: String read FSrcPath
write FSrcPath;
property TarHost : String read FTarHost
write FTarHost;
property TarPort : Integer read FTarPort
write FTarPort;
property TarSsl : Boolean read FTarSsl
write FTarSsl;
property IdleTimeout: Integer read FIdleTimeout
write FIdleTimeout;
property UpdateHttp : Boolean read FUpdateHttp
write FUpdateHttp;
property UpdateHtml : Boolean read FUpdateHtml
write FUpdateHtml;
end;
{ TIcsHosts defines a collection of TIcsHost }
TProxyTargets = class(TCollection)
private
FOwner: TPersistent;
function GetItem(Index: Integer): TProxyTarget;
procedure SetItem(Index: Integer; Value: TProxyTarget);
protected
function GetOwner: TPersistent; override;
public
constructor Create(Owner: TPersistent);
property Items[Index: Integer]: TProxyTarget read GetItem write SetItem; default;
end;
{ socket server client, one instance for each proxy remote target session }
TProxyClient = class(TSslWSocketClient)
private
FProxySource: TIcsProxy; // pointer back to our server
FSrcHost: String; // source host, same as SslServerName for SSL
FTarSocket: TSslWSocket; // remote target socket
FTarHost: String; // remote IP address or host
FTarIP: String; // remote IP address looked-up
FTarPort: String; // remote IP port
FTarSsl: Boolean; // is remote SSL
FTarHttp: Boolean; // are we processing HTTP requests and responses
FTarCurHost: String; // last host to which we connected, checking if changed
FSrcBuffer: TBytes; // temporary source data waiting to be sent to target
FSrcBufMax: Integer; // maximum size of SrcBuffer
FSrcWaitTot: Integer; // current data in of SrcBuffer
FTarBuffer: TBytes; // temporary target data waiting to be sent to server
FTarBufMax: Integer; // maximum size of TarBuffer
FTarWaitTot: integer; // current data in of TarBuffer
FClosingFlag: Boolean; // local client about to close
FTunnelling: Boolean; // tunnelling data without processing it (probably using SSL)
FForwardPrxy: Boolean; // HTTP forward proxy
FTarConditional: Boolean; // target is conditional upon path or something
FPxyTargetIdx: Integer; // which ProxyTarget are we using
FDelayedDisconn: Boolean; // do we need to send stuff before disconnecting
FIdleTimeout: Integer; // close an idle connection after x seconds, if non-zero
FLogDescr: String; // source description and clientId for logging
FSrcPendClose: Boolean; // close local client once all data forwarded
FTarClosedFlag: Boolean; // target has closed, must send any pending data to source
protected
procedure SourceDataAvailable(Sender: TObject; Error: Word);
procedure SourceSessionClosed(Sender: TObject; Error: Word); Virtual;
// procedure TargetDnsLookupDone(Sender: TObject; Error: Word);
procedure TargetSessionConnected(Sender: TObject; Error: Word);
procedure TargetSessionClosed(Sender: TObject; Error: Word); Virtual;
procedure TargetVerifyPeer(Sender: TObject; var Ok : Integer; Cert: TX509Base);
procedure TargetHandshakeDone(Sender: TObject; ErrCode: Word;
PeerCert: TX509Base; var Disconnect : Boolean);
procedure TargetDataAvailable(Sender: TObject; Error: Word);
procedure TargetCliNewSession(Sender: TObject; SslSession: Pointer;
WasReused: Boolean; var IncRefCount : Boolean);
procedure TargetCliGetSession(Sender: TObject;
var SslSession: Pointer; var FreeSession : Boolean);
procedure SourceDataSent(Sender: TObject; ErrCode : Word); Virtual;
procedure TargetDataSent(Sender: TObject; ErrCode : Word); Virtual;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure SourceBufRecv; Virtual;
procedure SourceXferData; Virtual;
procedure SourceBufXmit(SendNr: Integer); Virtual;
procedure TargetInitialiase; Virtual;
procedure TargetCheck; Virtual;
procedure TargetSpecify; Virtual;
function TargetConnect: Boolean;
procedure TargetBufRecv; Virtual;
procedure TargetXferData; Virtual;
procedure TargetBufXmit(SendNr: Integer); Virtual;
procedure LogEvent(const Msg: String);
procedure LogTarEvent(const Msg: String);
procedure LogSrcEvent(const Msg: String);
property TarHost: String read FTarHost
write FTarHost;
property TarPort: String read FTarPort
write FTarPort;
property TarSsl: Boolean read FTarSsl
write FTarSsl;
property SrcHost: String read FSrcHost;
property Tunnelling: Boolean read FTunnelling;
property TarConditional: Boolean read FTarConditional;
property PxyTargetIdx: Integer read FPxyTargetIdx;
end;
{ TIcsProxy - forwards TCP/IP streams from source (server) to target (client) and back again, without
examening any of the streams }
TIcsProxy = class(TIcsWndControl)
private
{ Private declarations }
FSourceServer: TSslWSocketServer;
FProxyTargets: TProxyTargets;
FSslSessCache: TSslAvlSessionCache;
FTarSslCtx: TSslContext;
FTarSslCertList: TStringList;
FMsCertChainEngine: TMsCertChainEngine;
FRxBuffSize: Integer;
FMaxClients: Integer;
FServerHeader: String;
FSocketErrs : TSocketErrs;
FExclusiveAddr: Boolean;
FLocalAddr: String;
FCertVerTar: TCertVerMethod;
FTarSecLevel: TSslSecLevel;
FSslRevocation: Boolean;
FSslReportChain: Boolean;
FDebugLevel: TDebugLevel;
FonProxyProg: TProxyProgEvent;
FOnSetTarget: TProxyTarEvent;
FOnDataSendTar: TProxyDataEvent;
FOnDataRecvTar: TProxyDataEvent;
FMsg_TARGET_CONNECTED: longword;
FCleanupTimer: TIcsTimer;
FTimerBusyFlag: Boolean;
FCurDate: Integer;
FFlushTick: LongWord;
FOnSrcConnect: TWSocketClientConnectEvent; // when source client connects
FOnSrcDisconnect: TWSocketClientConnectEvent; // when source client disconnects
FOnTarConnect: TWSocketClientConnectEvent; // when remote target connects
FOnTarDisconnect: TWSocketClientConnectEvent; // when remote target disconnects
function GetIcsHosts: TIcsHostCollection;
procedure SetIcsHosts(const Value: TIcsHostCollection);
function GetRootCA: String;
procedure SetRootCA(const Value: String);
function GetDHParams: String;
procedure SetDHParams(const Value: String);
procedure SetProxyTargets(const Value: TProxyTargets);
function GetRunning: Boolean;
function GetClientCount: Integer;
protected
{ Protected declarations }
procedure IcsLogEvent (Sender: TObject; LogOption: TLogOption;
const Msg : String);
procedure LogProgEvent (const Msg : String);
procedure LogErrEvent (const Msg : String);
procedure SocketBgException(Sender: TObject;
E: Exception; var CanClose: Boolean);
procedure ServerClientCreate(Sender : TObject; Client : TWSocketClient);
procedure ServerClientConnect(Sender: TObject;
Client: TWSocketClient; Error: Word);
procedure ServerClientDisconnect(Sender: TObject;
Client: TWSocketClient; Error: Word);
procedure ServerSetSessionIDContext(Sender : TObject;
var SessionIDContext : TSslSessionIdContext);
procedure ServerSvrNewSession(Sender: TObject; SslSession, SessId: Pointer;
Idlen: Integer; var AddToInternalCache: Boolean);
procedure ServerSvrGetSession(Sender: TObject; var SslSession: Pointer; SessId: Pointer;
Idlen: Integer; var IncRefCount: Boolean);
procedure ServerVerifyPeer(Sender: TObject; var Ok : Integer; Cert: TX509Base);
procedure ServerHandshakeDone(Sender: TObject; ErrCode: Word;
PeerCert: TX509Base; var Disconnect : Boolean);
procedure ServerServerName(Sender: TObject;
var Ctx: TSslContext; var ErrCode: TTlsExtError);
procedure WndProc(var MsgRec: TMessage); override;
procedure WMTargetConnected(var msg: TMessage);
function MsgHandlersCount: Integer; override;
procedure AllocateMsgHandlers; override;
procedure FreeMsgHandlers; override;
procedure CleanupTimerOnTimer (Sender : TObject);
public
FIcsLog : TIcsLogger;
{ Public declarations }
constructor Create(Owner:TComponent); override;
destructor Destroy; override;
function FindPxyTarget(const Tag: String): Integer;
function FindPxySourceHost(const HHostName: String; MLIndx: Integer): Integer;
function ValidateHosts(Stop1stErr: Boolean=True;
NoExceptions: Boolean=False): String;
function RecheckSslCerts(var CertsInfo: String;
Stop1stErr: Boolean=True; NoExceptions: Boolean=False): Boolean;
procedure Start;
procedure Stop;
function ListenAllOK: Boolean;
function ListenStates: String;
property Running: Boolean read GetRunning;
property ClientCount: Integer read GetClientCount;
property SourceServer: TSslWSocketServer read FSourceServer;
published
{ Published declarations }
property IcsHosts : TIcsHostCollection read GetIcsHosts
write SetIcsHosts;
property ProxyTargets : TProxyTargets read FProxyTargets
write SetProxyTargets;
property RxBuffSize: Integer read FRxBuffSize
write FRxBuffSize;
property MaxClients : Integer read FMaxClients
write FMaxClients;
property ServerHeader : String read FServerHeader
write FServerHeader;
property SocketErrs : TSocketErrs read FSocketErrs
write FSocketErrs;
property LocalAddr: String read FLocalAddr
write FLocalAddr;
property ExclusiveAddr : Boolean read FExclusiveAddr
write FExclusiveAddr;
property RootCA : String read GetRootCA
write SetRootCA;
property DHParams : String read GetDHParams
write SetDHParams;
property DebugLevel: TDebugLevel read FDebugLevel
write FDebugLevel;
property SslSessCache: TSslAvlSessionCache read FSslSessCache
write FSslSessCache;
property TarSecLevel: TSslSecLevel read FTarSecLevel
write FTarSecLevel;
property CertVerTar: TCertVerMethod read FCertVerTar
write FCertVerTar;
property SslRevocation: Boolean read FSslRevocation
write FSslRevocation;
property SslReportChain : boolean read FSslReportChain
write FSslReportChain;
property onProxyProg: TProxyProgEvent read FonProxyProg
write FonProxyProg;
property OnSetTarget: TProxyTarEvent read FOnSetTarget
write FOnSetTarget;
property OnDataSendTar: TProxyDataEvent read FOnDataSendTar
write FOnDataSendTar;
property OnDataRecvTar: TProxyDataEvent read FOnDataRecvTar
write FOnDataRecvTar;
property OnBgException;
property OnSrcConnect: TWSocketClientConnectEvent
read FOnSrcConnect
write FOnSrcConnect;
property OnSrcDisconnect: TWSocketClientConnectEvent
read FOnSrcDisconnect
write FOnSrcDisconnect;
property OnTarConnect: TWSocketClientConnectEvent
read FOnTarConnect
write FOnTarConnect;
property OnTarDisconnect: TWSocketClientConnectEvent
read FOnTarDisconnect
write FOnTarDisconnect;
end;
{ THtttpProxyClient - similar to TProxyClient, but processing HTTP/HTML }
THttpProxyClient = class(TProxyClient)
private
{ Private declarations }
FPxyReqState: TPxyTarState; // HTTP request state
FPxyRespState: TPxyTarState; // HTTP responsestate
FPxyChunkState: TPxyChunkState; // HTTTP response chunked state
FHttpInfo: array [0..MaxPipelineReqs] of THttpInfo; // pipelined requests
FHttpReqHdr: String; // HTTP request header lines
FHttpRespHdr: String; // HTTP response header lines
FHtmlReqBody: TBytes; // HTTP POST content
FHtmlReqBodyLen: Integer; // HTTP length of post content in buffer
FHtmlRespBody: TBytes; // HTTP response body content
FHtmlRespBodyLen: integer; // HTTP length of response body in buffer, zero no body
FHttpTotReqs: integer; // count of request in this connection
FHttpTotResps: integer; // count of responses in this connection
FHttpCurrReq: Integer; // next HttpInfo for new request
FHttpCurrResp: Integer; // next HttpInfo for response
FHttpWaiting: Integer; // total outstanding responses
FTarReqLenRemain: Int64; // request content length not yet received
FTarReqTooLarge: Boolean; // don't try to process massive bodies
FTarReqModified: Boolean; // did we modify request header
FTarRespLenRemain: Int64; // request content length not yet received
FTarRespTooLarge: Boolean; // don't try to process massive bodies
FTarRespModified: Boolean; // did we modify response header
// FChunkOff: Integer; // current offset into buffer
FChunkState: TPxyChunkState; // chunk state
FChunkRcvd: Integer; // how much chunked data so far
FChunkTot: Integer; // how many chunks in page
FChunkGzip: Boolean; // is each separate chunk compressed?
FLastReqPath: String; // last path conditionally checked for target
FReqKAFlag: Boolean; // did local client send Connection: Keep-Alive or Close
FReqKASecs: integer; // keep-alive timeout for idle client connection
FReqBinary: Boolean; // request POST content is binary
FRespBinary: Boolean; // response body content is binary
FRespGzip: Boolean; // response is compressed
FHttpSrcURL: String; // HTTP source URL for seaching
FHttpTarURL1: String; // HTTP target URL for seachingm with port
FHttpTarURL2: String; // HTTP target URL for seaching without port
FUpdateHttp: Boolean; // from Targets
FUpdateHtml: Boolean; // from Targets
{ following are parsed from HTTP request header }
FRequestMethod: THttpReqMethod; // HTTP request header field
FRequestVersion: String; // HTTP request header field
FRequestAccept: String; // HTTP request header field
FRequestAcceptEncoding: String; // HTTP request header field
FRequestConnection: String; // HTTP request header field
FRequestContentLength: Int64; // HTTP request header field
FRequestContentType: String; // HTTP request header field
FRequestCookies: String; // HTTP request header field
FRequestHost: String; // HTTP request header field
FRequestHostName: String; // HTTP request header field
FRequestHostPort: String; // HTTP request header field
FRequestIfModSince: TDateTime; // HTTP request header field
FRequestKeepAlive: String; // HTTP request header field
FRequestPath: String; // HTTP request header field
FRequestProxyAuthorization: String; // HTTP request header field
FRequestProxyConnection: String; // HTTP request header field
FRequestReferer: String; // HTTP request header field
FRequestStartLine: String; // HTTP request start line
FRequestUpgrade: String; // HTTP request header field
FRequestUserAgent: String; // HTTP request header field
// FRequestAcceptLanguage: String; // HTTP request header field
// FRequestAuth: String; // HTTP request header field
{ following are parsed from HTTP response header }
FRespStatusCode: integer; // HTTP response header field
FRespVersion: String; // HTTP response header field
FRespConnection: String; // HTTP response header field
FRespContentEncoding: String; // HTTP response header field
FRespContentLength: Int64; // HTTP response header field
FRespContentLenSet: Boolean; // HTTP response header field
FRespContentType: String; // HTTP response header field
FRespContent: String; // HTTP response header field
FRespCharset: String; // HTTP response header field
FRespCookies: String; // HTTP response header field
FRespKAFlag: Boolean; // did local client send Connection: Keep-Alive or Close
FRespKASecs: integer; // keep-alive timeout for idle client connection
FRespKeepAlive: String; // HTTP response header field
FRespLastModified: TDateTime; // HTTP response header field
FRespLocation: String; // HTTP response header field
FRespReasonPhase: String; // HTTP response header field
FRespStatusLine: String; // HTTP response status line
FRespTransferEncoding: String; // HTTP response header field
protected
{ Protected declarations }
procedure SourceSessionClosed(Sender: TObject; Error: Word); override;
procedure TargetSessionClosed(Sender: TObject; Error: Word); override;
procedure SourceDataSent(Sender: TObject; ErrCode : Word); override;
procedure TargetDataSent(Sender: TObject; ErrCode : Word); override;
public
{ Public declarations }
constructor Create(Owner:TComponent); override;
destructor Destroy; override;
procedure TargetSpecify; override;
function RemoveHdrLine(const Hdr: String; var Headers: string): boolean;
function UpdateHdrLine(const Hdr, Arg: String; var Headers: string): boolean;
procedure SourceHdrRespXmit;
procedure TargetHdrReqXmit;
procedure TargetBodyXmit;
procedure SourceBodyBufXmit;
// procedure SourceBodyStrXmit;
procedure TargetForwardProxy; Virtual;
function FindPxyPathTarget(const HTag, HPath: String): Integer; Virtual;
procedure UpdateBody; Virtual;
procedure CompressBody; Virtual;
procedure DecompressBody; Virtual;
procedure ParseReqHdr; Virtual;
procedure ParseRespHdr; Virtual;
procedure SourceXferData; override;
procedure TargetXferData; override;
property RequestMethod : THttpReqMethod read FRequestMethod;
property RequestVersion: String read FRequestVersion;
property RequestAccept : String read FRequestAccept;
property RequestAcceptEncoding : String read FRequestAcceptEncoding;
property RequestConnection : String read FRequestConnection;
property RequestContentLength : Int64 read FRequestContentLength;
property RequestContentType : String read FRequestContentType;
property RequestCookies : String read FRequestCookies;
property RequestHost : String read FRequestHost
write FRequestHost;
property RequestHostName : String read FRequestHostName;
property RequestHostPort : String read FRequestHostPort;
property RequestIfModSince : TDateTime read FRequestIfModSince;
property RequestKeepAlive: String read FRequestKeepAlive;
property RequestPath: String read FRequestPath
write FRequestPath;
property RequestProxyAuthorization : String read FRequestProxyAuthorization;
property RequestProxyConnection: String read FRequestProxyConnection;
property RequestReferer : String read FRequestReferer;
property RequestStartLine: String read FRequestStartLine;
property RequestUpgrade : string read FRequestUpgrade;
property RequestUserAgent : String read FRequestUserAgent;
property RespStatusCode: integer read FRespStatusCode;
property RespVersion: String read FRespVersion;
property RespConnection: String read FRespConnection;
property RespContentEncoding: String read FRespContentEncoding;
property RespContentLength: Int64 read FRespContentLength;
property RespContentType: String read FRespContentType;
property RespContent: String read FRespContent;
property RespCharset: String read FRespCharset;
property RespCookies: String read FRespCookies;
property RespKeepAlive: String read FRespKeepAlive;
property RespLastModified: TDateTime read FRespLastModified;
property RespLocation: String read FRespLocation;
property RespReasonPhase: String read FRespReasonPhase;
property RespStatusLine: String read FRespStatusLine;
property RespTransferEncoding: String read FRespTransferEncoding;
published
{ Published declarations }
end;
{ TIcsHtttpProxy - forwards HTTP requests from source (server) to target (client) and responses back again,
modifying the HTTP headers and HTML body if necessary to change host names and ports, and other headers,
uncompessing and compressing body content if required }
TIcsHttpProxy = class(TIcsProxy)
private
{ Private declarations }
FHttpIgnoreClose: Boolean; // HTTP force keep-alive
FHttpSrcCompress: Boolean; // HTTP Gzip source responses
FHttpTarCompress: Boolean; // HTTP Gzip target responses
FHttpCompMinSize: Integer; // minimum body size to compress
FHttpStripUpgrade: Boolean; // HTTP strip Upgrade: header to stop HTTP/2
FHttpStopCached: Boolean; // HTTP strip If-Modified header
FHttpMaxBody: Integer; // HTTP maximum body size to cached and process
FonHttpReqHdr: TProxyHttpEvent; // HTTP request header has been parsed
FonHttpRespHdr: TProxyHttpEvent; // HTTP response header has been parsed
FonHttpPxyAuth: TProxyHttpEvent; // HTTP proxy authorisation needed
FonHttpReqBody: TProxyHttpEvent; // HTTP request POST body has been read
FonHttpRespBody: TProxyHttpEvent; // HTTP response body has been read
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(Owner:TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property HttpIgnoreClose : Boolean read FHttpIgnoreClose
write FHttpIgnoreClose;
property HttpSrcCompress : Boolean read FHttpSrcCompress
write FHttpSrcCompress;
property HttpTarCompress : Boolean read FHttpTarCompress
write FHttpTarCompress;
property HttpCompMinSize : Integer read FHttpCompMinSize
write FHttpCompMinSize;
property HttpStripUpgrade : Boolean read FHttpStripUpgrade
write FHttpStripUpgrade;
property HttpStopCached: Boolean read FHttpStopCached
write FHttpStopCached;
property HttpMaxBody: Integer read FHttpMaxBody
write FHttpMaxBody;
property onHttpReqHdr: TProxyHttpEvent read FonHttpReqHdr
write FonHttpReqHdr;
property onHttpRespHdr: TProxyHttpEvent read FonHttpRespHdr
write FonHttpRespHdr;
property onHttpPxyAuth: TProxyHttpEvent read FonHttpPxyAuth
write FonHttpPxyAuth;
property onHttpReqBody: TProxyHttpEvent read FonHttpReqBody
write FonHttpReqBody;
property onHttpRespBody: TProxyHttpEvent read FonHttpRespBody
write FonHttpRespBody;
end;
{ public functions }
function IcsLoadProxyTargetsFromIni(MyIniFile: TCustomIniFile; ProxyTargets:
TProxyTargets; const Prefix: String = 'Target'): Integer;
procedure IcsLoadTIcsHttpProxyFromIni(MyIniFile: TCustomIniFile; IcsHttpProxy:
TIcsHttpProxy; const Section: String = 'Proxy');
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ we receive socket as single byte raw data into TBytes buffer without a
character set, then convertit onto Delphi Strings for each of processing }
{ Beware - this function treats buffers as ANSI, no Unicode conversion }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MoveTBytesToString(const Buffer: TBytes; OffsetFrom: Integer;
var Dest: String; OffsetTo: Integer; Count: Integer);
{$IFDEF UNICODE}
var
PSrc : PByte;
PDest : PChar;
begin
PSrc := Pointer(Buffer);
if Length(Dest) < (OffsetTo + Count - 1) then
SetLength(Dest, OffsetTo + Count - 1);
PDest := Pointer(Dest);
Dec(OffsetTo); // String index!
while Count > 0 do begin
PDest[OffsetTo] := Char(PSrc[OffsetFrom]);
Inc(OffsetTo);
Inc(OffsetFrom);
Dec(Count);
end;
{$ELSE}
begin
if Length(Dest) < (OffsetTo + Count - 1) then
SetLength(Dest, OffsetTo + Count - 1);
Move(Buffer[OffsetFrom], Dest[OffsetTo], Count);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Beware - this function treats buffers as ANSI, no Unicode conversion }
procedure MoveStringToTBytes(const Source: String; var Buffer: TBytes; Count: Integer);
{$IFDEF UNICODE}
var
PDest : PByte;
PSrc : PChar;
I : Integer;
begin
PSrc := Pointer(Source);
if Count > Length(Source) then
Count := Length(Source);
if Length(Buffer) < Count then
SetLength(Buffer, Count);
PDest := Pointer(Buffer);
for I := 0 to Count - 1 do begin
PDest[I] := Byte(PSrc[I]);
end;
{$ELSE}
begin
if Count > Length(Source) then
Count := Length(Source);
if Length(Buffer) < Count then
SetLength(Buffer, Count);
Move(Source[1], Buffer[0], Count);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MoveTBytes(var Buffer: TBytes; OffsetFrom: Integer; OffsetTo: Integer;
Count: Integer); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
Move(Buffer[OffsetFrom], Buffer[OffsetTo], Count);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MoveTBytesEx(const BufferFrom: TBytes; var BufferTo: TBytes;
OffsetFrom, OffsetTo, Count: Integer); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
Move(BufferFrom[OffsetFrom], BufferTo[OffsetTo], Count);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Pos that ignores nulls in the TBytes buffer, so avoid PAnsi functions }
function PosTBytes(const Substr: String; const S: TBytes; Offset, Count: Integer): Integer;
var
Ch: Byte;
SubLen, I, J: Integer;
Found: Boolean;
begin
Result := -1;
SubLen := Length(Substr);
if SubLen = 0 then Exit;
Ch := Byte(SubStr[1]);
for I := Offset to Count - SubLen do begin
if S[I] = Ch then begin
Found := True;
if SubLen > 1 then begin
for J := 2 to SubLen do begin
if Byte(Substr[J]) <> S[I+J-1] then begin
Found := False;
Break;
end;
end;
end;
if Found then begin
Result := I;
Exit;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TProxyTargets }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TProxyTargets.Create(Owner: TPersistent);
begin
FOwner := Owner;
inherited Create(TProxyTarget);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TProxyTargets.GetItem(Index: Integer): TProxyTarget;
begin
Result := TProxyTarget(inherited GetItem(Index));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyTargets.SetItem(Index: Integer; Value: TProxyTarget);
begin
inherited SetItem(Index, TCollectionItem(Value));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TProxyTargets.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TProxyTarget }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TProxyTarget.Create(Collection: TCollection);
begin
inherited;
FHostEnabled := True;
FIdleTimeout := 70; // seconds
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TProxyTarget.GetDisplayName: string;
begin
if TarHost <> '' then
Result := TarHost
else
Result := Inherited GetDisplayName
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TProxyClient }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TProxyClient.Create(Owner: TComponent);
begin
inherited Create(Owner);
FTarSocket := TSslWSocket.Create(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TProxyClient.Destroy;
begin
FreeAndNil(FTarSocket) ;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.LogEvent(const Msg : String);
begin
if Assigned (FProxySource.FonProxyProg) then
FProxySource.LogProgEvent(FLogDescr + Msg);
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.LogSrcEvent(const Msg : String);
var
dur: Integer;
begin
if Assigned (FProxySource.FonProxyProg) then begin
dur := IcsCalcTickDiff(Self.Counter.ConnectTick, IcsGetTickCount);
LogEvent('Source ' + FloatToStrF (dur / 1000, ffFixed, 7, 2) + ' - ' + Msg);
end;
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.LogTarEvent(const Msg : String);
var
dur: Integer;
begin
if Assigned (FProxySource.FonProxyProg) then begin
dur := IcsCalcTickDiff(FTarSocket.Counter.ConnectTick, IcsGetTickCount);
LogEvent('Target ' + FloatToStrF (dur / 1000, ffFixed, 7, 2) + ' - ' + Msg);
end;
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send buffered data to remote target }
procedure TProxyClient.TargetBufXmit(SendNr: Integer);
var
DataPtr: Pointer;
DataLen: Integer;
begin
if (FTarSocket.State <> wsConnected) then Exit ;
if (FSrcWaitTot <= 0) then Exit;
if (SendNr > FSrcWaitTot) then SendNr := FSrcWaitTot;
DataPtr := @FSrcBuffer[0];
DataLen := SendNr;
if Assigned(FProxySource.FOnDataSendTar) then begin
FProxySource.FOnDataSendTar(FProxySource, Self, DataPtr, DataLen);
if NOT Assigned(DataPtr) then DataLen := 0; // sanity test
end;
if (DataLen > 0) then
FTarSocket.Send(DataPtr, DataLen);
{ remove what we sent from buffer }
FSrcWaitTot := FSrcWaitTot - SendNr;
if FSrcWaitTot > 0 then
MoveTBytes(FSrcBuffer, SendNr, 0, FSrcWaitTot);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ receive as much data from remote target as buffer will take }
procedure TProxyClient.TargetBufRecv;
var
RxRead, RxCount, LoopCounter: Integer;
begin
LoopCounter := 0;
if FTarWaitTot < 0 then FTarWaitTot := 0; // sanity check
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
RxCount := FTarBufMax - FTarWaitTot - 1;
if RxCount <= 0 then Exit; // sanity check
RxRead := FTarSocket.Receive (@FTarBuffer[FTarWaitTot], RxCount);
if RxRead <= 0 then Exit; // nothing read
FTarWaitTot := FTarWaitTot + RxRead;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send buffered data to source server }
procedure TProxyClient.SourceBufXmit(SendNr: Integer);
var
DataPtr: Pointer;
DataLen: Integer;
begin
if (Self.State <> wsConnected) then Exit ;
if (FTarWaitTot <= 0) then Exit;
if (SendNr > FTarWaitTot) then SendNr := FTarWaitTot;
DataPtr := @FTarBuffer[0];
DataLen := SendNr;
if Assigned(FProxySource.FOnDataRecvTar) then begin
FProxySource.FOnDataRecvTar(FProxySource, Self, DataPtr, DataLen);
if NOT Assigned(DataPtr) then DataLen := 0; // sanity test
end;
if (DataLen > 0) then
Self.Send(DataPtr, DataLen);
{ remove what we sent from buffer }
FTarWaitTot := FTarWaitTot - SendNr;
if FTarWaitTot > 0 then
MoveTBytes(FTarBuffer, SendNr, 0, FTarWaitTot);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ receive as much data from source server as buffer will take }
procedure TProxyClient.SourceBufRecv;
var
RxRead, RxCount, LoopCounter: Integer;
begin
LoopCounter := 0;
if FSrcWaitTot < 0 then FSrcWaitTot := 0; // sanity check
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
RxCount := FSrcBufMax - FSrcWaitTot - 1;
if RxCount <= 0 then Exit; // sanity check
RxRead := Self.Receive (@FSrcBuffer[FSrcWaitTot], RxCount);
if RxRead <= 0 then Exit; // nothing read
FSrcWaitTot := FSrcWaitTot + RxRead;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ receive data from source server, and send to remote target }
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.SourceXferData;
var
LoopCounter: Integer;
begin
LoopCounter := 0;
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('Forwarding data to target');
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
if (FTarSocket.State <> wsConnected) then Exit;
SourceBufRecv;
if FSrcWaitTot = 0 then Exit; // nothing to send
TargetBufXmit(FSrcWaitTot);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.TargetXferData;
var
LoopCounter: Integer;
begin
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('Forwarding data to source');
LoopCounter := 0;
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
if (Self.State <> wsConnected) then Exit;
TargetBufRecv;
if FTarWaitTot = 0 then Exit; // nothing to send
SourceBufXmit(FTarWaitTot);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.SourceDataAvailable(Sender: TObject; Error: Word);
begin
{ target already connected, send data immediately }
if (FTarSocket.State = wsConnected) or FTarHttp then
SourceXferData
else begin
{ target not connected, buffer data until we can xfer it }
SourceBufRecv;
{ if we got something, see if need a new target connection }
if (FSrcWaitTot > 0) then begin
if (FProxySource.DebugLevel >= DebugAll) then begin
if FClosingFlag then
LogSrcEvent('Warning, received data while tryinmg to close')
else
LogSrcEvent('Received data before target connected, bytes ' + IntToStr(FSrcWaitTot));
end;
{ start another target connection if last one closed }
if (FTarCurHost <> '') and { (NOT FTarConnecting) and }
(FTarSocket.State in [wsClosed, wsInvalidState]) then begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Starting new target connection');
if NOT TargetConnect then begin
FClosingFlag := True;
Close;
end;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ triggered when all target data forwarded to client, see if closing client }
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.SourceDataSent(Sender: TObject; ErrCode : Word);
begin
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.SourceSessionClosed(Sender: TObject; Error: Word);
begin
FSrcPendClose := False;
if FTarSocket.State = wsConnected then FTarSocket.Close;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetInitialiase;
begin
{ setup client server socket to receive data }
Self.OnDataAvailable := SourceDataAvailable;
Self.OnDataSent := SourceDataSent;
Self.OnSessionClosed := SourceSessionClosed;
Self.OnBgException := FProxySource.SocketBgException;
Self.CreateCounter;
Self.Counter.SetConnected;
{ setup remote targer socket to which we connect and send data }
FTarSocket.SslContext := FProxySource.FTarSslCtx;
FTarSocket.SslMode := sslModeClient;
FTarSocket.Proto := 'tcp';
FTarSocket.OnDataAvailable := TargetDataAvailable;
FTarSocket.OnSessionClosed := TargetSessionClosed;
// FTarSocket.OnDnsLookupDone := TargetDnsLookupDone;
FTarSocket.OnSessionConnected := TargetSessionConnected;
FTarSocket.OnSslCliNewSession := TargetCliNewSession;
FTarSocket.OnSslCliGetSession := TargetCliGetSession;
FTarSocket.OnSslVerifyPeer := TargetVerifyPeer;
FTarSocket.OnSslHandshakeDone := TargetHandshakeDone;
FTarSocket.IcsLogger := FProxySource.FIcsLog;
FTarSocket.LingerOnOff := wsLingerOff;
FTarSocket.LingerTimeout := 0;
FTarSocket.LineMode := false;
FTarSocket.OnBgException := FProxySource.SocketBgException;
{ important, set AsyncDnsLookup so we don't need OnDnsLookup event }
FTarSocket.ComponentOptions := [wsoNoReceiveLoop, wsoAsyncDnsLookup, wsoIcsDnsLookup];
FTarSocket.LocalAddr := FProxySource.FLocalAddr;
FTarSocket.Addr := '';
FTarSocket.SocketErrs := wsErrFriendly;
FTarSocket.CreateCounter;
FTarSocket.Counter.SetConnected;
{ buffers to receive data }
FSrcBufMax := FProxySource.RxBuffSize;
FTarBufMax := FProxySource.RxBuffSize;
SetLength(FSrcBuffer, FSrcBufMax + 1);
SetLength(FTarBuffer, FTarBufMax + 1);
FSrcWaitTot := 0;
FTarWaitTot := 0;
{ other stuff }
// FTarConnecting := False;
FSrcPendClose := False;
FTarCurHost := '';
FTarClosedFlag := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ log source, find target according to HostTag }
procedure TProxyClient.TargetCheck;
begin
Self.FLogDescr := FProxySource.IcsHosts[IcsHostIdx].Descr +
' (' + IntToStr (FCliId) + ') ';
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Host #' + IntToStr(FIcsHostIdx) + ' ' + FSrcHost +
' - ' + FHostTag + ', Listener ' + CServerAddr + ':' + CServerPort);
{ find ProxyTarget may change later if checking path in HTTP header }
FPxyTargetIdx := FProxySource.FindPxyTarget(FHostTag);
if FPxyTargetIdx < 0 then begin { should have been checked earlier }
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Host #' + IntToStr(FIcsHostIdx) + ' -' +
FHostTag + ', no matching proxy target found');
FClosingFlag := True;
Self.Close;
exit;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ sets target host and stuff from ProxyTarget collection }
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.TargetSpecify;
begin
if FPxyTargetIdx < 0 then Exit;
FTarSocket.Counter.SetConnected; // reset
with FProxySource.ProxyTargets[FPxyTargetIdx] do begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Target #' + IntToStr(FPxyTargetIdx) + ' - ' +
TarHost + ':' + IntToStr(TarPort));
Self.FTarHost := TarHost;
self.FTarPort := IntToStr(TarPort);
Self.FTarSsl := TarSsl;
Self.FIdleTimeout := IdleTimeout;
end;
{ if IcsHost specified both non-SSL and SSL port, don't change SSL method }
with FProxySource.IcsHosts[IcsHostIdx] do begin
if (BindSslPort = 443) and (BindNonPort = 80) then begin
Self.FTarSsl := SslEnable;
Self.FTarPort := CServerPort;
end;
end;
{ let application change target before we connect }
if Assigned(FProxySource.FOnSetTarget) then begin
FProxySource.FOnSetTarget(FProxySource, Self);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TProxyClient.TargetConnect: Boolean;
begin
Result := True;
if (FTarSocket.State = wsConnected) then Exit;
// if FTarConnecting then Exit;
if (FTarHost = '') or (FTarPort = '') then begin
LogSrcEvent('Failed to Target #' +
IntToStr(FPxyTargetIdx) + ' - Host and/or Port Blank');
Result := False;
exit;
end;
FTarClosedFlag := False;
FTarSocket.Counter.SetConnected; // reset
FTarCurHost := FTarHost; // used to see if need to reconnect later
FTarSocket.SslEnable := FTarSsl;
FTarSocket.SslServerName := FTarHost; // SNI
{ localhost fails if real local address used }
if (FTarHost = ICS_LOCAL_HOST_V4) or (IcsLowerCase(FTarHost) = 'localhost') then
FTarSocket.LocalAddr := ICS_ANY_HOST_V4;
if (FProxySource.DebugLevel >= DebugConn) then begin
if FPxyTargetIdx >= 0 then
LogSrcEvent('Connecting to Target #' +
IntToStr(FPxyTargetIdx) + ' - ' + FTarHost + ':' + FTarPort)
else
LogSrcEvent('Connecting to conditional Target - ' + FTarHost + ':' + FTarPort);
end ;
try
FTarSocket.Addr := FTarHost; // use for new internal lookup
FTarSocket.Port := FTarPort;
FTarSocket.Connect;
Result := True;
except
on E:Exception do begin
LogSrcEvent('Target connection error: ' + E.Message);
Result := False;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetSessionConnected(Sender: TObject; Error: Word);
begin
try
if (Error <> 0) then begin
if (FProxySource.DebugLevel >= DebugConn) then begin
{ see if we looked up a DNS address, that might be silly }
if (FTarSocket.DnsResult <> '') then
LogTarEvent('Remote IP Adress ' + FTarSocket.DnsResult);
LogTarEvent('Remote connection failed (' + WSocketErrorDesc(Error) + ')');
end;
if Assigned(FProxySource.FOnTarConnect) then
FProxySource.FOnTarDisconnect(FProxySource, Self, Error);
Self.Close;
Exit;
end;
FTarSocket.Counter.SetConnected;
FTarIP := FTarSocket.GetPeerAddr; // keep looked-up IP>
if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Remote IP Adress ' + FTarIP);
if Assigned(FProxySource.FOnTarConnect) then
FProxySource.FOnTarDisconnect(FProxySource, Self, Error);
if FTarSocket.SslEnable then begin
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('Remote starting SSL handshake to ' + FTarHost);
FTarSocket.StartSslHandshake;
end
else begin
if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Remote connection OK to ' + FTarHost);
PostMessage(FProxySource.Handle, FProxySource.FMsg_TARGET_CONNECTED, 0, LPARAM(Self))
end;
except
on E:Exception do begin
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('Remote start SSL handshake error: ' + E.Message);
Self.Close;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetVerifyPeer(Sender: TObject; var Ok : Integer; Cert: TX509Base);
begin
OK := 1; // check certificate later
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetHandshakeDone(Sender: TObject; ErrCode: Word;
PeerCert: TX509Base; var Disconnect : Boolean);
var
CertChain: TX509List;
ChainVerifyResult: LongWord;
Hash, info, VerifyInfo: String;
Safe: Boolean;
begin
with Sender as TSslWSocket do begin
if (ErrCode <> 0) or Disconnect then begin
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('Remote SSL handshake failed - ' + SslHandshakeRespMsg);
Disconnect := TRUE;
CloseDelayed;
exit;
end ;
if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Remote connection OK to ' + FTarHost + ' - ' + SslHandshakeRespMsg) ;
PostMessage(FProxySource.Handle, FProxySource.FMsg_TARGET_CONNECTED, 0, LPARAM(Self));
{ it don't need to check SSL certificate, escape here }
if SslSessionReused OR (FProxySource.CertVerTar = CertVerNone) then begin
exit;
end ;
{ don't check localhost certificate, we trust our own server }
if (FTarHost = ICS_LOCAL_HOST_V4) or (IcsLowerCase(FTarHost) = 'localhost') then begin
exit;
end ;
{ Is current host already in the list of temporarily accepted hosts ? }
Hash := PeerCert.Sha1Hex ;
if (FProxySource.FTarSslCertList.IndexOf(SslServerName + Hash ) > -1) then begin
exit;
end ;
{ Property SslCertChain contains all certificates in current verify chain }
CertChain := SslCertChain;
{ see if validating against Windows certificate store }
if FProxySource.CertVerTar = CertVerWinStore then begin
{ start engine }
if not Assigned (FProxySource.FMsCertChainEngine) then
FProxySource.FMsCertChainEngine := TMsCertChainEngine.Create;
{ see if checking revoocation, CRL checks and OCSP checks in Vista+, very slow!!!! }
if FProxySource.SslRevocation then
FProxySource.FMsCertChainEngine.VerifyOptions := [mvoRevocationCheckChainExcludeRoot]
else
FProxySource.FMsCertChainEngine.VerifyOptions := [];
{ This option doesn't seem to work, at least when a DNS lookup fails }
FProxySource.FMsCertChainEngine.UrlRetrievalTimeoutMsec := 10 * 1000;
{ Pass the certificate and the chain certificates to the engine }
FProxySource.FMsCertChainEngine.VerifyCert (PeerCert, CertChain, ChainVerifyResult, True);
Safe := (ChainVerifyResult = 0) or
{ We ignore the case if a revocation status is unknown. }
(ChainVerifyResult = CERT_TRUST_REVOCATION_STATUS_UNKNOWN) or
(ChainVerifyResult = CERT_TRUST_IS_OFFLINE_REVOCATION) or
(ChainVerifyResult = CERT_TRUST_REVOCATION_STATUS_UNKNOWN or
CERT_TRUST_IS_OFFLINE_REVOCATION);
{ The MsChainVerifyErrorToStr function works on chain error codes }
VerifyInfo := MsChainVerifyErrorToStr (ChainVerifyResult);
{ MSChain ignores host name, so see if it failed using OpenSSL }
if PeerCert.VerifyResult = X509_V_ERR_HOSTNAME_MISMATCH then begin
Safe := False;
VerifyInfo := PeerCert.FirstVerifyErrMsg;
end;
end
else if FProxySource.CertVerTar = CertVerBundle then begin
VerifyInfo := PeerCert.FirstVerifyErrMsg;
{ check whether SSL chain verify result was OK }
Safe := (PeerCert.VerifyResult = X509_V_OK);
end
else begin
exit; // unknown method
end ;
{ allow self signed certs }
if (CertChain.Count > 0) and (CertChain[0].FirstVerifyResult =
X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) then begin
Safe := true;
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('SSL self signed certificate succeeded: ' +
PeerCert.UnwrapNames (PeerCert.IssuerCName));
end;
{ tell user verification failed }
if (FProxySource.DebugLevel >= DebugConn) and (NOT Safe) then begin
info := 'SSL chain verification failed: ' + VerifyInfo + ', Domain: ';
if PeerCert.SubAltNameDNS = '' then
info := info + IcsUnwrapNames(PeerCert.SubjectCName)
else
info := info + IcsUnwrapNames(PeerCert.SubAltNameDNS);
info := info + ', Expected: ' + SslServerName;
LogTarEvent(info);
end
{ check certificate was issued to remote host for out connection }
else begin
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('SSL chain verification succeeded, Domain: ' + SslCertPeerName);
end;
{ if certificate checking failed, see if the host is specifically listed as being allowed anyway }
if (NOT Safe) and (FProxySource.FTarSslCertList.IndexOf(SslServerName) > -1) then begin
Safe := true;
if (FProxySource.DebugLevel >= DebugSsl) then
LogTarEvent('SSL succeeded with acceptable Host Name');
end;
{ keep this server name and certificate in server list to stop if being check again for a few hours }
if Safe then begin
FProxySource.FTarSslCertList.Add(SslServerName + Hash);
end;
{ tell user about all the certificates we found }
if (FProxySource.DebugLevel >= DebugSsl) and
(FProxySource.SslReportChain) and (CertChain.Count > 0) then begin
if (FProxySource.CertVerTar = CertVerWinStore) then
info := 'Verify result: ' + MsCertVerifyErrorToStr(CertChain[0].CustomVerifyResult) + #13#10
else
info := 'Verify result: ' + CertChain[0].FirstVerifyErrMsg + #13#10 ;
info := info + IntToStr(CertChain.Count) + ' SSL certificates in the verify chain:' +
#13#10 + CertChain.AllCertInfo (true, true) ;
LogTarEvent(info);
end;
{ all failed, die }
if NOT Safe then
begin
Disconnect := TRUE;
exit ;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetDataAvailable(Sender: TObject; Error: Word);
begin
if Self.State = wsConnected then
TargetXferData
else begin
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Send data after source server disconnected');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ !!! might not need this }
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.TargetDataSent(Sender: TObject; ErrCode : Word);
begin
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetCliNewSession(Sender: TObject; SslSession: Pointer;
WasReused: Boolean; var IncRefCount : Boolean);
begin
if NOT Assigned (FProxySource.SslSessCache) then exit;
if (NOT WasReused) then begin
with Sender as TSslWSocket do
FProxySource.SslSessCache.CacheCliSession(SslSession, PeerAddr + PeerPort, IncRefCount);
if (FProxySource.DebugLevel >= DebugSsl) then LogTarEvent('SSL New Session');
end
else begin
if (FProxySource.DebugLevel >= DebugSsl) then LogTarEvent('SSL Session Reused');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TProxyClient.TargetCliGetSession(Sender: TObject;
var SslSession: Pointer; var FreeSession : Boolean);
begin
if NOT Assigned (FProxySource.SslSessCache) then exit;
with Sender as TSslWSocket do
SslSession := FProxySource.SslSessCache.GetCliSession(PeerAddr + PeerPort, FreeSession);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ note this is overwritten for the HTTP client, it's more compicated }
procedure TProxyClient.TargetSessionClosed(Sender: TObject; Error: Word);
begin
FTarClosedFlag := True;
if (Self.State = wsConnected) and (FTarWaitTot <> 0) then
TargetXferData;
if (FProxySource.DebugLevel >= DebugConn) then begin
if (Error = 0) or (Error = 10053) then
LogTarEvent('Remote closed, Data sent ' +
IntToStr (FTarSocket.WriteCount) + ', Data recvd ' + IntToStr (FTarSocket.ReadCount))
else
LogTarEvent('Remote lost (' + WSocketErrorDesc(Error) + '), Data sent ' +
IntToStr (FTarSocket.WriteCount) + ', Data recvd ' + IntToStr (FTarSocket.ReadCount));
end;
if Assigned(FProxySource.FOnTarDisconnect) then
FProxySource.FOnTarDisconnect(FProxySource, Self, Error);
if (NOT FClosingFlag) then begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Client closing after target');
Self.CloseDelayed;
FClosingFlag := True;
end
else if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Client already closing');
FDelayedDisconn := false;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsProxy main proxy component }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsProxy.Create(Owner: TComponent);
begin
inherited Create(Owner);
{ several component properties set FSourceServer so it must be created
first and never freed }
FSourceServer := TSslWSocketServer.Create(Self);
FSourceServer.ClientClass := TProxyClient;
FProxyTargets := TProxyTargets.Create(Self);
FTarSslCtx := TSslContext.Create(Self);
FTarSslCertList := TStringList.Create;
FTarSecLevel := sslSecLevel80bits;
FCertVerTar := CertVerNone;
FDebugLevel := DebugSsl;
FSocketErrs := wsErrFriendly;
FMaxClients := 999;
FRxBuffSize := DefRxBuffSize;
FMsCertChainEngine := Nil;
FIcsLog := TIcsLogger.Create (nil);
FIcsLog.OnIcsLogEvent := IcsLogEvent;
FIcsLog.LogOptions := [loDestEvent];
FCurDate := Trunc(Date);
FFlushTick := IcsGetTickCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsProxy.Destroy;
begin
Stop;
FreeAndNil(FMsCertChainEngine);
FreeAndNil(FTarSslCtx);
FreeAndNil(FProxyTargets);
FreeAndNil(FTarSslCertList);
FreeAndNil(FSourceServer);
FreeAndNil(FCleanupTimer);
FreeAndNil(FIcsLog);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.MsgHandlersCount : Integer;
begin
Result := 1 + inherited MsgHandlersCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.AllocateMsgHandlers;
begin
inherited AllocateMsgHandlers;
FMsg_TARGET_CONNECTED := FWndHandler.AllocateMsgHandler(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.FreeMsgHandlers;
begin
if Assigned(FWndHandler) then
FWndHandler.UnregisterMessage(FMsg_TARGET_CONNECTED);
inherited FreeMsgHandlers;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.WndProc(var MsgRec: TMessage);
var
CanClose: boolean;
begin
with MsgRec do begin
if Msg = FMsg_TARGET_CONNECTED then begin
{ We *MUST* handle all exception to avoid application shutdown }
try
WMTargetConnected(MsgRec)
except
on E:Exception do
SocketBgException(Self, E, CanClose);
end;
end
else
inherited WndProc(MsgRec);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.IcsLogEvent(Sender: TObject; LogOption: TLogOption;
const Msg : String);
begin
if Assigned (FonProxyProg) then FonProxyProg(Self, LogOption, Msg) ;
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.LogProgEvent(const Msg : String);
begin
if Assigned (FonProxyProg) then FonProxyProg(Self, loProtSpecInfo, Msg) ;
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.LogErrEvent(const Msg : String);
begin
if Assigned (FonProxyProg) then FonProxyProg(Self, loProtSpecErr, Msg) ;
end ;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.SetProxyTargets(const Value: TProxyTargets);
begin
FProxyTargets.Assign(Value);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.GetIcsHosts: TIcsHostCollection;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.GetIcsHosts
else
Result := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.SetIcsHosts(const Value: TIcsHostCollection);
begin
if Assigned(FSourceServer) then FSourceServer.SetIcsHosts(Value);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.GetRootCA: String;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.RootCA
else
Result := '';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.SetRootCA(const Value: String);
begin
if Assigned(FSourceServer) then FSourceServer.RootCA := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.GetDHParams: String;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.DHParams
else
Result := '';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.SetDHParams(const Value: String);
begin
if Assigned(FSourceServer) then FSourceServer.DHParams := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.ValidateHosts(Stop1stErr: Boolean=True;
NoExceptions: Boolean=False): String;
var
I, J, K: Integer;
HTag: String;
begin
Result := '';
if Assigned(FSourceServer) then begin
Result := TSslWSocketServer(FSourceServer).ValidateHosts(Stop1stErr, NoExceptions);
{ each IcsHost must have at least one matching Target HostTag }
for I := 0 to IcsHosts.Count - 1 do begin
if NOT IcsHosts[I].HostEnabled then Continue;
if IcsHosts[I].ForwardProxy then Continue; // no target needed
HTag := IcsHosts[I].HostTag;
J := FindPxyTarget(HTag);
if (J < 0) then begin
Result := Result + 'Host ' + IntToStr(I) +
HTag + ', no matching proxy target found';
if Stop1stErr then raise ESocketException.Create(Result);
continue;
end;
{ check source tag is not a duplicate }
if I > 0 then begin
for K := 0 to I - 1 do begin
if NOT IcsHosts[K].HostEnabled then Continue;
if HTag = IcsHosts[K].HostTag then begin
Result := Result + 'Host ' + IntToStr(I) +
HTag + ' is a duplicate';
if Stop1stErr then raise ESocketException.Create(Result);
continue;
end;
end;
end;
if Assigned(FSslSessCache) then begin
IcsHosts[I].SslCtx.SslSessionCacheModes := [sslSESS_CACHE_CLIENT,
sslSESS_CACHE_NO_INTERNAL_LOOKUP, sslSESS_CACHE_NO_INTERNAL_STORE];
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.RecheckSslCerts(var CertsInfo: String;
Stop1stErr: Boolean=True; NoExceptions: Boolean=False): Boolean;
begin
Result := False;
if Assigned(FSourceServer) then begin
Result := TSslWSocketServer(FSourceServer).RecheckSslCerts(CertsInfo,
Stop1stErr, NoExceptions);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.ListenAllOK: Boolean;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.ListenAllOK
else
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.ListenStates: String;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.ListenStates
else
Result := '';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.GetRunning: Boolean;
begin
if Assigned(FSourceServer) then
Result := (FSourceServer.State = wsListening)
else
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsProxy.GetClientCount: Integer;
begin
if Assigned(FSourceServer) then
Result := FSourceServer.ClientCount
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ find first enabled matching proxy target, there may be more than one ! }
function TIcsProxy.FindPxyTarget(const Tag: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to ProxyTargets.Count - 1 do begin
if NOT ProxyTargets[I].HostEnabled then Continue;
if ProxyTargets[I].HostTag = Tag then begin
Result := I;
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ find matching proxy target, checking hostname, no change if not found }
function TIcsProxy.FindPxySourceHost(const HHostName: String; MLIndx: Integer): Integer;
var
I, J: Integer;
begin
Result := -1;
if IcsHosts.Count > 0 then begin
for I := 0 to IcsHosts.Count - 1 do begin
with IcsHosts[I] do begin
if NOT HostEnabled then continue;
if ((BindIdxNone = MLIndx) or (BindIdx2None = MLIndx) or
(BindIdxSsl = MLIndx) or (BindIdx2Ssl = MLIndx)) and
(HostNameTot > 0) then begin
for J := 0 to HostNameTot - 1 do begin
if ((HostNames[J] = '*') or
(HostNames[J] = HHostName)) then begin
Result := I;
Exit;
end;
end;
end;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.Start;
var
I: Integer;
begin
{ If already listening, then do nothing }
if FSourceServer.State = wsListening then Exit;
{ without these collections, nothing will work }
if IcsHosts.Count = 0 then begin
raise ESocketException.Create('Must specify Proxy Server Listen Hosts');
exit ;
end;
if ProxyTargets.Count = 0 then begin
raise ESocketException.Create('Must specify Proxy Server Targets');
exit ;
end;
{ each IcsHost must have at least one matching Target HostTag }
if Assigned(FSslSessCache) then begin
for I := 0 to IcsHosts.Count - 1 do begin
IcsHosts[I].SslCtx.SslSessionCacheModes := [sslSESS_CACHE_CLIENT,
sslSESS_CACHE_NO_INTERNAL_LOOKUP, sslSESS_CACHE_NO_INTERNAL_STORE];
end;
end;
{ allocates message windows and numbers in TIcsWndControl, needed before TIcsTimer }
Self.Handle;
{ single SslContext for all target sockets }
FTarSslCtx.IcsLogger := FIcsLog;
FTarSslCtx.SslSessionCacheModes := [];
if Assigned(FSslSessCache) then begin
FTarSslCtx.SslSessionCacheModes := [sslSESS_CACHE_CLIENT,
sslSESS_CACHE_NO_INTERNAL_LOOKUP, sslSESS_CACHE_NO_INTERNAL_STORE];
end;
FTarSslCtx.SslVerifyPeer := false;
FTarSslCtx.SslVerifyPeerModes := [] ;
FTarSslCtx.SslSecLevel := FTarSecLevel;
if FCertVerTar > CertVerNone then begin
FTarSslCtx.SslVerifyPeer := true;
FTarSslCtx.SslVerifyPeerModes := [SslVerifyMode_PEER];
end;
FTarSslCtx.SslVersionMethod := sslBestVer_CLIENT ;
FTarSslCtx.SslMinVersion := sslVerTLS1;
FTarSslCtx.SslMaxVersion := sslVerMax;
FTarSslCtx.SslECDHMethod := sslECDHAuto;
FTarSslCtx.SslCipherList := sslCiphersNoDH;
FTarSslCtx.SslOptions := [];
if RootCA <> '' then begin
if (Pos(PEM_STRING_HDR_BEGIN, RootCA) > 0) then
FTarSslCtx.SslCALines.Text := RootCA
else
FTarSslCtx.SslCAFile := RootCA;
end;
FTarSslCtx.InitContext;
{ setup SocketServer events and properties, start it }
with FSourceServer do begin
OnClientCreate := ServerClientCreate;
OnClientConnect := ServerClientConnect;
OnClientDisconnect := ServerClientDisconnect;
SslMode := sslModeServer;
OnSslVerifyPeer := ServerVerifyPeer;
OnSslSetSessionIDContext := ServerSetSessionIDContext;
OnSslSvrNewSession := ServerSvrNewSession;
OnSslSvrGetSession := ServerSvrGetSession;
OnSslHandshakeDone := ServerHandshakeDone;
OnSslServerName := ServerServerName;
Banner := ''; { must not send anything upon connect }
BannerTooBusy := '';
Proto := 'tcp';
MaxClients := FMaxClients;
ExclusiveAddr := FExclusiveAddr;
SocketErrs := FSocketErrs;
IcsLogger := FIcsLog;
CreateCounter;
MultiListen; { listen on multiple sockets, if more than one configured }
{ Warning - need to check all sockets are actually listening, conflicts are ignored }
if FSourceServer.ListenAllOK then
LogProgEvent('Proxy server started listening OK' +
cCRLF + FSourceServer.ListenStates)
else
LogProgEvent('Proxy server failed to start listening' +
cCRLF + FSourceServer.ListenStates);
end;
if NOT Assigned(FCleanupTimer) then begin
FCleanupTimer := TIcsTimer.Create(Self);
FCleanupTimer.OnTimer := CleanupTimerOnTimer;
FCleanupTimer.Interval := 5000;
end;
FCleanupTimer.Enabled := True;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.Stop;
begin
if not Assigned(FSourceServer) then Exit;
if FSourceServer.State = wsListening then begin
FCleanupTimer.Enabled := False;
FSourceServer.MultiClose;
LogProgEvent('Proxy server stopped listening');
{ Disconnect all clients }
FSourceServer.DisconnectAll;
{ may take a while for all connections to cease, you should
wait until ClientCount drops to zero }
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.SocketBgException(Sender: TObject; E: Exception; var CanClose: Boolean);
begin
LogErrEvent('Socket Bg Exception - ' + E.Message);
CanClose := true ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerClientCreate(Sender : TObject; Client : TWSocketClient);
begin
// do we need to do anythinf before ClientConnect??
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerClientConnect(Sender: TObject; Client: TWSocketClient; Error: Word);
var
MyClient: TProxyClient;
begin
MyClient := Client as TProxyClient;
MyClient.FProxySource := Self; // before logging
try
if Error <> 0 then begin
if Assigned(FOnSrcConnect) then
FOnSrcConnect(Sender, Client, Error);
LogErrEvent('Source listen connect error: ' + WSocketErrorDesc(Error));
MyClient.FClosingFlag := True;
MyClient.Close;
exit;
end;
{ create target socket, sets up event handlers and buffers, and counters }
MyClient.FPxyTargetIdx := -1; // not found yet, may be forward proxy without one
MyClient.FLogDescr := IcsHosts[MyClient.IcsHostIdx].Descr +
' (' + IntToStr (MyClient.CliId) + ') ';
MyClient.FTarHttp := (Pos('HTTP', IcsHosts[MyClient.IcsHostIdx].Proto) = 1);
MyClient.FForwardPrxy := IcsHosts[MyClient.IcsHostIdx].ForwardProxy;
if MyClient.FForwardPrxy then MyClient.FTarConditional := True;
MyClient.TargetInitialiase; { no LogDurEvent before this }
{ application may be interested }
if Assigned(FOnSrcConnect) then
FOnSrcConnect(Sender, Client, Error);
{ is source SSL connection - note SocketServer starts handshake }
{ note MyClient.FPxyTargetIdx may be changed when SNI is checked for SSL }
if MyClient.SslEnable then begin
if (DebugLevel >= DebugSsl) then
MyClient.LogSrcEvent('Client SSL handshake start from ' + MyClient.CPeerAddr);
end
else begin
if (DebugLevel >= DebugConn) then
MyClient.LogSrcEvent('Client connection from ' + MyClient.CPeerAddr);
{ check HTTP Host: header later }
if NOT MyClient.FTarHttp then begin
MyClient.FSrcHost := IcsHosts[MyClient.IcsHostIdx].HostNames [0];
MyClient.TargetCheck;
{ start target connection, beware server may be receive data before it connects }
MyClient.TargetSpecify;
if NOT MyClient.TargetConnect then begin
MyClient.FClosingFlag := True;
MyClient.Close;
end;
end;
end;
except
on E:Exception do begin
LogErrEvent('Source server connect exception: ' + E.Message);
MyClient.FClosingFlag := True;
MyClient.Close;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerClientDisconnect(Sender: TObject; Client: TWSocketClient; Error: Word);
begin
try
if Assigned(FOnSrcDisconnect) then
FOnSrcDisconnect(Sender, Client, Error);
if Assigned (Client) then begin
with Client as TProxyClient do begin
if (DebugLevel >= DebugConn) then begin
if (Error = 0) or (Error = 10053) then
LogSrcEvent('Client disconnection from ' + CPeerAddr +
', Data sent ' + IntToStr(WriteCount) + ', Data recvd ' + IntToStr(ReadCount))
else
LogSrcEvent('Client disconnection from ' + CPeerAddr + ': ' + WSocketErrorDesc(Error) +
', Data sent ' + IntToStr(WriteCount) + ', Data recvd ' + IntToStr(ReadCount)) ;
end;
end
end
else begin
if (DebugLevel >= DebugConn) then
LogProgEvent('Source client disconnection: ' + WSocketErrorDesc(Error));
end;
except
on E:Exception do begin
LogErrEvent('Source client disconnection exception: ' + E.Message);
end;
end;
end;
procedure TIcsProxy.ServerServerName(Sender: TObject; var Ctx: TSslContext; var ErrCode: TTlsExtError);
begin
if (DebugLevel >= DebugSsl) then begin
with Sender as TProxyClient do
LogSrcEvent('Client SNI: ' + SslServerName);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerSetSessionIDContext(Sender : TObject;
var SessionIDContext : TSslSessionIdContext);
begin
{ Tell Openssl a Session_ID_Context. }
{ Openssl uses this data to tag a session before it's cached. }
SessionIDContext := Ssl_Session_ID_Context;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerSvrNewSession(Sender: TObject; SslSession, SessId: Pointer;
Idlen: Integer; var AddToInternalCache: Boolean);
var
LookupKey : string;
MyClient: TProxyClient;
begin
if NOT Assigned(FSslSessCache) then Exit;
MyClient := Sender as TProxyClient;
{$IFDEF UNICODE}
{ We need to get binary data into a UnicodeString, allocate enough space. }
{ Not nice, however works in this case. }
SetLength(LookupKey, (IDLen div 2) + (IdLen mod 2));
{$ELSE}
SetLength(LookupKey, IDLen);
{$ENDIF}
Move(SessId^, Pointer(LookupKey)^, IDLen);
FSslSessCache.CacheSvrSession(SslSession, LookupKey + Ssl_Session_ID_Context, AddToInternalCache);
if (DebugLevel >= DebugSsl) then
MyClient.LogSrcEvent('Client new SSL session created and cached');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerSvrGetSession(Sender: TObject; var SslSession: Pointer; SessId: Pointer;
Idlen: Integer; var IncRefCount: Boolean);
var
LookupKey : string;
begin
if NOT Assigned(FSslSessCache) then Exit;
{$IFDEF UNICODE}
{ We need to get binary data into a UnicodeString, allocate enough space. }
{ Not nice, however works in this case. }
SetLength(LookupKey, (IDLen div 2) + (IdLen mod 2));
{$ELSE}
SetLength(LookupKey, IDLen);
{$ENDIF}
Move(SessId^, Pointer(LookupKey)^, IDLen);
SslSession := FSslSessCache.GetSvrSession(LookupKey + Ssl_Session_ID_Context, IncRefCount);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerVerifyPeer(Sender: TObject; var Ok : Integer; Cert: TX509Base);
begin
OK := 1; // don't check certificate for server
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.ServerHandshakeDone(Sender: TObject; ErrCode: Word;
PeerCert: TX509Base; var Disconnect : Boolean);
var
MyClient: TProxyClient;
begin
try
MyClient := Sender as TProxyClient;
if (ErrCode <> 0) or Disconnect then begin
if (DebugLevel >= DebugSsl) then
MyClient.LogSrcEvent('Client SSL handshake failed: ' + MyClient.SslHandshakeRespMsg);
Disconnect := TRUE;
end
else begin
if (DebugLevel >= DebugSsl) then
MyClient.LogSrcEvent('Client ' + MyClient.SslHandshakeRespMsg);
{ check HTTP Host: header later }
if NOT MyClient.FTarHttp then begin
MyClient.FSrcHost := MyClient.SslServerName;
MyClient.TargetCheck;
{ start target connection, beware server may be receive data before it connects }
MyClient.TargetSpecify;
if NOT MyClient.TargetConnect then begin
MyClient.FClosingFlag := True;
MyClient.Close;
end;
end;
end;
except
on E:Exception do begin
LogErrEvent('Source listen SSL handshake exception: ' + E.Message);
Disconnect := TRUE;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.WMTargetConnected(var msg: TMessage);
var
MyClient: TProxyClient;
Resp: String;
begin
MyClient := TProxyClient(Msg.LParam);
if NOT Assigned (MyClient) then exit;
if NOT MyClient.FTunnelling then begin
MyClient.SourceXferData;
end
else begin
Resp := 'HTTP/1.1 200 Connection established' + cCRLF +
'Server: Proxy' + cDoubleCRLF;
MyClient.LogSrcEvent('Sending Response to Source: ' + cCRLF + Resp);
MyClient.SendText (Resp);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsProxy.CleanupTimerOnTimer(Sender : TObject);
var
MyClient: TProxyClient;
I, Timeout, Duration : integer;
CurTicks : LongWord;
begin
if FTimerBusyFlag then Exit;
FTimerBusyFlag := true;
{ midnight }
if (FCurDate <> Trunc(Date)) then begin
FCurDate := Trunc(Date);
end;
{ periodically flush SSL host list so certificates are rechecked }
Duration := IcsCalcTickDiff (FFlushTick, IcsGetTickCount) div (1000*60);
if (Duration > FlushSslCacheMins) then begin
FFlushTick := IcsGetTickCount;
if FTarSslCertList.Count > 0 then begin
LogProgEvent('Clearing target SSL certificate cache, total ' +
IntToStr(FTarSslCertList.Count));
FTarSslCertList.Clear;
end;
end;
{ look for idle clients }
try
if FSourceServer.ClientCount = 0 then exit; // no clients
try
CurTicks := IcsGetTickCount;
for I := Pred (FSourceServer.ClientCount) downto 0 do begin
MyClient := FSourceServer.Client[I] as TProxyClient;
if MyClient.FClosingFlag then Continue ;
if MyClient.FSessionClosedFlag then Continue; // Client will close soon
if MyClient.Counter = Nil then Continue;
{ different length timeouts depending on what's happening }
Timeout := MyClient.FIdleTimeout;
if Timeout > 0 then begin
Duration := IcsCalcTickDiff(MyClient.Counter.LastAliveTick, CurTicks) div 1000;
if Duration >= Timeout then begin { seconds }
if (MyClient.FTarSocket.State = wsConnected) then begin // see if receiving remote data
if MyClient.FTarSocket.Counter = Nil then Continue;
Duration := IcsCalcTickDiff(MyClient.FTarSocket.Counter.LastAliveTick, CurTicks) div 1000;
if Duration < Timeout then continue; { seconds }
if (DebugLevel >= DebugConn) then
MyClient.LogTarEvent('Closing target and client on proxy server timeout');
MyClient.FTarSocket.Close;
end
else
if (DebugLevel >= DebugConn) then
MyClient.LogSrcEvent('Closing client on proxy server timeout');
MyClient.FClosingFlag := True;
MyClient.Close;
end;
end;
end;
except
on E:Exception do begin
LogErrEvent('Exception in Client Timeout Loop: ' + E.Message);
end;
end;
finally
FTimerBusyFlag := False;
end ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ THttpProxyClient }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpProxyClient.Create(Owner: TComponent);
begin
inherited Create(Owner);
FHttpTotReqs := 0;
FHttpTotResps := 0;
FHttpCurrReq := 0;
FHttpCurrResp := 0;
FHttpWaiting := 0;
FPxyReqState := PxyHdrFind; // HTTP request state
FPxyRespState := PxyHdrFind; // HTTP response state
FPxyChunkState := PxyChunkGetSize; // HTTTP response chunked state
FLastReqPath := 'xxx';
FSrcHost := 'xxx';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpProxyClient.Destroy;
begin
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send HTTP response to source client }
procedure THttpProxyClient.SourceHdrRespXmit;
var
Actual: Integer;
begin
if (Self.State <> wsConnected) then Exit ;
if Length(FHttpRespHdr) = 0 then Exit;
Actual := Self.SendStr(FHttpRespHdr);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Sent response header to source, length ' + IntToStr(Actual));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send request header to remote target }
procedure THttpProxyClient.TargetHdrReqXmit;
var
Actual: Integer;
begin
if (FTarSocket.State <> wsConnected) then Exit ;
if Length(FHttpReqHdr) = 0 then Exit;
Actual := FTarSocket.SendStr(FHttpReqHdr);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Sent request header to target, length ' + IntToStr(Actual));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send POST data to remote target }
procedure THttpProxyClient.TargetBodyXmit;
var
DataPtr: Pointer;
DataLen, Actual: Integer;
begin
if (FTarSocket.State <> wsConnected) then Exit ;
if (FHtmlReqBodyLen <= 0) then Exit;
DataPtr := @FHtmlReqBody[0];
DataLen := FHtmlReqBodyLen;
if Assigned(FProxySource.FOnDataSendTar) then begin
FProxySource.FOnDataSendTar(FProxySource, Self, DataPtr, DataLen);
if NOT Assigned(DataPtr) then DataLen := 0; // sanity test
end;
if (DataLen > 0) then begin
Actual := FTarSocket.Send(DataPtr, DataLen);
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Sent POST content to target, length ' + IntToStr(Actual));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send content body in bytes buffer to source client }
procedure THttpProxyClient.SourceBodyBufXmit;
var
DataPtr: Pointer;
DataLen, Actual: Integer;
begin
if (Self.State <> wsConnected) then Exit ;
if (FHtmlRespBodyLen <= 0) then Exit;
DataPtr := @FHtmlRespBody[0];
DataLen := FHtmlRespBodyLen;
if Assigned(FProxySource.FOnDataRecvTar) then begin
FProxySource.FOnDataRecvTar(FProxySource, Self, DataPtr, DataLen);
if NOT Assigned(DataPtr) then DataLen := 0; // sanity test
end;
if (DataLen > 0) then begin
Actual := Self.Send(DataPtr, DataLen);
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Sent body content to source, length ' + IntToStr(Actual));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ triggered when all target data forwarded to client, see if closing client }
procedure THttpProxyClient.SourceDataSent(Sender: TObject; ErrCode : Word);
begin
if (NOT FTarHttp) or FTunnelling then Exit;
{ processing response, event is triggered in other places }
if (FHttpCurrResp <> FHttpCurrReq) or (FHttpCurrResp < 1) then Exit; // sanity check
if (FHttpInfo [FHttpCurrResp].HttpReqState = httpStRespDone) then begin
FHttpInfo [FHttpCurrResp].TickRespEnd := IcsGetTickCount;
FHttpInfo [FHttpCurrResp].HttpReqState := httpStNone;
// ReportStats (FPxyRouting.rtNextResp);
if FSrcPendClose then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Finished Forwarding Response Data, Closing');
if (Self.State = wsConnected) and (not FClosingFlag) then begin
Self.CloseDelayed;
FClosingFlag := True;
end;
end
else if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Finished Forwarding Response Data, Leave Open');
end;
end;
{ !!! might not need this }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpProxyClient.TargetDataSent(Sender: TObject; ErrCode : Word);
begin
inherited TargetDataSent(Sender, ErrCode);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpProxyClient.SourceSessionClosed(Sender: TObject; Error: Word);
begin
inherited SourceSessionClosed(Sender, Error);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ create the URLs we need to search and replace in headers and bodies }
procedure THttpProxyClient.TargetSpecify;
begin
inherited TargetSpecify;
if FSslEnable then
FHttpSrcURL := 'https://' // HTTP source URL for seaching
else
FHttpSrcURL := 'http://';
FHttpSrcURL := FHttpSrcURL + IcsLowercase(FSrcHost);
if (FServerPort <> '80') and (FServerPort <> '443') then
FHttpSrcURL := FHttpSrcURL + ':' + FServerPort;
if FTarSsl then
FHttpTarURL1 := 'https://' // HTTP target URL for seaching
else
FHttpTarURL1 := 'http://';
FHttpTarURL1 := FHttpTarURL1 + IcsLowercase(FTarHost);
FHttpTarURL2 := FHttpTarURL1; // without port
if (FTarPort <> '80') and (FTarPort <> '443') then
FHttpTarURL1 := FHttpTarURL1 + ':' + FTarPort;
LogTarEvent('Source URL: ' + FHttpSrcURL + ', Target URL: ' + FHttpTarURL1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ remote target has closed, ensure anything received is sent to client }
procedure THttpProxyClient.TargetSessionClosed(Sender: TObject; Error: Word);
begin
// FTarConnecting := False;
FTarClosedFlag := True;
if (Self.State = wsConnected) and (FTarWaitTot <> 0) then
TargetXferData;
if (FHttpTotReqs <> FHttpTotResps) and (NOT FTunnelling) then begin
LogTarEvent('Warning, did not receive response');
FRespKAFlag := false;
FDelayedDisconn := false;
end;
if (FProxySource.DebugLevel >= DebugConn) then begin
if (Error = 0) or (Error = 10053) then
LogTarEvent('Remote closed, Data sent ' +
IntToStr(FTarSocket.WriteCount) + ', Data recvd ' + IntToStr(FTarSocket.ReadCount))
else
LogTarEvent('Remote lost (' + WSocketErrorDesc(Error) + '), Data sent ' +
IntToStr(FTarSocket.WriteCount) + ', Data recvd ' + IntToStr(FTarSocket.ReadCount));
end;
{ if still sending data, don't close yet }
if FTarHttp and (NOT FTunnelling) then begin
if NOT (FDelayedDisconn or (FRespKAFlag and
(FProxySource as TIcsHttpProxy).FHttpIgnoreClose)) then begin
if ((FHttpCurrReq >= 1) and (FHttpCurrResp = FHttpCurrReq) and
(FHttpInfo [FHttpCurrResp].HttpReqState = httpStRespDone)) then begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Source client will close when all data forwarded');
FSrcPendClose := True;
end
else begin
// ReportStats (FPxyRouting.rtNextResp);
if Self.State = wsConnected then begin
if (not FClosingFlag) then begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Source client closing after target');
Self.CloseDelayed;
FClosingFlag := True;
end
else if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Source client already closing');
end
else if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Source client already closed');
end;
end
else begin // if target was keep-alive we must close
if FRespKAFlag then
FSrcPendClose := True;
end;
end
else begin
if (NOT FClosingFlag) then begin
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Client closing after target');
Self.CloseDelayed;
FClosingFlag := True;
end
else if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Client already closing');
FDelayedDisconn := false;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ remove request header line, true if found and removed }
function THttpProxyClient.RemoveHdrLine(const Hdr: String; var Headers: string): boolean;
var
P, Q: Integer;
begin
Result := false ;
P := Pos(cCRLF + Hdr, Headers) + 2;
if P <= 2 then Exit;
Q := PosEx(cCRLF, Headers, P);
if Q > P then begin
Delete (Headers, P, Q - P + 2);
Result := True;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ update request header line, false if updated, true if new header added }
function THttpProxyClient.UpdateHdrLine(const Hdr, Arg: String; var Headers: string): boolean;
var
P, Q: Integer;
begin
Result := false ;
P := Pos(cCRLF + Hdr, Headers) + 2;
if P <= 2 then begin
Q := PosEx(cDoubleCRLF, Headers, P);
if P > Q then Exit; // sanity check
Insert(cCRLF + Hdr + ' ' + Arg, Headers, Q);
Result := True
end
else begin
Q := PosEx(cCRLF, Headers, P);
if P > Q then Exit; // sanity check
P := P + Length(Hdr);
if Headers[P] = ' ' then P := P + 1;
Headers := StuffString(Headers, P, Q - P, Arg);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ send request header to remote target }
procedure THttpProxyClient.TargetForwardProxy;
var
Arg: String;
Proto, User, Pass, Host, Port, Path: String;
procedure FindPort(AStr: String);
var
R: Integer;
begin
R := Pos(':', AStr);
if R > 1 then begin
FTarHost := Copy (AStr, 1, R - 1);
FTarPort := Copy (AStr, R + 1, 5);
end
else begin
FTarHost := AStr;
FTarPort := FServerPort;
end;
end;
begin
{ check proxy authorisation }
if FRequestProxyAuthorization <> '' then begin
with FProxySource as TIcsHttpProxy do begin
if Assigned(FonHttpPxyAuth) then begin
if Pos ('basic ', IcsLowercase(FRequestProxyAuthorization)) = 1 then
Arg := Base64Decode(Copy(FRequestProxyAuthorization, 7, 999))
else
Arg := FRequestProxyAuthorization;
LogTarEvent('Testing Proxy-Authorization: ' + Arg);
FonHttpPxyAuth(FProxySource, Self, Arg);
if Arg = '' then begin
LogTarEvent('Failed Proxy-Authorization, Closing');
FClosingFlag := True;
Close;
Exit;
end;
end;
end;
RemoveHdrLine('Proxy-Authorization:', FHttpReqHdr) ;
FTarReqModified := True;
end;
{ MSIE and Firefox send an illegal header we need to remove }
if (FRequestProxyConnection <> '') then begin
FReqKAFlag := (Pos('Close', FRequestProxyConnection) > 0);
RemoveHdrLine('Proxy-Connection:', FHttpReqHdr) ;
FTarReqModified := True;
end;
{ CONNECT method means open a transparent tunnel, usually for SSL }
if FRequestMethod = httpMethodConnect then begin
LogTarEvent('Tunnel requested to: ' + FRequestPath);
LogTarEvent('Beware, no more headers will be logged');
FindPort(FRequestPath); // check for :port, keep host and port
{ SECURITY RISK, only allow HTTP ports to stop 25, etc. }
if (FTarPort <> '80') and (FTarPort <> '443') then begin
LogTarEvent('Tunnel only allowed for HTTP, not port ' + FTarPort);
FClosingFlag := True;
Close;
Exit;
end;
FTarSsl := False; // no SSL for tunnel itself
FTunnelling := True; // so we don't process anything more
FHttpReqHdr := ''; // do not forward this request, create 200 response on succesful connect
end
else begin
{ not CONNECT, look for absolute URL }
ParseURL(IcsLowercase(FRequestPath), Proto, User, Pass, Host, Port, Path);
LogTarEvent('Proxy URL: ' + FRequestPath + ', Host: ' + FRequestHost);
FTarSsl := (Proto = 'https');
if FTarSSL or (Proto = 'http') then begin
if Port <> '' then begin
FTarHost := Host;
FTarPort := Port;
end
else begin
FTarHost := Host;
if FTarSSL then
FTarPort := '443'
else
FTarPort := '80';
end;
{ update HOST header with new host, or add one }
UpdateHdrLine('Host:', Host, FHttpReqHdr);
end
{ not absolute URL, process HOST header }
else if (FRequestHostName <> '') then begin
FTarHost := FRequestHostName;
FTarPort := FRequestHostPort;
FTarSSL := (FTarPort = '443');
end
else begin
LogTarEvent('Forward proxy failed to find Host: header, Closing');
FClosingFlag := True;
Close;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ find matching proxy target, checking path }
{ returns last matching tag if no specific paths found }
function THttpProxyClient.FindPxyPathTarget(const HTag, HPath: String): Integer;
var
I: Integer;
begin
Result := -1;
with FProxySource do begin
for I := 0 to ProxyTargets.Count - 1 do begin
if NOT ProxyTargets[I].HostEnabled then Continue;
if ProxyTargets[I].HostTag = HTag then begin
Result := I;
if Pos(ProxyTargets[I].FSrcPath, HPath) = 1 then begin
Exit;
end;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ update response body, checking for URLs }
procedure THttpProxyClient.UpdateBody;
var
P, DoneNr: Integer;
BodyStr, OldBody: string;
begin
P := PosTBytes(FHttpTarURL2, FHtmlRespBody, 0, FHtmlRespBodyLen); // URL without port
if Assigned((FProxySource as TIcsHttpProxy).onHttpRespBody) or (P > 0) then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updating body content URLs');
{ PENDING - check header sybmol set for UTF8 !!!!! }
{ first, need to copy body into String buffer from TBytes buffer so easier to manipulate }
{ the String is sent instead of YBytes if not empty }
SetLength(BodyStr, FHtmlRespBodyLen);
MoveTBytesToString(FHtmlRespBody, 0, BodyStr, 1, FHtmlRespBodyLen);
FHtmlRespBodyLen := 0; // now in string, clear buffer so it's not sent
DoneNr := 0;
while (Pos(FHttpTarURL1, BodyStr) > 0) do begin // URL with port
DoneNr := DoneNr + 1;
BodyStr := StringReplace(BodyStr, FHttpTarURL1, FHttpSrcURL, [rfIgnoreCase]);
if DoneNr > 100 then break; // sanity check, too many URLS
end;
while (Pos(FHttpTarURL2, BodyStr) > 0) do begin // URL without port
DoneNr := DoneNr + 1;
BodyStr := StringReplace(BodyStr, FHttpTarURL2, FHttpSrcURL, [rfIgnoreCase]);
if DoneNr > 100 then break; // sanity check, too many URLS
end;
{ application event may process body }
if Assigned((FProxySource as TIcsHttpProxy).onHttpRespBody) then begin
OldBody := BodyStr;
(FProxySource as TIcsHttpProxy).onHttpRespBody(FProxySource, Self, BodyStr);
if OldBody <> BodyStr then DoneNr := 1;
end;
{ update HTML header with new content length }
if DoneNr > 0 then begin
FHtmlRespBodyLen := Length(BodyStr);
FRespContentLength := FHtmlRespBodyLen;
{ now move string back into TBytes buffer }
{ !! PENDING - Unicode and UTF8 }
if (Length(FHtmlRespBody) <= FHtmlRespBodyLen) then
SetLength(FHtmlRespBody, FHtmlRespBodyLen + 1);
MoveStringToTBytes(BodyStr, FHtmlRespBody, FHtmlRespBodyLen);
UpdateHdrLine('Content-Length:', IntToStr(FRespContentLength), FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updated ' + IntToStr(DoneNr) +
' URLs, modified body new content length ' +
IntToStr(FRespContentLength));
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ we don't want to process or display binary stuff, only HTML }
function CheckBinaryContent(const CType: String): Boolean;
begin
Result := (Pos('image/', CType) > 0) OR
(Pos('audio/', CType) > 0) OR
(Pos('video/', CType) > 0) OR
(Pos('/x-ms', CType) > 0) OR // exe, etc,
(Pos('/pdf', CType) > 0) OR // pdf
(Pos('/octet-stream', CType) > 0); // exe etc
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ we only want to compress textual stuff, not binary }
function CheckTextualCotent(const CType: String): Boolean;
begin
Result := (Pos('text/', CType) > 0) OR
(Pos('json', CType) > 0) OR
(Pos('javascript', CType) > 0) OR
(Pos('xml', CType) > 0);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ GZIP compress response body being sent back to to source to save bandwidth }
procedure THttpProxyClient.CompressBody;
var
ContentEncoding: String;
InStream, OutStream: TMemoryStream;
ZStreamType: TZStreamType;
begin
{ skip small and big files }
if FHtmlRespBodyLen < (FProxySource as TIcsHttpProxy).FHttpCompMinSize then Exit;
if FHtmlRespBodyLen > CompressMaxSize then Exit;
{ only compress textual content }
if NOT CheckTextualCotent(FRespContentType) then Exit;
try // except
if (Pos('deflate', FHttpInfo [FHttpCurrResp].ReqAcceptEnc) > 0) then begin
ContentEncoding := 'deflate';
ZStreamType := zsRaw;
end
else if (Pos('gzip', FHttpInfo [FHttpCurrResp].ReqAcceptEnc) > 0) then begin
ContentEncoding := 'gzip';
ZStreamType := zSGZip;
end
else begin
LogTarEvent('Ignored compression, unknown encoding: ' +
FHttpInfo [FHttpCurrResp].ReqAcceptEnc);
exit;
end;
{ read into temp stream, return to same buffer }
{ PENDING - zlib unit needs to be able to read and write buffers!!! }
InStream := TMemoryStream.Create;
OutStream := TMemoryStream.Create;
try
try
InStream.Write (FHtmlRespBody[0], FHtmlRespBodyLen);
InStream.Seek (0, 0); { reset to start }
ZlibCompressStreamEx(InStream, OutStream, clDefault, ZStreamType, true);
OutStream.Seek (0, 0); { reset to start }
FHtmlRespBodyLen := OutStream.Size;
{ unlikely compressed version will be larger than raw... }
if (Length(FHtmlRespBody) <= FHtmlRespBodyLen) then
SetLength(FHtmlRespBody, FHtmlRespBodyLen + 1);
OutStream.ReadBuffer (FHtmlRespBody[0], FHtmlRespBodyLen);
except
on E:Exception do begin
LogTarEvent('Exception compesssing content: ' + E.Message);
exit;
end;
end;
UpdateHdrLine('Content-Encoding:', ContentEncoding, FHttpRespHdr);
FRespContentLength := FHtmlRespBodyLen;
UpdateHdrLine('Content-Length:', IntToStr(FRespContentLength), FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Compressed body from ' + IntToStr(InStream.Size) +
' to ' + IntToStr(FRespContentLength)) ;
finally
InStream.Destroy;
OutStream.Destroy;
end;
except
on E:Exception do begin
LogTarEvent('Exception in CompressResponse: ' + E.Message);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ GZIP decompress response body sent from remote target so we can read it }
procedure THttpProxyClient.DecompressBody;
var
InStream, OutStream: TMemoryStream;
begin
if FRespContentEncoding = '' then exit;
if FHtmlRespBodyLen > CompressMaxSize then Exit;
try // except
InStream := TMemoryStream.Create;
OutStream := TMemoryStream.Create;
try
try
InStream.Write(FHtmlRespBody[0], FHtmlRespBodyLen);
InStream.Seek(0, 0); { reset to start }
ZlibDecompressStream(InStream, OutStream);
OutStream.Seek(0, 0); { reset to start }
FHtmlRespBodyLen := OutStream.Size;
FRespContentLength := FHtmlRespBodyLen;
if (Length(FHtmlRespBody) <= FHtmlRespBodyLen) then
SetLength(FHtmlRespBody, FHtmlRespBodyLen + 1);
OutStream.ReadBuffer(FHtmlRespBody[0], FHtmlRespBodyLen);
except
on E:Exception do begin
LogTarEvent('Exception decompesssing content: ' + E.Message);
exit;
end;
end;
RemoveHdrLine('Content-Encoding:', FHttpRespHdr);
FRespContentEncoding := ''; // clear so we know body is uncompressed
UpdateHdrLine('Content-Length:', IntToStr(FRespContentLength), FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Decompressed body from ' + IntToStr(InStream.Size) +
' to ' + IntToStr(FRespContentLength)) ;
finally
InStream.Destroy;
OutStream.Destroy;
end;
except
on E:Exception do begin
LogTarEvent('Exception in DecompresssResponse: ' + E.Message);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpProxyClient.ParseReqHdr;
var
Line, Arg: String;
I, J, K, L, Lines: Integer;
begin
FRequestMethod := httpMethodNone;
FRequestStartLine := '';
FRequestVersion := '';
FRequestAccept := '';
FRequestAcceptEncoding := '';
FRequestConnection := '';
FRequestContentLength := 0;
FRequestContentType := '';
FRequestCookies := '';
FRequestHost := '';
FRequestHostName := '';
FRequestHostPort := '';
FRequestIfModSince := 0;
FRequestKeepAlive := '';
FRequestPath := '/';
FRequestProxyAuthorization := '';
FRequestProxyConnection := '';
FRequestReferer := '';
FRequestUpgrade := '';
FRequestUserAgent := '';
FReqKAFlag := True;
FReqKASecs := 0;
FTarReqLenRemain := 0;
FTarReqTooLarge := false;
FTarReqModified := false;
FHtmlReqBodyLen := 0;
{ process one line in header at a time }
if Length(FHttpReqHdr) <= 4 then Exit; // sanity check
I := 1; // start of line
Lines := 1;
for J := 1 to Length(FHttpReqHdr) - 2 do begin
if (FHttpReqHdr[J] = cCR) and (FHttpReqHdr[J + 1] = cLF) then begin // end of line
if (J - I) <= 2 then continue; // ignore blank line, usually at start
Line := Copy(FHttpReqHdr, I, J - I);
K := Pos (':', Line) + 1;
if Lines = 1 then begin
FRequestStartLine := Line;
if (Pos('GET ', Line) = 1) then FRequestMethod := httpMethodGet;
if (Pos('POST ', Line) = 1) then FRequestMethod := httpMethodPost;
if (Pos('HEAD ', Line) = 1) then FRequestMethod := httpMethodHead;
if (Pos('OPTIONS ', Line) = 1) then FRequestMethod := httpMethodOptions;
if (Pos('PUT ', Line) = 1) then FRequestMethod := httpMethodPut;
if (Pos('DELETE ', Line) = 1) then FRequestMethod := httpMethodDelete;
if (Pos('TRACE ', Line) = 1) then FRequestMethod := httpMethodTrace;
if (Pos('PATCH ', Line) = 1) then FRequestMethod := httpMethodPatch;
if (Pos('CONNECT ', Line) = 1) then FRequestMethod := httpMethodConnect;
L := Pos(' ', Line);
If (L > 0) then Line := Copy(Line, L + 1, 99999); // strip request
L := Pos(' HTTP/1', Line);
if (L > 0) then begin
FRequestPath := Copy(Line, 1, L - 1);
FRequestVersion := Copy(Line, L + 1, 99999);
end;
end
else if (K > 3) then begin
Arg := IcsTrim(Copy(Line, K, 999)); // convert any arguments we scan to lower case later
if (Pos('Accept:', Line) = 1) then FRequestAccept := Arg;
if (Pos('Accept-Encoding:', Line) = 1) then FRequestAcceptEncoding := IcsLowercase(Arg);
if (Pos('Connection:', Line) = 1) then FRequestConnection := IcsLowercase(Arg); // Keep-Alive or Close
if (Pos('Content-Length:', Line) = 1) then FRequestContentLength := atoi64(Arg);
if (Pos('Content-Type:', Line) = 1) then FRequestContentType := IcsLowercase(Arg);
if (Pos('Cookie:', Line) = 1) then FRequestCookies := Arg;
if (Pos('Host:', Line) = 1) then begin
FRequestHost := Arg;
L := Pos(':', FRequestHost);
if L > 0 then begin
FRequestHostName := Copy(FRequestHost, 1, L - 1);
FRequestHostPort := Copy(FRequestHost, L + 1, 99);
end
else begin
FRequestHostName := FRequestHost;
FRequestHostPort := FServerPort;
end;
end;
if (Pos('If-Modified-Since:', Line) = 1) then begin
try
FRequestIfModSince := RFC1123_StrToDate(Arg);
except
FRequestIfModSince := 0;
end;
end;
if (Pos('Keep-Alive:', Line) = 1) then FRequestKeepAlive := Arg;
if (Pos('Proxy-Authorization:', Line) = 1) then FRequestProxyAuthorization := Arg;
if (Pos('Proxy-Connection:', Line) = 1) then FRequestProxyConnection := IcsLowercase(Arg);
if (Pos('Referer:', Line) = 1) then FRequestReferer := IcsLowercase(Arg);
if (Pos('Upgrade:', Line) = 1) then FRequestUpgrade := Arg;
if (Pos('User-Agent:', Line) = 1) then FRequestUserAgent := Arg;
end
else begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Warning, ignored header line: ' + Line);
end;
Lines := Lines + 1;
I := J + 2; // start of next line
end;
end;
if FRequestConnection <> '' then begin
FReqKAFlag := (Pos('keep-alive', FRequestConnection) > 0);
end;
{ we don't want to process or display binary stuff, only HTML }
FReqBinary := CheckBinaryContent(FRespContentType);
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Parsed request header lines, total: ' + IntToStr (Lines));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpProxyClient.ParseRespHdr;
var
Line, Arg: String;
I, J, K, L, Lines: Integer;
begin
FRespStatusCode := 0;
FRespVersion := '';
FRespReasonPhase := '';
FRespConnection := '';
FRespContentEncoding := '';
FRespContentLength := 0;
FRespContentLenSet := False;
FRespContentType := '';
FRespContent := '';
FRespCharset := '';
FRespCookies := '';
FRespKAFlag := False;
FRespKASecs := 0;
FRespKeepAlive := '';
FRespLastModified := 0;
FRespLocation := '';
FRespStatusLine := '';
FRespTransferEncoding := '';
FHtmlRespBodyLen := 0;
FTarRespModified := false;
FRespBinary := false;
FRespGzip := false;
{ process one line in header at a time }
if Length(FHttpRespHdr) <= 4 then Exit; // sanity check
I := 1; // start of line
Lines := 1;
for J := 1 to Length(FHttpRespHdr) - 2 do begin
if (FHttpRespHdr[J] = cCR) and (FHttpRespHdr[J + 1] = cLF) then begin // end of line
if (J - I) <= 2 then continue; // ignore blank line, usually at start
Line := Copy(FHttpRespHdr, I, J - I);
K := Pos (':', Line) + 1;
if Lines = 1 then begin
FRespStatusLine := Line;
if Pos('HTTP', Line) <> 1 then Exit; // not a valid response header
L := Pos (' ', Line);
if (L > 0) then begin
FRespVersion := Copy(Line, 1, L - 1);
FRespReasonPhase := Copy(Line, L + 1, 999);
FRespStatusCode := atoi(FRespReasonPhase);
end;
end
else if (K > 3) then begin
Arg := Trim(Copy(Line, K, 999)); // convert any arguments we scan to lower case later
if (Pos('Content-Encoding:', Line) = 1) then FRespContentEncoding := IcsLowercase(Arg);
if (Pos('Connection:', Line) = 1) then FRespConnection := IcsLowercase(Arg); // Keep-Alive or Close
if (Pos('Content-Length:', Line) = 1) then begin
FRespContentLength := atoi64(Arg);
FRespContentLenSet := True;
end;
if (Pos('Content-Type:', Line) = 1) then begin
FRespContentType := IcsLowercase(Arg);
L := Pos('; charset=', FRespContentType);
if L > 1 then begin
FRespContent := Copy(FRespContentType, 1, L - 1);
FRespCharset := Copy(FRespContentType, L + 10, 99);
end
else
FRespContent := FRespContentType;
end;
if (Pos('Last-Modified:', Line) = 1) then begin
try
FRespLastModified := RFC1123_StrToDate(Arg);
except
FRespLastModified := 0;
end;
end;
if (Pos('Location:', Line) = 1) then FRespLocation := IcsLowercase(Arg);
if (Pos('Keep-Alive:', Line) = 1) then FRespKeepAlive := Arg;
if (Pos('Set-Cookie:', Line) = 1) then FRespCookies := Arg;
if (Pos('Transfer-Encoding:', Line) = 1) then FRespTransferEncoding := IcsLowercase(Arg);
end
else begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Warning, ignored header line: ' + Line);
end;
Lines := Lines + 1;
I := J + 2; // start of next line
end;
end;
if FRespConnection <> '' then begin
FRespKAFlag := (Pos('keep-alive', FRequestConnection) > 0);
end;
{ we don't want to process or display binary stuff, only HTML }
FRespBinary := CheckBinaryContent(FRespContentType);
{ Content-Encoding, deflate or gzip - applied to content after unchunking }
{ beware Transfer-Encoding: gzip only relates to chunks }
if (FRespContentEncoding <> '') then begin
if (Pos('deflate', FRespContentEncoding) > 0) or
(Pos('gzip', FRespContentEncoding) > 0) or
(Pos('compress', FRespContentEncoding) > 0) then begin
FRespGzip := True;
end;
end;
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Parsed response header lines, total: ' + IntToStr (Lines));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ receive data from source server, process request headers, and send to remote target }
procedure THttpProxyClient.SourceXferData;
var
LoopCounter, HdrLen, NewLen, I: Integer;
S: String;
begin
LoopCounter := 0;
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Forwarding data to target');
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
// if (FTarSocket.State <> wsConnected) then Exit;
SourceBufRecv; { read anything pending }
{ not HTTP, just send it }
if (NOT FTarHttp) or FTunnelling then begin
if (FSrcWaitTot = 0) then Exit; // nothing to process
TargetBufXmit(FSrcWaitTot);
Exit;
end;
{ waiting for headers to arrive }
if FPxyReqState = PxyHdrFind then begin
if (FSrcWaitTot = 0) then Exit; // nothing to process
{ search for blank line in receive buffer which means we have complete request header }
HdrLen := PosTBytes(cDoubleCRLF, FSrcBuffer, 0, FSrcWaitTot);
if (HdrLen <= 0) then begin
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('Waiting for more source data');
Exit;
end ;
HdrLen := HdrLen + 4; // add blank line length
FPxyReqState := PxyNoBody; // assume no body, check length later
inc (FHttpTotReqs);
{ keep headers in string so they are easier to process, remove from receive buffer }
SetLength(FHttpReqHdr, HdrLen);
MoveTBytesToString(FSrcBuffer, 0, FHttpReqHdr, 1, HdrLen);
FSrcWaitTot := FSrcWaitTot - HdrLen;
if FSrcWaitTot > 0 then
MoveTBytes(FSrcBuffer, HdrLen, 0, FSrcWaitTot);
{ keep all header arguments }
ParseReqHdr;
if (FRequestMethod = httpMethodNone) then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('No HTTP header fields found, sending anyway');
{ send request header to remote target }
TargetHdrReqXmit;
Exit;
end ;
{ increment request pipeline and keep it, client may send us several requests
without waiting for responses, so we need to keep stuff to process responses
correctly }
if FHttpCurrReq < 1 then begin
FHttpCurrReq := 1;
end
else begin
if FHttpInfo[FHttpCurrReq].HttpReqState <> httpStReqStart then begin
inc (FHttpCurrReq);
inc (FHttpWaiting) ;
if (FHttpWaiting > 1) and (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Pipe Lining Requests, Depth ' + IntToStr(FHttpWaiting)) ;
if FHttpCurrReq > MaxPipelineReqs then FHttpCurrReq := 1;
end;
end;
with FHttpInfo[FHttpCurrReq] do begin
HttpReqState := httpStReqHdrWait; // request and response
TickReqStart := IcsGetTickCount;
TickReqSend := 0;
TickWaitResp := 0;
TickRespStart := 0;
TickRespBody := 0;
TickRespSend := 0;
TickRespDone := 0;
TickRespEnd := 0;
HttpReqMethod := FRequestMethod;
ReqStartLine := FRequestStartLine;
ReqContentLen := FRequestContentLength;
ReqAcceptEnc := FRequestAcceptEncoding;
end;
{ tell user what we got }
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Original Request Header: #' +
IntToStr(FHttpTotReqs) + cCRLF + FHttpReqHdr)
else if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Request: #' + IntToStr(FHttpTotReqs) + ': ' + FRequestStartLine);
{ application event may process header and update parsed fields }
if Assigned((FProxySource as TIcsHttpProxy).onHttpReqHdr) then begin
(FProxySource as TIcsHttpProxy).onHttpReqHdr(FProxySource, Self, FHttpReqHdr);
end;
{ first check Host: to find correct source and target }
if (NOT FForwardPrxy) and (FSrcHost <> FRequestHostName) then begin
FSrcHost := FRequestHostName;
I := FProxySource.FindPxySourceHost(FSrcHost, Self.MultiListenIdx);
if I >= 0 then begin
Self.FIcsHostIdx := I ;
Self.FHostTag := FProxySource.IcsHosts[I].HostTag;
TargetCheck; // logs hostidx, find new target
if FClosingFlag then Exit;
with FProxySource.ProxyTargets[FPxyTargetIdx] do begin
if SrcPath <> '' then FTarConditional := True;
Self.FUpdateHttp := FUpdateHttp;
Self.FUpdateHtml := FUpdateHttp;
end;
end;
end;
{ check path for conditional stuff }
{ may exit here, and then come back and reprocess buffer again after target answers }
if FTarConditional AND (FLastReqPath <> FRequestPath) then begin
{ forward proxy, get target from CONNECT method or HOST header }
if FForwardPrxy then begin
TargetForwardProxy;
if FClosingFlag then Exit; // error
end
{ not forward proxy, look for conditional forwarders based on the path }
else begin
if FRequestMethod in [httpMethodGet, httpMethodHead, httpMethodPost, httpMethodPut] then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogSrcEvent('Checking conditional forwarding for ' + FRequestPath);
FPxyTargetIdx := FindPxyPathTarget(HostTag, FRequestPath);
if FPxyTargetIdx < 0 then begin { should have been checked earlier }
if (FProxySource.DebugLevel >= DebugConn) then
LogSrcEvent('Host #' + IntToStr(IcsHostIdx) + ' -' +
HostTag + ', no matching proxy target found for Path: ' + FRequestPath);
FClosingFlag := True;
Close;
exit;
end;
TargetSpecify;
end;
end;
end;
{ if this a new targert }
if (FTarSocket.State <> wsConnected) or (FTarHost <> FTarCurHost) or
(FTarPort <> FTarSocket.Port) then begin
{ do we need to disconnect existing session }
if (FTarSocket.State = wsConnected) then begin
LogTarEvent('Target disconnecting ready for new host');
FDelayedDisconn := true;
FTarSocket.Close;
FDelayedDisconn := false;
end;
{ start connection to target server, request won't be sent until later once target connects }
if NOT FForwardPrxy then TargetSpecify; // logs target #
FTarSocket.Counter.SetConnected;
if NOT TargetConnect then begin
FClosingFlag := True;
Close;
Exit;
end;
end;
{ sanity text }
if (FTarHost = '') then begin
LogSrcEvent('Host #' + IntToStr(IcsHostIdx) + ' -' +
HostTag + ', failed to find new target host, closing');
FClosingFlag := True;
Close;
exit;
end;
{ look for Content-Length header, keep size, POST only }
if FRequestContentLength > 1 then begin
FHttpInfo[FHttpCurrReq].ReqContentLen := FRequestContentLength;
FPxyReqState := PxyLenEnd;
FTarReqLenRemain := FRequestContentLength;
FHtmlReqBodyLen := 0;
if FRequestContentLength > (FProxySource as TIcsHttpProxy).FHttpMaxBody then
FTarReqTooLarge := true
else
SetLength(FHtmlReqBody, FTarReqLenRemain);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Got headers, expected POST request content-length=' + IntToStr(FRequestContentLength));
end;
{ see if allowed to update headers }
if FUpdateHttp then begin
{ update Host: and Referrer: headers to those of target }
if (FRequestHostName <> FTarHost) then begin
UpdateHdrLine('Host:', FTarHost, FHttpReqHdr);
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updated Host header to: ' + FTarHost);
// pending update referrer - may need to change http<>https
if FRequestReferer <> '' then begin
if Pos (FHttpSrcURL, FRequestReferer) > 0 then begin
S := StringReplace(FRequestReferer, FHttpSrcURL, FHttpTarURL1, [rfReplaceAll]);
UpdateHdrLine('Referer:', S, FHttpReqHdr);
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updated Referer Header from: ' + FRequestReferer + ', to: ' + S);
end;
end;
end;
{ look for Accept-Encoding: header, may need to remove it }
if (FRequestAcceptEncoding <> '') and (NOT FForwardPrxy) then begin
if NOT (FProxySource as TIcsHttpProxy).FHttpTarCompress then begin // don't support GZIP of target responses
if RemoveHdrLine('Accept-Encoding:', FHttpReqHdr) then begin
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Removed Accept-Encoding: header') ;
end;
end;
end
else begin
// pending - should we add new Accept-Encoding:
// if FProxySource.FHttpTarCompress then begin
end;
{ Keep Alive - remove or update request Connection: header and related Keep-Alive header }
if (FRequestConnection <> '') and (FProxySource as TIcsHttpProxy).FHttpIgnoreClose then begin
if (NOT FRespKAFlag) then begin
UpdateHdrLine('Connection:', 'Keep-Alive', FHttpReqHdr);
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Changed connection header to Keep-Alive');
end
else begin
UpdateHdrLine('Connection:', 'Close', FHttpReqHdr);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Changed connection header to Close');
RemoveHdrLine('Keep-Alive:', FHttpReqHdr);
FTarReqModified := True;
end
end
else begin
if (NOT FRespKAFlag) then begin
UpdateHdrLine('Connection:', 'Keep-Alive', FHttpReqHdr);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Added new header: Connection: Keep-Alive');
FTarReqModified := True;
end;
end;
{ see if removing conditional headers to force server to return data }
if (FRequestIfModSince > 0) and (FProxySource as TIcsHttpProxy).FHttpStopCached then begin
if RemoveHdrLine('If-Modified-Since:', FHttpReqHdr) then begin
RemoveHdrLine('If-None-Match:', FHttpReqHdr);
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Removed If-Modified-Since: to stop cached response');
end;
end;
{ see if removeing Upgrade header to stop HTTP/2 }
if (FProxySource as TIcsHttpProxy).FHttpStripUpgrade then begin
if (FRequestUpgrade <> '') then begin
if RemoveHdrLine('Upgrade:', FHttpReqHdr) then begin
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Removed Upgrade: ' + FRequestUpgrade);
end;
end;
{ stop server redirecting to SSL site }
if RemoveHdrLine('Upgrade-Insecure-Requests:', FHttpReqHdr) then begin
FTarReqModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Removed Upgrade-Insecure-Requests: header to stop SSL');
end;
end;
end;
end;
{ can not send anything, will return here once connected }
if (FTarSocket.State <> wsConnected) then Exit ;
{ send request header to remote target, once connected }
if (FPxyReqState > PxyHdrFind) and
(FHttpInfo[FHttpCurrReq].HttpReqState = httpStReqHdrWait) then begin
if FTarReqModified and (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Modified Request Header: #' +
IntToStr(FHttpTotReqs) + cCRLF + FHttpReqHdr);
TargetHdrReqXmit;
FHttpInfo[FHttpCurrReq].HttpReqState := httpStWaitResp;
end;
{ POST content according to length in header }
if FPxyReqState = PxyLenEnd then begin
if FSrcWaitTot = 0 then Exit; // nothing to send
NewLen := FSrcWaitTot;
if (NewLen > FTarReqLenRemain) then
NewLen := FTarReqLenRemain; // might have body and next header
FTarReqLenRemain := FTarReqLenRemain - NewLen;
{ if POST content more than 5MB, just send it without processing }
if FTarReqTooLarge then begin
TargetBufXmit(NewLen);
end
else begin
// keep POST content in buffer and remove from receive buffer
MoveTBytesEx(FSrcBuffer, FHtmlReqBody, 0, FHtmlReqBodyLen, NewLen); // build body buffer
FHtmlReqBodyLen := FHtmlReqBodyLen + NewLen;
FSrcWaitTot := FSrcWaitTot - NewLen;
if FSrcWaitTot > 0 then
MoveTBytes(FSrcBuffer, NewLen, 0, FSrcWaitTot); // remove from receive buffer
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Building POST body, Length ' + IntToStr(FRequestContentLength) +
', Added ' + IntToStr(NewLen) + ', Remaining ' + IntToStr(FTarReqLenRemain) +
', Left Over ' + IntToStr(FSrcWaitTot)) ;
// got whole POST content, send it to target
if (FTarReqLenRemain <= 0) then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Finished request content, length=' + IntToStr(FRequestContentLength));
{ application event may process body }
if Assigned((FProxySource as TIcsHttpProxy).onHttpReqBody) then begin
// pending, not got body in string !!!
// (FProxySource as TIcsHttpProxy).onHttpReqBody(FProxySource, Self, BodyStr);
end;
if (FProxySource.DebugLevel >= DebugHttpBody) then begin
if NOT FReqBinary then begin
NewLen := FHtmlReqBodyLen;
if NewLen > MaxBodyDumpSize then NewLen := MaxBodyDumpSize;
SetLength(S, NewLen);
MoveTBytesToString(FHtmlReqBody, 0, S, 1, NewLen);
if NewLen = MaxBodyDumpSize then S := S + cCRLF + '!!! TRUNCATED !!!';
LogTarEvent('Body:'+ cCRLF + S);
end;
end;
TargetBodyXmit;
FPxyReqState := PxyHdrFind; // reset state for next request header
LoopCounter := 0;
end
end;
end;
// no request body, send header
if FPxyReqState = PxyNoBody then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Finished request, zero content');
FPxyReqState := PxyHdrFind; // reset state for next request header
end;
{ should never get this state }
if FPxyReqState = PxyClosed then begin
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ receive data from remote target, process response headers, and send to source client }
procedure THttpProxyClient.TargetXferData;
var
LoopCounter, HdrLen, NewLen, LineLen, P: Integer;
S, BodyStr: String;
{ send response header to source client }
procedure SendRespHdr;
begin
if FHttpInfo [FHttpCurrResp].HttpReqState <> httpStRespHdrWait then Exit;
if FTarRespModified and (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Modified Response Header: #' +
IntToStr(FHttpTotResps) + cCRLF + FHttpRespHdr);
SourceHdrRespXmit;
FHttpInfo [FHttpCurrResp].HttpReqState := httpStRespSend;
end;
procedure DoneResponse;
begin
FHtmlRespBodyLen := 0;
if FHttpInfo [FHttpCurrResp].HttpReqState = httpStRespSend then begin
FHttpInfo [FHttpCurrResp].HttpReqState := httpStRespDone;
FHttpInfo [FHttpCurrResp].TickRespDone := IcsGetTickCount;
end;
end;
begin
LoopCounter := 0;
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('Forwarding data to source');
while TRUE do begin
inc (LoopCounter);
if (LoopCounter > 100) then Exit; // sanity check
if (Self.State <> wsConnected) then Exit;
TargetBufRecv; { read anything pending }
{ not HTTP, just send it }
if (NOT FTarHttp) or FTunnelling then begin
if (FTarWaitTot = 0) then Exit; // nothing to process
SourceBufXmit(FTarWaitTot);
Exit;
end;
{ waiting for headers to arrive }
if FPxyRespState = PxyHdrFind then begin
if (FTarWaitTot = 0) then Exit; // nothing to process
{ search for blank line in receive buffer which means we have complete request header }
HdrLen := PosTBytes(cDoubleCRLF, FTarBuffer, 0, FTarWaitTot);
if (HdrLen <= 0) then begin
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('Waiting for more target data');
Exit;
end ;
HdrLen := HdrLen + 4; // add blank line length
FPxyRespState := PxyNoBody; // assume no body, check length later
inc (FHttpTotResps);
{ keep headers in string so they are easier to process, remove from receive buffer }
SetLength(FHttpRespHdr, HdrLen);
MoveTBytesToString(FTarBuffer, 0, FHttpRespHdr, 1, HdrLen);
FTarWaitTot := FTarWaitTot - HdrLen;
if FTarWaitTot > 0 then
MoveTBytes(FTarBuffer, HdrLen, 0, FTarWaitTot);
{ keep all header arguments, give up if none found }
ParseRespHdr;
if (FRespStatusCode = 0) then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('No HTTP header fields found, sending anyway');
{ send response header to source client }
SourceHdrRespXmit;
Exit;
end ;
{ update pipeline responses }
FHtmlRespBodyLen := 0;
FTarRespLenRemain := 0;
FChunkRcvd := 0;
FChunkTot := 0; // how many chunks in page
inc (FHttpCurrResp);
if FHttpCurrResp > MaxPipelineReqs then FHttpCurrResp := 1;
if FHttpWaiting > 0 then dec (FHttpWaiting) ;
FHttpInfo [FHttpCurrResp].HttpReqState := httpStRespStart;
FHttpInfo [FHttpCurrResp].TickRespStart := IcsGetTickCount;
{ tell user what we got }
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Original Response Header: #' + IntToStr(FHttpTotResps) +
', for Request: ' + FHttpInfo [FHttpCurrResp].ReqStartLine + cCRLF + FHttpRespHdr)
else if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Response: #' + IntToStr(FHttpTotResps) + ', for: ' +
FHttpInfo [FHttpCurrResp].ReqStartLine + ', Status: ' +
FRespStatusLine + ', Length: ' + IntToStr(FRespContentLength));
{ application event may process header and update parsed fields }
if Assigned((FProxySource as TIcsHttpProxy).onHttpRespHdr) then begin
(FProxySource as TIcsHttpProxy).onHttpRespHdr(FProxySource, Self, FHttpRespHdr);
end;
{ Transfer-Encoding may be chunked, deflate or gzip - after checking content length }
{ note Transfer-Encoding: chunked and Content-Encoding: gzip is common, uncompress after unchunk }
if (FRespTransferEncoding <> '') then begin
FChunkGzip := false;
if (Pos('deflate', FRespTransferEncoding) > 0) or
(Pos('gzip', FRespTransferEncoding) > 0) or
(Pos('compress', FRespTransferEncoding) > 0) then begin
FChunkGzip := True;
LogTarEvent('Expecting compressed chunks');
end;
if (Pos('chunked', FRespTransferEncoding) > 0) then begin
if (Pos('image/', FRespContentType) > 0) then { because we don't parse images }
LogTarEvent('Ignored chunked image')
else begin
FPxyRespState := PxyCnkEnd;
FChunkState := PxyChunkGetSize;
SetLength(FHtmlRespBody, (FProxySource as TIcsHttpProxy).FHttpMaxBody);
LogTarEvent('Expecting multiple body chunks');
end;
end;
{ not found a way to test this combination, so cheat for now }
if FChunkGzip and (FPxyRespState = PxyCnkEnd) then begin
FRespGzip := True;
FChunkGzip := false;
LogTarEvent('!!! Warning, not tested compressed chunks, will attempt content decompress');
end;
end;
{ if not chunked, look for Content-Length header, keep size }
if FPxyRespState <> PxyCnkEnd then begin
if FRespContentLength > 0 then begin
{ ignore actual content with HEAD request }
if FHttpInfo [FHttpCurrResp].HttpReqMethod <> httpMethodHead then begin
FPxyRespState := PxyLenEnd;
FTarRespLenRemain := FRespContentLength;
if FRespContentLength > (FProxySource as TIcsHttpProxy).FHttpMaxBody then
FTarRespTooLarge := true
else
SetLength(FHtmlRespBody, FTarRespLenRemain);
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Expected body content length ' +
IntToStr(FRespContentLength));
end
else
FPxyRespState := PxyNoBody; // for HEAD
end
else begin
if FRespContentLenSet or
(FRespStatusCode = 204) or (FRespStatusCode = 205) or
(FRespStatusCode = 304) or (FRespStatusCode = 400) then begin
FPxyRespState := PxyNoBody;
if FUpdateHttp and (NOT FRespContentLenSet) then begin
UpdateHdrLine('Content-Length:', '0', FHttpRespHdr); // add zero content length header
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('No content length found, added zero length');
end;
end
else begin
FPxyRespState := PxyGetBody;
FSrcPendClose := True; // close after response
FTarRespLenRemain := $7FFFFFFFFFFFFFFF; // aka MaxInt64
SetLength(FHtmlRespBody, (FProxySource as TIcsHttpProxy).FHttpMaxBody);
if FUpdateHttp then begin
RemoveHdrLine('Connection:', FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('No content length found, will close connection');
end;
end;
end;
end;
{ may need to change Location: header http<>https and or fix host }
if (FRespLocation <> '') and FUpdateHttp then begin
if Pos (FHttpTarURL1, FRespLocation) > 0 then begin // URL with port
S := StringReplace(FRespLocation, FHttpTarURL1, FHttpSrcURL, [rfReplaceAll]);
UpdateHdrLine('Location:', S, FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updated Location Header from: ' + FRespLocation + ', to: ' + S);
FRespLocation := S;
end;
if Pos (FHttpTarURL2, FRespLocation) > 0 then begin // URL without port
S := StringReplace(FRespLocation, FHttpTarURL2, FHttpSrcURL, [rfReplaceAll]);
UpdateHdrLine('Location:', S, FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Updated Location Header from: ' + FRespLocation + ', to: ' + S);
FRespLocation := S;
end;
end ;
{ Connection: Close effects keep alive }
if (FRespConnection <> '') then begin
if NOT FRespKAFlag then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Remote target connection should close after this response');
{ change header to keep-alive, don't close local client yet }
if FRespKAFlag and ((FProxySource as TIcsHttpProxy).FHttpIgnoreClose) and
FUpdateHttp then begin
UpdateHdrLine('Connection:', 'Keep-Alive', FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Changed connection header to Keep-Alive');
end
else
FSrcPendClose := True; // close after response
end
end
else begin
{ don't mess with authentication requests }
if FRespStatusCode = 401 then
FRespKAFlag := true
else begin
FRespKAFlag := false;
FSrcPendClose := True; // close after response
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('No Connection: header found, disable Keep-Alive');
end;
end;
FHttpInfo [FHttpCurrResp].HttpReqState := httpStRespHdrWait;
end;
{ can not send anything }
if (Self.State <> wsConnected) then Exit ;
{ keep lots of short chunks in FHtmlRespBody TBytes buffer }
if (FPxyRespState = PxyCnkEnd) then begin
while TRUE do begin
Inc(LoopCounter);
if LoopCounter > 100 then exit; // sanity check
{ get chunk size, short line with single word hex, ie 5ee5 }
if (FChunkState = PxyChunkGetSize) and (FTarWaitTot > 2) then begin
LineLen := PosTBytes(cCRLF, FTarBuffer, 0, FTarWaitTot);
if LineLen < 1 then Break; // not found a line end
SetLength(S, LineLen);
MoveTBytesToString(FTarBuffer, 0, S, 1, LineLen); // get line
LineLen := LineLen + 2; // add CRLF
if FTarWaitTot > LineLen then
FTarWaitTot := FTarWaitTot - LineLen // gone from buffer
else
FTarWaitTot := 0;
if FTarWaitTot > 0 then
MoveTBytes(FTarBuffer, LineLen, 0, FTarWaitTot); // remove from receive buffer
P := Pos(';', S); // strip off Chunk Extension
if P > 1 then SetLength(S, P - 1);
NewLen := htoin(PChar(S), Length(S));
if (NewLen < 0) or (NewLen > 20000000) then begin // 20MB snaity check
LogTarEvent('!! Warning, invalid chunk encoding length: ' +
S + ' (' + IntToStr(NewLen) + ')');
if (FProxySource.DebugLevel >= DebugAll) then begin
SetLength(S, FTarWaitTot);
MoveTBytesToString(FTarBuffer, 0, S, 1, FTarWaitTot);
LogTarEvent('Raw Chunked Data, Len=' + IntToStr(FTarWaitTot) + cCRLF + S);
end;
FPxyRespState := PxyGetBody; // stop chunk processing
Break;
end
{ zero size is end of response, but may be followed by trailer header fields, wait for blank line }
else if NewLen = 0 then begin
if FTarWaitTot = 2 then begin
// check for CRLF ??
FTarWaitTot := 0; // remove trailing CRLF
end;
FChunkState := PxyChunkDone;
if (FProxySource.DebugLevel >= DebugAll) then LogTarEvent('End of chunked data');
end
{ got chunk length, get ready to read it }
else begin
FChunkState := PxyChunkGetData;
FChunkRcvd := NewLen;
{ increase buffer to take chunk, it was initially 1MB }
while (Length(FHtmlRespBody) <= (FHtmlRespBodyLen + FChunkRcvd)) do
SetLength(FHtmlRespBody, Length(FHtmlRespBody) * 2);
LoopCounter := 0;
if (FProxySource.DebugLevel >= DebugChunks) then
LogTarEvent('Extracting chunk, size=' + IntToStr(FChunkRcvd) +
', new content-len=' + IntToStr(FHtmlRespBodyLen + FChunkRcvd)) ;
end;
end;
{ keep chunk data block }
if FChunkState = PxyChunkGetData then begin
NewLen := FTarWaitTot;
if (NewLen > FChunkRcvd) then
NewLen := FChunkRcvd; // might have two chunks
FChunkRcvd := FChunkRcvd - NewLen;
{ keep it in FHtmlRespBody, remove from receive buffer }
MoveTBytesEx(FTarBuffer, FHtmlRespBody, 0, FHtmlRespBodyLen, NewLen); // build body buffer
FHtmlRespBodyLen := FHtmlRespBodyLen + NewLen;
if (FChunkRcvd <= 0) then NewLen := NewLen + 2; // add trailing CRLF
if FTarWaitTot > NewLen then
FTarWaitTot := FTarWaitTot - NewLen // gone from buffer
else
FTarWaitTot := 0;
if FTarWaitTot > 0 then
MoveTBytes(FTarBuffer, NewLen, 0, FTarWaitTot); // remove from receive buffer
{ whole chunked data block is available }
if (FChunkRcvd <= 0) then begin
{ ??? chunk might be compressed, not found a server to test against yet }
inc (FChunkTot);
FChunkState := PxyChunkGetSize;
end
{ need to wait for more chunked data to arrive }
else begin
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Waiting for more chunked data'); // !! TEMP
Exit;
end;
end;
{ finished getting all data, remove 'chunked', add Content-Length header }
if FChunkState = PxyChunkDone then begin
RemoveHdrLine('Transfer-Encoding:', FHttpRespHdr);
if (FTarWaitTot <> 0) then begin
if (FProxySource.DebugLevel >= DebugHttpHdr) then begin
SetLength(S, FTarWaitTot);
MoveTBytesToString(FTarBuffer, 0, S, 1, FTarWaitTot);
LogTarEvent('!! Still got chunked content, len=' + IntToStr(FTarWaitTot) + ', Data: ' + S);
end;
end;
FRespContentLength := FHtmlRespBodyLen;
UpdateHdrLine('Content-Length:', IntToStr(FRespContentLength), FHttpRespHdr);
FTarRespModified := True;
if (FProxySource.DebugLevel >= DebugHttpHdr) then begin
LogTarEvent('Unchunked content, total chunks=' + IntToStr(FChunkTot) +
', removed Encoding header, added body content length ' + IntToStr(FRespContentLength));
end;
FPxyRespState := PxySendBody;
Break;
end;
end;
end
{ keep body content in FHtmlRespBody TBytes buffer }
else if (FPxyRespState = PxyLenEnd) or (FPxyRespState = PxyGetBody) then begin
if FTarWaitTot = 0 then Exit; // nothing to send
NewLen := FTarWaitTot;
if (NewLen > FTarRespLenRemain) then
NewLen := FTarRespLenRemain; // might have body and next header
FTarRespLenRemain := FTarRespLenRemain - NewLen;
{ if content large, just send it without processing, better response for browser }
if FTarRespTooLarge then begin
// send response header now, only once, then partial body
if (FHttpInfo [FHttpCurrResp].HttpReqState = httpStRespHdrWait) then begin
SendRespHdr;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Sending multi-block body content, length ' +
IntToStr(FRespContentLength));
end;
SourceBufXmit(NewLen);
{ got whole body content or target closed, send it to target }
if (FTarRespLenRemain <= 0) or FTarClosedFlag then begin
FPxyRespState := PxyHdrFind; // reset state for next response header
LoopCounter := 0;
DoneResponse;
if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Finished sending multi-block response');
end;
end
else begin
{ increase buffer size for vatiable length pages }
while (Length(FHtmlRespBody) <= (FHtmlRespBodyLen + NewLen)) do
SetLength(FHtmlRespBody, Length(FHtmlRespBody) * 2);
{ keep body content in buffer and remove from receive buffer }
MoveTBytesEx(FTarBuffer, FHtmlRespBody, 0, FHtmlRespBodyLen, NewLen); // build body buffer
FHtmlRespBodyLen := FHtmlRespBodyLen + NewLen;
FTarWaitTot := FTarWaitTot - NewLen;
if FTarWaitTot < 0 then begin
LogTarEvent('!! Invalid FTarWaitTot: ' + IntToStr(FTarWaitTot)); // TEMP
FTarWaitTot := 0; // sanity check
end;
if FTarWaitTot > 0 then
MoveTBytes(FTarBuffer, NewLen, 0, FTarWaitTot); // remove from receive buffer
if (FProxySource.DebugLevel >= DebugAll) then
LogTarEvent('Building content body, Length ' +
IntToStr(FRespContentLength) + ', Added ' + IntToStr(NewLen) +
', Remaining ' + IntToStr(FTarRespLenRemain) +
', Left Over ' + IntToStr(FTarWaitTot)) ;
{ got whole body content or target closed, send it to target }
if (FTarRespLenRemain <= 0) or FTarClosedFlag then
FPxyRespState := PxySendBody;
end;
end
{ no body, just send header, nothing more }
else if (FPxyRespState = PxyNoBody) then begin
SendRespHdr;
FHttpInfo [FHttpCurrResp].HttpReqState := httpStRespSend;
FHttpInfo [FHttpCurrResp].TickRespSend := IcsGetTickCount;
LoopCounter := 0;
DoneResponse;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Finished response');
FPxyRespState := PxyHdrFind; // look for another response header
end;
{ got complete body, process it, send header then body }
if FPxyRespState = PxySendBody then begin
{ uncompress body so we can mess with it }
if FRespContentEncoding <> '' then begin
DecompressBody;
end;
{ do we need to modify body with new URLs ??? }
if (NOT FRespBinary) and FUpdateHtml then begin
UpdateBody;
end ;
{ see if need to get body into string for debugging or application }
if (FProxySource.DebugLevel >= DebugHttpBody) and (NOT FRespBinary) then begin
SetLength(BodyStr, FHtmlRespBodyLen);
MoveTBytesToString(FHtmlRespBody, 0, BodyStr, 1, FRespContentLength);
end;
{ see if compressing body for source, browser may not be interested }
{ beware, changes headers, so must be before they are sent }
if ((FProxySource as TIcsHttpProxy).FHttpSrcCompress) and
(FHttpInfo [FHttpCurrResp].ReqAcceptEnc <> '') then begin
if FRespContentEncoding = '' then // only if not compressed already
CompressBody;
end;
{ send modified response header, then modified body }
SendRespHdr;
if (FProxySource.DebugLevel >= DebugHttpHdr) then
LogTarEvent('Sending single-block body content, length ' +
IntToStr(FRespContentLength));
if FHtmlRespBodyLen > 0 then begin
{ add body to debug log, before it was compressed }
if (FProxySource.DebugLevel >= DebugHttpBody) then begin
if NOT FRespBinary then begin
if FRespContentLength > MaxBodyDumpSize then begin
SetLength(BodyStr, MaxBodyDumpSize);
BodyStr := BodyStr + cCRLF + '!!! TRUNCATED !!!';
end;
LogTarEvent('Body:'+ cCRLF + BodyStr);
end;
end;
SourceBodyBufXmit;
end;
FPxyRespState := PxyHdrFind; // reset state for next response header
LoopCounter := 0;
DoneResponse;
BodyStr := '';
if (FProxySource.DebugLevel >= DebugConn) then
LogTarEvent('Finished sending response');
end;
{ should never get this state }
if FPxyRespState = PxyClosed then begin
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsHttpProxy main HTTP proxy component }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsHttpProxy.Create(Owner: TComponent);
begin
inherited Create(Owner);
FSourceServer.ClientClass := THttpProxyClient;
FHttpMaxBody := DefMaxBodySize;
FHttpCompMinSize := CompressMinSize;
FHttpStripUpgrade := True;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsHttpProxy.Destroy;
begin
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IcsLoadProxyTargetsFromIni(MyIniFile: TCustomIniFile; ProxyTargets:
TProxyTargets; const Prefix: String = 'Target'): Integer;
var
J: Integer;
section, S: String;
begin
Result := 0;
if NOT Assigned (MyIniFile) then
raise ESocketException.Create('Must open and assign INI file first');
if NOT Assigned (ProxyTargets) then
raise ESocketException.Create('Must assign ProxyTargets first');
ProxyTargets.Clear;
{ allow up to 100 hosts }
for J := 1 to 100 do begin
section := Prefix + IntToStr (J);
S := IcsTrim(MyIniFile.ReadString(section, 'HostTag', ''));
if S = '' then continue;
if NOT IcsCheckTrueFalse(MyIniFile.ReadString (section, 'HostEnabled', 'False')) then continue;
ProxyTargets.Add;
Result := Result + 1;
// read site hosts from INI file
with ProxyTargets[ProxyTargets.Count - 1] do begin
HostEnabled := True;
HostTag := S;
Descr := IcsTrim(MyIniFile.ReadString(section, 'Descr', ''));
SrcPath := MyIniFile.ReadString(section, 'SrcPath', '');
TarHost := MyIniFile.ReadString(section, 'TarHost', '');
TarPort := MyIniFile.ReadInteger(section, 'TarPort', 0);
TarSsl := IcsCheckTrueFalse(MyIniFile.ReadString (section, 'TarSsl', 'False'));
IdleTimeout := MyIniFile.ReadInteger(section, 'IdleTimeout', 0);
UpdateHttp := IcsCheckTrueFalse(MyIniFile.ReadString (section, 'UpdateHttp', 'False'));
UpdateHtml := IcsCheckTrueFalse(MyIniFile.ReadString (section, 'UpdateHtml', 'False'));
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure IcsLoadTIcsHttpProxyFromIni(MyIniFile: TCustomIniFile; IcsHttpProxy:
TIcsHttpProxy; const Section: String = 'Proxy');
begin
if NOT Assigned (MyIniFile) then
raise ESocketException.Create('Must open and assign INI file first');
if NOT Assigned (IcsHttpProxy) then
raise ESocketException.Create('Must assign IcsHttpProxy first');
with IcsHttpProxy do begin
RxBuffSize := MyIniFile.ReadInteger(Section, 'RxBuffSize', 65536);
MaxClients := MyIniFile.ReadInteger(Section, 'MaxClients', 999);
ServerHeader := IcsTrim(MyIniFile.ReadString(Section, 'ServerHeader', ''));
LocalAddr := MyIniFile.ReadString(Section, 'LocalAddr', '');
RootCA := IcsTrim(MyIniFile.ReadString(Section, 'RootCA', ''));
DHParams := MyIniFile.ReadString(Section, 'DHParams', '');
DebugLevel := TDebugLevel(MyIniFile.ReadInteger (Section, 'DebugLevel', 2));
TarSecLevel := TSslSecLevel(MyIniFile.ReadInteger(Section, 'TarSecLevel', 1));
CertVerTar := TCertVerMethod(MyIniFile.ReadInteger(Section, 'CertVerTar', 1));
SslRevocation := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'SslRevocation', 'False'));
SslReportChain := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'SslReportChain', 'False'));
HttpIgnoreClose := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'HttpIgnoreClose', 'False'));
HttpSrcCompress := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'HttpSrcCompress', 'False'));
HttpTarCompress := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'HttpTarCompress', 'False'));
HttpStripUpgrade := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'HttpStripUpgrade', 'True'));
HttpStopCached := IcsCheckTrueFalse(MyIniFile.ReadString (Section, 'SslReportChain', 'False'));
HttpMaxBody := MyIniFile.ReadInteger(Section, 'HttpMaxBody', 1000000);
HttpCompMinSize := MyIniFile.ReadInteger(Section, 'HttpCompMinSize', CompressMinSize);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$ENDIF USE_SSL}
end.
|
unit acSkinPack;
{$I sDefs.inc}
{$WARNINGS OFF}
// ZLib version 1.2.3 used (http://www.zlib.net)
interface
uses
Windows, Messages, SysUtils, Classes;
type
TacImageItem = record
FileName : string;
IsBitmap : boolean;
FileStream : TMemoryStream;
end;
TacImageItems = array of TacImageItem;
TacSkinConvertor = class(TPersistent)
public
// Unpacked data
ImageCount : integer;
Files : TacImageItems;
Options : TMemoryStream;
// Packed data
PackedData : TMemoryStream;
procedure Clear;
destructor Destroy; override;
end;
const
acAbbr = 'ASzf';
procedure PackDir(const SrcPath, FileName : string);
procedure UnpackSkinFile(const Filename, DestDirectory : String);
procedure LoadSkinFromFile(const FileName : string; var Convertor : TacSkinConvertor; FreePackedData : boolean = True);
procedure ExtractPackedData(var Convertor : TacSkinConvertor);
implementation
uses acntUtils, sConst, acZLibEx, Dialogs;
procedure GetFiles(const DirPath, FileExt: acString; FileList: TStringList);
var
Status: THandle;
FindData: TacWin32FindData;
begin
Status := acFindFirstFile(PacChar(DirPath + FileExt), FindData);
if Status <> INVALID_HANDLE_VALUE then repeat
if (FindData.cFileName[0] <> '.') and (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0) then FileList.Add(FindData.cFileName);
until not acFindNextFile(Status, FindData);
Windows.FindClose(Status);
end;
procedure CompressFiles(FilesDir : string; Files : TStrings; const Filename : String);
var
InFile, OutFile : TFileStream;
TmpFile : TMemoryStream;
Compr : TZCompressionStream;
i, l : Integer;
s : String;
begin
if Files.Count > 0 then begin
OutFile := TFileStream.Create(Filename, fmCreate);
FilesDir := NormalDir(FilesDir);
try
OutFile.Write(acAbbr, SizeOf(acAbbr));
l := Files.Count;
OutFile.Write(l, SizeOf(l));
for i := 0 to Files.Count - 1 do begin
InFile := TFileStream.Create(FilesDir + Files[i], fmOpenRead);
try
s := Files[i];
l := Length(s);
OutFile.Write(l, SizeOf(l));
OutFile.Write(s[1], l);
l := InFile.Size;
OutFile.Write(l, SizeOf(l));
TmpFile := TMemoryStream.Create;
Compr := TZCompressionStream.Create(TmpFile);
Compr.CopyFrom(InFile, l);
FreeAndNil(Compr);
OutFile.CopyFrom(TmpFile, 0);
FreeAndNil(TmpFile);
finally
FreeAndNil(InFile);
end;
end;
finally
FreeAndNil(OutFile);
end;
end;
end;
procedure PackDir(const SrcPath, FileName : string);
var
FilesList : TStringList;
begin
FilesList := TStringList.Create;
GetFiles(SrcPath, '*.dat', FilesList);
GetFiles(SrcPath, '*.bmp', FilesList);
GetFiles(SrcPath, '*.png', FilesList);
GetFiles(SrcPath, '*.jpg', FilesList);
CompressFiles(SrcPath, FilesList, FileName);
FreeAndNil(FilesList);
end;
procedure UnpackSkinFile(const Filename, DestDirectory : String);
var
dest, s : String;
decompr : TZDecompressionStream;
infile, outfile : TFilestream;
i,l,c : Integer;
begin
Dest := NormalDir(DestDirectory);
if not acDirExists(Dest) then acCreateDir(Dest);
InFile := TFileStream.Create(Filename, fmOpenRead);
try
SetLength(s, 4);
InFile.Read(s[1], 4);
if s <> acAbbr then begin
MessageDlg(FileName + ' is not packed AlphaSkin file', mtWarning, [mbOk], 0);
FreeAndnil(InFile);
Exit;
end;
InFile.Read(c, SizeOf(c));
for i := 1 to c do begin
Dest := NormalDir(Dest);
InFile.Read(l, SizeOf(l));
SetLength(s, l);
InFile.Read(s[1], l);
InFile.Read(l, SizeOf(l));
s := Dest + s;
if FileExists(s) then DeleteFile(s);
OutFile := TFileStream.Create(s, fmCreate);
Decompr := TZDecompressionStream.Create(InFile);
OutFile.CopyFrom(decompr, l);
OutFile.Free;
Decompr.Free;
end;
finally
infile.Free;
end;
end;
procedure LoadSkinFromFile(const FileName : string; var Convertor : TacSkinConvertor; FreePackedData : boolean = True);
begin
if FileExists(FileName) then begin
if Convertor = nil then Convertor := TacSkinConvertor.Create else Convertor.Clear;
Convertor.PackedData := TMemoryStream.Create;
Convertor.PackedData.LoadFromFile(FileName);
ExtractPackedData(Convertor);
if FreePackedData then FreeAndnil(Convertor.PackedData);
end;
end;
procedure ExtractPackedData(var Convertor : TacSkinConvertor);
var
s : OldString;
decompr : TZDecompressionStream;
i, l, c : Integer;
begin
SetLength(s, 4);
Convertor.PackedData.Seek(0, 0);
Convertor.PackedData.Read(s[1], 4);
if s <> acAbbr then begin
Convertor.Clear;
FreeAndnil(Convertor);
raise Exception.Create('Loaded data is not a packed AlphaSkin file');
end;
Convertor.PackedData.Read(c, SizeOf(c));
Convertor.ImageCount := c - 1;
for i := 1 to c do begin
Convertor.PackedData.Read(l, SizeOf(l));
SetLength(s, l);
Convertor.PackedData.Read(s[1], l);
Convertor.PackedData.Read(l, SizeOf(l));
Decompr := TZDecompressionStream.Create(Convertor.PackedData);
if UpperCase(s) = UpperCase(OptionsDatName) then begin
Convertor.Options := TMemoryStream.Create;
Convertor.Options.CopyFrom(Decompr, l);
end
else begin
SetLength(Convertor.Files, Length(Convertor.Files) + 1);
Convertor.Files[Length(Convertor.Files) - 1].FileName := s;
Convertor.Files[Length(Convertor.Files) - 1].IsBitmap := UpperCase(ExtractFileExt(s)) = '.BMP';
Convertor.Files[Length(Convertor.Files) - 1].FileStream := TMemoryStream.Create;
Convertor.Files[Length(Convertor.Files) - 1].FileStream.CopyFrom(Decompr, l);
end;
FreeAndNil(Decompr);
end;
end;
{ TacSkinConvertor }
procedure TacSkinConvertor.Clear;
begin
while Length(Files) > 0 do begin
Files[Length(Files) - 1].FileStream.Free;
SetLength(Files, Length(Files) - 1);
end;
if Options <> nil then FreeAndNil(Options);
if PackedData <> nil then FreeAndNil(PackedData);
end;
destructor TacSkinConvertor.Destroy;
begin
Clear;
inherited;
end;
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.TestFramework;
type
ConvertTest = public class (Testcase)
public
method ToStringByte;
method ToStringInt32;
method ToStringInt64;
method ToStringDouble;
method ToStringChar;
method ToStringObject;
method ToInt32Byte;
method ToInt32Int64;
method ToInt32Double;
method ToInt32Char;
method ToInt32String;
method ToInt64Byte;
method ToInt64Int32;
method ToInt64Double;
method ToInt64Char;
method ToInt64String;
method ToDoubleByte;
method ToDoubleInt32;
method ToDoubleInt64;
method ToDoubleString;
method ToByteDouble;
method ToByteInt32;
method ToByteInt64;
method ToByteChar;
method ToByteString;
method ToCharInt32;
method ToCharInt64;
method ToCharByte;
method ToCharString;
method ToBooleanDouble;
method ToBooleanInt32;
method ToBooleanInt64;
method ToBooleanByte;
method ToBooleanString;
end;
implementation
method ConvertTest.ToStringByte;
begin
Assert.CheckString("0", Convert.ToString(Byte(0)));
Assert.CheckString("255", Convert.ToString(Byte(255)));
end;
method ConvertTest.ToStringInt32;
begin
Assert.CheckString("2147483647", Convert.ToString(Consts.MaxInteger));
Assert.CheckString("-2147483648", Convert.ToString(Consts.MinInteger));
Assert.CheckString("0", Convert.ToString(Int32(0)));
end;
method ConvertTest.ToStringInt64;
begin
Assert.CheckString("9223372036854775807", Convert.ToString(Consts.MaxInt64));
Assert.CheckString("-9223372036854775808", Convert.ToString(Consts.MinInt64));
Assert.CheckString("0", Convert.ToString(Int64(0)));
end;
method ConvertTest.ToStringDouble;
begin
Assert.CheckString("1.797693134862E+308", Convert.ToString(Double(1.797693134862E+308)));
Assert.CheckString("-1.797693134862E+308", Convert.ToString(Double(-1.797693134862E+308)));
Assert.CheckString("1E-09", Convert.ToString(Double(0.000000001)));
Assert.CheckString("NaN", Convert.ToString(Consts.NaN));
Assert.CheckString("-Infinity", Convert.ToString(Consts.NegativeInfinity));
Assert.CheckString("Infinity", Convert.ToString(Consts.PositiveInfinity));
Assert.CheckString("0.1", Convert.ToString(Double(0.1)));
Assert.CheckString("-4.2", Convert.ToString(Double(-4.2)));
end;
method ConvertTest.ToStringChar;
begin
Assert.CheckString("x", Convert.ToString(Char('x')));
Assert.CheckString(#0, Convert.ToString(Char(0)));
end;
method ConvertTest.ToStringObject;
begin
Assert.CheckString("42", Convert.ToString(new CodeClass(42)));
end;
method ConvertTest.ToInt32Byte;
begin
Assert.CheckInt(0, Convert.ToInt32(Byte(0)));
Assert.CheckInt(255, Convert.ToInt32(Byte(255)));
end;
method ConvertTest.ToInt32Int64;
begin
Assert.CheckInt(0, Convert.ToInt32(Int64(0)));
Assert.CheckInt(45678942, Convert.ToInt32(Int64(45678942)));
Assert.IsException(->Convert.ToInt32(Consts.MaxInt64));
Assert.IsException(->Convert.ToInt32(Consts.MinInt64));
end;
method ConvertTest.ToInt32Double;
begin
Assert.CheckInt(1, Convert.ToInt32(Double(1.0)));
Assert.CheckInt(1, Convert.ToInt32(Double(1.1)));
Assert.CheckInt(1, Convert.ToInt32(Double(1.2)));
Assert.CheckInt(1, Convert.ToInt32(Double(1.3)));
Assert.CheckInt(1, Convert.ToInt32(Double(1.4)));
Assert.CheckInt(1, Convert.ToInt32(Double(1.5)));
Assert.CheckInt(2, Convert.ToInt32(Double(1.6)));
Assert.CheckInt(2, Convert.ToInt32(Double(1.7)));
Assert.CheckInt(2, Convert.ToInt32(Double(1.8)));
Assert.CheckInt(2, Convert.ToInt32(Double(1.9)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.0)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.1)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.2)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.3)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.4)));
Assert.CheckInt(2, Convert.ToInt32(Double(2.5)));
Assert.CheckInt(3, Convert.ToInt32(Double(2.6)));
Assert.CheckInt(3, Convert.ToInt32(Double(2.7)));
Assert.CheckInt(3, Convert.ToInt32(Double(2.8)));
Assert.CheckInt(3, Convert.ToInt32(Double(2.9)));
Assert.IsException(->Convert.ToInt32(Double(21474836483.15)));
Assert.IsException(->Convert.ToInt32(Double(-21474836483.15)));
Assert.IsException(->Convert.ToInt32(Consts.NaN));
Assert.IsException(->Convert.ToInt32(Consts.PositiveInfinity));
Assert.IsException(->Convert.ToInt32(Consts.NegativeInfinity));
end;
method ConvertTest.ToInt32Char;
begin
Assert.CheckInt(13, Convert.ToInt32(Char(#13)));
Assert.CheckInt(0, Convert.ToInt32(Char(#0)));
end;
method ConvertTest.ToInt32String;
begin
Assert.CheckInt(42, Convert.ToInt32("42"));
Assert.CheckInt(-42, Convert.ToInt32("-42"));
Assert.CheckInt(0, Convert.ToInt32(nil));
Assert.IsException(->Convert.ToInt32("9223372036854775807"));
Assert.IsException(->Convert.ToInt32("4.2"));
Assert.IsException(->Convert.ToInt32("1F"));
end;
method ConvertTest.ToInt64Byte;
begin
Assert.CheckInt64(0, Convert.ToInt64(Byte(0)));
Assert.CheckInt64(255, Convert.ToInt64(Byte(255)));
end;
method ConvertTest.ToInt64Int32;
begin
Assert.CheckInt64(2147483647, Convert.ToInt64(Consts.MaxInteger));
Assert.CheckInt64(-2147483648, Convert.ToInt64(Consts.MinInteger));
end;
method ConvertTest.ToInt64Double;
begin
Assert.CheckInt64(1, Convert.ToInt64(Double(1.0)));
Assert.CheckInt64(1, Convert.ToInt64(Double(1.1)));
Assert.CheckInt64(1, Convert.ToInt64(Double(1.2)));
Assert.CheckInt64(1, Convert.ToInt64(Double(1.3)));
Assert.CheckInt64(1, Convert.ToInt64(Double(1.4)));
Assert.CheckInt64(1, Convert.ToInt64(Double(1.5)));
Assert.CheckInt64(2, Convert.ToInt64(Double(1.6)));
Assert.CheckInt64(2, Convert.ToInt64(Double(1.7)));
Assert.CheckInt64(2, Convert.ToInt64(Double(1.8)));
Assert.CheckInt64(2, Convert.ToInt64(Double(1.9)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.0)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.1)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.2)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.3)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.4)));
Assert.CheckInt64(2, Convert.ToInt64(Double(2.5)));
Assert.CheckInt64(3, Convert.ToInt64(Double(2.6)));
Assert.CheckInt64(3, Convert.ToInt64(Double(2.7)));
Assert.CheckInt64(3, Convert.ToInt64(Double(2.8)));
Assert.CheckInt64(3, Convert.ToInt64(Double(2.9)));
Assert.IsException(->Convert.ToInt64(Double(Consts.MaxDouble)));
Assert.IsException(->Convert.ToInt64(Double(Consts.MinDouble)));
Assert.IsException(->Convert.ToInt64(Consts.NaN));
Assert.IsException(->Convert.ToInt64(Consts.PositiveInfinity));
Assert.IsException(->Convert.ToInt64(Consts.NegativeInfinity));
end;
method ConvertTest.ToInt64Char;
begin
Assert.CheckInt64(13, Convert.ToInt64(Char(#13)));
Assert.CheckInt64(0, Convert.ToInt64(Char(#0)));
end;
method ConvertTest.ToInt64String;
begin
Assert.CheckInt64(42, Convert.ToInt64("42"));
Assert.CheckInt64(-42, Convert.ToInt64("-42"));
Assert.CheckInt64(Consts.MaxInt64, Convert.ToInt64("9223372036854775807"));
Assert.CheckInt64(Consts.MinInt64, Convert.ToInt64("-9223372036854775808"));
Assert.CheckInt(0, Convert.ToInt64(nil));
Assert.IsException(->Convert.ToInt64("92233720368547758071"));
Assert.IsException(->Convert.ToInt64("4.2"));
Assert.IsException(->Convert.ToInt64("1F"));
end;
method ConvertTest.ToDoubleByte;
begin
Assert.CheckDouble(1.0, Convert.ToDouble(Byte(1)));
Assert.CheckDouble(255.0, Convert.ToDouble(Byte(255)));
end;
method ConvertTest.ToDoubleInt32;
begin
Assert.CheckDouble(2147483647.0, Convert.ToDouble(Consts.MaxInteger));
Assert.CheckDouble(-2147483648.0, Convert.ToDouble(Consts.MinInteger));
end;
method ConvertTest.ToDoubleInt64;
begin
Assert.CheckDouble(9223372036854775807.0, Convert.ToDouble(Consts.MaxInt64));
Assert.CheckDouble(Double(-9223372036854775808.0), Convert.ToDouble(Consts.MinInt64));
end;
method ConvertTest.ToDoubleString;
begin
Assert.CheckDouble(1.1, Convert.ToDouble("1.1")); // '.' - decimal separator
Assert.CheckDouble(11, Convert.ToDouble("1,1")); // ',' - group separator
Assert.CheckDouble(10241.5, Convert.ToDouble("1024,1.5"));
Assert.CheckDouble(-1.38e10, Convert.ToDouble("-1.38e10"));
Assert.CheckDouble(0.0, Convert.ToDouble(nil));
Assert.IsException(->Convert.ToDouble("1.29e325"));
Assert.IsException(->Convert.ToDouble("1F"));
Assert.IsException(->Convert.ToDouble("1024.1,5"));
end;
method ConvertTest.ToByteDouble;
begin
Assert.CheckInt(1, Convert.ToByte(Double(1.0)));
Assert.CheckInt(1, Convert.ToByte(Double(1.1)));
Assert.CheckInt(1, Convert.ToByte(Double(1.2)));
Assert.CheckInt(1, Convert.ToByte(Double(1.3)));
Assert.CheckInt(1, Convert.ToByte(Double(1.4)));
Assert.CheckInt(1, Convert.ToByte(Double(1.5)));
Assert.CheckInt(2, Convert.ToByte(Double(1.6)));
Assert.CheckInt(2, Convert.ToByte(Double(1.7)));
Assert.CheckInt(2, Convert.ToByte(Double(1.8)));
Assert.CheckInt(2, Convert.ToByte(Double(1.9)));
Assert.CheckInt(2, Convert.ToByte(Double(2.0)));
Assert.CheckInt(2, Convert.ToByte(Double(2.1)));
Assert.CheckInt(2, Convert.ToByte(Double(2.2)));
Assert.CheckInt(2, Convert.ToByte(Double(2.3)));
Assert.CheckInt(2, Convert.ToByte(Double(2.4)));
Assert.CheckInt(2, Convert.ToByte(Double(2.5)));
Assert.CheckInt(3, Convert.ToByte(Double(2.6)));
Assert.CheckInt(3, Convert.ToByte(Double(2.7)));
Assert.CheckInt(3, Convert.ToByte(Double(2.8)));
Assert.CheckInt(3, Convert.ToByte(Double(2.9)));
Assert.IsException(->Convert.ToByte(Double(Consts.MaxDouble)));
Assert.IsException(->Convert.ToByte(Double(Consts.MinDouble)));
Assert.IsException(->Convert.ToByte(Consts.NaN));
Assert.IsException(->Convert.ToByte(Consts.PositiveInfinity));
Assert.IsException(->Convert.ToByte(Consts.NegativeInfinity));
end;
method ConvertTest.ToByteInt32;
begin
Assert.CheckInt(0, Convert.ToByte(Int32(0)));
Assert.CheckInt(42, Convert.ToByte(Int32(42)));
Assert.IsException(->Convert.ToByte(Int32(259)));
Assert.IsException(->Convert.ToByte(Int32(-1)));
end;
method ConvertTest.ToByteInt64;
begin
Assert.CheckInt(0, Convert.ToByte(Int64(0)));
Assert.CheckInt(42, Convert.ToByte(Int64(42)));
Assert.IsException(->Convert.ToByte(Int64(259)));
Assert.IsException(->Convert.ToByte(Int64(-1)));
end;
method ConvertTest.ToByteChar;
begin
Assert.CheckInt(0, Convert.ToByte(Char(#0)));
Assert.CheckInt(13, Convert.ToByte(Char(#13)));
Assert.IsException(->Convert.ToByte(Char(#388)));
end;
method ConvertTest.ToByteString;
begin
Assert.CheckInt(0, Convert.ToByte("0"));
Assert.CheckInt(255, Convert.ToByte("255"));
Assert.IsException(->Convert.ToByte("-1"));
Assert.IsException(->Convert.ToByte("5.25"));
Assert.IsException(->Convert.ToByte("FF"));
end;
method ConvertTest.ToCharInt32;
begin
Assert.CheckString(#13, Convert.ToChar(Int32(13)));
Assert.CheckString(#0, Convert.ToChar(Int32(0)));
Assert.IsException(->Convert.ToChar(Consts.MaxInteger));
Assert.IsException(->Convert.ToChar(Consts.MinInteger));
end;
method ConvertTest.ToCharInt64;
begin
Assert.CheckString(#13, Convert.ToChar(Int64(13)));
Assert.CheckString(#0, Convert.ToChar(Int64(0)));
Assert.IsException(->Convert.ToChar(Consts.MaxInt64));
Assert.IsException(->Convert.ToChar(Consts.MinInt64));
end;
method ConvertTest.ToCharByte;
begin
Assert.CheckString(#13, Convert.ToChar(Byte(13)));
Assert.CheckString(#0, Convert.ToChar(Byte(0)));
Assert.CheckString(#255, Convert.ToChar(Byte(255)));
end;
method ConvertTest.ToCharString;
begin
Assert.CheckString(#32, Convert.ToChar(" "));
Assert.IsException(->Convert.ToChar(""));
Assert.IsException(->Convert.ToChar(nil));
Assert.IsException(->Convert.ToChar("xx"));
end;
method ConvertTest.ToBooleanDouble;
begin
Assert.CheckBool(false, Convert.ToBoolean(Double(0.0)));
Assert.CheckBool(true, Convert.ToBoolean(Double(0.1)));
Assert.CheckBool(true, Convert.ToBoolean(Double(-1.1)));
Assert.CheckBool(true, Convert.ToBoolean(Consts.NaN));
Assert.CheckBool(true, Convert.ToBoolean(Consts.NegativeInfinity));
Assert.CheckBool(true, Convert.ToBoolean(Consts.PositiveInfinity));
end;
method ConvertTest.ToBooleanInt32;
begin
Assert.CheckBool(false, Convert.ToBoolean(Int32(0)));
Assert.CheckBool(true, Convert.ToBoolean(Int32(1)));
Assert.CheckBool(true, Convert.ToBoolean(Int32(-1)));
end;
method ConvertTest.ToBooleanInt64;
begin
Assert.CheckBool(false, Convert.ToBoolean(Int64(0)));
Assert.CheckBool(true, Convert.ToBoolean(Int64(1)));
Assert.CheckBool(true, Convert.ToBoolean(Int64(-1)));
end;
method ConvertTest.ToBooleanByte;
begin
Assert.CheckBool(false, Convert.ToBoolean(Byte(0)));
Assert.CheckBool(true, Convert.ToBoolean(Byte(1)));
Assert.CheckBool(true, Convert.ToBoolean(Byte(-1)));
end;
method ConvertTest.ToBooleanString;
begin
Assert.CheckBool(true, Convert.ToBoolean(Consts.TrueString));
Assert.CheckBool(false, Convert.ToBoolean(Consts.FalseString));
Assert.CheckBool(false, Convert.ToBoolean(nil));
Assert.IsException(->Convert.ToBoolean(""));
Assert.IsException(->Convert.ToBoolean("a"));
Assert.IsException(->Convert.ToBoolean("yes"));
Assert.IsException(->Convert.ToBoolean("no"));
end;
end.
|
unit Data.DataProxy;
interface
uses
System.Classes,
System.SysUtils,
Data.DB;
type
TGenericDataSetProxy = class(TComponent)
private
protected
FDataSet: TDataSet;
procedure ConnectFields; virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// -------------
procedure ConnectWithDataSet(aDataSet: TDataSet);
// -------------
procedure Append; inline;
procedure Cancel; inline;
procedure Close; inline;
function ControlsDisabled: Boolean;
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
procedure Delete; inline;
procedure DisableControls;
procedure Edit; inline;
procedure EnableControls;
procedure First; inline;
procedure Insert; inline;
procedure InsertRecord(const Values: array of const);
function IsEmpty: Boolean; inline;
procedure Last; inline;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
procedure Next; inline;
procedure Open;
procedure Post; inline;
procedure Prior; inline;
procedure Refresh; inline;
function UpdateStatus: TUpdateStatus;
end;
TDatasetProxy = class(TGenericDataSetProxy)
procedure ForEach(OnElem: TProc<TDatasetProxy>);
end;
implementation
{ TGenericDataObject }
uses Helper.TDataSet;
procedure TGenericDataSetProxy.Append;
begin
FDataSet.Append;
end;
procedure TGenericDataSetProxy.Cancel;
begin
FDataSet.Cancel;
end;
procedure TGenericDataSetProxy.Close;
begin
FDataSet.Close;
end;
procedure TGenericDataSetProxy.ConnectWithDataSet(aDataSet: TDataSet);
begin
FDataSet := aDataSet;
end;
function TGenericDataSetProxy.ControlsDisabled: Boolean;
begin
Result := FDataSet.ControlsDisabled;
end;
constructor TGenericDataSetProxy.Create(AOwner: TComponent);
begin
inherited;
// TODO: Implement
end;
function TGenericDataSetProxy.CreateBlobStream(Field: TField;
Mode: TBlobStreamMode): TStream;
begin
Result := FDataSet.CreateBlobStream(Field, Mode);
end;
procedure TGenericDataSetProxy.Delete;
begin
FDataSet.Delete;
end;
destructor TGenericDataSetProxy.Destroy;
begin
inherited;
end;
procedure TGenericDataSetProxy.DisableControls;
begin
FDataSet.DisableControls;
end;
procedure TGenericDataSetProxy.Edit;
begin
FDataSet.Edit;
end;
procedure TGenericDataSetProxy.EnableControls;
begin
FDataSet.EnableControls;
end;
procedure TGenericDataSetProxy.First;
begin
FDataSet.First;
end;
procedure TGenericDataSetProxy.Insert;
begin
FDataSet.Insert;
end;
procedure TGenericDataSetProxy.InsertRecord(const Values: array of const);
begin
FDataSet.InsertRecord(Values);
end;
function TGenericDataSetProxy.IsEmpty: Boolean;
begin
Result := FDataSet.IsEmpty;
end;
procedure TGenericDataSetProxy.Last;
begin
FDataSet.Last;
end;
function TGenericDataSetProxy.Locate(const KeyFields: string;
const KeyValues: Variant; Options: TLocateOptions): Boolean;
begin
Result := FDataSet.Locate(KeyFields, KeyValues, Options);
end;
function TGenericDataSetProxy.Lookup(const KeyFields: string;
const KeyValues: Variant; const ResultFields: string): Variant;
begin
Result := FDataSet.Lookup(KeyFields, KeyValues, ResultFields);
end;
procedure TGenericDataSetProxy.Next;
begin
FDataSet.Next;
end;
procedure TGenericDataSetProxy.Open;
begin
FDataSet.Open;
ConnectFields;
end;
procedure TGenericDataSetProxy.Post;
begin
FDataSet.Post;
end;
procedure TGenericDataSetProxy.Prior;
begin
FDataSet.Prior;
end;
procedure TGenericDataSetProxy.Refresh;
begin
FDataSet.Refresh;
end;
function TGenericDataSetProxy.UpdateStatus: TUpdateStatus;
begin
Result := FDataSet.UpdateStatus;
end;
{ TItarableDataObject }
procedure TDatasetProxy.ForEach(OnElem: TProc<TDatasetProxy>);
begin
// TODO: Wyciągnij kod z helper-a (reużywalność vs wydajność)
FDataSet.WhileNotEof(
procedure()
begin
OnElem (self);
end);
end;
end.
|
(* Б) Напишите функцию для приведения любой буквы к верхнему регистру
(включая и русские). Подсказка: вспомните о таблице кодировки. *)
function UpChar(aChar : char): char;
const cHighChars = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЪЫЭЮЯ';
cLowChars = 'абвгдеёжзийклмнопрстуфхцчшщьъыэюя';
var j : byte;
begin
if aChar in ['a'..'z'] then
aChar := UpCase(aChar)
else if aChar in ['а'..'я'] then
for j := 1 to Length(cLowChars) do
if aChar = cLowChars[j] then
aChar := cHighChars[j];
UpChar := aChar;
end;
procedure UpAllChars(var aStr : string);
var
i, len : word;
begin
len := Length((aStr));
for i := 1 to len do begin
aStr[i] := UpChar(aStr[i]);
end;
end;
var
strEn, strRu : string;
begin
strEn := 'pascal is awesome!';
strRu := 'паскаль шикарен! (а п р я)';
Writeln(strEn);
UpAllChars(strEn);
Writeln(strEn);
Writeln(strRu);
UpAllChars(strRu);
Writeln(strRu);
end. |
unit UCL.TUForm;
interface
uses
UCL.Classes, UCL.SystemSettings, UCL.TUThemeManager, UCL.TUTooltip,
System.Classes, System.SysUtils,
Winapi.Windows, Winapi.Messages,
VCL.Forms, VCL.Controls, VCL.ExtCtrls, VCL.Graphics;
type
TUForm = class(TForm, IUThemeComponent)
const
DEFAULT_BORDERCOLOR_ACTIVE_LIGHT = $707070;
DEFAULT_BORDERCOLOR_ACTIVE_DARK = $242424;
DEFAULT_BORDERCOLOR_INACTIVE_LIGHT = $9B9B9B;
DEFAULT_BORDERCOLOR_INACTIVE_DARK = $414141;
private
var BorderColor: TColor;
FThemeManager: TUThemeManager;
FIsActive: Boolean;
FResizable: Boolean;
FPPI: Integer;
// Setters
procedure SetThemeManager(const Value: TUThemeManager);
// Messages
procedure WM_Activate(var Msg: TWMActivate); message WM_ACTIVATE;
procedure WM_DPIChanged(var Msg: TWMDpi); message WM_DPICHANGED;
procedure WM_DWMColorizationColorChanged(var Msg: TMessage); message WM_DWMCOLORIZATIONCOLORCHANGED;
procedure WM_NCCalcSize(var Msg: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WM_NCHitTest(var Msg: TWMNCHitTest); message WM_NCHITTEST;
protected
procedure Paint; override;
procedure Resize; override;
public
constructor Create(aOwner: TComponent); override;
procedure UpdateTheme;
procedure UpdateBorderColor;
published
property ThemeManager: TUThemeManager read FThemeManager write SetThemeManager;
property IsActive: Boolean read FIsActive default true;
property Resizable: Boolean read FResizable write FResizable default true;
property PPI: Integer read FPPI write FPPI default 96;
end;
implementation
{ TUForm }
// UTILS
procedure TUForm.UpdateBorderColor;
begin
// Border color
if ThemeManager = nil then
BorderColor := DEFAULT_BORDERCOLOR_ACTIVE_LIGHT // Not set ThemeManager
else if IsActive then
begin
if ThemeManager.ColorOnBorder then
BorderColor := ThemeManager.AccentColor
else if ThemeManager.Theme = utLight then
BorderColor := DEFAULT_BORDERCOLOR_ACTIVE_LIGHT
else
BorderColor := DEFAULT_BORDERCOLOR_ACTIVE_DARK;
end
else
begin
if ThemeManager.Theme = utLight then
BorderColor := DEFAULT_BORDERCOLOR_INACTIVE_LIGHT
else
BorderColor := DEFAULT_BORDERCOLOR_INACTIVE_DARK;
end;
end;
// THEME
procedure TUForm.SetThemeManager(const Value: TUThemeManager);
begin
if Value <> FThemeManager then
begin
if FThemeManager <> nil then
FThemeManager.Disconnect(Self);
if Value <> nil then
Value.Connect(Self);
FThemeManager := Value;
UpdateTheme;
end;
end;
procedure TUForm.UpdateTheme;
begin
// Background color & tooltip style
if ThemeManager = nil then
begin
Color := $FFFFFF;
HintWindowClass := THintWindow; // Default hint style
end
else if ThemeManager.Theme = utLight then
begin
Color := $FFFFFF;
HintWindowClass := TULightTooltip;
end
else
begin
Color := $000000;
HintWindowClass := TUDarkTooltip;
end;
UpdateBorderColor;
Invalidate;
end;
// MAIN CLASS
constructor TUForm.Create(aOwner: TComponent);
var
CurrentScreen: TMonitor;
begin
inherited;
FIsActive := true;
FResizable := true;
Padding.SetBounds(0, 1, 0, 0); // Top space
// Get PPI from current screen
CurrentScreen := Screen.MonitorFromWindow(Handle);
FPPI := CurrentScreen.PixelsPerInch;
UpdateTheme;
end;
// CUSTOM METHODS
procedure TUForm.Paint;
begin
inherited;
if WindowState <> wsMaximized then // No border on maximized
begin
Canvas.Pen.Color := BorderColor;
Canvas.MoveTo(0, 0);
Canvas.LineTo(Width, 0); // Paint top border
end;
end;
procedure TUForm.Resize;
begin
inherited;
if WindowState = wsMaximized then
Padding.SetBounds(0, 0, 0, 0)
else
Padding.SetBounds(0, 1, 0, 0);
end;
// MESSAGES
procedure TUForm.WM_Activate(var Msg: TWMActivate);
begin
inherited;
FIsActive := Msg.Active <> WA_INACTIVE;
// Paint top border
if WindowState <> wsMaximized then
begin
UpdateBorderColor;
Canvas.Pen.Color := BorderColor;
Canvas.MoveTo(0, 0);
Canvas.LineTo(Width, 0);
end;
end;
procedure TUForm.WM_DPIChanged(var Msg: TWMDpi);
begin
PPI := Msg.XDpi;
inherited;
end;
procedure TUForm.WM_DWMColorizationColorChanged(var Msg: TMessage);
begin
if ThemeManager <> nil then
ThemeManager.ReloadAutoSettings;
inherited;
end;
procedure TUForm.WM_NCCalcSize(var Msg: TWMNCCalcSize);
var
CaptionBarHeight: Integer;
BorderSpace: Integer;
begin
inherited;
CaptionBarHeight :=
GetSystemMetrics(SM_CYFRAME) +
GetSystemMetrics(SM_CYCAPTION) +
GetSystemMetrics(SM_CXPADDEDBORDER);
Dec(Msg.CalcSize_Params.rgrc[0].Top, CaptionBarHeight); // Hide caption bar
if WindowState = wsMaximized then // Add space on top
begin
BorderSpace := GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);
Inc(Msg.CalcSize_Params.rgrc[0].Top, BorderSpace);
end;
end;
procedure TUForm.WM_NCHitTest(var Msg: TWMNCHitTest);
begin
inherited;
if Resizable then
begin
if Msg.YPos - BoundsRect.Top < 5 then
Msg.Result := HTTOP;
end
else if // Preparing to resize
Msg.Result in [HTTOP, HTTOPLEFT, HTTOPRIGHT, HTLEFT, HTRIGHT, HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT]
then
Msg.Result := HTNOWHERE;
end;
end.
|
// Copyright (c) 2017, Jordi Corbilla
// 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
unit uFormTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, lib.firebase.rest, DBXJSON,
System.JSON, Data.DBXJSONCommon, lib.document, generics.collections,
Vcl.OleCtrls, SHDocVw, Vcl.ComCtrls;
type
TForm3 = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Button1: TButton;
Memo1: TMemo;
Edit1: TEdit;
Edit2: TEdit;
Button2: TButton;
AddFile: TButton;
Button3: TButton;
Memo2: TMemo;
Button4: TButton;
ListBox1: TListBox;
WebBrowser1: TWebBrowser;
Button5: TButton;
OpenDialog1: TOpenDialog;
Edit3: TEdit;
Label1: TLabel;
Button6: TButton;
Edit4: TEdit;
Label2: TLabel;
Memo3: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure AddFileClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure ListBox1DblClick(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
function LoadDocuments(jsonString: string): TList<IDocument>;
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
uses
NetEncoding, IdCoderMIME, IdHash, IdHMAC, IdHMACSHA1, IdGlobal, StrUtils;
{$R *.dfm}
procedure TForm3.AddFileClick(Sender: TObject);
var
strFileStream: TFileStream;
arr : TJSONArray;
s : string;
ByteArray: array of Byte;
begin
OpenDialog1.InitialDir := GetCurrentDir;
// Only allow existing files to be selected
OpenDialog1.Options := [ofFileMustExist];
// Allow only .dpr and .pas files to be selected
OpenDialog1.Filter :=
'PDF Files|*.pdf|MS Word|*.docx';
// Select pascal files as the starting filter type
//OpenDialog1.FilterIndex := 2;
// Display the open file dialog
if OpenDialog1.Execute then
begin
//ShowMessage('File : '+OpenDialog1.FileName);
strFileStream := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
arr := TDBXJSONTools.StreamToJSON(strFileStream, 0, strFileStream.Size);
strFileStream.Position := 0;
SetLength(ByteArray, strFileStream.Size);
strFileStream.Read(ByteArray[0], strFileStream.Size);
strFileStream.Free;
//s := String(TNetEncoding.URL.EncodeBytesToString(TIdEncoderMIME.EncodeBytes(IndyTextEncoding_UTF8.GetBytes(ByteArray))));
s := '{"document":"'+extractfilename(OpenDialog1.FileName)+'","array":'+arr.toJSON+'}';
TFirebaseRest.New.Add(s);
//arr.
end
else
begin
ShowMessage('Open file was cancelled');
end;
// Free up the dialog
OpenDialog1.Free;
end;
procedure TForm3.Button1Click(Sender: TObject);
var
firebase : string;
List : TList<IDocument>;
i: Integer;
begin
firebase := TFirebaseRest.New.GetCollection;
List := LoadDocuments(firebase);
//Memo1.Lines.Add(firebase);
for i := 0 to list.Count-1 do
begin
listbox1.AddItem(list[i].FileName, TDocument(list[i]));
end;
end;
procedure TForm3.Button2Click(Sender: TObject);
var
jsonString : string;
begin
jsonString := '{"param1":"'+Edit1.text+'","value":"'+Edit2.text+'"}';
if TFirebaseRest.New.Add(jsonString) then
begin
showMessage('Item has been successfully added!');
end
else
showMessage('There was an error adding the data to the cloud storage');
end;
procedure TForm3.Button3Click(Sender: TObject);
begin
TFirebaseRest.New.Delete();
end;
procedure TForm3.ListBox1DblClick(Sender: TObject);
var
document : TDOcument;
begin
if (ListBox1.ItemIndex >= 0) then
begin
WebBrowser1.Navigate2('about:blank');
sleep(2000);
Application.ProcessMessages;
document := (listBox1.Items.Objects[ListBox1.ItemIndex] as TDocument);
document.Save;
WebBrowser1.Navigate2('file://c:/temp/' + document.FileName);
end;
end;
function TForm3.LoadDocuments(jsonString : string) : TList<IDocument>;
var
s : string;
i : integer;
j, k : integer;
doc : string;
name : string;
list : TList<IDocument>;
begin
list := TList<IDocument>.Create;
s := jsonString;
i := 1;
while i > 0 do
begin
i := AnsiPos('array', s);
j := AnsiPos('document', s);
if ((i > 0) and (j>0)) then
begin
doc := copy(s, i, j-i);
doc := doc.Replace('array":', '');
doc := doc.Replace(',"', '');
name := AnsiRightStr(s, length(s)-j+1);
k := AnsiPos('}', name);
name := copy(name, 0, k);
name := name.Replace('document":"', '');
name := name.Replace('"}', '');
s := AnsiRightStr(s, length(s)-(j+k));
list.Add(TDocument.New(name, doc));
end;
end;
result := list;
end;
procedure TForm3.Button4Click(Sender: TObject);
var
s : string;
i : integer;
j, k : integer;
doc : string;
name : string;
jsonArray : TJSONArray;
fs: TFileStream;
Stream : TStream;
buf: TBytes;
begin
//Parse the following string
//{"-KUmo1JUUAVTRAiZVXKd":{"array":[37,80],"document":"TESTING FIREBASE.pdf"}}
s := '{"-KUmo1JUUAVTRAiZVXKd":{"array":[37,80],"document":"TESTING FIREBASE.pdf"},"-KUmo1JUUAVTRAiZVXKd":{"array":[37,80],"document":"TESTING FIREBASE.pdf"}}'; //memo1.Lines.ToString;
s := memo1.Lines.Text;
i := 1;
while i > 0 do
begin
i := AnsiPos('array', s);
j := AnsiPos('document', s);
if ((i > 0) and (j>0)) then
begin
doc := copy(s, i, j-i);
//array":[37,80],"
doc := doc.Replace('array":', '');
doc := doc.Replace(',"', '');
memo2.Lines.Add(doc);
name := AnsiRightStr(s, length(s)-j+1);
k := AnsiPos('}', name);
name := copy(name, 0, k);
name := name.Replace('document":"', '');
name := name.Replace('"}', '');
memo2.Lines.Add(name);
s := AnsiRightStr(s, length(s)-(j+k));
//document":"TESTING FIREBASE.pdf"}
end;
end;
jsonArray := TJSONObject.ParseJSONValue(doc) as TJSONArray;
fs := TFileStream.Create('c:\temp\' + name, fmCreate);
Stream := TDBXJSONTools.JSONToStream(jsonArray);
SetLength(buf, Stream.Size);
Stream.Position := 0;
Stream.ReadBuffer(buf[0], Stream.Size);
fs.WriteBuffer(buf[0], Stream.Size);
Stream.Free;
fs.Free;
end;
procedure TForm3.Button5Click(Sender: TObject);
begin
WebBrowser1.Navigate2('file://c:/temp/TESTING FIREBASE 2.pdf');
// WebBrowser1.Navigate('www.google.co.uk');
end;
procedure TForm3.Button6Click(Sender: TObject);
var
firebase : IFirebaseRest;
result : string;
begin
TThread.Synchronize(TThread.CurrentThread, procedure
begin
firebase := TFirebaseRest.New;
try
result := firebase.RegisterDeviceToken(edit3.Text, edit4.text);
memo3.Lines.Add(result);
finally
end;
end);
end;
end.
|
unit CreateConstraint;
interface
uses
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CreateObjectDialog, Vcl.Buttons,
Vcl.Grids, JvExGrids, JvStringGrid, BCControls.StringGrid, Vcl.StdCtrls, BCControls.ComboBox, BCControls.Edit,
Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, Vcl.ActnList, Vcl.ComCtrls, Vcl.ToolWin, JvExComCtrls, SynEdit,
Vcl.ExtCtrls, JvComCtrls, BCControls.PageControl, Ora, BCControls.ToolBar, BCDialogs.Dlg, System.Actions,
BCControls.ImageList;
type
TCreateConstraintDialog = class(TCreateObjectBaseDialog)
CheckRadioButton: TRadioButton;
ColumnBottomPanel: TPanel;
ColumnsPanel: TPanel;
ColumnsStringGrid: TBCStringGrid;
ColumnsTabSheet: TTabSheet;
ConditionPanel: TPanel;
ConditionSynEdit: TSynEdit;
ConditionTabSheet: TTabSheet;
ConstraintNameEdit: TBCEdit;
ConstraintNameLabel: TLabel;
ForeignKeyRadioButton: TRadioButton;
Label1: TLabel;
MoveDownColumnAction: TAction;
MoveDownRefColumnAction: TAction;
MoveupColumnAction: TAction;
MoveupRefColumnAction: TAction;
PrimaryKeyRadioButton: TRadioButton;
RefColumnsPanel: TPanel;
RefColumnsStringGrid: TBCStringGrid;
RefColumnTopPanel: TPanel;
ReferencedColumnsBottomPanel: TPanel;
ReferencedColumnsTabSheet: TTabSheet;
RefTableNameComboBox: TBCComboBox;
TableLabel: TLabel;
TableNameComboBox: TBCComboBox;
TableNameEdit: TBCEdit;
TypeLabel: TLabel;
UniqueRadioButton: TRadioButton;
ColumnsToolBar: TBCToolBar;
MoveUpToolButton: TToolButton;
MoveDownToolButton: TToolButton;
RefColumnsToolBar: TBCToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
procedure FormDestroy(Sender: TObject);
procedure MoveDownColumnActionExecute(Sender: TObject);
procedure MoveDownRefColumnActionExecute(Sender: TObject);
procedure MoveupColumnActionExecute(Sender: TObject);
procedure MoveupRefColumnActionExecute(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure RefTableNameComboBoxChange(Sender: TObject);
procedure TableNameComboBoxChange(Sender: TObject);
private
{ Private declarations }
procedure GetColumnNames(TableName: string; Grid: TBCStringGrid);
procedure GetTableNames;
protected
function CheckFields: Boolean; override;
procedure CreateSQL; override;
procedure Initialize; override;
public
{ Public declarations }
end;
function CreateConstraintDialog: TCreateConstraintDialog;
implementation
{$R *.dfm}
uses
DataModule, Lib, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.Lib;
var
FCreateConstraintDialog: TCreateConstraintDialog;
function CreateConstraintDialog: TCreateConstraintDialog;
begin
if not Assigned(FCreateConstraintDialog) then
Application.CreateForm(TCreateConstraintDialog, FCreateConstraintDialog);
Result := FCreateConstraintDialog;
SetStyledFormSize(TDialog(Result));
end;
procedure TCreateConstraintDialog.FormDestroy(Sender: TObject);
begin
inherited;
FCreateConstraintDialog := nil;
end;
procedure TCreateConstraintDialog.MoveDownColumnActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveStringGridRow(ColumnsStringGrid, 1);
end;
procedure TCreateConstraintDialog.MoveDownRefColumnActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveStringGridRow(RefColumnsStringGrid, 1);
end;
procedure TCreateConstraintDialog.MoveupColumnActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveStringGridRow(ColumnsStringGrid, -1);
end;
procedure TCreateConstraintDialog.MoveupRefColumnActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveStringGridRow(RefColumnsStringGrid, -1);
end;
procedure TCreateConstraintDialog.PageControlChange(Sender: TObject);
begin
ReferencedColumnsTabSheet.TabVisible := ForeignKeyRadioButton.Checked;
ConditionTabSheet.TabVisible := CheckRadioButton.Checked;
inherited;
end;
procedure TCreateConstraintDialog.RefTableNameComboBoxChange(Sender: TObject);
begin
inherited;
GetColumnNames(RefTableNameComboBox.Text, RefColumnsStringGrid);
CreateSQL;
end;
procedure TCreateConstraintDialog.TableNameComboBoxChange(Sender: TObject);
begin
inherited;
GetColumnNames(TableNameComboBox.Text, ColumnsStringGrid);
CreateSQL;
end;
function TCreateConstraintDialog.CheckFields: Boolean;
var
i: Integer;
TrueCount: Integer;
begin
Result := False;
if Trim(ConstraintNameEdit.Text) = '' then
begin
ShowErrorMessage('Set constraint name.');
ConstraintNameEdit.SetFocus;
Exit;
end;
if Trim(TableNameComboBox.Text) = '' then
begin
ShowErrorMessage('Set table name.');
TableNameComboBox.SetFocus;
Exit;
end;
TrueCount := 0;
for i := 0 to ColumnsStringGrid.RowCount - 1 do
if ColumnsStringGrid.Cells[1, i] = 'True' then
Inc(TrueCount);
if TrueCount = 0 then
begin
ShowErrorMessage('Set columns.');
Exit;
end;
if (UniqueRadioButton.Checked or CheckRadioButton.Checked) and
(TrueCount <> 1) then
begin
ShowErrorMessage('Unique and Check type allow only one column.');
Exit;
end;
if ForeignKeyRadioButton.Checked then
begin
TrueCount := 0;
for i := 0 to RefColumnsStringGrid.RowCount - 1 do
if RefColumnsStringGrid.Cells[1, i] = 'True' then
Inc(TrueCount);
if TrueCount = 0 then
begin
ShowErrorMessage('Set referenced columns.');
Exit;
end;
end;
Result := True;
end;
procedure TCreateConstraintDialog.GetTableNames;
var
OraQuery: TOraQuery;
begin
OraQuery := TOraQuery.Create(nil);
OraQuery.Session := FOraSession;
OraQuery.SQL.Add(DM.StringHolder.StringsByName['AllTablesOfSchemaSQL'].Text);
with OraQuery do
try
ParamByName('P_SCHEMA').AsWideString := FSchemaParam;
Prepare;
Open;
while not Eof do
begin
TableNameComboBox.Items.Add(FieldByName('TABLE_NAME').AsString);
RefTableNameComboBox.Items.Add(FieldByName('TABLE_NAME').AsString);
Next;
end;
finally
Close;
UnPrepare;
FreeAndNil(OraQuery);
end;
end;
procedure TCreateConstraintDialog.GetColumnNames(TableName: string; Grid: TBCStringGrid);
var
i: Integer;
OraQuery: TOraQuery;
begin
OraQuery := TOraQuery.Create(nil);
OraQuery.Session := FOraSession;
OraQuery.SQL.Add(DM.StringHolder.StringsByName['TableColumnsSQL'].Text);
with OraQuery do
try
ParamByName('P_TABLE_NAME').AsWideString := TableName;
ParamByName('P_SCHEMA').AsWideString := FSchemaParam;
Prepare;
Open;
i := 1; // header & first row
Grid.RowCount := RecordCount + 1;
while not Eof do
begin
Grid.Cells[0, i] := FieldByName('COLUMN_NAME').AsString;
Grid.Cells[1, i] := 'False';
Inc(i);
Next;
end;
finally
Close;
UnPrepare;
FreeAndNil(OraQuery);
end;
end;
procedure TCreateConstraintDialog.Initialize;
begin
inherited;
ReferencedColumnsTabSheet.TabVisible := False;
ConditionTabSheet.TabVisible := False;
ColumnsStringGrid.Cells[0, 0] := 'Column';
ColumnsStringGrid.Cells[1, 0] := 'Selected';
RefColumnsStringGrid.Cells[0, 0] := 'Column';
RefColumnsStringGrid.Cells[1, 0] := 'Selected';
GetTableNames;
SourceSynEdit.Text := '';
if FObjectName <> '' then
begin
TableNameEdit.Visible := True;
TableNameEdit.Text := FObjectName;
TableNameComboBox.Visible := False;
TableNameComboBox.Text := FObjectName;
GetColumnNames(TableNameComboBox.Text, ColumnsStringGrid);
end;
end;
function GetColumns(Grid: TBCStringGrid): string;
var
i: Integer;
begin
Result := '';
for i := 0 to Grid.RowCount - 1 do
begin
if Grid.Cells[1, i] = 'True' then
begin
if Result <> '' then
Result := Result + ', ';
Result := Result + Grid.Cells[0, i];
end;
end;
end;
procedure TCreateConstraintDialog.CreateSQL;
var
Columns: string;
begin
SourceSynEdit.Lines.Clear;
SourceSynEdit.Lines.BeginUpdate;
SourceSynEdit.Lines.Text := Format('ALTER TABLE %s', [TableNameComboBox.Text]) + CHR_ENTER;
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' ADD CONSTRAINT %s', [ConstraintNameEdit.Text]) + CHR_ENTER;
Columns := GetColumns(ColumnsStringGrid);
if PrimaryKeyRadioButton.Checked then
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' PRIMARY KEY (%s);', [Columns]) + CHR_ENTER;
if ForeignKeyRadioButton.Checked then
begin
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' FOREIGN KEY (%s)', [Columns]) + CHR_ENTER;
Columns := GetColumns(RefColumnsStringGrid);
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' REFERENCING %s (%s);', [RefTableNameComboBox.Text, Columns]) + CHR_ENTER;
end;
if UniqueRadioButton.Checked then
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' UNIQUE (%s);', [Columns]) + CHR_ENTER;
if CheckRadioButton.Checked then
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format(' CHECK (%s = %s);', [Columns, ConditionSynEdit.Text]) + CHR_ENTER;
SourceSynEdit.Lines.Text := Trim(SourceSynEdit.Lines.Text);
SourceSynEdit.Lines.EndUpdate;
end;
end.
|
unit DropTable;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ExtCtrls, BCDialogs.Dlg, BCControls.CheckBox, JvExStdCtrls, JvCheckBox;
type
TDropTableDialog = class(TDialog)
CancelButton: TButton;
CascadeConstraintsCheckBox: TBCCheckBox;
GrayLinePanel: TPanel;
InfoImage: TImage;
MessageLabel: TLabel;
OKButton: TButton;
Panel1: TPanel;
PurgeCheckBox: TBCCheckBox;
Separator1Panel: TPanel;
TopPanel: TPanel;
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
function GetCascadeConstraints: Boolean;
function GetPurge: Boolean;
public
{ Public declarations }
function Open(TableName: string): Boolean;
property CascadeConstraints: Boolean read GetCascadeConstraints;
property Purge: Boolean read GetPurge;
end;
function DropTableDialog: TDropTableDialog;
implementation
{$R *.dfm}
uses
System.Math, BCCommon.StyleUtils;
const
CAPTION_TEXT = 'Drop table %s, are you sure?';
var
FDropTableDialog: TDropTableDialog;
function DropTableDialog: TDropTableDialog;
begin
if not Assigned(FDropTableDialog) then
Application.CreateForm(TDropTableDialog, FDropTableDialog);
Result := FDropTableDialog;
SetStyledFormSize(Result);
end;
procedure TDropTableDialog.FormDestroy(Sender: TObject);
begin
FDropTableDialog := nil;
end;
function TDropTableDialog.GetCascadeConstraints: Boolean;
begin
Result := CascadeConstraintsCheckBox.Checked;
end;
function TDropTableDialog.GetPurge: Boolean;
begin
Result := PurgeCheckBox.Checked;
end;
function TDropTableDialog.Open(TableName: string): Boolean;
begin
MessageLabel.Caption := Format(CAPTION_TEXT, [TableName]);
InfoImage.Picture.Icon.Handle := LoadIcon(0, IDI_INFORMATION);
Width := Max(220, InfoImage.Width + MessageLabel.Width + 40);
Result := ShowModal = mrOk;
end;
end.
|
unit uDMCore;
interface
uses
System.SysUtils, System.Classes, System.StrUtils, OraCall, Data.DB, DBAccess,
Ora, MemDS;
type
TdmCore = class(TDataModule)
oSession: TOraSession;
oqGetPrivName: TOraQuery;
oqGetUserInfo: TOraQuery;
oSQLSetTCorrRecord: TOraSQL;
oqGetDogsWithNoECopyDate: TOraQuery;
ospSetECopyDateForDog: TOraStoredProc;
ospSetECopyPagesForDog: TOraStoredProc;
oqGetFullECopyName: TOraQuery;
oqGetEmpNameByLN: TOraQuery;
private
public
function GetPrivilegeName(const UserPoln: integer): string;
procedure GetUserInfo(const UserPoln: integer = 0);
function GetXLTemplate(const FileID: integer): string;
procedure SetTCORRRecord(const pRectype, pTable, pOper: string;
const pDog: string = ''; const pKPRED: string = '';
const pPRDPK: string = ''; const pKORG: integer = 0;
const pDogID: integer = 0);
function GetFullECopyName(const DogID: integer; var FullName: string)
: boolean; overload;
function GetFullECopyName(const DogID: integer): string; overload;
function GetEmpNameByLN(const ln: integer): string;
end;
var
dmCore: TdmCore;
implementation
uses uAppVersion, uGlobals;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
function TdmCore.GetPrivilegeName(const UserPoln: integer): string;
begin
if not oSession.Connected then
oSession.Connect;
oqGetPrivName.ParamByName('appcode').AsInteger := AppVerRecord.major;
oqGetPrivName.ParamByName('rcode').AsInteger := UserPoln;
oqGetPrivName.Open;
result := oqGetPrivName.Fields[0].AsString;
oqGetPrivName.Close;
end;
procedure TdmCore.GetUserInfo(const UserPoln: integer);
begin
gvUserInfo.RightsN := UserPoln;
gvUserInfo.RightsS := dmCore.GetPrivilegeName(UserPoln);
gvUserInfo.OSName := LowerCase(GetEnvironmentVariable('username'));
oqGetUserInfo.Params[0].AsString := gvUserInfo.OSName;
oqGetUserInfo.Open;
if oqGetUserInfo.RecordCount > 0 then
begin
gvUserInfo.NameFull := oqGetUserInfo.Fields[0].AsString;
gvUserInfo.NameShort := oqGetUserInfo.Fields[1].AsString;
gvUserInfo.Shop := oqGetUserInfo.Fields[2].AsInteger;
gvUserInfo.Phone := oqGetUserInfo.Fields[3].AsString;
gvUserInfo.SMTP := oqGetUserInfo.Fields[4].AsString;
gvUserInfo.LNOM := oqGetUserInfo.Fields[5].AsInteger;
end;
oqGetUserInfo.Close;
end;
function TdmCore.GetXLTemplate(const FileID: integer): string;
begin
result := self.oSession.ExecProc('TYPES.GET_PATH_FILE',
[AppVerRecord.major, FileID]);
end;
function TdmCore.GetEmpNameByLN(const ln: integer): string;
begin
oqGetEmpNameByLN.Params[0].AsInteger := ln;
oqGetEmpNameByLN.Open;
result := oqGetEmpNameByLN.Fields[0].AsString;
oqGetEmpNameByLN.Close;
end;
function TdmCore.GetFullECopyName(const DogID: integer): string;
begin
oqGetFullECopyName.Params[0].AsInteger := DogID;
oqGetFullECopyName.Open;
result := ifThen(oqGetFullECopyName.RecordCount > 0,
oqGetFullECopyName.Fields[0].AsString, EmptyStr);
oqGetFullECopyName.Close;
end;
function TdmCore.GetFullECopyName(const DogID: integer;
var FullName: string): boolean;
begin
FullName := GetFullECopyName(DogID);
result := not FullName.IsEmpty;
end;
procedure TdmCore.SetTCORRRecord(const pRectype, pTable, pOper: string;
const pDog: string = ''; const pKPRED: string = ''; const pPRDPK: string = '';
const pKORG: integer = 0; const pDogID: integer = 0);
begin
oSQLSetTCorrRecord.ParamByName('pRectype').AsString := pRectype;
oSQLSetTCorrRecord.ParamByName('pKS').AsInteger := gvUserInfo.Shop;
oSQLSetTCorrRecord.ParamByName('pKP').AsInteger := gvUserInfo.LNOM;
oSQLSetTCorrRecord.ParamByName('pUser').AsString := gvUserInfo.NameShort;
oSQLSetTCorrRecord.ParamByName('pTable').AsString := pTable;
oSQLSetTCorrRecord.ParamByName('pOper').AsString := pOper;
oSQLSetTCorrRecord.ParamByName('pKORG').AsString :=
ifThen(pKORG > 0, IntToStr(pKORG), EmptyStr);
oSQLSetTCorrRecord.ParamByName('pDOG').AsString := pDog;
oSQLSetTCorrRecord.ParamByName('pGOD').AsString :=
ifThen(pDogID > 0, IntToStr(pDogID), EmptyStr);
oSQLSetTCorrRecord.ParamByName('pKPRED').AsString := pKPred;
oSQLSetTCorrRecord.ParamByName('pPRDPK').AsString := pPRDPK;
oSQLSetTCorrRecord.Execute;
end;
end.
|
unit Slider;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics;
type
TSlider = class(TCustomControl)
private
fCaption:String;
fColorBackGrnd:TColor;
fColorSlot:TColor;
fMin:Integer;
fMax:Integer;
fPos:Integer;
fOnChange : TNotifyEvent;
Procedure Set_Caption(Value:String);
Procedure Set_ColorSlot(Value:TColor);
Procedure Set_ColorBackGrnd(Value:TColor);
Procedure Set_Min(Value:Integer);
Procedure Set_Max(Value:Integer);
Procedure Set_Pos(Value:Integer);
protected
procedure Resize; override;
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
Property Caption : String Read fCaption Write Set_Caption;
Property ColorSlot:TColor Read fColorSlot Write Set_ColorSlot;
Property ColorBackGrnd:TColor Read fColorBackGrnd Write Set_ColorBackGrnd;
Property Min:Integer Read fMin Write Set_Min;
Property Max:Integer Read fMax Write Set_Max;
Property Pos:Integer Read fPos Write Set_Pos;
Property Tag;
Property Enabled;
Property OnMouseDown;
Property OnMouseMove;
Property OnMouseUp;
Property OnClick;
Property OnDblClick;
Property Color;
Property OnChange:TNotifyEvent Read fOnChange Write fOnChange;
Property OnEnter;
Property OnExit;
Property OnKeyPress;
Property OnKeyDown;
Property OnKeyUp;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MUSIC_PRO', [TSlider]);
end;
constructor TSlider.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DoubleBuffered:=True;
Width:=44;
fMin:=-50;
fMax:=50;
fPos:=0;
Color:=$00A3B4BE;
ColorSlot:=clWhite;
end;
destructor TSlider.Destroy;
begin
inherited;
end;
Procedure TSlider.Set_Caption(Value:String);
begin
fCaption:=Value;
Invalidate;
end;
Procedure TSlider.Set_ColorSlot(Value:TColor);
begin
fColorSlot:=Value;
Invalidate;
end;
Procedure TSlider.Set_ColorBackGrnd(Value:TColor);
begin
fColorBackGrnd:=Value;
Invalidate;
end;
Procedure TSlider.Set_Min(Value:Integer);
begin
if (Value<=fPos) And (Value<fMax) Then
Begin
fMin:=Value;
Invalidate;
End;
end;
Procedure TSlider.Set_Max(Value:Integer);
begin
if (Value>=fPos) And (Value>fMin) Then
Begin
fMax:=Value;
Invalidate;
End;
end;
Procedure TSlider.Set_Pos(Value:Integer);
begin
if (Value>=fMin) And (Value<=fMax) Then
Begin
fPos:=Value;
Invalidate;
End;
end;
procedure TSlider.Resize;
Begin
InHerited;
Width:=100;
Height:=35;
End;
procedure TSlider.Paint;
Var
UpperCorner,LowerCorner:Array [0..2] Of TPoint;
SlotRect,Rect:TRect;
X,WidthText,HeightText:Integer;
ValueStr:String;
Begin
InHerited;
With Canvas Do
Begin
Pen.Width:=2;
UpperCorner[0]:=Point(0,Height);
UpperCorner[1]:=Point(0,0);
UpperCorner[2]:=Point(Width,0);
LowerCorner[0]:=Point(0,Self.Height);
LowerCorner[1]:=Point(Width,Height);
LowerCorner[2]:=Point(Width,0);
Pen.Color:=ClWhite;
Polyline(UpperCorner);
Pen.Color:=$00657271;
Polyline(LowerCorner);
Pen.Width:=1;
Brush.Color:=fColorBackGrnd;
With Rect Do
Begin
Left:=Width Div 10;
Right:=9*Width Div 10;
Top:=55*Height Div 100;
Bottom:=95*Height Div 100;
End;
Rectangle(Rect);
X:=(8*Width Div 10)*(fPos-fMin) Div (fMax-fMin)+Width Div 10;
Pen.Width:=1;
Brush.Color:=fColorSlot;
With SlotRect Do
Begin
Left:=X-2;
Right:=X+2;
Top:=55*Height Div 100;
Bottom:=95*Height Div 100;
End;
Rectangle(SlotRect);
Pen.Width:=0;
ValueStr:=fCaption+' '+IntToStr(fPos);
WidthText:=(Width-TextWidth(ValueStr)) Div 2;
HeightText:=(Height Div 2 - TextHeight(ValueStr)) Div 2;
Brush.Style:=BsClear;
TextOut(WidthText,HeightText,ValueStr);
End;
End;
procedure TSlider.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
Begin
InHerited;
If SSLeft In Shift Then
MouseMove(Shift, X, Y);
End;
procedure TSlider.MouseMove(Shift: TShiftState; X, Y: Integer);
Begin
InHerited;
If SSLeft In Shift Then
Begin
fPos:=(X-Width Div 10)*(fMax-fMin) Div (8*Width Div 10)+fMin;
If fPos>fMax Then fPos:=fMax;
if fPos<fMin Then fPos:=fMin;
Invalidate;
If Assigned(fOnChange) Then fOnChange(Self);
End;
End;
end.
|
unit Materials;
{ Fireworks shader based on Martijn Steinrucken's "[SH17A] Fireworks" shader.
https://www.shadertoy.com/view/ldBfzw }
interface
uses
System.Classes,
System.SysUtils,
FMX.Types3D,
FMX.Graphics,
FMX.Materials,
FMX.MaterialSources;
type
TFireworksMaterialSource = class(TMaterialSource)
private
function GetTimeInSeconds: Single;
procedure SetTimeInSeconds(const AValue: Single);
function GetFireworksCount: Integer;
procedure SetFireworksCount(const AValue: Integer);
function GetSparkCount: Integer;
procedure SetSparkCount(const AValue: Integer);
protected
function CreateMaterial: TMaterial; override;
published
property TimeInSeconds: Single read GetTimeInSeconds write SetTimeInSeconds;
property SparkCount: Integer read GetSparkCount write SetSparkCount;
property FireworksCount: Integer read GetFireworksCount write SetFireworksCount;
end;
type
TFireworksMaterial = class(TCustomMaterial)
private class var
FShaderArch: TContextShaderArch;
FVertexShaderData: TBytes;
FPixelShaderData: TBytes;
FMatrixIndex: Integer;
FMatrixSize: Integer;
FFloatSize: Integer;
private
FTimeInSeconds: Single;
FFireworksCount: Integer;
FSparkCount: Integer;
procedure SetTimeInSeconds(const AValue: Single);
procedure SetFireworksCount(const AValue: Integer);
procedure SetSparkCount(const AValue: Integer);
private
class procedure LoadShaders; static;
class function LoadShader(const AResourceName: String): TBytes; static;
protected
procedure DoInitialize; override;
procedure DoApply(const Context: TContext3D); override;
public
constructor Create; override;
property TimeInSeconds: Single read FTimeInSeconds write SetTimeInSeconds;
property FireworksCount: Integer read FFireworksCount write SetFireworksCount;
property SparkCount: Integer read FSparkCount write SetSparkCount;
end;
implementation
uses
System.Types,
System.Math.Vectors,
{$IF Defined(MSWINDOWS)}
FMX.Context.DX9,
FMX.Context.DX11;
{$ELSEIF Defined(ANDROID)}
FMX.Context.GLES;
{$ELSEIF Defined(IOS)}
FMX.Context.GLES,
FMX.Context.Metal;
{$ELSEIF Defined(MACOS)}
FMX.Context.Mac,
FMX.Context.Metal;
{$ELSE}
{$MESSAGE Error 'Unsupported platform'}
{$ENDIF}
{$R 'Shaders\Shaders.res'}
{ TFireworksMaterialSource }
function TFireworksMaterialSource.CreateMaterial: TMaterial;
begin
Result := TFireworksMaterial.Create;
end;
function TFireworksMaterialSource.GetFireworksCount: Integer;
begin
Result := TFireworksMaterial(Material).FireworksCount;
end;
function TFireworksMaterialSource.GetSparkCount: Integer;
begin
Result := TFireworksMaterial(Material).SparkCount;
end;
function TFireworksMaterialSource.GetTimeInSeconds: Single;
begin
Result := TFireworksMaterial(Material).TimeInSeconds;
end;
procedure TFireworksMaterialSource.SetFireworksCount(const AValue: Integer);
begin
TFireworksMaterial(Material).FireworksCount := AValue;
end;
procedure TFireworksMaterialSource.SetSparkCount(const AValue: Integer);
begin
TFireworksMaterial(Material).SparkCount := AValue;
end;
procedure TFireworksMaterialSource.SetTimeInSeconds(const AValue: Single);
begin
TFireworksMaterial(Material).TimeInSeconds := AValue;
end;
{ TFireworksMaterial }
constructor TFireworksMaterial.Create;
begin
inherited;
FFireworksCount := 9;
FSparkCount := 50;
end;
procedure TFireworksMaterial.DoApply(const Context: TContext3D);
begin
inherited;
Context.SetShaderVariable('Time', [Vector3D(FTimeInSeconds, 0, 0, 0)]);
{ NOTE: In the shader, to loop variable starts at -2, so we need to subtract
2 from FFireworksCount to set the correct count. }
Context.SetShaderVariable('FireworksCount', [Vector3D(FFireworksCount - 2, 0, 0, 0)]);
Context.SetShaderVariable('SparkCount', [Vector3D(FSparkCount, 0, 0, 0)]);
end;
procedure TFireworksMaterial.DoInitialize;
begin
inherited;
if (FShaderArch = TContextShaderArch.Undefined) then
LoadShaders;
FVertexShader := TShaderManager.RegisterShaderFromData('fireworks.fvs',
TContextShaderKind.VertexShader, '', [
TContextShaderSource.Create(FShaderArch, FVertexShaderData,
[TContextShaderVariable.Create('MVPMatrix', TContextShaderVariableKind.Matrix,
FMatrixIndex, FMatrixSize)])
]);
FPixelShader := TShaderManager.RegisterShaderFromData('fireworks.fps',
TContextShaderKind.PixelShader, '', [
TContextShaderSource.Create(FShaderArch, FPixelShaderData,
[TContextShaderVariable.Create('Time', TContextShaderVariableKind.Float, 0, FFloatSize),
TContextShaderVariable.Create('FireworksCount', TContextShaderVariableKind.Float, FFloatSize, FFloatSize),
TContextShaderVariable.Create('SparkCount', TContextShaderVariableKind.Float, FFloatSize * 2, FFloatSize)])
]);
end;
class function TFireworksMaterial.LoadShader(const AResourceName: String): TBytes;
begin
var Stream := TResourceStream.Create(HInstance, AResourceName, RT_RCDATA);
try
SetLength(Result, Stream.Size);
Stream.ReadBuffer(Result, Length(Result));
finally
Stream.Free;
end;
end;
class procedure TFireworksMaterial.LoadShaders;
begin
var Suffix := '';
var ContextClass := TContextManager.DefaultContextClass;
{$IF Defined(MSWINDOWS)}
if (ContextClass.InheritsFrom(TCustomDX9Context)) then
begin
FShaderArch := TContextShaderArch.DX9;
FMatrixIndex := 0;
FMatrixSize := 4;
FFloatSize := 1;
Suffix := 'DX9';
end
else if (ContextClass.InheritsFrom(TCustomDX11Context)) then
begin
FShaderArch := TContextShaderArch.DX11;
FMatrixIndex := 0;
FMatrixSize := 64;
FFloatSize := 4;
Suffix := 'DX11';
end;
{$ELSE}
if (ContextClass.InheritsFrom(TCustomContextOpenGL)) then
begin
FShaderArch := TContextShaderArch.GLSL;
FMatrixIndex := 0;
FMatrixSize := 4;
FFloatSize := 1;
Suffix := 'GL';
end;
{$ENDIF}
{$IF Defined(MACOS)}
if (ContextClass.InheritsFrom(TCustomContextMetal)) then
begin
FShaderArch := TContextShaderArch.Metal;
FMatrixIndex := 1;
FMatrixSize := 4;
FFloatSize := 1;
Suffix := 'MTL';
end;
{$ENDIF}
if (FShaderArch = TContextShaderArch.Undefined) then
raise EContext3DException.Create('Unknown or unsupported 3D context class');
FVertexShaderData := LoadShader('VERTEX_SHADER_' + Suffix);
FPixelShaderData := LoadShader('PIXEL_SHADER_' + Suffix);
end;
procedure TFireworksMaterial.SetFireworksCount(const AValue: Integer);
begin
if (AValue <> FFireworksCount) then
begin
FFireworksCount := AValue;
DoChange;
end;
end;
procedure TFireworksMaterial.SetSparkCount(const AValue: Integer);
begin
if (AValue <> FSparkCount) then
begin
FSparkCount := AValue;
DoChange;
end;
end;
procedure TFireworksMaterial.SetTimeInSeconds(const AValue: Single);
begin
if (AValue <> FTimeInSeconds) then
begin
FTimeInSeconds := AValue;
DoChange;
end;
end;
end.
|
unit VisibleDSA.AlgoVisualizer;
interface
uses
System.SysUtils,
System.Types,
FMX.Graphics,
FMX.Forms,
System.Generics.Collections,
VisibleDSA.AlgoVisHelper,
VisibleDSA.Circle,
VisibleDSA.MonteCarloPiData;
type
TAlgoVisualizer = class(TObject)
private
_circle: TCircle;
_form: TForm;
_count: integer;
_data: TMonteCarloPiData;
public
constructor Create(form: TForm; n: integer);
destructor Destroy; override;
procedure Paint(canvas: TCanvas);
procedure Run;
end;
implementation
uses
Winapi.Windows, VisibleDSA.AlgoForm;
{ TAlgoVisualizer }
constructor TAlgoVisualizer.Create(form: TForm; n: integer);
var
x, y, r: integer;
begin
inherited Create;
_form := form;
_count := n;
if _form.ClientWidth <> _form.ClientHeight then
raise Exception.Create('This demo must be run in a square windows.');
x := form.ClientWidth div 2;
y := form.ClientHeight div 2;
r := form.ClientWidth div 2;
_circle := TCircle.Create(x, y, r);
_data := TMonteCarloPiData.Create(_circle);
AllocConsole;
end;
destructor TAlgoVisualizer.Destroy;
begin
FreeAndNil(_data);
FreeAndNil(_circle);
FreeConsole;
inherited Destroy;
end;
procedure TAlgoVisualizer.Paint(canvas: TCanvas);
var
p: TPoint;
i: integer;
begin
TAlgoVisHelper.SetStroke(3, CL_BLUE);
TAlgoVisHelper.DrawCircle(canvas, _circle.X, _circle.Y, _circle.R);
for i := 0 to _data.GetPointNumber - 1 do
begin
p := _data.GetPoint(i);
if _circle.Contain(p) then
begin
TAlgoVisHelper.SetFill(CL_GREEN);
end
else
begin
TAlgoVisHelper.SetFill(CL_RED);
end;
TAlgoVisHelper.FillCircle(canvas, p.X, p.Y, 1);
end;
end;
procedure TAlgoVisualizer.Run;
var
x, y, i: integer;
begin
Randomize;
for i := 0 to _count - 1 do
begin
x := Random(_form.ClientWidth);
y := Random(_form.ClientHeight);
_data.AddPoint(TPoint.Create(x, y));
Writeln(FloatToStr(_data.EstimatePI));
end;
TAlgoVisHelper.Pause(10);
AlgoForm.PaintBox.Repaint;
end;
end.
|
{ Subroutine STRING_PAD (S)
*
* Pad the string S with blanks, out to its maximum allowable
* length. The new length of S will be its maximum length.
}
module string_pad;
define string_pad;
%include 'string2.ins.pas';
procedure string_pad ( {extend string to max length by adding blanks}
in out s: univ string_var_arg_t); {string}
var
i: sys_int_machine_t; {string index}
begin
for i := s.len+1 to s.max do {once for each unused char}
s.str[i] := ' '; {write one blank}
s.len := s.max; {set S to its maximum length}
end;
|
{
Exemplo da precedencia:
- Considre que existe 3 aspectos A1, A2, A3
- todos implementam todos os advices
- foi registrado CLASSEA.METODO1 para os métodos A1 e A3
Precedencia será
A1.Around
A1.Proceed? ---> A3.Around
A3.Proceed? ---> A1.Before, A3.Before, Real, A3.After, A1.After
Problemas:
- Quando chama proceed de um advice before ou after entra em loop
}
unit InfraAspect;
{$I 'InfraAspect.Inc'}
interface
uses
{$IFDEF USE_GXDEBUG}DBugIntf,{$ENDIF}
Classes,
InfraAspectIntf,
InfraCommonIntf,
InfraCommon,
InfraAspectUtil;
type
{
Classe base para construção de um aspecto
Qualquer aspecto de sua aplicação deve herdar desta classe.
Esta Classe possui o que chamamos na POA de Advices, representados
aqui por Around, Before e After.
}
TInfraAspect = class(TElement, IInfraAspect)
protected
// descendentes implementam este Advice quando precisa enclausurar a
// chamada ao método real. Muito usado em situações como controle de
// transações. Internamente este método pode ou nao chamar o método
// Proceed.
function Around(const Sender: IElement;
const Params: IInterfaceList): IInterface; virtual;
// descendentes implementam este Advice quando precisa de algo que seja
// executado antes da chamada ao método real.
procedure Before(const Sender: IElement;
const Params: IInterfaceList); virtual;
// descendentes implementam este Advice quando precisa de algo que seja
// executado após a chamada ao método real.
procedure After(const Sender: IElement;
const Params: IInterfaceList); virtual;
// chama Proceed no servico de aspectos
function Proceed: IInterface;
end;
{
Esta classe mapeia um método a um aspecto. Objetos deste tipo são criados
usando o AspectService.AddPointCut.
}
TInfraJointPoint = class(TBaseElement, IInfraJointPoint)
private
FAspectClass: TClass;
FMethodInfo: IMethodInfo;
FMethodIndex: integer;
function GetAspectClass: TClass;
function GetMethodInfo: IMethodInfo;
function GetMethodIndex: Integer;
procedure SetAspectClass(Value: TClass);
procedure SetMethodInfo(const Value: IMethodInfo);
procedure SetMethodIndex(Value: Integer);
function GetParamsCount: integer;
public
property AspectClass: TClass read GetAspectClass write SetAspectClass;
property MethodInfo: IMethodInfo read GetMethodInfo write SetMethodInfo;
property MethodIndex: integer read GetMethodIndex write SetMethodIndex;
property ParamsCount: integer read GetParamsCount;
constructor Create; override;
end;
// classe resposavel por manter o contexto entre a execução dos aspectos
// e poder chamá-los recursivamente.
TInterceptedStackItem = class(TInterfacedObject, IInterceptedStackItem)
private
FAspect: IInfraAspect;
FInstance: Pointer;
FJointPoint: IInfraJointPoint;
FParams: IInterfaceList;
function GetAspect: IInfraAspect;
function GetInstance: Pointer;
function GetJointPoint: IInfraJointPoint;
function GetRealMethodInfo: IMethodInfo;
procedure SetAspect(const Value: IInfraAspect);
procedure SetInstance(const Value: Pointer);
procedure SetJointPoint(const Value: IInfraJointPoint);
function GetParams: IInterfaceList;
procedure SetParams(const Value: IInterfaceList);
public
property Aspect: IInfraAspect read FAspect write FAspect;
property Instance: Pointer read FInstance write FInstance;
property JointPoint: IInfraJointPoint read FJointPoint write FJointPoint;
property RealMethodInfo: IMethodInfo read GetRealMethodInfo;
property Params: IInterfaceList read GetParams write SetParams;
end;
{
Serviço para se programar orientada a aspectos no delphi.
Este serviço armazena:
- uma pilha de aspectos para manter o contexto de execução;
- uma lista de stubs. Um stub é um bloco de memoria que chama o
AspectService para chamar os Advices. Existe um Stub para cada
Indice de método interceptado (economizando memoria)
Os métodos reais tem seus endereços substituídos pelo endereço
do stub corresponde ao indice do metodo na tabela de métodos virtuais
da classe
- uma lista de jointpoints
}
TInfraAspectService = class(TBaseElement, IInfraAspectService)
private
FInterceptedStack: IInterceptedStack;
FJointPoints: IInfraJointPoints;
FStubs: TStubArray;
FAspectPointcutEval: IAspectPointcutEval;
// Define um ou mais métodos de classes da aplicação onde um determinado
// aspecto deve atuar. Os métodos sao escolhidos atraves de uma expressao.
procedure AddPointCut(const pExpression: string; pAspectClass: TClass);
// Chama todos os Advices recursivamente até o ultimo Joint Point
// e então chama o método real
function Proceed: IInterface;
// Retorna a lista de JointPoints registrados no AspectService.
function GetJointPoints: IInfraJointPoints;
// Cria um novo Stub caso ainda nao exista um para o indice do método
// passado como parametro.
function SetStub(const pMethodInfo: IMethodInfo): integer;
// Aramazena o JointPoint na pilha de execução, Cria o Aspecto definido
// neste JointPoint e chama o Advice Around do aspecto criado.
function CallAdvices(const pJointPoint: IInfraJointPoint;
pInstance: Pointer; const pParams: IInterfaceList): IInterface;
// Verifica se o nome de um método é compatível a uma expressao
function Match(const pMethodName, pExpression: string): boolean;
// Tenta retornar o próximo JointPoint que aponta para o mesmo método que
// está sendo atualmente processado.
function GetNextJointPoint(
const pJointPoint: IInfraJointPoint): IInfraJointPoint;
// Pega o JointPoint atual, chama todos os Advices Before, o método real e
// depois todos os Advices After.
function CallMethod: IInterface;
// Chama Advices do tipo before para todos os aspectos relacionados ao
// metodo atual;
procedure CallBeforeAdvices;
// Chama Advices do tipo after para todos os aspectos relacionados ao
// metodo atual;
procedure CallAfterAdvices;
// Cria um JointPoint, relacionando uma classe de aspecto a um metodo.
// metodo atual. Caso necessário um stub é criado;
procedure CreateJointPoint(pAspectClass: TClass;
const vTypeInfo: IMethodInfo);
public
constructor Create; override;
// detroi todos os stubs criados
destructor Destroy; override;
end;
implementation
uses
SysUtils,
List_InterceptMethod,
List_JointPoint,
InfraAspectEval;
{ TInfraAspect }
function TInfraAspect.Around(const Sender: IElement;
const Params: IInterfaceList): IInterface;
begin
Result := Proceed;
end;
procedure TInfraAspect.Before(const Sender: IElement;
const Params: IInterfaceList);
begin
end;
procedure TInfraAspect.After(const Sender: IElement;
const Params: IInterfaceList);
begin
end;
function TInfraAspect.Proceed: IInterface;
begin
Result := AspectService.Proceed;
end;
{ TInfraJointPoint }
constructor TInfraJointPoint.Create;
begin
inherited Create;
end;
function TInfraJointPoint.GetAspectClass: TClass;
begin
Result := FAspectClass;
end;
function TInfraJointPoint.GetMethodInfo: IMethodInfo;
begin
Result := FMethodInfo;
end;
function TInfraJointPoint.GetMethodIndex: Integer;
begin
Result := FMethodIndex;
end;
function TInfraJointPoint.GetParamsCount: integer;
begin
Result := FMethodInfo.Parameters.Count;
end;
procedure TInfraJointPoint.SetAspectClass(Value: TClass);
begin
if Value <> FAspectClass then
FAspectClass := Value;
end;
procedure TInfraJointPoint.SetMethodInfo(const Value: IMethodInfo);
begin
if Value <> FMethodInfo then
FMethodInfo := Value;
end;
procedure TInfraJointPoint.SetMethodIndex(Value: Integer);
begin
if Value <> FMethodIndex then
FMethodIndex := Value;
end;
{ TInterceptedStackItem }
function TInterceptedStackItem.GetAspect: IInfraAspect;
begin
Result := FAspect
end;
function TInterceptedStackItem.GetInstance: Pointer;
begin
Result := FInstance
end;
function TInterceptedStackItem.GetJointPoint: IInfraJointPoint;
begin
Result := FJointPoint
end;
function TInterceptedStackItem.GetRealMethodInfo: IMethodInfo;
begin
if Assigned(FJointPoint) then
Result := JointPoint.MethodInfo
else
Result := nil;
end;
function TInterceptedStackItem.GetParams: IInterfaceList;
begin
Result := FParams;
end;
procedure TInterceptedStackItem.SetAspect(const Value: IInfraAspect);
begin
FAspect := Value;
end;
procedure TInterceptedStackItem.SetInstance(const Value: Pointer);
begin
FInstance := Value;
end;
procedure TInterceptedStackItem.SetJointPoint(
const Value: IInfraJointPoint);
begin
FJointPoint := Value;
end;
procedure TInterceptedStackItem.SetParams(const Value: IInterfaceList);
begin
FParams := Value;
end;
{ TInfraAspectService }
constructor TInfraAspectService.Create;
begin
inherited;
FInterceptedStack := TInterceptedStack.Create;
FJointPoints := TInfraJointPoints.Create;
FAspectPointcutEval := TAspectPointcutEval.Create;
end;
destructor TInfraAspectService.Destroy;
var
i: integer;
begin
for i := 0 to Length(FStubs)-1 do
FreeMem(FStubs[i], SIZE_OF_STUB);
inherited;
end;
procedure TInfraAspectService.AddPointCut(const pExpression: string;
pAspectClass: TClass);
var
vClassInfoIterator: IClassInfoIterator;
vMethodsIterator: IMethodInfoIterator;
vMethodInfo: IMethodInfo;
begin
vClassInfoIterator := TypeService.NewClassInfoIterator;
while not vClassInfoIterator.IsDone do
begin
vMethodsIterator := vClassInfoIterator.CurrentItem.GetMethods;
while not vMethodsIterator.IsDone do
begin
vMethodInfo := (vMethodsIterator.CurrentItem as IMethodInfo);
if Match(vMethodInfo.FullName, pExpression) then
CreateJointPoint(pAspectClass, vMethodInfo);
vMethodsIterator.Next;
end;
vClassInfoIterator.Next;
end;
end;
procedure TInfraAspectService.CreateJointPoint(pAspectClass: TClass;
const vTypeInfo: IMethodInfo);
var
IndexJointPoint, Index: Integer;
begin
Index := SetStub(vTypeInfo);
IndexJointPoint := FJointPoints.Add(
TInfraJointPoint.Create as IInfraJointPoint);
with FJointPoints[IndexJointPoint] do
begin
AspectClass := pAspectClass;
MethodInfo := vTypeInfo;
MethodIndex := Index;
end;
end;
function TInfraAspectService.SetStub(const pMethodInfo: IMethodInfo): integer;
var
i: integer;
begin
Result := -1;
for i := 0 to FJointPoints.Count-1 do
if FJointPoints[i].MethodInfo.MethodPointer = pMethodInfo.MethodPointer then
begin
Result := FJointPoints[i].MethodIndex;
break;
end;
if Result = -1 then
Result := CreateStub(FStubs, pMethodInfo);
end;
function TInfraAspectService.Match(const pMethodName,
pExpression: string): boolean;
begin
Result := FAspectPointcutEval.Evaluate(pMethodName, pExpression);
end;
function TInfraAspectService.GetJointPoints: IInfraJointPoints;
begin
if not Assigned(FJointPoints) then
FJointPoints := TInfraJointPoints.Create;
Result := FJointPoints;
end;
function TInfraAspectService.CallAdvices(
const pJointPoint: IInfraJointPoint; pInstance: Pointer;
const pParams: IInterfaceList): IInterface;
var
Intercepted: IInterceptedStackItem;
pAspect: IInfraAspect;
pSender: IElement;
begin
Assert(Supports(pJointPoint.AspectClass.Create, IInfraAspect, pAspect),
'Class not supports IInfraAspect');
Intercepted := TInterceptedStackItem.Create;
with Intercepted do
begin
JointPoint := pJointPoint;
Aspect := pAspect as IInfraAspect;
Instance := pInstance;
Params := pParams;
end;
if not Supports(TObject(Intercepted.Instance), IElement, pSender) then
Raise Exception.Create('Instance not supports Element');
FInterceptedStack.Push(Intercepted);
Result := Intercepted.Aspect.Around(pSender, Intercepted.Params);
FInterceptedStack.Pop;
end;
function TInfraAspectService.GetNextJointPoint(
const pJointPoint: IInfraJointPoint): IInfraJointPoint;
var
i, j: integer;
begin
Result := nil;
i := FJointPoints.Indexof(pJointPoint)+1;
if i <> FJointPoints.Count then
for j := i to FJointPoints.Count-1 do
if FJointPoints[j].MethodInfo = pJointPoint.MethodInfo then
begin
Result := FJointPoints[j];
Break;
end;
end;
function TInfraAspectService.Proceed: IInterface;
var
NextJointPoint: IInfraJointPoint;
begin
Result := nil;
with FInterceptedStack do
begin
NextJointPoint := GetNextJointPoint(Peek.JointPoint);
if Assigned(NextJointPoint) then
Result := CallAdvices(NextJointPoint, Peek.Instance, Peek.Params)
else
Result := CallMethod;
end;
end;
procedure TInfraAspectService.CallBeforeAdvices;
var
vIterator: IInfraIterator;
vStackItem: IInterceptedStackItem;
vSender: IElement;
begin
vIterator := FInterceptedStack.NewIterator;
while not vIterator.IsDone do
begin
vStackItem := (vIterator.CurrentItem as IInterceptedStackItem);
with vStackItem do
if JointPoint.MethodInfo = RealMethodInfo then
begin
if not Supports(TObject(Instance), IElement, vSender) then
Raise Exception.Create('Instance not supports Element');
Aspect.Before(vSender, Params);
end;
vIterator.Next;
end;
end;
procedure TInfraAspectService.CallAfterAdvices;
var
vIterator: IInfraIterator;
vStackItem: IInterceptedStackItem;
vSender: IElement;
begin
vIterator := FInterceptedStack.NewInverseIterator;
while not vIterator.IsDone do
begin
vStackItem := (vIterator.CurrentItem as IInterceptedStackItem);
with vStackItem do
if JointPoint.MethodInfo = RealMethodInfo then
begin
if not Supports(TObject(Instance), IElement, vSender) then
Raise Exception.Create('Instance not supports Element');
Aspect.After(vSender, Params);
end;
vIterator.Next;
end;
end;
function TInfraAspectService.CallMethod: IInterface;
begin
Result := nil;
with FInterceptedStack do
begin
CallBeforeAdvices;
Result := Peek.RealMethodInfo.Invoke(
TObject(Peek.Instance), Peek.Params);
CallAfterAdvices;
end;
end;
// Não entendi mas se por direto no Initialization acontece
// Access Violations.
procedure InjectAspectService;
begin
(ApplicationContext as IBaseElement).Inject(
IInfraAspectService, TInfraAspectService.Create);
end;
initialization
InjectAspectService;
end.
|
unit ufrmDialogMasterCustomer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, StdCtrls, ufraFooterDialog2Button, ExtCtrls,
uConn, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogMasterCustomer = class(TfrmMasterDialog)
Panel1: TPanel;
lbl5: TLabel;
lbl1: TLabel;
edtCustCode: TEdit;
edtCustName: TEdit;
lbl12: TLabel;
edtContactPerson: TEdit;
lbl8: TLabel;
edtTitle: TEdit;
Panel2: TPanel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
lbl7: TLabel;
lbl11: TLabel;
edtAddress: TEdit;
edtCity: TEdit;
edtTelephone: TEdit;
edtPostCode: TEdit;
edtFaxNo: TEdit;
Panel3: TPanel;
lbl13: TLabel;
lbl15: TLabel;
cbbPKP: TComboBox;
edtTaxNo: TEdit;
lbl14: TLabel;
lbl16: TLabel;
cbbPPH: TComboBox;
edtNPWP: TEdit;
lbl23: TLabel;
lbl24: TLabel;
lbl27: TLabel;
edtTermOP: TEdit;
cbpTypeOfPay: TComboBox;
Panel4: TPanel;
lbl10: TLabel;
edtCustDesc: TEdit;
chkPrincipal: TCheckBox;
lblSubCode: TLabel;
edtSupName: TEdit;
edtSupMGCode: TcxButtonEdit;
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure chkPrincipalClick(Sender: TObject);
procedure edtSupMGCodeKeyPress(Sender: TObject; var Key: Char);
procedure edtSupMGCodeExit(Sender: TObject);
procedure edtSupMGCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtSupMGCodePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
FMasterCustomerId : Integer;
// FNewCustomer: TNewCustomer;
function GetIsBKP: Integer;
function GetIsPPH: Integer;
function IsBisaLanjut: Boolean;
procedure ShowDataEdit(AMasterCustomerId: Integer);
procedure PrepareAddData();
function SaveMasterCustomer(aCustomer_ID: integer = 0): boolean;
procedure SetDataAlamat(aCustomerSewa: Integer);
procedure SetDataKodeDanNamaCustomer(aCustomerSewa: Integer);
procedure SetDataKontakPerson(aCustomerSewa: Integer);
procedure SetDataPajak(aCustomerSewa: Integer);
procedure SetDataPrincipal(aCustomerSewa: Integer);
procedure SetDataTipeBayar(aCustomerSewa: Integer);
public
function GetIsPrincipal: Integer;
function GetMasterCustomerId: Integer;
function getTOP: Integer;
function IsDataSubMGValid(aSubSupCode : String; aUnitID : Integer): Boolean;
function IsKodeCustomerDouble(aSubSupCode : String; aUnitID : Integer;
aExSubSupId : Integer): Boolean;
procedure LoadDataTipePembayaran(aUnitID : Integer);
procedure SetMasterCustomerId(const Value: Integer);
{ Public declarations }
published
end;
var
frmDialogMasterCustomer: TfrmDialogMasterCustomer;
implementation
uses uTSCommonDlg, uRetnoUnit, ufrmSearchRekening;
{$R *.dfm}
procedure TfrmDialogMasterCustomer.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
if not IsBisaLanjut then
Exit;
if SaveMasterCustomer(FMasterCustomerId) then
Close;
end;
function TfrmDialogMasterCustomer.SaveMasterCustomer(aCustomer_ID: integer =
0): boolean;
// sSUPMG: string;
// P: Integer;
// idTPPAY: Integer;
begin
Result := False;
{FNewCustomer.UpdateData(
edtAddress.Text,
edtCustDesc.Text,
edtFaxNo.Text,
aCustomer_ID,
GetIsBKP,
GetIsPPH,
GetIsPrincipal,
edtCustCode.Text,
edtPostCode.Text,
edtContactPerson.Text,
edtCity.Text,
edtTaxNo.Text,
edtCustName.Text,
DialogUnit,
edtNPWP.Text,
edtSupMGCode.Text,
edtTelephone.Text,
cGetIDfromCombo(cbpTypeOfPay),
edtTitle.Text,
getTOP );
try
if not FNewCustomer.ExecuteGenerateSQL then
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Menyimpan Data');
end else
begin
Result := True;
cCommitTrans;
CommonDlg.ShowMessage('Berhasil Menyimpan Data');
end;
finally
cRollbackTrans;
end;
}
end;
procedure TfrmDialogMasterCustomer.FormShow(Sender: TObject);
begin
inherited;
// FNewCustomer := TNewCustomer.CreateWithUser(Self, FLoginId, FLoginUnitId);
LoadDataTipePembayaran(DialogUnit);
if FMasterCustomerId > 0 then
ShowDataEdit(FMasterCustomerId)
else
PrepareAddData();
edtCustCode.SetFocus;
end;
procedure TfrmDialogMasterCustomer.ShowDataEdit(AMasterCustomerId: Integer);
begin
// if FNewCustomer.LoadByID(FMasterCustomerId, DialogUnit) then
// begin
// SetDataKodeDanNamaCustomer(FNewCustomer);
// SetDataPajak(FNewCustomer);
// SetDataTipeBayar(FNewCustomer);
//
// edtTermOP.Text := IntToStr(FNewCustomer.TOP);
// edtCustDesc.Text := FNewCustomer.Deskripsi;
//
// SetDataAlamat(FNewCustomer);
// SetDataKontakPerson(FNewCustomer);
// SetDataPrincipal(FNewCustomer);
// end;
end;
procedure TfrmDialogMasterCustomer.PrepareAddData;
begin
end;
procedure TfrmDialogMasterCustomer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogMasterCustomer.FormDestroy(Sender: TObject);
begin
inherited;
// FNewCustomer.Free;
frmDialogMasterCustomer := nil;
end;
procedure TfrmDialogMasterCustomer.chkPrincipalClick(Sender: TObject);
begin
inherited;
if chkPrincipal.Checked then
begin
lblSubCode.Visible := True;
edtSupMGCode.Visible := True;
edtSupName.Visible := True;
end
else
begin
lblSubCode.Visible := False;
edtSupMGCode.Visible := False;
edtSupName.Visible := False;
end
end;
procedure TfrmDialogMasterCustomer.edtSupMGCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := UpCase(Key);
end;
procedure TfrmDialogMasterCustomer.edtSupMGCodeExit(Sender: TObject);
begin
inherited;
// with TNewSupplierMerGroup.Create(Self) do
// begin
// try
// if LoadByKode(edtSupMGCode.Text) then
// begin
// edtSupName.Text := Nama;
// end else begin
// edtSupName.Text := '';
// end;
// finally
// Free;
// end;
// end;
end;
procedure TfrmDialogMasterCustomer.edtSupMGCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
sSQL : String;
begin
inherited;
if (Key = VK_F5) then
begin
sSQL := 'select supmg_sub_code, supmg_name'
+ ' from suplier_merchan_grup';
// with cLookUp('Daftar Sub Supplier', sSQL) do
// begin
// try
// if Strings[0] <> '' then
// begin
// edtSupMGCode.Text := Strings[0];
// edtSupName.Text := Strings[1];
// edtSupMGCode.SetFocus;
// end;
// finally
// Free;
// end;
// end;
end;
end;
procedure TfrmDialogMasterCustomer.edtSupMGCodePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
sSQL : String;
begin
inherited;
sSQL := 'select supmg_sub_code, supmg_name'
+ ' from suplier_merchan_grup';
// with cLookUp('Daftar Supplier', sSQL) do
// begin
// try
// if Strings[0] <> '' then
// begin
// edtSupMGCode.Text := Strings[0];
// edtSupName.Text := Strings[1];
// edtSupMGCode.SetFocus;
// end;
// finally
// Free;
// end;
// end;
end;
function TfrmDialogMasterCustomer.GetIsBKP: Integer;
begin
if cbbPKP.Text = 'PKP' then
Result := 1
else
Result := 0;
end;
function TfrmDialogMasterCustomer.GetIsPPH: Integer;
begin
if cbbPPH.Text = 'PPH' then
Result := 1
else
Result := 0;
end;
function TfrmDialogMasterCustomer.GetIsPrincipal: Integer;
begin
if chkPrincipal.Checked then
Result := 1
else
Result := 0;
end;
function TfrmDialogMasterCustomer.GetMasterCustomerId: Integer;
begin
Result := FMasterCustomerId;
end;
function TfrmDialogMasterCustomer.getTOP: Integer;
begin
Result := StrToIntDef(edtTermOP.Text, 0);
end;
function TfrmDialogMasterCustomer.IsBisaLanjut: Boolean;
var
iTOP: Integer;
begin
Result := False;
if edtCustCode.Text = '' then
begin
CommonDlg.ShowErrorEmpty('CUSTOMER CODE');
edtCustCode.SetFocus;
Exit;
end;
if edtCustName.Text='' then
begin
CommonDlg.ShowErrorEmpty('CUSTOMER NAME');
edtCustName.SetFocus;
Exit;
end;
iTOP := StrToIntDef(edtTermOP.Text, 0);
if iTOP < 1 then
begin
CommonDlg.ShowErrorEmpty('TOP');
edtTermOP.SetFocus;
Exit;
end;
if chkPrincipal.Checked then
begin
if not IsDataSubMGValid(edtSupMGCode.Text, DialogUnit) then
begin
CommonDlg.ShowErrorEmpty('SUB CODE');
edtSupMGCode.SetFocus;
Exit;
end;
end;
if IsKodeCustomerDouble(edtCustCode.Text, DialogUnit, FMasterCustomerId) then
begin
CommonDlg.ShowErrorExist('KODE CUSTOMER', edtCustCode.Text);
edtCustCode.SetFocus;
Exit;
end;
Result := True;
end;
function TfrmDialogMasterCustomer.IsDataSubMGValid(aSubSupCode : String;
aUnitID : Integer): Boolean;
begin
Result := False;
// with TNewSupplierMerGroup.Create(Self) do
// begin
// try
// if LoadByKode(edtSupMGCode.Text) then
// begin
// Result := True;
// end;
// finally
// Free;
// end;
// end;
end;
function TfrmDialogMasterCustomer.IsKodeCustomerDouble(aSubSupCode : String;
aUnitID : Integer; aExSubSupId : Integer): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(cust_id)'
+ ' from customer'
+ ' where cust_unt_id = ' + IntToStr(aUnitID)
+ ' and cust_code = ' + QuotedStr(aSubSupCode)
+ ' and cust_id <> ' + IntToStr(aExSubSupId);
// with cOpenQuery(sSQL) do
// begin
// try
// while not EOF do
// begin
// if Fields[0].AsInteger > 0 then
// begin
// Result := True;
// Exit;
// end;
//
// Next;
// end;
// finally
// Free;
// end;
// end;
end;
procedure TfrmDialogMasterCustomer.LoadDataTipePembayaran(aUnitID : Integer);
var
sSQL: string;
begin
sSQL := 'select tpbyr_id, tpbyr_name'
+ ' from REF$TIPE_PEMBAYARAN'
+ ' order by tpbyr_name';
// cQueryToComboObject(cbpTypeOfPay, sSQL);
end;
procedure TfrmDialogMasterCustomer.SetDataAlamat(aCustomerSewa: Integer);
begin
// edtAddress.Text := aCustomerSewa.Alamat;
// edtCity.Text := aCustomerSewa.Kota;
// edtTelephone.Text := aCustomerSewa.Telepon;
// edtPostCode.Text := aCustomerSewa.KodePos;
// edtFaxNo.Text := aCustomerSewa.Fax;
end;
procedure TfrmDialogMasterCustomer.SetDataKodeDanNamaCustomer(aCustomerSewa:
Integer);
begin
// edtCustCode.Text := aCustomerSewa.Kode;
// edtCustName.Text := aCustomerSewa.Nama;
end;
procedure TfrmDialogMasterCustomer.SetDataKontakPerson(aCustomerSewa: Integer);
begin
// edtContactPerson.Text := aCustomerSewa.KontakPerson;
// edtTitle.Text := aCustomerSewa.Title;
end;
procedure TfrmDialogMasterCustomer.SetDataPajak(aCustomerSewa: Integer);
begin
// cbbPKP.ItemIndex := aCustomerSewa.IsPKP;
// edtTaxNo.Text := aCustomerSewa.LRTax;
// cbbPPH.ItemIndex := aCustomerSewa.ISPPH23;
// edtNPWP.Text := aCustomerSewa.NPWP;
end;
procedure TfrmDialogMasterCustomer.SetDataPrincipal(aCustomerSewa: Integer);
begin
// if (FNewCustomer.ISPRINCIPAL = 1) then
// begin
// chkPrincipal.Checked := True;
// lblSubCode.Visible := True;
// edtSupMGCode.Visible := True;
// edtSupName.Visible := True;
//
// edtSupMGCode.Text := FNewCustomer.SUPMGSUBCODE.Kode;
// edtSupName.Text := FNewCustomer.SUPMGSUBCODE.Nama;
// end
// else
begin
chkPrincipal.Checked := False;
lblSubCode.Visible := False;
edtSupMGCode.Visible := False;
edtSupName.Visible := False;
end;
end;
procedure TfrmDialogMasterCustomer.SetDataTipeBayar(aCustomerSewa: Integer);
begin
// cSetItemAtComboObject(cbpTypeOfPay,aCustomerSewa.TipeBayar.ID);
end;
procedure TfrmDialogMasterCustomer.SetMasterCustomerId(const Value: Integer);
begin
FMasterCustomerId := Value;
end;
end.
|
unit WebSiteControllerU;
interface
uses
MVCFramework, MVCFramework.Commons, System.Diagnostics, System.JSON,
MVCFramework.Serializer.Commons;
type
[MVCNameCase(ncLowerCase)]
TSpeedValue = class
private
FValue: string;
procedure SetValue(const Value: string);
public
property Value: string read FValue write SetValue;
constructor Create(aValue: string);
end;
[MVCPath('/')]
TWebSiteController = class(TMVCController)
private
FStopWatch: TStopwatch;
function GetSpeed: TSpeedValue;
protected
procedure OnBeforeAction(Context: TWebContext; const AActionNAme: string;
var Handled: Boolean); override;
public
[MVCPath('/people')]
[MVCHTTPMethods([httpGET])]
procedure PeopleList;
[MVCPath('/people/($guid)')]
[MVCHTTPMethods([httpDELETE])]
procedure DeletePerson(const guid: string);
[MVCPath('/people')]
[MVCHTTPMethods([httpPOST])]
[MVCConsumes('application/x-www-form-urlencoded')]
procedure SavePerson;
[MVCPath('/newperson')]
[MVCHTTPMethods([httpGET])]
procedure NewPerson;
[MVCPath('/')]
[MVCHTTPMethods([httpGET])]
procedure Index;
end;
implementation
{ TWebSiteController }
uses DAL, System.SysUtils, Web.HTTPApp;
procedure TWebSiteController.DeletePerson(const guid: string);
var
LDAL: IPeopleDAL;
begin
LDAL := TServicesFactory.GetPeopleDAL;
LDAL.DeleteByGUID(guid);
end;
function TWebSiteController.GetSpeed: TSpeedValue;
begin
Result := TSpeedValue.Create(FStopWatch.Elapsed.TotalMilliseconds.ToString);
end;
procedure TWebSiteController.Index;
begin
Redirect('/people');
end;
procedure TWebSiteController.NewPerson;
begin
PushObjectToView('speed', GetSpeed);
LoadView(['header', 'editperson', 'footer']);
RenderResponseStream;
end;
procedure TWebSiteController.OnBeforeAction(Context: TWebContext;
const AActionNAme: string; var Handled: Boolean);
begin
inherited;
ContentType := 'text/html';
Handled := False;
FStopWatch := TStopwatch.StartNew;
end;
procedure TWebSiteController.PeopleList;
var
LDAL: IPeopleDAL;
lCookie: TCookie;
begin
LDAL := TServicesFactory.GetPeopleDAL;
PushObjectToView('people', LDAL.GetPeople);
PushObjectToView('speed', GetSpeed);
LoadView(['header', 'people_list', 'footer']);
// send a cookie with the server datetime at the page rendering
lCookie := Context.Response.Cookies.Add;
lCookie.Name := 'lastresponse';
lCookie.Value := DateTimeToStr(now);
lCookie.Expires := 0; // session cookie
// END cookie sending
RenderResponseStream; // rember to call render!!!
end;
procedure TWebSiteController.SavePerson;
var
lFirstName: string;
lLastName: string;
lAge: string;
lPeopleDAL: IPeopleDAL;
lItems: TArray<string>;
begin
lItems := Context.Request.ParamsMulti['items'];
lFirstName := Context.Request.Params['first_name'].Trim;
lLastName := Context.Request.Params['last_name'].Trim;
lAge := Context.Request.Params['age'];
if LFirstName.IsEmpty or LLastName.IsEmpty or LAge.IsEmpty then
begin
{ TODO -oDaniele -cGeneral : Show how to properly render an exception }
raise EMVCException.Create('Invalid data',
'First name, last name and age are not optional', 0);
end;
LPeopleDAL := TServicesFactory.GetPeopleDAL;
LPeopleDAL.AddPerson(LFirstName, LLastName, LAge.ToInteger(), lItems);
Redirect('/people');
end;
{ TSpeedValue }
constructor TSpeedValue.Create(aValue: string);
begin
inherited Create;
FValue := aValue;
end;
procedure TSpeedValue.SetValue(const Value: string);
begin
FValue := Value;
end;
end.
|
unit Classe.Request;
interface
uses
IdTCPClient, IdHTTP, system.Classes, Classe.DiretorioWEB, System.SysUtils;
type
TRequest = class
public
var
HTTP: TIdHTTP;
public
function GET(pServico: String): String;
function DELETE(pServico: String): String;
function PUT(pServico: String; pParametro: TStringStream): String;
function POST(pServico: String; pParametro: TStringList): String;
constructor Create();
destructor Destroy(); override;
end;
implementation
{ TRequest }
constructor TRequest.Create;
begin
inherited;
HTTP := TIdHTTP.Create(nil);
HTTP.Request.ContentType := 'application/json';
HTTP.Request.ContentEncoding := 'utf-8';
end;
destructor TRequest.Destroy;
begin
if Assigned(HTTP) then
FreeAndNil(HTTP);
inherited;
end;
function TRequest.DELETE(pServico: String): String;
begin
HTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
Result := HTTP.Delete(TServicoWeb.Diretorio + pServico);
end;
function TRequest.GET(pServico: String): String;
begin
HTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
Result := HTTP.Get(TServicoWeb.Diretorio + pServico);
end;
function TRequest.PUT (pServico: String; pParametro: TStringStream): String;
begin
HTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
Result := HTTP.Put(TServicoWeb.Diretorio + pServico, pParametro);
end;
function TRequest.POST(pServico: String; pParametro: TStringList): String;
begin
HTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
Result := HTTP.Post(TServicoWeb.Diretorio + pServico, pParametro);
end;
end.
|
object SynonymDialog: TSynonymDialog
Left = 0
Top = 0
BorderStyle = bsDialog
Caption = 'Create Synonym For %s.%s'
ClientHeight = 132
ClientWidth = 280
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
OnDestroy = FormDestroy
DesignSize = (
280
132)
PixelsPerInch = 96
TextHeight = 13
object OwnerLabel: TLabel
Left = 12
Top = 43
Width = 32
Height = 13
Caption = 'Owner'
end
object NameLabel: TLabel
Left = 12
Top = 70
Width = 27
Height = 13
Caption = 'Name'
end
object OKButton: TButton
Left = 116
Top = 99
Width = 75
Height = 25
Action = OKAction
Anchors = [akRight, akBottom]
Default = True
TabOrder = 4
end
object CancelButton: TButton
Left = 197
Top = 99
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = 'Cancel'
ModalResult = 2
TabOrder = 5
end
object PrivateRadioButton: TRadioButton
Left = 67
Top = 8
Width = 113
Height = 17
Caption = 'Private'
TabOrder = 1
end
object PublicRadioButton: TRadioButton
Left = 12
Top = 8
Width = 53
Height = 17
Caption = 'Public'
Checked = True
TabOrder = 0
TabStop = True
end
object OwnerComboBox: TBCComboBox
Left = 67
Top = 40
Width = 202
Height = 21
ItemHeight = 13
ReadOnly = False
TabOrder = 2
EditColor = clInfoBk
DeniedKeyStrokes = True
end
object NameEdit: TBCEdit
Left = 67
Top = 67
Width = 202
Height = 21
TabOrder = 3
OnlyNumbers = False
NumbersWithDots = False
NumbersWithSpots = False
EditColor = clInfoBk
NumbersAllowNegative = False
end
object ActionList: TActionList
Left = 28
Top = 88
object OKAction: TAction
Caption = '&OK'
OnExecute = OKActionExecute
end
end
end
|
unit unTrocaSenha;
interface
uses
Variants, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, DB, uniGUIForm,
SqlExpr, FMTBcd, uniGUIBaseClasses, uniGUIClasses, uniButton, uniBitBtn,
uniSpeedButton, uniPanel, uniLabel, uniImage, uniEdit;
type
TfrmTrocaSenha = class(TUniForm)
sqldUsuarios: TSQLDataSet;
sqldSenhaAtual: TSQLDataSet;
sqldSenhaAtualUSERS: TIntegerField;
btGrava: TUniSpeedButton;
btCancel: TUniSpeedButton;
lbSenhaAtu: TUniLabel;
lbNovaSenha: TUniLabel;
lbConfirma: TUniLabel;
edAtual: TUniEdit;
edNova: TUniEdit;
edConfirma: TUniEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btGravaClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
private
function VerificaSenhaAtual(Senha: String): Boolean;
public
end;
var
frmTrocaSenha: TfrmTrocaSenha;
implementation
uses Funcoes, VarGlobal;
{$R *.dfm}
procedure TfrmTrocaSenha.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
sqldUsuarios.Close;
sqldSenhaAtual.Close;
Action := caFree;
end;
procedure TfrmTrocaSenha.btCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmTrocaSenha.FormShow(Sender: TObject);
begin
edAtual.Clear;
edNova.Clear;
edConfirma.Clear;
edAtual.SetFocus;
end;
procedure TfrmTrocaSenha.btGravaClick(Sender: TObject);
begin
if (edAtual.Text = '') then
begin
MsgAviso('','Digite a senha atual.');
edAtual.SetFocus;
Exit;
end;
if (edNova.Text = '') then
begin
MsgAviso('','Digite a nova senha.');
edNova.SetFocus;
Exit;
end;
if (edConfirma.Text = '') then
begin
MsgAviso('','Digite a senha de confirmação.');
edConfirma.SetFocus;
Exit;
end;
if (edConfirma.Text <> edNova.Text) then
begin
MsgErro('','Senha de confirmação não confere com a nova senha.');
edConfirma.SetFocus;
Exit;
end;
if not VerificaSenhaAtual(edAtual.Text) then
begin
MsgErro('','A sua senha atual não confere, digite novamente.');
edAtual.SetFocus;
Exit;
end;
try
with sqldUsuarios do
begin
Close;
Params.ParamByName('SENHA').AsString := edNova.Text;
Params.ParamByName('LOGIN').AsString := Usuario;
ExecSQL;
MsgAviso('','Senha alterada com sucesso.');
self.Close;
end;
except
raise Exception.Create('Erro ao alterar senha.');
end;
end;
function TfrmTrocaSenha.VerificaSenhaAtual(Senha: String): Boolean;
begin
with sqldSenhaAtual do
begin
Close;
Params.ParamByName('PLOGIN').AsString := Trim(Usuario);
Params.ParamByName('PSENHA').AsString := Trim(Senha);
Open;
Result := (FieldByName('USERS').AsInteger > 0);
end;
end;
procedure TfrmTrocaSenha.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Chr(13) then
begin
Key := Chr(0);
PostMessage(Handle, WM_KEYDOWN, VK_TAB, 1);
end;
end;
procedure TfrmTrocaSenha.FormCreate(Sender: TObject);
begin
CentralizaForm(Self);
end;
initialization
RegisterClass(TfrmTrocaSenha);
finalization
UnRegisterClass(TfrmTrocaSenha);
end.
|
unit ObjectBookmark;
interface
uses Classes, WfxPlugin, SysUtils;
{$DEFINE NOFORMS}
type
TBookmark = class(TObject)
BMList: TStringList;
Plugin:TWfxPlugin;
procedure Add(URL: string);
procedure Delete(URL: string);
constructor Create(APlugin:TWFXPlugin);
destructor Destroy; override;
private
procedure Save;
end;
implementation
uses ObjectLines, ObjectIni;
{ TBookmark }
procedure TBookmark.Add(URL: string);
begin
if URL = '' then
Exit;
URL := URL.Replace(';', '%3B');
BMList.Add(URL);
Plugin.TCShowMessage(Plugin.Strings[2], Format(Plugin.Strings[5], [URL]));
// MessageDlg(Format(Strings[5], [URL]), mtInformation, [mbOK], 0);
Save;
end;
procedure TBookmark.Save;
var
s: string;
begin
s := BMList.DelimitedText;
Plugin.Ini.SetValue('Bookmark', s);
end;
constructor TBookmark.Create(APlugin:TWFXPlugin);
begin
Plugin := APlugin;
BMList := TStringList.Create;
BMList.Sorted := True;
BMList.Duplicates := dupIgnore;
BMList.Delimiter := ';';
BMList.DelimitedText := Plugin.Ini.GetS('Bookmark');
end;
procedure TBookmark.Delete(URL: string);
var
i: Integer;
begin
i := BMList.IndexOf(URL);
if i > -1 then
BMList.Delete(i);
Save;
end;
destructor TBookmark.Destroy;
begin
FreeAndNil(BMList);
inherited;
end;
end.
|
unit DAO.Estados;
interface
uses DAO.Base, Model.Estados, Generics.Collections, System.Classes;
type
TEstadosDAO = class(TDAO)
public
function Insert(aEstados: TEstados): Boolean;
function Update(aEstados: TEstados): Boolean;
function Delete(sUF: String): Boolean;
function FindByUF(sUF: String): TObjectList<Testados>;
end;
const
TABLENAME = 'tbestados';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TEstadosDAO.Insert(aEstados: TEstados): Boolean;
var
sSQL : System.string;
begin
Result := False;
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(UF_ESTADO, NOM_ESTADO) ' +
'VALUES ' +
'(:UF, :NOME);';
Connection.ExecSQL(sSQL,[aEstados.UF, aEstados.Nome],
[ftString, ftString]);
Result := True;
end;
function TEstadosDAO.Update(aEstados: TEstados): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'NOM_ESTADO = :NOME ' +
'WHERE UF_ESTADO = :UF;';
Connection.ExecSQL(sSQL,[aEstados.Nome, aEstados.UF],
[ftString, ftString]);
Result := True;
end;
function TEstadosDAO.Delete(sUF: String): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE UF_ESTADO = :UF';
Connection.ExecSQL(sSQL,[sUF],[ftString]);
Result := True;
end;
function TEstadosDAO.FindByUF(sUF: string): TObjectList<TEstados>;
var
FDQuery: TFDQuery;
estados: TObjectList<TEstados>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
if sUF.IsEmpty then
begin
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
end
else
begin
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME + ' WHERE UF_ESTADO = :UF');
FDQuery.ParamByName('UF').AsString := sUF;
end;
FDQuery.Open();
estados := TObjectList<TEstados>.Create();
while not FDQuery.Eof do
begin
estados.Add(TEstados.Create(FDQuery.FieldByName('UF_ESTADO').AsString, FDQuery.FieldByName('NOM_ESTADO').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := estados;
end;
end.
|
unit SnomedCombiner;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
Windows, SysUtils, Classes,
ThreadSupport, GuidSupport, FileSupport, StringSupport,
AdvGenerics, AdvObjects,
SnomedServices;
Type
TTabWriter = class (TAdvObject)
private
FStream : TFileStream;
FDiv : boolean;
public
constructor Create(filename : String);
destructor destroy; override;
procedure field(s : String);
procedure endRecord;
end;
TSnomedCombinedStoreEntry = class (TAdvObject)
private
id : int64;
public
Constructor create(s : String); overload;
Constructor create(i : int64); overload;
end;
TSnomedCombinedItem = class (TAdvObject)
private
FId : Int64;
public
property id : Int64 read FId write FId;
end;
TSnomedCombinedConcept = class;
TSnomedCombinedDescription = class (TSnomedCombinedItem)
private
FDate : TSnomedDate;
FModule : Int64;
FKind : TSnomedCombinedConcept; // not linked
FCaps : TSnomedCombinedConcept; // not linked
FActive : boolean;
FLang : byte;
FValue : String;
public
function link : TSnomedCombinedDescription; overload;
end;
TSnomedCombinedRelationship = class (TSnomedCombinedItem)
private
FTarget : TSnomedCombinedConcept;
FRelType : TSnomedCombinedConcept;
FModule : Int64;
FKind : TSnomedCombinedConcept;
FModifier : TSnomedCombinedConcept;
FDate : TSnomedDate;
FActive : boolean;
source : TSnomedServices;
public
Constructor Create(source : TSnomedServices);
function link : TSnomedCombinedRelationship; overload;
function copy : TSnomedCombinedRelationship;
end;
TSnomedCombinedRelationshipGroup = class (TAdvObject)
private
FRelationships : TAdvList<TSnomedCombinedRelationship>;
FGroup : Integer;
source : TSnomedServices;
public
Constructor Create(source : TSnomedServices);
Destructor Destroy; Override;
function link : TSnomedCombinedRelationshipGroup; overload;
function copy : TSnomedCombinedRelationshipGroup;
end;
TSnomedCombinedConcept = class (TSnomedCombinedItem)
private
FDescriptions : TAdvList<TSnomedCombinedDescription>;
FFlags : byte;
FModule : Int64;
FDate : TSnomedDate;
source : TSnomedServices;
FNoGroup : TSnomedCombinedRelationshipGroup;
FGroups : TAdvList<TSnomedCombinedRelationshipGroup>;
FChildren : TAdvList<TSnomedCombinedConcept>;
public
Constructor Create; Override;
Destructor Destroy; Override;
function group(svc : TSnomedServices; grp : integer) : TSnomedCombinedRelationshipGroup;
function link : TSnomedCombinedConcept; overload;
end;
TSnomedCombinedReferenceSetEntry = class (TAdvObject)
private
id : TGuid;
date : TSnomedDate;
module : int64;
FItem : TSnomedCombinedItem;
FValues : TStringList;
public
Constructor Create; Override;
Destructor Destroy; Override;
end;
TSnomedCombinedReferenceSet = class (TAdvObject)
private
FName : String;
FFilename : String;
FDefinition : TSnomedCombinedConcept;
FTypes : TStringList;
FFields : TStringList;
DefaultLanguage : boolean;
FMembers : TAdvMap<TSnomedCombinedReferenceSetEntry>;
function getByItem(item : TSnomedCombinedItem; values : TStringList) : TSnomedCombinedReferenceSetEntry;
public
Constructor Create; Override;
Destructor Destroy; Override;
function abbrev : String;
end;
TSnomedCombinedDependency = class (TAdvObject)
private
id : TGuid;
FDate : TSnomedDate;
source, target : Int64;
sourceName, targetName : String;
startDate, endDate : TSnomedDate;
function key : String;
public
end;
TSnomedCombiner = class (TAdvObject)
private
FInternational: TSnomedServices;
FOthers: TAdvList<TSnomedServices>;
FStore : TAdvMap<TSnomedCombinedStoreEntry>;
FDependencies : TAdvMap<TSnomedCombinedDependency>;
FConcepts : TAdvMap<TSnomedCombinedConcept>;
FDescriptions : TAdvMap<TSnomedCombinedDescription>;
FRelationships : TAdvMap<TSnomedCombinedRelationship>;
FRefSets : TAdvMap<TSnomedCombinedReferenceSet>;
FCallback: TInstallerCallback;
FCurrent, FTotal, FPercent, FLast, FPathCount, FDescCount, FRelnCount : cardinal;
FMessage : String;
FSummary : TStringList;
FIssues : TStringList;
FDestination: String;
FStoreLocation: String;
nextRelationship : integer;
nextDescription : integer;
FModuleId : int64;
function generateId(k, t : integer) : int64; // t: 0 = concept, 1 = description, 2 = relationship
function getDescriptionId(d : String) : int64;
function getRelationshipId(s, rt, t : int64; grp : integer) : int64;
procedure determineTotal;
procedure loadDependency(svc: TSnomedServices; rm : TSnomedReferenceSetMember);
procedure loadDependencies(svc : TSnomedServices); overload;
procedure loadDependencies; overload;
function LoadConcept(svc : TSnomedServices; i : integer) : TSnomedCombinedConcept;
Procedure UpdateConcept(svc : TSnomedServices; i : integer; concept : TSnomedCombinedConcept);
procedure loadConcepts;
function LoadDescription(svc : TSnomedServices; i : integer) : boolean;
procedure loadDescriptions;
function LoadRelationship(svc : TSnomedServices; i : integer) : boolean;
procedure loadRelationships;
function LoadReferenceSet(svc : TSnomedServices; i : integer) : boolean;
procedure loadReferenceSets;
procedure checkForCircles; overload;
procedure checkForCircles(svc : TSnomedServices); overload;
procedure checkForCircles(root : UInt64); overload;
procedure checkForCircles(focus : TSnomedCombinedConcept; parents : Array of TSnomedCombinedConcept); overload;
function subsumes(this, other : TSnomedCombinedConcept) : boolean;
function matches(this, other : TSnomedCombinedRelationship) : boolean; overload;
procedure step(desc : String);
procedure classify; overload;
procedure classify(concept : TSnomedCombinedConcept); overload;
procedure forceRelationship(concept : TSnomedCombinedConcept; group : TSnomedCombinedRelationshipGroup; relationship : TSnomedCombinedRelationship);
function exists(list : TAdvList<TSnomedCombinedRelationship>; relationship : TSnomedCombinedRelationship) : boolean;
procedure addToRefSet(rsId, conceptId : UInt64);
procedure identify;
procedure updateDependencies;
procedure saveToRF2;
procedure SetInternational(const Value: TSnomedServices);
procedure recordIssue(s : String);
procedure recordSummary(s : String);
procedure loadStore;
procedure saveStore;
public
Constructor Create; override;
Destructor Destroy; override;
procedure Execute;
property international : TSnomedServices read FInternational write SetInternational;
property others : TAdvList<TSnomedServices> read FOthers;
property callback : TInstallerCallback read FCallback write FCallback;
property issues : TStringList read FIssues;
property summary : TStringList read FSummary;
property destination : String read FDestination write FDestination;
property store : String read FStoreLocation write FStoreLocation;
end;
implementation
{ TTabWriter }
constructor TTabWriter.Create(filename: String);
begin
inherited create;
FStream := TFileStream.Create(filename, fmCreate);
FDiv := false;
end;
destructor TTabWriter.destroy;
begin
FStream.Free;
inherited;
end;
procedure TTabWriter.field(s: String);
var
b : TBytes;
begin
if FDiv then
begin
setLength(b, 1);
b[0] := 9;
FStream.Write(b[0], 1);
end;
b := TEncoding.UTF8.GetBytes(s);
FStream.Write(b[0], length(b));
FDiv := true;
end;
procedure TTabWriter.endRecord;
var
b : TBytes;
begin
setLength(b, 2);
b[0] := 13;
b[1] := 10;
FStream.Write(b[0], 2);
FDiv := false;
end;
{ TSnomedCombinedRelationship }
constructor TSnomedCombinedRelationship.Create(source : TSnomedServices);
begin
inherited Create;
self.source := source;
end;
function TSnomedCombinedRelationship.link: TSnomedCombinedRelationship;
begin
result := TSnomedCombinedRelationship(inherited Link);
end;
function TSnomedCombinedRelationship.copy: TSnomedCombinedRelationship;
begin
result := TSnomedCombinedRelationship.Create(source);
result.FId := FId;
result.FTarget := FTarget.link;
result.FRelType := FRelType.link;
result.FModule := FModule;
result.FKind := FKind.link;
result.FModifier := FModifier.link;
result.FDate := FDate;
result.FActive := FActive;
end;
{ TSnomedCombinedRelationshipGroup }
constructor TSnomedCombinedRelationshipGroup.Create(source : TSnomedServices);
begin
inherited Create;
self.source := source;
FRelationships := TAdvList<TSnomedCombinedRelationship>.create;
end;
destructor TSnomedCombinedRelationshipGroup.Destroy;
begin
FRelationships.Free;
inherited;
end;
function TSnomedCombinedRelationshipGroup.link: TSnomedCombinedRelationshipGroup;
begin
result := TSnomedCombinedRelationshipGroup(inherited link);
end;
function TSnomedCombinedRelationshipGroup.copy: TSnomedCombinedRelationshipGroup;
var
t : TSnomedCombinedRelationship;
begin
result := TSnomedCombinedRelationshipGroup.create(source);
for t in FRelationships do
result.FRelationships.add(t.copy);
result.FGroup := FGroup;
end;
{ TSnomedCombinedConcept }
constructor TSnomedCombinedConcept.Create;
begin
inherited;
FDescriptions := TAdvList<TSnomedCombinedDescription>.create;
FGroups := TAdvList<TSnomedCombinedRelationshipGroup>.create;
FChildren := TAdvList<TSnomedCombinedConcept>.create;
end;
destructor TSnomedCombinedConcept.Destroy;
begin
FChildren.Free;
FGroups.Free;
FDescriptions.Free;
inherited;
end;
function TSnomedCombinedConcept.group(svc : TSnomedServices; grp: integer): TSnomedCombinedRelationshipGroup;
var
t : TSnomedCombinedRelationshipGroup;
begin
for t in FGroups do
if t.FGroup = grp then
exit(t);
result := TSnomedCombinedRelationshipGroup.Create(svc);
result.FGroup := grp;
FGroups.add(result);
end;
function TSnomedCombinedConcept.link: TSnomedCombinedConcept;
begin
result := TSnomedCombinedConcept(inherited Link);
end;
{ TSnomedCombiner }
constructor TSnomedCombiner.Create;
begin
inherited;
FStore := TAdvMap<TSnomedCombinedStoreEntry>.create;
FOthers := TAdvList<TSnomedServices>.create;
FConcepts := TAdvMap<TSnomedCombinedConcept>.create(500000);
FDependencies := TAdvMap<TSnomedCombinedDependency>.Create;
FDescriptions := TAdvMap<TSnomedCombinedDescription>.create(1500000);
FRelationships := TAdvMap<TSnomedCombinedRelationship>.create(3000000);
FRefSets := TAdvMap<TSnomedCombinedReferenceSet>.create(1000);
FSummary := TStringList.create;
FIssues := TStringList.create;
end;
destructor TSnomedCombiner.Destroy;
begin
FStore.Free;
FRefSets.Free;
FDescriptions.Free;
FDependencies.Free;
FRelationships.Free;
FSummary.free;
FIssues.free;
FConcepts.Free;
FInternational.free;
FOthers.free;
inherited;
end;
procedure TSnomedCombiner.SetInternational(const Value: TSnomedServices);
begin
FInternational.free;
FInternational := Value;
end;
procedure TSnomedCombiner.recordIssue(s: String);
begin
FIssues.Add(s);
end;
procedure TSnomedCombiner.recordSummary(s: String);
begin
FSummary.Add(s);
end;
procedure TSnomedCombiner.step(desc: String);
var
pct : integer;
begin
inc(FCurrent);
pct := trunc(FCurrent * 100 / FTotal);
if (pct <> FPercent) or (GetTickCount > FLast + 1000) or (FMessage <> desc) then
begin
callback(pct, desc);
FMessage := desc;
FPercent := pct;
FLast := GetTickCount;
end;
end;
procedure TSnomedCombiner.Execute;
begin
// 1. merging
determineTotal;
loadStore;
loadDependencies;
loadConcepts;
loadDescriptions;
loadRelationships;
loadReferenceSets;
// 2. classifying
checkForCircles;
classify;
identify;
updateDependencies;
// 3. save to RF2
saveStore;
saveToRF2;
end;
procedure TSnomedCombiner.determineTotal;
var
svc : TSnomedServices;
begin
FTotal := (FInternational.Concept.Count * 2) + FInternational.Desc.Count + FInternational.ChildRelationshipCount + FInternational.Rel.Count + FInternational.RefSetCount;
for svc in others do
FTotal := FTotal + (svc.Concept.Count * 2) + svc.Desc.Count + svc.ChildRelationshipCount + svc.Rel.Count + svc.RefSetCount;
FTotal := FTotal + 3; // admin overhead
FCurrent := 0;
FPercent := 0;
FLast := GetTickCount;
end;
procedure TSnomedCombiner.UpdateConcept(svc : TSnomedServices; i : integer; concept : TSnomedCombinedConcept);
var
Identity : UInt64;
Flags : Byte;
effectiveTime : TSnomedDate;
Parents, Descriptions, Inbounds, outbounds, refsets : Cardinal;
begin
svc.Concept.GetConcept(i, Identity, Flags, effectiveTime, Parents, Descriptions, Inbounds, outbounds, refsets);
concept.Fflags := flags or concept.Fflags;
if (concept.FDate < effectiveTime) then
concept.FDate := effectiveTime;
end;
procedure TSnomedCombiner.updateDependencies;
var
refset : TSnomedCombinedReferenceSet;
fsm : TSnomedCombinedReferenceSetEntry;
dep : TSnomedCombinedDependency;
begin
refset := FRefSets['900000000000534007'];
refset.FMembers.Clear;
for dep in FDependencies.Values do
begin
fsm := TSnomedCombinedReferenceSetEntry.Create;
fsm.id := dep.id;
refset.FMembers.add(GUIDToString(fsm.id), fsm);
fsm.date := dep.FDate;
fsm.module := dep.source;
fsm.FItem := FConcepts[inttostr(dep.target)];
fsm.FValues := TStringList.create;
fsm.FValues.Add(formatDateTime('yyyymmdd', dep.startDate));
fsm.FValues.Add(formatDateTime('yyyymmdd', dep.endDate));
end;
end;
function TSnomedCombiner.LoadConcept(svc: TSnomedServices; i: integer): TSnomedCombinedConcept;
var
Identity : UInt64;
Flags : Byte;
effectiveTime : TSnomedDate;
Parents, Descriptions, Inbounds, outbounds, refsets : Cardinal;
begin
svc.Concept.GetConcept(i, Identity, Flags, effectiveTime, Parents, Descriptions, Inbounds, outbounds, refsets);
result := TSnomedCombinedConcept.Create;
result.FNoGroup := TSnomedCombinedRelationshipGroup.Create(svc);
result.FGroups.Add(result.FNoGroup);
result.FId := Identity;
result.FFlags := Flags;
result.FDate := effectiveTime;
result.FModule := svc.Concept.getConceptId(svc.Concept.GetModuleId(i));
result.source := svc;
end;
procedure TSnomedCombiner.loadConcepts;
var
i : integer;
concept : TSnomedCombinedConcept;
svc : TSnomedServices;
id : Int64;
begin
recordSummary(FInternational.EditionName+' concepts: '+inttostr(FInternational.Concept.Count));
for i := 0 to FInternational.Concept.Count - 1 do
begin
step('Process Concepts for '+FInternational.EditionName);
concept := LoadConcept(FInternational, i * CONCEPT_SIZE);
FConcepts.Add(inttostr(concept.id), concept);
end;
for svc in FOthers do
begin
recordSummary(svc.EditionName+' concepts: '+inttostr(svc.Concept.Count));
for i := 0 to svc.Concept.Count - 1 do
begin
step('Process Concepts for '+svc.EditionName);
id := svc.Concept.getConceptId(i * CONCEPT_SIZE);
if FConcepts.TryGetValue(inttostr(id), concept) then
updateConcept(svc, i * CONCEPT_SIZE, concept)
else
begin
concept := LoadConcept(svc, i * CONCEPT_SIZE);
FConcepts.Add(inttostr(concept.id), concept);
end;
end;
end;
recordSummary('Total Concepts: '+inttostr(FConcepts.Count));
end;
procedure TSnomedCombiner.loadDependencies(svc: TSnomedServices);
var
rm : TSnomedReferenceSetMember;
rml : TSnomedReferenceSetMemberArray;
begin
rml := svc.getRefSet(900000000000534007);
for rm in rml do
loadDependency(svc, rm);
end;
procedure TSnomedCombiner.loadDependencies;
var
svc : TSnomedServices;
begin
step('Checking Dependencies');
loadDependencies(international);
for svc in others do
loadDependencies(svc);
end;
procedure TSnomedCombiner.loadDependency(svc: TSnomedServices; rm: TSnomedReferenceSetMember);
var
str : TCardinalArray;
dep, depE : TSnomedCombinedDependency;
begin
dep := TSnomedCombinedDependency.Create;
try
dep.id := rm.id;
dep.FDate := rm.date;
dep.source := svc.Concept.getConceptId(rm.module);
dep.target := svc.Concept.getConceptId(rm.Ref);
dep.sourceName := svc.GetPNForConcept(rm.module);
dep.targetName := svc.GetPNForConcept(rm.Ref);
str := svc.Refs.GetReferences(rm.values);
dep.startDate := readDate(svc.Strings.GetEntry(str[0]));
dep.endDate := readDate(svc.Strings.GetEntry(str[2]));
if (FDependencies.TryGetValue(dep.key, depE)) then
begin
if (dep.startDate <> depE.startDate) then
depE.startDate := dep.startDate;
if (dep.endDate <> depE.endDate) then
depE.endDate := dep.endDate;
end
else
FDependencies.Add(dep.key, dep.Link as TSnomedCombinedDependency);
finally
dep.Free;
end;
end;
function TSnomedCombiner.LoadDescription(svc: TSnomedServices; i: integer): boolean;
var
iDesc : Cardinal;
id, cid : UInt64;
date : TSnomedDate;
concept, module, kind, caps, refsets, valueses : Cardinal;
active : boolean;
c : TSnomedCombinedConcept;
d, t : TSnomedCombinedDescription;
lang : byte;
begin
svc.Desc.getDescription(i, iDesc, id, date, concept, module, kind, caps, refsets, valueses, active, lang);
cid := svc.Concept.getConceptId(concept);
if not FConcepts.TryGetValue(inttostr(cid), c) then
raise Exception.create('no find concept '+inttostr(cid))
else
begin
d := nil;
for t in c.Fdescriptions do
if t.Fid = id then
begin
d := t;
break;
end;
result := d = nil;
if d <> nil then
begin
if not SameText(d.FValue, svc.Strings.GetEntry(iDesc)) then
recordIssue('Module '+svc.EditionName+' changes value of description '+inttostr(d.FId)+' from "'+d.FValue+'" to "'+ svc.Strings.GetEntry(iDesc)+'"');
end
else
begin
d := TSnomedCombinedDescription.create;
c.FDescriptions.Add(d);
FDescriptions.Add(inttostr(id), d.Link);
d.FId := id;
d.FDate := date;
d.FModule := svc.Concept.getConceptId(module);
d.FKind := FConcepts[inttostr(svc.Concept.getConceptId(kind))];
d.FCaps := FConcepts[inttostr(svc.Concept.getConceptId(caps))];
d.FActive := active;
d.FLang := lang;
d.FValue := svc.Strings.GetEntry(iDesc);
end;
end;
end;
procedure TSnomedCombiner.loadDescriptions;
var
i, t : integer;
svc : TSnomedServices;
begin
t := 0;
recordSummary(FInternational.EditionName+' descriptions: '+inttostr(FInternational.Desc.Count));
for i := 0 to FInternational.Desc.Count - 1 do
begin
step('Process Descriptions for '+FInternational.EditionName);
if LoadDescription(FInternational, i*DESC_SIZE) then
inc(t);
end;
for svc in FOthers do
begin
recordSummary(svc.EditionName+' descriptions: '+inttostr(svc.Desc.Count));
for i := 0 to svc.Desc.Count - 1 do
begin
step('Process Descriptions for '+svc.EditionName);
if LoadDescription(svc, i*DESC_SIZE) then
inc(t);
end;
end;
recordSummary('Total Descriptions: '+inttostr(t));
FDescCount := t;
end;
function TSnomedCombiner.LoadReferenceSet(svc: TSnomedServices; i: integer): boolean;
var
definition, members, dummy, types, t, iFilename, name, names : cardinal;
ui, s, uid : string;
rs : TSnomedCombinedReferenceSet;
nl, tl, vl : TCardinalArray;
ml : TSnomedReferenceSetMemberArray;
m : TSnomedReferenceSetMember;
rm : TSnomedCombinedReferenceSetEntry;
j : integer;
new : boolean;
item : TSnomedCombinedItem;
guid : TGuid;
begin
svc.RefSetIndex.GetReferenceSet(i, name, iFilename, definition, members, dummy, types, names);
ui := svc.GetConceptId(definition);
if (ui = '900000000000534007') then
s := 'test';
new := not FRefSets.ContainsKey(ui);
if new then
begin
rs := TSnomedCombinedReferenceSet.Create;
FRefSets.Add(ui, rs);
rs.FDefinition := FConcepts[ui];
rs.FName := svc.Strings.GetEntry(name);
rs.FFilename := svc.Strings.GetEntry(iFilename);
if rs.FName = '' then
rs.FName := ui;
end
else
rs := FRefSets[ui];
if (svc = FInternational) and (definition = FInternational.DefaultLanguageRefSet) then
rs.DefaultLanguage := true;
if (types <> 0) then
begin
tl := svc.Refs.GetReferences(types);
j := 0;
for t in tl do
begin
s := chr(t);
if new then
rs.FTypes.Add(s)
else if rs.FTypes[j] <> s then
recordIssue('Value set mismatch - type '+inttostr(i)+' for '+rs.FName+' ('+inttostr(rs.FDefinition.id)+') was '+rs.FTypes[j]+', now found '+s);
inc(j);
end;
nl := svc.Refs.GetReferences(names);
j := 0;
for t in nl do
begin
s := svc.Strings.GetEntry(t);
if new then
rs.FFields.Add(s)
else if rs.FFields[j] <> s then
recordIssue('Value set mismatch - field '+inttostr(i)+' for '+rs.FName+' ('+inttostr(rs.FDefinition.id)+') was '+rs.FFields[j]+', now found '+s);
inc(j);
end;
end;
ml := svc.RefSetMembers.GetMembers(members);
result := false;
for m in ml do
begin
step('Process Reference Sets for '+svc.EditionName);
guid := m.id;
if IsNilGUID(guid) then
guid := CreateGUID;
uid := GuidToString(guid);
if new or not rs.FMembers.ContainsKey(uid) then
begin
result := true;
rm := TSnomedCombinedReferenceSetEntry.Create;
rs.FMembers.Add(uid, rm);
rm.id := guid;
rm.date := m.date;
if (m.module <> 0) then
rm.module := svc.Concept.getConceptId(m.module);
case m.kind of
0: rm.FItem := FConcepts[svc.GetConceptId(m.ref)];
1: rm.FItem := FDescriptions[svc.GetDescriptionId(m.ref)];
2: rm.FItem := FRelationships[svc.GetRelationshipId(m.ref)];
end;
if (m.values <> 0) then
begin
rm.FValues := TStringList.Create;
vl := svc.Refs.GetReferences(m.values);
for j := 0 to length(tl) - 1 do
case vl[j*2+1] of
1 {concept} : rm.FValues.add(svc.GetConceptId(vl[j*2]));
2 {desc} : rm.FValues.add(svc.GetDescriptionId(vl[j*2]));
3 {rel} : rm.FValues.add(svc.GetRelationshipId(vl[j*2]));
4 {integer} : rm.FValues.add(inttostr(vl[j*2]));
5 {string} : rm.FValues.add(svc.Strings.GetEntry(vl[j*2]));
else
raise exception.create('Unknown Cell Type '+inttostr(vl[j*2+1]));
end;
end;
end
end;
end;
procedure TSnomedCombiner.loadReferenceSets;
var
i, t : integer;
svc : TSnomedServices;
begin
t := 0;
recordSummary(FInternational.EditionName+' Reference Sets : '+inttostr(FInternational.Rel.Count));
for i := 0 to FInternational.RefSetIndex.Count - 1 do
begin
step('Process Reference Sets for '+FInternational.EditionName);
if LoadReferenceSet(FInternational, i) then
inc(t);
end;
for svc in FOthers do
begin
recordSummary(svc.EditionName+' reference sets: '+inttostr(svc.Rel.Count));
for i := 0 to svc.RefSetIndex.Count - 1 do
begin
step('Process Reference Sets for '+svc.EditionName);
if LoadReferenceSet(svc, i) then
inc(t);
end;
end;
recordSummary('Total Reference Sets: '+inttostr(t));
FRelnCount := t;
end;
function TSnomedCombiner.LoadRelationship(svc: TSnomedServices; i: integer): boolean;
var
// iDesc : Cardinal;
cid : UInt64;
// date : TSnomedDate;
// concept, module, kind, refsets, valueses : Cardinal;
// iFlags : Byte;
c, ct, cr : TSnomedCombinedConcept;
r, t : TSnomedCombinedRelationship;
identity : UInt64;
Source, Target, RelType, module, kind, modifier : Cardinal;
date : TSnomedDate;
Flags : Byte;
Group : Integer;
active, defining : boolean;
g : TSnomedCombinedRelationshipGroup;
begin
svc.Rel.GetRelationship(i, identity, Source, Target, RelType, module, kind, modifier, date, active, defining, group);
// if (RelType = svc.Is_a_Index) then
// // these are handled differently (in reverse, so we can iterate the children)
// begin
// if group <> 0 then
// raise Exception.Create('is_a in a group - '+inttostr(identity));
// cid := svc.Concept.getConceptId(target);
// if not FConcepts.TryGetValue(inttostr(cid), c) then
// raise Exception.create('no find concept '+inttostr(cid));
// cid := svc.Concept.getConceptId(source);
// if not FConcepts.TryGetValue(inttostr(cid), ct) then
// raise Exception.create('no find concept '+inttostr(cid));
// cid := svc.Concept.getConceptId(reltype);
// if not FConcepts.TryGetValue(inttostr(cid), cr) then
// raise Exception.create('no find concept '+inttostr(cid));
//
// r := nil;
// for t in c.FNoGroup.FRelationships do
// if (t.FTarget = ct) and t.FIsChild then
// begin
// r := t;
// break;
// end;
// result := r = nil; // don't count this
// if r = nil then
// begin
// r := TSnomedCombinedRelationship.Create(svc);
// r.FIsChild := true; // mark that it's the wrong way around
// c.FNoGroup.FRelationships.Add(r);
// r.FId := identity;
// r.FDate := date;
// r.FRelType := cr;
// r.Fmodule := svc.Concept.getConceptId(module);
// r.FTarget := ct;
// if (kind <> 0) then
// r.Fkind := FConcepts[inttostr(svc.Concept.getConceptId(kind))];
// if (modifier <> 0) then
// r.Fmodifier := FConcepts[inttostr(svc.Concept.getConceptId(modifier))];
// r.FDate := date;
// r.FActive := active;
// end;
// end
// else
// begin
cid := svc.Concept.getConceptId(source);
if not FConcepts.TryGetValue(inttostr(cid), c) then
raise Exception.create('no find concept '+inttostr(cid));
cid := svc.Concept.getConceptId(target);
if not FConcepts.TryGetValue(inttostr(cid), ct) then
raise Exception.create('no find concept '+inttostr(cid));
cid := svc.Concept.getConceptId(RelType);
if not FConcepts.TryGetValue(inttostr(cid), cr) then
raise Exception.create('no find concept '+inttostr(cid));
if group = 0 then
g := c.FNoGroup
else
g := c.group(svc, group);
r := nil;
for t in g.FRelationships do
if (t.Fid = identity) then
begin
r := t;
break;
end;
result := r = nil;
if r <> nil then
begin
if r.FDate < date then
r.FDate := date;
if not r.FActive and active then
r.FActive := active;
if r.FModule <> svc.Concept.getConceptId(module) then
recordIssue('Module '+svc.EditionName+' changes module of description '+inttostr(r.FId)+' from '+inttostr(r.FModule) +' to '+ inttostr(svc.Concept.getConceptId(module)));
if r.FTarget <> FConcepts[inttostr(svc.Concept.getConceptId(target))] then
recordIssue('Module '+svc.EditionName+' changes Target of relationship '+inttostr(r.FId)+' from '+inttostr(r.FTarget.id) +' to '+ inttostr(FConcepts[inttostr(svc.Concept.getConceptId(target))].id));
if r.FRelType <> FConcepts[inttostr(svc.Concept.getConceptId(RelType))] then
recordIssue('Module '+svc.EditionName+' changes RelType of relationship '+inttostr(r.FId)+' from '+inttostr(r.FRelType.id) +' to '+ inttostr(FConcepts[inttostr(svc.Concept.getConceptId(RelType))].id));
if (r.FKind = nil) and (kind <> 0) then
recordIssue('Module '+svc.EditionName+' assigns kind to relationship '+inttostr(r.FId)+' (to '+ inttostr(kind)+')')
else if (r.FKind <> nil) and (kind = 0) then
recordIssue('Module '+svc.EditionName+' removes kind from relationship '+inttostr(r.FId)+' (is '+ inttostr(r.FKind.id)+')')
else if (r.FKind <> nil) and (r.FKind <> FConcepts[inttostr(svc.Concept.getConceptId(kind))]) then
recordIssue('Module '+svc.EditionName+' changes kind of relationship '+inttostr(r.FId)+' from '+inttostr(r.FKind.id) +' to '+ inttostr(FConcepts[inttostr(svc.Concept.getConceptId(kind))].id));
if (r.Fmodifier = nil) and (modifier <> 0) then
recordIssue('Module '+svc.EditionName+' assigns modifier to relationship '+inttostr(r.FId)+' (to '+ inttostr(modifier)+')')
else if (r.Fmodifier <> nil) and (modifier = 0) then
recordIssue('Module '+svc.EditionName+' removes modifier from relationship '+inttostr(r.FId)+' (is '+ inttostr(r.Fmodifier.id)+')')
else if (r.Fmodifier <> nil) and (r.Fmodifier <> FConcepts[inttostr(svc.Concept.getConceptId(modifier))]) then
recordIssue('Module '+svc.EditionName+' changes modifier of relationship '+inttostr(r.FId)+' from '+inttostr(r.Fmodifier.id) +' to '+ inttostr(FConcepts[inttostr(svc.Concept.getConceptId(modifier))].id));
end
else
begin
r := TSnomedCombinedRelationship.create(svc);
g.FRelationships.Add(r);
FRelationships.add(inttostr(identity), r.link);
r.FId := identity;
r.FDate := date;
r.FTarget := ct;
r.FRelType := cr;
r.Fmodule := svc.Concept.getConceptId(module);
if (kind <> 0) then
r.Fkind := FConcepts[inttostr(svc.Concept.getConceptId(kind))];
if (modifier <> 0) then
r.Fmodifier := FConcepts[inttostr(svc.Concept.getConceptId(modifier))];
r.FDate := date;
r.FActive := active;
if (RelType <> svc.Is_a_Index) and active then
r.FTarget.FChildren.Add(c.link)
end;
// end;
end;
procedure TSnomedCombiner.loadRelationships;
var
i, t : integer;
svc : TSnomedServices;
begin
t := 0;
recordSummary(FInternational.EditionName+' relationships: '+inttostr(FInternational.Rel.Count));
for i := 0 to FInternational.Rel.Count - 1 do
begin
step('Process Relationships for '+FInternational.EditionName);
if LoadRelationship(FInternational, i*RELATIONSHIP_SIZE) then
inc(t);
end;
for svc in FOthers do
begin
recordSummary(svc.EditionName+' relationships: '+inttostr(svc.Rel.Count));
for i := 0 to svc.Rel.Count - 1 do
begin
step('Process Relationships for '+svc.EditionName);
if LoadRelationship(svc, i*RELATIONSHIP_SIZE) then
inc(t);
end;
end;
recordSummary('Total Relationships: '+inttostr(t));
FRelnCount := t;
end;
procedure TSnomedCombiner.loadStore;
var
s, l, r : String;
sl : TStringList;
begin
Step('Loading Persistent Identity Store');
if FileExists(FStoreLocation) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(FStoreLocation);
nextRelationship := StrToInt(sl[0]);
nextDescription := StrToInt(sl[1]);
sl.Delete(0);
sl.Delete(0);
for s in sl do
begin
StringSplit(s, '=', l, r);
FStore.Add(r, TSnomedCombinedStoreEntry.Create(l));
end;
finally
sl.Free;
end;
end;
FModuleId := generateId(1, 0);
end;
procedure TSnomedCombiner.checkForCircles;
var
svc : TSnomedServices;
begin
callback(0, '2nd Pass: Searching for Circular definitions');
checkForCircles(FInternational);
for svc in others do
checkForCircles(svc);
end;
procedure TSnomedCombiner.checkForCircles(svc : TSnomedServices);
var
i : int64;
begin
for i in svc.ActiveRoots do
checkForCircles(i);
for i in svc.InactiveRoots do
checkForCircles(i);
end;
procedure TSnomedCombiner.checkForCircles(root : UInt64);
var
concept : TSnomedCombinedConcept;
child : TSnomedCombinedConcept;
begin
concept := FConcepts[inttostr(root)];
for child in concept.FChildren do
checkForCircles(child, [concept]);
end;
procedure TSnomedCombiner.addToRefSet(rsId, conceptId: UInt64);
var
entry : TSnomedCombinedReferenceSetEntry;
begin
entry := TSnomedCombinedReferenceSetEntry.Create;
entry.id := CreateGUID;
FRefSets[inttostr(rsId)].FMembers.add(GuidToString(entry.id), entry);
entry.FItem := FConcepts[inttostr(conceptId)].link;
end;
procedure TSnomedCombiner.checkForCircles(focus : TSnomedCombinedConcept; parents : Array of TSnomedCombinedConcept);
var
c : TSnomedCombinedConcept;
s : String;
f : boolean;
np : Array of TSnomedCombinedConcept;
i : integer;
child : TSnomedCombinedConcept;
begin
inc(FPathCount);
f := false;
for c in parents do
if focus = c then
f := true;
if f then
begin
s := '';
for c in parents do
if s = '' then
s := inttostr(c.FID)
else
s := s+','+inttostr(c.FID);
raise Exception.Create('Circular Dependency found: SCT concept '+inttostr(focus.FId)+' has itself as a parent ('+s+')');
end;
SetLength(np, length(parents)+1);
for i := 0 to length(parents) - 1 do
np[i] := parents[i];
np[length(parents)] := focus;
for child in focus.FChildren do
checkForCircles(child, np);
end;
function intCompare(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2, i3 : int64;
begin
i1 := StrToInt64(list[index1]);
i2 := StrToInt64(list[index2]);
i3 := i1-i2;
if (i3 > 0) then
result := 1
else if (i3 < 0) then
result := -1
else
result := 0;
end;
function charForBool(bool : boolean) : String;
begin
if bool then
result := '1'
else
result := '0';
end;
procedure TSnomedCombiner.saveStore;
var
s : String;
f : System.Text;
begin
Step('Saving Persistent Identity Store');
assignfile(f, FStoreLocation);
rewrite(f);
writeln(f, nextRelationship);
writeln(f, nextDescription);
for s in FStore.Keys do
writeln(f, inttostr(FStore[s].id)+'='+s);
closefile(f);
end;
procedure TSnomedCombiner.saveToRF2;
var
c,d,r : TTabWriter;
concept : TSnomedCombinedConcept;
desc : TSnomedCombinedDescription;
rel : TSnomedCombinedRelationship;
relg : TSnomedCombinedRelationshipGroup;
st : TStringList;
s : String;
i : integer;
rs : TSnomedCombinedReferenceSet;
rm : TSnomedCombinedReferenceSetEntry;
filename : String;
begin
step('Sorting Concepts');
st := TStringList.Create;
try
for s in FConcepts.Keys do
st.AddObject(s, FConcepts[s]);
st.CustomSort(intCompare);
CreateDir(IncludeTrailingBackslash(destination)+'Terminology');
CreateDir(IncludeTrailingBackslash(destination)+'RefSet');
CreateDir(IncludeTrailingBackslash(destination)+'RefSet\Language');
c := TTabWriter.Create(IncludeTrailingBackslash(destination)+'Terminology\concepts.txt');
d := TTabWriter.Create(IncludeTrailingBackslash(destination)+'Terminology\descriptions.txt');
r := TTabWriter.Create(IncludeTrailingBackslash(destination)+'Terminology\relationships.txt');
try
c.field('id');
c.field('effectiveTime');
c.field('active');
c.field('moduleId');
c.field('definitionStatusId');
c.endRecord;
d.field('id');
d.field('effectiveTime');
d.field('active');
d.field('moduleId');
d.field('conceptId');
d.field('languageCode');
d.field('typeId');
d.field('term');
d.field('caseSignificanceId');
d.endRecord;
r.field('id');
r.field('effectiveTime');
r.field('active');
r.field('moduleId');
r.field('sourceId');
r.field('destinationId');
r.field('relationshipGroup');
r.field('typeId');
r.field('characteristicTypeId');
r.field('modifierId');
r.endRecord;
for i := 0 to st.Count - 1 do
begin
step('Saving RF2 format');
concept := TSnomedCombinedConcept(st.Objects[i]);
c.field(inttostr(concept.id));
c.field(formatDateTime('yyyymmdd', concept.Fdate));
if concept.FFlags and MASK_CONCEPT_STATUS > 0 then
c.field('0')
else
c.field('1');
c.field(inttostr(concept.FModule));
if concept.FFlags and MASK_CONCEPT_PRIMITIVE > 0 then
c.field(inttostr(RF2_MAGIC_PRIMITIVE))
else
c.field(inttostr(RF2_MAGIC_DEFINED));
c.endRecord;
for desc in concept.FDescriptions do
begin
d.field(inttostr(desc.FId));
d.field(formatDateTime('yyyymmdd', desc.FDate));
d.field(charForBool(desc.FActive));
d.field(inttostr(desc.FModule));
d.field(inttostr(concept.id));
d.field(codeForLang(desc.FLang));
d.field(inttostr(desc.FKind.FId));
d.field(desc.FValue);
d.field(inttostr(desc.FCaps.FId));
d.endRecord;
end;
for relg in concept.FGroups do
begin
for rel in relg.FRelationships do
begin
r.field(inttostr(rel.FId)); // id
r.field(formatDateTime('yyyymmdd', rel.FDate)); // effectiveTime
r.field(charForBool(rel.FActive)); // active
r.field(inttostr(rel.FModule)); // moduleId
r.field(inttostr(concept.id)); // sourceId
r.field(inttostr(rel.FTarget.FID)); // destinationId
r.field(inttostr(relg.FGroup)); // relationshipGroup
r.field(inttostr(rel.FRelType.FId)); // typeId
r.field(inttostr(rel.FKind.FId)); // characteristicTypeId
r.field(inttostr(rel.FModifier.FId)); // modifierId
r.endRecord;
end;
end;
end;
finally
c.free;
d.Free;
r.Free;
end;
finally
st.Free;
end;
for rs in FRefSets.Values do
begin
if rs.DefaultLanguage then
filename := IncludeTrailingBackslash(destination)+'RefSet\Language\'+rs.FFilename
else
filename := IncludeTrailingBackslash(destination)+'RefSet\'+rs.FFilename;
ForceFolder(ExtractFilePath(filename));
r := TTabWriter.Create(filename);
try
r.field('id');
r.field('effectiveTime');
r.field('active');
r.field('moduleId');
r.field('refsetId');
r.field('referencedComponentId');
for i := 0 to rs.FTypes.Count - 1 do
r.field(rs.Ffields[i]);
r.endRecord;
for rm in rs.FMembers.Values do
begin
r.field(NewGuidId);
if (rm.Date = 0) then
r.field(formatDateTime('yyyymmdd', rs.FDefinition.FDate))
else
r.field(formatDateTime('yyyymmdd', rm.Date));
r.field('1');
if (rm.module = 0) then
r.field(inttostr(rs.FDefinition.FModule))
else
r.field(inttostr(rm.module));
r.field(inttostr(rs.FDefinition.id));
r.field(inttostr(rm.FItem.FId));
if (rm.FValues <> nil) then
for i := 0 to rm.FValues.Count - 1 do
r.field(rm.FValues[i]);
r.endRecord;
end;
finally
r.Free;
end;
end;
end;
procedure TSnomedCombiner.classify;
var
concept : TSnomedCombinedConcept;
begin
for concept in FConcepts.Values do
classify(concept);
end;
procedure TSnomedCombiner.classify(concept : TSnomedCombinedConcept);
var
child : TSnomedCombinedConcept;
rel : TSnomedCombinedRelationship;
relg : TSnomedCombinedRelationshipGroup;
begin
step('Classifying');
for relg in concept.FGroups do
begin
for rel in relg.FRelationships do
begin
if (rel.FActive) and // ignore things that are not active
(rel.FRelType.FId <> IS_A_MAGIC) and // ignore is_a - don't classify them
(rel.source = FInternational) then // anything from internationa is fully classified
begin
for child in concept.FChildren do
forceRelationship(child, relg, rel);
end;
end;
end;
end;
procedure TSnomedCombiner.forceRelationship(concept : TSnomedCombinedConcept; group : TSnomedCombinedRelationshipGroup; relationship : TSnomedCombinedRelationship);
var
child : TSnomedCombinedConcept;
g : TSnomedCombinedRelationshipGroup;
r : TSnomedCombinedRelationship;
begin
if (concept.source <> international) and (concept.source <> relationship.source) then
begin
// ok, the relationship was added by a different edition to the concept. So the concept might not have this
// relationship on it. ensure that it exists
g := concept.group(group.source, group.FGroup);
if not exists(g.FRelationships, relationship) then
begin
r := TSnomedCombinedRelationship.Create(relationship.source);
g.FRelationships.Add(r);
r.id := getRelationshipId(concept.id, relationship.FRelType.id, relationship.FTarget.id, group.FGroup);
r.FTarget := relationship.FTarget;
r.FRelType := relationship.FRelType;
r.FKind := relationship.FKind;
r.FModifier := relationship.FModifier;
r.FDate := relationship.FDate;
r.FModule := FModuleId;
r.FActive := relationship.FActive;
end;
end;
for child in concept.FChildren do
forceRelationship(child, group, relationship);
end;
function TSnomedCombiner.generateId(k, t: integer): int64;
var
s : String;
begin
s := inttostr(k)+inttostr(SCT_FHIR_NS)+'1'+inttostr(t);
s := s + genCheckDigit(s);
result := StrToInt64(s);
end;
function TSnomedCombiner.getDescriptionId(d: String): int64;
var
k : TSnomedCombinedStoreEntry;
begin
if FStore.TryGetValue(d, k) then
result := k.id
else
begin
inc(nextDescription);
result := generateId(nextDescription, 1);
FStore.Add(d, TSnomedCombinedStoreEntry.create(result));
end;
end;
function TSnomedCombiner.getRelationshipId(s, rt, t: int64; grp : integer): int64;
var
k : TSnomedCombinedStoreEntry;
id : String;
begin
id := inttostr(s)+':'+inttostr(rt)+':'+inttostr(t)+':'+inttostr(grp);
if FStore.TryGetValue(id, k) then
result := k.id
else
begin
inc(nextRelationship);
result := generateId(nextRelationship, 2);
FStore.Add(id, TSnomedCombinedStoreEntry.create(result));
end;
end;
procedure TSnomedCombiner.identify;
function concept(id : int64; fsn, pn : String; parent : int64) : int64;
var
concept : TSnomedCombinedConcept;
relationship : TSnomedCombinedRelationship;
desc : TSnomedCombinedDescription;
begin
concept := TSnomedCombinedConcept.Create;
FConcepts.Add(inttostr(id), concept);
concept.FId := id;
concept.FFlags := MASK_CONCEPT_PRIMITIVE or MASK_CONCEPT_STATUS;
concept.FDate := trunc(now);
concept.FModule := FModuleId;
desc := TSnomedCombinedDescription.Create;
concept.FDescriptions.add(desc);
desc.id := getDescriptionId(fsn);
desc.FDate := trunc(now);
desc.FModule := FModuleId;
desc.FKind := FConcepts[inttostr(RF2_MAGIC_FSN)];
desc.FCaps := FConcepts[inttostr(900000000000448009)];
desc.FActive := true;
desc.Flang := 1;
desc.FValue := FSN;
desc := TSnomedCombinedDescription.Create;
concept.FDescriptions.add(desc);
desc.id := getDescriptionId(pn);
desc.FDate := trunc(now);
desc.FModule := FModuleId;
desc.FKind := FConcepts[inttostr(900000000000013009)];
desc.FCaps := FConcepts[inttostr(900000000000448009)];
desc.FActive := true;
desc.Flang := 1;
desc.FValue := pn;
relationship := TSnomedCombinedRelationship.create(nil);
concept.group(nil, 0).FRelationships.add(relationship);
relationship.id := getRelationshipId(concept.id, IS_A_MAGIC, parent, 0);
relationship.FTarget := FConcepts[inttostr(parent)];
relationship.FRelType := FConcepts[inttostr(IS_A_MAGIC)];
relationship.FModule := FModuleId;
relationship.FKind := FConcepts[inttostr(900000000000010007)];
relationship.FModifier := FConcepts[inttostr(900000000000451002)];
relationship.FDate := trunc(now);
relationship.FActive := true;
end;
procedure relationship(source, reltype, target : int64);
var
concept : TSnomedCombinedConcept;
relationship : TSnomedCombinedRelationship;
desc : TSnomedCombinedDescription;
begin
concept := FConcepts[inttostr(source)];
relationship := TSnomedCombinedRelationship.create(nil);
concept.group(nil, 0).FRelationships.add(relationship);
relationship.id := getRelationshipId(source, reltype, target, 0);
relationship.FTarget := FConcepts[inttostr(target)];
relationship.FRelType := FConcepts[inttostr(reltype)];
relationship.FModule := FModuleId;
relationship.FKind := FConcepts[inttostr(900000000000010007)];
relationship.FModifier := FConcepts[inttostr(900000000000451002)];
relationship.FDate := trunc(now);
relationship.FActive := true;
end;
var
rid : int64;
svc : TSnomedServices;
st : TStringList;
dep : TSnomedCombinedDependency;
s : String;
begin
concept(FModuleId, 'Custom Combined Module (core metadata concept)', 'Custom Combined Module', 900000000000443000);
rid := generateId(2, 0);
concept(rid, 'Combines (linkage concept)', 'Combines', 106237007);
relationship(FModuleId, rid, StrToInt64(international.EditionId));
for svc in others do
relationship(FModuleId, rid, StrToInt64(svc.EditionId));
st := TStringList.Create;
try
st.Sorted := true;
st.Duplicates := dupIgnore;
for dep in FDependencies.Values do
st.Add(inttostr(dep.source));
for s in st do
begin
dep := TSnomedCombinedDependency.Create;
try
dep.id := CreateGUID;
dep.FDate := trunc(now);
dep.source := FModuleId;
dep.target := StrToInt64(s);
dep.startDate := trunc(now);
dep.endDate := trunc(now);
FDependencies.Add(dep.key, dep.Link as TSnomedCombinedDependency);
finally
dep.Free;
end;
end;
finally
st.Free;
end;
end;
function TSnomedCombiner.exists(list: TAdvList<TSnomedCombinedRelationship>; relationship: TSnomedCombinedRelationship): boolean;
var
t : TSnomedCombinedRelationship;
begin
for t in list do
if matches(relationship, t) then
exit(true);
exit(false);
end;
function TSnomedCombiner.matches(this, other: TSnomedCombinedRelationship): boolean;
begin
result := ((this.FRelType = other.FRelType) or subsumes(other.FRelType, this.FRelType)) and
((this.FTarget = other.FTarget) or subsumes(other.FTarget, this.FTarget));
end;
function TSnomedCombiner.subsumes(this, other: TSnomedCombinedConcept): boolean;
var
st, so: String;
svc : TSnomedServices;
begin
if this.FId = other.FId then
exit(true);
st := inttostr(this.FId);
so := inttostr(other.FId);
result := false;
if international.Subsumes(st, so) then
exit(true);
for svc in others do
if svc.Subsumes(st, so) then
exit(true);
result := false;
end;
{ TSnomedCombinedDescription }
function TSnomedCombinedDescription.link: TSnomedCombinedDescription;
begin
result := TSnomedCombinedDescription(inherited Link);
end;
{ TSnomedCombinedReferenceSetEntry }
constructor TSnomedCombinedReferenceSetEntry.Create;
begin
inherited;
end;
destructor TSnomedCombinedReferenceSetEntry.Destroy;
begin
FValues.Free;
inherited;
end;
{ TSnomedCombinedReferenceSet }
function TSnomedCombinedReferenceSet.abbrev: String;
var
s : String;
begin
result := '';
for s in FTypes do
result := result + s;
end;
constructor TSnomedCombinedReferenceSet.Create;
begin
inherited;
FTypes := TStringList.create;
FFields := TStringList.create;
FMembers := TAdvMap<TSnomedCombinedReferenceSetEntry>.create;
end;
destructor TSnomedCombinedReferenceSet.Destroy;
begin
FTypes.Free;
FFields.Free;
FMembers.Free;
inherited;
end;
function TSnomedCombinedReferenceSet.getByItem(item: TSnomedCombinedItem; values : TStringList): TSnomedCombinedReferenceSetEntry;
var
t : TSnomedCombinedReferenceSetEntry;
i : integer;
ok : boolean;
begin
for t in FMembers.Values do
if t.FItem.id = item.id then
begin
if (t.FValues = nil) and (values.Count = 0) then
exit(t);
if (t.FValues <> nil) and (t.FValues.Count > 0) and (values.Count = t.FValues.Count) then
begin
ok := true;
for i := 0 to values.Count - 1 do
if values[i] <> t.FValues[i] then
ok := false;
if (ok) then
exit(t);
end;
end;
exit(nil);
end;
{ TSnomedCombinedDependency }
function TSnomedCombinedDependency.key: String;
begin
result := inttostr(source)+':'+inttostr(target);
end;
{ TSnomedCombinedStoreEntry }
constructor TSnomedCombinedStoreEntry.create(s: String);
begin
inherited create;
id := Strtoint64(s);
end;
constructor TSnomedCombinedStoreEntry.create(i: int64);
begin
inherited create;
id := i;
end;
end.
|
unit UDbfCommon;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, ExtCtrls, DBCtrls, Grids, DBGrids, Menus, Buttons,
ComCtrls;
type
TDbfFieldType = char;
{$I _DbfCommon.inc}
{$ifndef DELPHI_5}
procedure FreeAndNil(var v);
{$endif}
procedure FileCopy(source,dest:string);
const
// _MAJOR_VERSION
_MAJOR_VERSION = 4;
// _MINOR_VERSION
_MINOR_VERSION = 010;
type
EDBFError = Exception;
PBookMarkData = ^rBookMarkData;
rBookmarkData = record
IndexBookmark:longint;
RecNo:longint;
end;
implementation
procedure FileCopy(source,dest:string);
begin
CopyFile(PCHAR(source),PCHAR(dest),FALSE);
end;
{$ifndef DELPHI_5}
procedure FreeAndNil(var v);
begin
try
TObject(v).Free;
finally
TObject(v):=nil;
end;
end;
{$endif}
initialization
end.
|
unit DBAureliusConnection;
// ==> settare nelle variabili di compilazione
// -- tipo di DB
{.$DEFINE DBMSSQL}
{.$DEFINE DBSQLITE}
{.$DEFINE DBORACLE}
{.$DEFINE DBPARSE}
// -- tipo di connessione
{.$DEFINE REMOTEDB}
{.$DEFINE FIREDAC}
{.$DEFINE MORMOT}
{.$DEFINE PARSE}
{$IFDEF FIREDAC}
{$DEFINE DBMONITOR}
{$ENDIF}
{.$UNDEF DBMONITOR}
interface
uses
Generics.Collections, Classes, IniFiles,
Aurelius.Commands.Listeners,
Aurelius.Drivers.Interfaces,
Aurelius.Engine.AbstractManager,
Aurelius.Engine.ObjectManager,
Aurelius.Engine.DatabaseManager
;
type
TDBConnection = class sealed
private
class var FInstance: TDBConnection;
class var FManager: TObjectManager;
private
FConnection: IDBConnection;
FListeners: TList<ICommandExecutionListener>;
FTransaction: IDBTransaction;
procedure PrivateCreate;
procedure PrivateDestroy;
function CreateConnection: IDBConnection;
function GetConnection: IDBConnection;
procedure AddListeners(AManager: TAbstractManager);
public
class function GetInstance: TDBConnection;
class function GetObjectManager: TObjectManager;
class procedure ClearObjectManager;
function CreateObjectManager: TObjectManager;
procedure AddCommandListener(Listener: ICommandExecutionListener);
class procedure AddLines(List: TStrings; SQL: string; Params: TEnumerable<TDBParam>);
property Connection: IDBConnection read GetConnection;
property Transaction: IDBTransaction read FTransaction;
function HasConnection: boolean;
function GetNewDatabaseManager: TDatabaseManager;
procedure UnloadConnection;
(*
procedure GetDbSettings(var pSettings: TProjectSettings);
procedure SaveDbSettings(pSettings: TProjectSettings);
*)
end;
implementation
uses
Aurelius.Global.Config,
VCL.Dialogs,
uCMDLineOptions,
Variants, DB, TypInfo, System.SysUtils,
{$IF Defined(DBMSSQL)}
// Aurelius.Sql.MSSQL,
Aurelius.Sql.MSSQL2014,
{$ELSEIF Defined(DBSQLITE)}
Aurelius.Sql.SQLite,
{$ELSEIF Defined(DBORACLE)}
Aurelius.Sql.Oracle,
{$ELSEIF Defined(DBPARSE)}
Aurelius.Sql.ParseGenerator,
{$IFEND}
{$IF Defined(REMOTEDB)}
Aurelius.Drivers.RemoteDB,
RemoteDB.Client.Database
{$ELSEIF Defined(FIREDAC)}
Aurelius.Drivers.FireDac,
{$IFDEF DBMONITOR}
FireDAC.Moni.RemoteClient,
{$ENDIF}
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
{$IFDEF DBMSSQL}
// FireDAC.Phys.ODBCBase,
FireDAC.Phys.MSSQL,
{$ENDIF}
{$IFDEF DBSQLITE}
FireDAC.Phys.SQLite,
{$ENDIF}
{$IFDEF DBORACLE}
FireDAC.Phys.Oracle,
{$ENDIF}
FireDAC.Comp.Client,
// FireDAC.FMXUI.Wait,
FireDAC.VCLUI.Wait,
FireDAC.Comp.UI,
FireDAC.DApt
{$ELSEIF Defined(MORMOT)}
mORMotInterface,
Aurelius.Drivers.mORMot
{$ELSEIF Defined(PARSE)}
Aurelius.Drivers.Parse
{$IFEND}
;
{$REGION 'My Secret Keys'}
const
PARSE_App_Id = '6KNDQpnRilc62wg1zVhmCiRvkv2hZosvMCykqJOY';
PARSE_RESTApi_Key = 'IBCG5N1W2OgsSLdHoZBTnPwNtEihp9Row0WKvS2h';
PARSE_Master_Key = 'x4DXgxJjvSTFOlyi3MK6m9Or5KGKCY7paeZpUuso';
{$ENDREGION}
procedure TDBConnection.AddCommandListener(
Listener: ICommandExecutionListener);
begin
FListeners.Add(Listener);
end;
class procedure TDBConnection.AddLines(List: TStrings; SQL: string;
Params: TEnumerable<TDBParam>);
var
P: TDBParam;
ValueAsString: string;
HasParams: Boolean;
begin
List.Add(SQL);
if Params <> nil then
begin
HasParams := False;
for P in Params do
begin
if not HasParams then
begin
List.Add('');
HasParams := True;
end;
if P.ParamValue = Variants.Null then
ValueAsString := 'NULL'
else
if P.ParamType = ftDateTime then
ValueAsString := '"' + DateTimeToStr(P.ParamValue) + '"'
else
if P.ParamType = ftDate then
ValueAsString := '"' + DateToStr(P.ParamValue) + '"'
else
ValueAsString := '"' + VarToStr(P.ParamValue) + '"';
List.Add(P.ParamName + ' = ' + ValueAsString + ' (' +
GetEnumName(TypeInfo(TFieldType), Ord(P.ParamType)) + ')');
end;
end;
List.Add('');
List.Add('================================================');
end;
procedure TDBConnection.AddListeners(AManager: TAbstractManager);
var
Listener: ICommandExecutionListener;
begin
for Listener in FListeners do
AManager.AddCommandListener(Listener);
end;
procedure TDBConnection.UnloadConnection;
begin
if FConnection <> nil then
begin
FConnection.Disconnect;
FConnection := nil;
end;
end;
{$REGION 'Connessioni al DB per tipo'}
{$IFDEF REMOTEDB}
function TDBConnection.CreateConnection: IDBConnection;
//const
// ServerUrl = 'http://localhost:2001/tms/business/remotedb/basic/';
// ServerUrl = 'http://win7-delphixe5:2001/tms/xdata/';
// ServerUrl = 'http://localhost:2001/fstile/';
var
XDB: TRemoteDBDatabase;
begin
XDB := TRemoteDBDatabase.Create(nil);
XDB.Timeout := 15000; // 10 sec.
Result := TRemoteDBConnectionAdapter.Create(XDB, true);
XDB.ServerUri := format('http://%s:%s/%s/',[TCMDLineOptions.Server,TCMDLineOptions.Porta.ToString,TCMDLineOptions.NomeDB]);
// XDB.Connected := true;
end;
{$ENDIF}
{$IFDEF FIREDAC}
function TDBConnection.CreateConnection: IDBConnection;
var
{$IFDEF DBMONITOR}
Monitor: TFDMoniRemoteClientLink;
{$ENDIF}
conn: TFDConnection;
{$IFDEF DBORACLE}
Odriver: TFDPhysOracleDriverLink;
{$ENDIF}
begin
{$IFDEF DBMONITOR}
Monitor := TFDMoniRemoteClientLink.Create(nil);
Monitor.Tracing := True;
{$ENDIF}
conn := TFDConnection.Create(nil);
{$IFDEF DBMSSQL}
conn.Params.Add(format('Database=%s',[TCMDLineOptions.NomeDB]));
conn.Params.Add(format('User_Name=%s',[TCMDLineOptions.User]));
conn.Params.Add(format('Password=%s',[TCMDLineOptions.Pswd]));
conn.Params.Add(format('Server=%s',[TCMDLineOptions.Server]));
conn.Params.Add('DriverID=MSSQL');
{$ENDIF}
{$IFDEF DBSQLITE}
conn.Params.Add('Database=C:\Apps\SuMisura\Common\SuMisura.sdb.db');
// conn.Params.Add('User_Name=iouri');
// conn.Params.Add('Password=iouri');
// conn.Params.Add('Server=DEVWIN7-32\SQLEXPRESS');
conn.Params.Add('DriverID=SQLite');
{$ENDIF}
{$IFDEF DBORACLE}
Odriver := TFDPhysOracleDriverLink.Create(nil);
conn.Params.Add(format('Database=%s',[TCMDLineOptions.NomeDB]));
conn.Params.Add(format('User_Name=%s',[TCMDLineOptions.User]));
conn.Params.Add(format('Password=%s',[TCMDLineOptions.Pswd]));
// conn.Params.Add(format('Server=%s',[TCMDLineOptions.Server]));
conn.Params.Add('OSAuthent=No');
conn.Params.Add('DriverID=Ora');
conn.Params.Add('AuthMode=Normal');
// -- per Instant Client (togliere per Client)
// Odriver.NLSLang := 'AMERICAN_AMERICA.CL8MSWIN1251';
// Odriver.VendorLib := 'C:\instantclient\oci.dll';
// Odriver.VendorLib := 'C:\Oracle\bin\oci.dll';
{$ENDIF}
{$IFDEF DBMONITOR}
conn.Params.Add('MonitorBy=Remote');
{$ENDIF}
FTransaction := TFireDacTransactionAdapter.Create(conn);
Result := TFireDacConnectionAdapter.Create(conn, true);
end;
{$ENDIF}
{$IFDEF MORMOT}
function TDBConnection.CreateConnection: IDBConnection;
var
conn: TProjectSettings;
begin
conn := TProjectSettings.Create;
conn.HOST := 'localhost';
conn.PORT := '888';
conn.Engine := rseODBC;
conn.ServerName := 'TestFS';
conn.DatabaseName := 'GestioneFS';
conn.UserID := 'iouri';
conn.PassWord := 'iouri';
Result := TmORMotConnectionAdapter.Create(conn);
end;
{$ENDIF}
{$IFDEF PARSE}
function TDBConnection.CreateConnection: IDBConnection;
var
conn: TProjectSettings;
begin
conn := TProjectSettings.Create;
conn.ApplicationID := PARSE_App_Id;
conn.RestApiKey := PARSE_RESTApi_Key;
conn.MasterKey := PARSE_Master_Key;
Result := TParseConnectionAdapter.Create(conn);
end;
{$ENDIF}
{$ENDREGION}
function TDBConnection.GetConnection: IDBConnection;
begin
if FConnection=nil then
begin
Result := CreateConnection;
if Result = nil then
raise Exception.Create('Invalid connection settings. Cannot connect to database.');
if not Result.IsConnected then
Result.Connect;
FConnection := Result;
end
else
result := FConnection;
end;
class function TDBConnection.GetInstance: TDBConnection;
begin
if FInstance = nil then
begin
FInstance := TDBConnection.Create;
FInstance.PrivateCreate;
end;
Result := FInstance;
end;
class function TDBConnection.GetObjectManager: TObjectManager;
begin
if FManager = nil then
begin
FManager := GetInstance.CreateObjectManager;
end;
Result := FManager;
end;
class procedure TDBConnection.ClearObjectManager;
begin
FManager.Clear;
FManager.Free;
FManager := nil;
FInstance.Free;
FInstance := nil;
end;
function TDBConnection.GetNewDatabaseManager: TDatabaseManager;
begin
Result := TDatabaseManager.Create(Connection);
AddListeners(Result);
end;
function TDBConnection.CreateObjectManager: TObjectManager;
begin
Result := TObjectManager.Create(Connection);
Result.OwnsObjects := True;
AddListeners(Result);
end;
function TDBConnection.HasConnection: boolean;
begin
// Result := CreateConnection <> nil;
Result := FConnection <> nil;
end;
procedure TDBConnection.PrivateCreate;
begin
FListeners := TList<ICommandExecutionListener>.Create;
end;
procedure TDBConnection.PrivateDestroy;
begin
UnloadConnection;
FListeners.Free;
end;
initialization
TGlobalConfigs.GetInstance.MaxEagerFetchDepth := 2;
finalization
if TDBConnection.FInstance <> nil then
begin
TDBConnection.FInstance.PrivateDestroy;
TDBConnection.FInstance.Free;
TDBConnection.FInstance := nil;
end;
end.
|
unit uSchEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids,
StdCtrls, Menus, ComCtrls, uStrUtils, Math, uEditEvent, uCustomTypes,
uEventClassifier, uBchEditor, uAlarmTemplateEditor;
type
{ TfSchEditor }
TfSchEditor = class(TForm)
bCancel: TButton;
bOK: TButton;
pmiCopyTask: TMenuItem;
miCopyTask: TMenuItem;
pmiDelTask: TMenuItem;
pmiEditTask: TMenuItem;
pmiAddTask: TMenuItem;
miDelTask: TMenuItem;
miEditTask: TMenuItem;
miAddTask: TMenuItem;
miActions: TMenuItem;
mmSch: TMainMenu;
pmSch: TPopupMenu;
sgSch: TStringGrid;
procedure bCancelClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure MenuItem1Click(Sender: TObject);
procedure miAddTaskClick(Sender: TObject);
procedure miCopyTaskClick(Sender: TObject);
procedure miDelTaskClick(Sender: TObject);
procedure miEditTaskClick(Sender: TObject);
procedure pmiAddTaskClick(Sender: TObject);
procedure pmiCopyTaskClick(Sender: TObject);
procedure pmiDelTaskClick(Sender: TObject);
procedure pmiEditTaskClick(Sender: TObject);
procedure sgSchDblClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
fSchEditor: TfSchEditor;
IsSchEditorRuning:boolean;
COPYarrServerSch:array of TSchedulerEvent;
procedure StartSchEdit;
procedure RefreshList;
procedure AddEvent;
procedure EditEvent;
procedure CopyEvent;
procedure DelEvent;
function EventNameUsed(event_name,initial_event_name:string):boolean;
implementation
uses uMain;
{$R *.lfm}
{ TfSchEditor }
function EventNameUsed(event_name,initial_event_name:string):boolean;
var
x:integer;
begin
result:=false;
if UPPERCASE(event_name)=UPPERCASE(initial_event_name) then
begin
exit;
end;
for x:=1 to length(COPYarrServerSch) do
begin
if UPPERCASE(event_name)=UPPERCASE(COPYarrServerSch[x-1].event_name) then
begin
result:=true;
exit;
end;
end;
end;
procedure TfSchEditor.miAddTaskClick(Sender: TObject);
begin
AddEvent;
end;
procedure TfSchEditor.miCopyTaskClick(Sender: TObject);
begin
CopyEvent;
end;
procedure TfSchEditor.miDelTaskClick(Sender: TObject);
begin
DelEvent;
end;
procedure TfSchEditor.miEditTaskClick(Sender: TObject);
begin
EditEvent;
end;
procedure TfSchEditor.pmiAddTaskClick(Sender: TObject);
begin
AddEvent;
end;
procedure TfSchEditor.pmiCopyTaskClick(Sender: TObject);
begin
CopyEvent;
end;
procedure TfSchEditor.pmiDelTaskClick(Sender: TObject);
begin
DelEvent;
end;
procedure TfSchEditor.pmiEditTaskClick(Sender: TObject);
begin
EditEvent;
end;
procedure TfSchEditor.sgSchDblClick(Sender: TObject);
begin
EditEvent;
end;
procedure StartSchEdit;
var
x:integer;
begin
if IsSchEditorRuning then
begin
fSchEditor.SetFocus;
end
else
begin
Setlength(COPYarrServerSch,length(uMain.arrServerSch));
for x:=1 to length(uMain.arrServerSch) do
begin
COPYarrServerSch[x-1]:=uMain.arrServerSch[x-1];
end;
Setlength(COPYarrServerBatchList,length(uMain.arrServerBatchList));
for x:=1 to length(uMain.arrServerBatchList) do
begin
COPYarrServerBatchList[x-1]:=uMain.arrServerBatchList[x-1];
end;
Application.CreateForm(TfSchEditor, fSchEditor);
RefreshList;
IsSchEditorRuning:=true;
fSchEditor.Show;
end;
end;
procedure TfSchEditor.FormClose(Sender: TObject; var CloseAction: TCloseAction
);
begin
IsSchEditorRuning:=false;
CloseAction:=caFree;
end;
procedure TfSchEditor.MenuItem1Click(Sender: TObject);
begin
end;
procedure TfSchEditor.bCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfSchEditor.bOKClick(Sender: TObject);
var
x:integer;
begin
Setlength(uMain.arrServerBatchList,length(uBchEditor.COPYarrServerBatchList));
for x:=1 to length(uBchEditor.COPYarrServerBatchList) do
begin
uMain.arrServerBatchList[x-1]:=uBchEditor.COPYarrServerBatchList[x-1];
end;
Setlength(uMain.arrServerAlarmList,length(uAlarmTemplateEditor.COPYarrServerAlarmList));
for x:=1 to length(uAlarmTemplateEditor.COPYarrServerAlarmList) do
begin
uMain.arrServerAlarmList[x-1]:=uAlarmTemplateEditor.COPYarrServerAlarmList[x-1];
end;
Setlength(uMain.arrServerSch,length(COPYarrServerSch));
for x:=1 to length(COPYarrServerSch) do
begin
uMain.arrServerSch[x-1]:=COPYarrServerSch[x-1];
end;
WaitSocketForOp(6); // save schedule and batch list to server
close;
end;
procedure RefreshList;
var
x,l,r:integer;
event_type_text:string;
begin
r:=fSchEditor.sgSch.Row;
l:=length(COPYarrServerSch);
fSchEditor.sgSch.RowCount:=max(l+1,2);
if l=0 then
begin
fSchEditor.sgSch.Cells[0,1]:='';
fSchEditor.sgSch.Cells[1,1]:='';
end;
for x:=1 to l do
begin
event_type_text:=uEventClassifier.GetEventNameFromID(uEventClassifier.GetEventTypePart(COPYarrServerSch[x-1].event_str));
fSchEditor.sgSch.Cells[0,x]:=COPYarrServerSch[x-1].event_name;
fSchEditor.sgSch.Cells[1,x]:=event_type_text;
end;
fSchEditor.sgSch.Row:=r;
end;
procedure EditEvent;
var
r:integer;
e_res:TEventResult;
begin
r:=fSchEditor.sgSch.Row;
if r<1 then
begin
ShowMessage('Select task first!');
exit;
end;
if r>Length(COPYarrServerSch) then
begin
ShowMessage('Select task first!');
exit;
end;
e_res:=uEditEvent.EditEvent(COPYarrServerSch[r-1]);
if e_res.res then
begin
COPYarrServerSch[r-1]:=e_res.er_event;
RefreshList;
end;
end;
procedure CopyEvent;
var
r:integer;
e_res:TEventResult;
e:TSchedulerEvent;
begin
r:=fSchEditor.sgSch.Row;
if r<1 then
begin
ShowMessage('Select task first!');
exit;
end;
if r>Length(COPYarrServerSch) then
begin
ShowMessage('Select task first!');
exit;
end;
e:=COPYarrServerSch[r-1];
e.event_name:='';
e_res:=uEditEvent.EditEvent(e);
if e_res.res then
begin
setlength(COPYarrServerSch,length(COPYarrServerSch)+1);
COPYarrServerSch[length(COPYarrServerSch)-1]:=e_res.er_event;
RefreshList;
end;
end;
procedure AddEvent;
var
e_res:TEventResult;
e_src:TSchedulerEvent;
begin
e_src.event_alarm_str:='';
e_src.event_execution_str:='0'+ParamLimiter+'0'+ParamLimiter+'';
e_src.event_main_param:='';
e_src.event_name:='';
e_src.event_str:='4'+ParamLimiter+'1'+ParamLimiter+'1'+ParamLimiter+
'1/1'+ParamLimiter+'0'+ParamLimiter+'0'+ParamLimiter+''+ParamLimiter;
e_src.ev_days_of_month:='01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,';
e_src.ev_days_of_week:='1,2,3,4,5,6,7';
e_src.ev_end_time_h:=23;
e_src.ev_end_time_m:=59;
e_src.ev_end_time_s:=59;
e_src.ev_time_h:=0;
e_src.ev_time_m:=0;
e_src.ev_time_s:=0;
e_src.ev_repeat_interval:=3600;
e_src.ev_repeat_type:=1;
e_res:=uEditEvent.EditEvent(e_src);
if e_res.res then
begin
setlength(COPYarrServerSch,length(COPYarrServerSch)+1);
COPYarrServerSch[length(COPYarrServerSch)-1]:=e_res.er_event;
RefreshList;
end;
end;
procedure DelEvent;
var
r:integer;
x:integer;
begin
r:=fSchEditor.sgSch.Row;
if r<1 then
begin
ShowMessage('Select task first!');
exit;
end;
if r>Length(COPYarrServerSch) then
begin
ShowMessage('Select task first!');
exit;
end;
if MessageDlg('Are you sure?','Delete task '+COPYarrServerSch[r-1].event_name+'?',mtConfirmation,[mbYes, mbNo],0)=mrYes then
begin
for x:=r to Length(COPYarrServerSch)-1 do
begin
COPYarrServerSch[x-1]:=COPYarrServerSch[x];
end;
SetLength(COPYarrServerSch,Length(COPYarrServerSch)-1);
RefreshList;
end;
end;
end.
|
{Created by mwSynGen}
{+--------------------------------------------------------------------------+
| Unit: mwGeneralSyn
| Created: 12.98
| Last change: 1999-11-11
| Author: Martin Waldenburg
| Copyright 1998, No rights reserved.
| Description: A general HighLighter for Use with mwCustomEdit.
| The KeyWords in the string list KeyWords have to be UpperCase and sorted.
| Version: 0.73
| Status Public Domain
| DISCLAIMER: This is provided as is, expressly without a warranty of any kind.
| You use it at your own risc.
|
| Thanks to: Primoz Gabrijelcic, James Jacobson, Kees van Spelde, Andy Jeffries
|
| Version history: see version.rtf
|
+--------------------------------------------------------------------------+}
unit mwGeneralSyn;
interface
uses
SysUtils, Windows, Messages, Classes, Controls, Graphics, Registry,
mwHighlighter, mwLocalStr,
mwExport;
Type
TtkTokenKind = (
tkComment,
tkIdentifier,
tkKey,
tkNull,
tkNumber,
tkSpace,
tkString,
tkSymbol,
tkUnknown);
TCommentStyle = (csAnsiStyle, csPasStyle, csCStyle, csAsmStyle, csBasStyle);
CommentStyles = Set of TCommentStyle;
TRangeState = (rsANil, rsAnsi, rsPasStyle, rsCStyle, rsUnKnown);
TStringDelim = (sdSingleQuote, sdDoubleQuote);
TProcTableProc = procedure of Object;
type
TmwGeneralSyn = class(TmwCustomHighLighter)
private
fRange: TRangeState;
fLine: PChar;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fLineNumber : Integer;
fStringAttri: TmwHighLightAttributes;
fSymbolAttri: TmwHighLightAttributes;
fKeyAttri: TmwHighLightAttributes;
fNumberAttri: TmwHighLightAttributes;
fCommentAttri: TmwHighLightAttributes;
fSpaceAttri: TmwHighLightAttributes;
fIdentifierAttri: TmwHighLightAttributes;
fKeyWords: TStrings;
fComments: CommentStyles;
fStringDelimCh: char;
fIdentChars: TIdentChars;
procedure AsciiCharProc;
procedure BraceOpenProc;
procedure PointCommaProc;
procedure CRProc;
procedure IdentProc;
procedure IntegerProc;
procedure LFProc;
procedure NullProc;
procedure NumberProc;
procedure RoundOpenProc;
procedure SlashProc;
procedure SpaceProc;
procedure StringProc;
procedure UnknownProc;
procedure MakeMethodTables;
function IsKeyWord(aToken: String): Boolean;
procedure AnsiProc;
procedure PasStyleProc;
procedure CStyleProc;
procedure SetKeyWords(const Value: TStrings);
procedure SetComments(Value: CommentStyles);
function GetStringDelim: TStringDelim;
procedure SetStringDelim(const Value: TStringDelim);
function GetIdentifierChars: string;
procedure SetIdentifierChars(const Value: string);
protected
function GetLanguageName: string; override;
function GetIdentChars: TIdentChars; override;
function GetCapability: THighlighterCapability; override;
public
constructor Create(AOwner: TComponent); override;
procedure ExportNext;override;
destructor Destroy; override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetTokenID: TtkTokenKind;
procedure SetLine(NewValue: String; LineNumber:Integer); override;
function GetToken: String; override;
function GetTokenAttribute: TmwHighLightAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
procedure SetLineForExport(NewValue: String); override;
procedure SetRange(Value: Pointer); override;
procedure ReSetRange; override;
function SaveToRegistry(RootKey: HKEY; Key: string): boolean; override;
function LoadFromRegistry(RootKey: HKEY; Key: string): boolean; override;
published
property Comments: CommentStyles read fComments write SetComments;
property CommentAttri: TmwHighLightAttributes read fCommentAttri write fCommentAttri;
property IdentifierAttri: TmwHighLightAttributes read fIdentifierAttri write fIdentifierAttri;
property IdentifierChars: string read GetIdentifierChars write SetIdentifierChars;
property KeyAttri: TmwHighLightAttributes read fKeyAttri write fKeyAttri;
property KeyWords: TStrings read fKeyWords write SetKeyWords;
property NumberAttri: TmwHighLightAttributes read fNumberAttri write fNumberAttri;
property SpaceAttri: TmwHighLightAttributes read fSpaceAttri write fSpaceAttri;
property StringAttri: TmwHighLightAttributes read fStringAttri write fStringAttri;
property SymbolAttri: TmwHighLightAttributes read fSymbolAttri write fSymbolAttri;
property StringDelim: TStringDelim read GetStringDelim write SetStringDelim
default sdSingleQuote;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents(MWS_HighlightersPage, [TmwGeneralSyn]);
end;
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable: array[#0..#255] of Integer;
procedure MakeIdentTable;
var
I, J: Char;
begin
for I := #0 to #255 do
begin
Case I of
'_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True;
else Identifiers[I] := False;
end;
J := UpperCase(I)[1];
Case I in ['_', 'a'..'z', 'A'..'Z'] of
True: mHashTable[I] := Ord(J) - 64
else mHashTable[I] := 0;
end;
end;
end;
function TmwGeneralSyn.IsKeyWord(aToken: String): Boolean;
var
First, Last, I, Compare: Integer;
Token: String;
begin
First := 0;
Last := fKeywords.Count - 1;
Result := False;
Token := UpperCase(aToken);
while First <= Last do
begin
I := (First + Last) shr 1;
Compare := CompareStr(fKeywords[i], Token);
if Compare = 0 then
begin
Result := True;
break;
end
else
if Compare < 0 then First := I + 1 else Last := I - 1;
end;
end; { IsKeyWord }
procedure TmwGeneralSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
'#': fProcTable[I] := AsciiCharProc;
'{': fProcTable[I] := BraceOpenProc;
';': fProcTable[I] := PointCommaProc;
#13: fProcTable[I] := CRProc;
'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;
'$': fProcTable[I] := IntegerProc;
#10: fProcTable[I] := LFProc;
#0: fProcTable[I] := NullProc;
'0'..'9': fProcTable[I] := NumberProc;
'(': fProcTable[I] := RoundOpenProc;
'/': fProcTable[I] := SlashProc;
#1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;
else fProcTable[I] := UnknownProc;
end;
fProcTable[fStringDelimCh] := StringProc;
end;
function TmwGeneralSyn.GetCapability: THighlighterCapability;
begin
Result := inherited GetCapability + [hcExportable];
end;
constructor TmwGeneralSyn.Create(AOwner: TComponent);
begin
fKeyWords := TStringList.Create;
TStringList(fKeyWords).Sorted := True;
TStringList(fKeyWords).Duplicates := dupIgnore;
fCommentAttri := TmwHighLightAttributes.Create(MWS_AttrComment);
fCommentAttri.Style := [fsItalic];
fIdentifierAttri := TmwHighLightAttributes.Create(MWS_AttrIdentifier);
fKeyAttri := TmwHighLightAttributes.Create(MWS_AttrReservedWord);
fKeyAttri.Style := [fsBold];
fNumberAttri := TmwHighLightAttributes.Create(MWS_AttrNumber);
fSpaceAttri := TmwHighLightAttributes.Create(MWS_AttrSpace);
fStringAttri := TmwHighLightAttributes.Create(MWS_AttrString);
fSymbolAttri := TmwHighLightAttributes.Create(MWS_AttrSymbol);
inherited Create(AOwner);
AddAttribute(fCommentAttri);
AddAttribute(fIdentifierAttri);
AddAttribute(fKeyAttri);
AddAttribute(fNumberAttri);
AddAttribute(fSpaceAttri);
AddAttribute(fStringAttri);
AddAttribute(fSymbolAttri);
SetAttributesOnChange(DefHighlightChange);
fStringDelimCh := '''';
fIdentChars := inherited GetIdentChars;
MakeMethodTables;
fRange := rsUnknown;
end; { Create }
destructor TmwGeneralSyn.Destroy;
begin
fKeyWords.Free;
inherited Destroy;
end; { Destroy }
procedure TmwGeneralSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end; { SetLine }
procedure TmwGeneralSyn.AnsiProc;
begin
fTokenID := tkComment;
case FLine[Run] of
#0:
begin
NullProc;
exit;
end;
#10:
begin
LFProc;
exit;
end;
#13:
begin
CRProc;
exit;
end;
end;
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = ')' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TmwGeneralSyn.PasStyleProc;
begin
fTokenID := tkComment;
case FLine[Run] of
#0:
begin
NullProc;
exit;
end;
#10:
begin
LFProc;
exit;
end;
#13:
begin
CRProc;
exit;
end;
end;
while FLine[Run] <> #0 do
case FLine[Run] of
'}':
begin
fRange := rsUnKnown;
inc(Run);
break;
end;
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TmwGeneralSyn.CStyleProc;
begin
fTokenID := tkComment;
case FLine[Run] of
#0:
begin
NullProc;
exit;
end;
#10:
begin
LFProc;
exit;
end;
#13:
begin
CRProc;
exit;
end;
end;
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = '/' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TmwGeneralSyn.AsciiCharProc;
begin
fTokenID := tkString;
inc(Run);
while FLine[Run] in ['0'..'9'] do inc(Run);
end;
procedure TmwGeneralSyn.BraceOpenProc;
begin
if csPasStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsPasStyle;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
'}':
begin
fRange := rsUnKnown;
inc(Run);
break;
end;
#10: break;
#13: break;
else inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TmwGeneralSyn.PointCommaProc;
begin
if (csASmStyle in fComments) or (csBasStyle in fComments) then
begin
fTokenID := tkComment;
fRange := rsUnknown;
inc(Run);
while FLine[Run] <> #0 do
begin
fTokenID := tkComment;
inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TmwGeneralSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure TmwGeneralSyn.IdentProc;
begin
while Identifiers[fLine[Run]] do inc(Run);
if IsKeyWord(GetToken) then fTokenId := tkKey else fTokenId := tkIdentifier;
end;
procedure TmwGeneralSyn.IntegerProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', 'A'..'F', 'a'..'f'] do inc(Run);
end;
procedure TmwGeneralSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TmwGeneralSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure TmwGeneralSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', '.', 'e', 'E'] do
begin
case FLine[Run] of
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
procedure TmwGeneralSyn.RoundOpenProc;
begin
inc(Run);
if csAnsiStyle in fComments then
begin
case fLine[Run] of
'*':
begin
fTokenID := tkComment;
fRange := rsAnsi;
inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = ')' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
'.':
begin
inc(Run);
fTokenID := tkSymbol;
end;
else
begin
FTokenID := tkSymbol;
end;
end;
end else fTokenId := tkSymbol;
end;
procedure TmwGeneralSyn.SlashProc;
begin
case FLine[Run + 1] of
'/':
begin
inc(Run, 2);
fTokenID := tkComment;
while FLine[Run] <> #0 do
begin
case FLine[Run] of
#10, #13: break;
end;
inc(Run);
end;
end;
'*':
begin
if csCStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsCStyle;
inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = '/' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end
else
begin
inc(Run);
fTokenId := tkSymbol;
end;
end;
else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
end;
procedure TmwGeneralSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run);
end;
procedure TmwGeneralSyn.StringProc;
begin
fTokenID := tkString;
if (fLine[Run + 1] = fStringDelimCh) and (fLine[Run + 2] = fStringDelimCh) then Inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
end;
inc(Run);
until FLine[Run] = fStringDelimCh;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TmwGeneralSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnKnown;
end;
procedure TmwGeneralSyn.Next;
begin
fTokenPos := Run;
Case fRange of
rsAnsi: AnsiProc;
rsPasStyle: PasStyleProc;
rsCStyle: CStyleProc;
else fProcTable[fLine[Run]];
end;
end;
function TmwGeneralSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function TmwGeneralSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TmwGeneralSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TmwGeneralSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TmwGeneralSyn.GetTokenAttribute: TmwHighLightAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fSymbolAttri;
else Result := nil;
end;
end;
function TmwGeneralSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TmwGeneralSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TmwGeneralSyn.ReSetRange;
begin
fRange := rsUnknown;
end;
procedure TmwGeneralSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
procedure TmwGeneralSyn.SetKeyWords(const Value: TStrings);
var
i: Integer;
begin
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do
Value[i] := UpperCase(Value[i]);
Value.EndUpdate;
end;
fKeyWords.Assign(Value);
DefHighLightChange(nil);
end;
procedure TmwGeneralSyn.SetComments(Value: CommentStyles);
begin
fComments := Value;
DefHighLightChange(nil);
end;
function TmwGeneralSyn.GetLanguageName: string;
begin
Result := MWS_LangGeneral;
end;
function TmwGeneralSyn.LoadFromRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r:= TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKeyReadOnly(Key) then begin
if r.ValueExists('KeyWords') then KeyWords.Text:= r.ReadString('KeyWords');
Result := inherited LoadFromRegistry(RootKey, Key);
end
else Result := false;
finally r.Free; end;
end;
function TmwGeneralSyn.SaveToRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r:= TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKey(Key,true) then begin
Result := true;
r.WriteString('KeyWords', KeyWords.Text);
Result := inherited SaveToRegistry(RootKey, Key);
end
else Result := false;
finally r.Free; end;
end;
function TmwGeneralSyn.GetStringDelim: TStringDelim;
begin
if fStringDelimCh = ''''
then Result := sdSingleQuote
else Result := sdDoubleQuote;
end;
procedure TmwGeneralSyn.SetStringDelim(const Value: TStringDelim);
var
newCh: char;
begin
case Value of
sdSingleQuote: newCh := '''';
else newCh := '"';
end; //case
if newCh <> fStringDelimCh then begin
fStringDelimCh := newCh;
MakeMethodTables;
end;
end;
function TmwGeneralSyn.GetIdentifierChars: string;
var
ch: char;
s: shortstring;
begin
s := '';
for ch := #0 to #255 do
if ch in fIdentChars then s := s + ch;
Result := s;
end;
procedure TmwGeneralSyn.SetIdentifierChars(const Value: string);
var
i: integer;
begin
fIdentChars := [];
for i := 1 to Length(Value) do begin
fIdentChars := fIdentChars + [Value[i]];
end; //for
end;
function TmwGeneralSyn.GetIdentChars: TIdentChars;
begin
Result := fIdentChars;
end;
procedure TmwGeneralSyn.SetLineForExport(NewValue: String);
begin
fLine := PChar(NewValue);
Run := 0;
ExportNext;
end; { SetLineForExport }
procedure TmwGeneralSyn.ExportNext;
begin
fTokenPos := Run;
Case fRange of
rsAnsi: AnsiProc;
rsPasStyle: PasStyleProc;
rsCStyle: CStyleProc;
else fProcTable[fLine[Run]];
end;
if Assigned(Exporter) then
with TmwCustomExport(Exporter) do begin
Case GetTokenID of
tkComment:FormatToken(GetToken, fCommentAttri, True,False);
tkIdentifier:FormatToken(GetToken, fIdentifierAttri, False,False);
tkKey:FormatToken(GetToken, fKeyAttri, False,False);
tkNumber:FormatToken(GetToken, fNumberAttri, False,False);
{Needed to catch Line breaks}
tkNull:FormatToken('', nil, False,False);
tkSpace:FormatToken(GetToken, fSpaceAttri, False,True);
tkString:FormatToken(GetToken, fStringAttri, True,False);
tkSymbol:FormatToken(GetToken, fSymbolAttri,True,False);
tkUnknown:FormatToken(GetToken, fSymbolAttri, True,False);
end;
end; //with
end;
Initialization
MakeIdentTable;
end.
|
unit Parameter;
interface
uses Registrator, BaseObjects, Classes, ClientCommon, SysUtils, MeasureUnits, ComCtrls;
type
TParameterValuesByWell = class;
TParameter = class(TRegisteredIDObject)
private
FRefCount: integer;
FMeasureUnit: TMeasureUnit;
procedure SetMeasureUnit(const Value: TMeasureUnit);
protected
procedure AssignTo(Dest: TPersistent); override;
public
property RefCount: integer read FRefCount write FRefCount;
property MeasureUnit: TMeasureUnit read FMeasureUnit write SetMeasureUnit;
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
end;
TParameters = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TParameter;
public
property Items[Index: integer]: TParameter read GetItems;
constructor Create; override;
end;
TParameterValue = class(TRegisteredIDObject)
private
FValue: variant;
FParameter: TParameter;
FNumValue: single;
FNumber: integer;
procedure SetParameter(const Value: TParameter);
procedure SetValue(const Value: variant);
protected
procedure AssignTo(Dest: TPersistent); override;
public
property Number: integer read FNumber write FNumber;
property Parameter: TParameter read FParameter write SetParameter;
property Value: variant read FValue write SetValue;
property NumValue: single read FNumValue write FNumValue;
function List(AListOption: TListOption = loBrief): string; override;
function AsString: string;
constructor Create(ACollection: TIDObjects); override;
end;
TParameterValues = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TParameterValue;
public
procedure Delete(Index: integer); override;
function Remove(AObject: TObject): Integer; override;
function Add: TIDObject; override;
function ParameterValueByParameter(AParameter: TParameter): TParameterValue;
property Items[Index: integer]: TParameterValue read GetItems;
constructor Create; override;
end;
// параметры по скважине
TParameterByWell = class(TRegisteredIDObject)
private
FValues: TParameterValuesByWell;
FMeasureUnit: TMeasureUnit;
function GetValues: TParameterValuesByWell;
protected
procedure AssignTo(Dest: TPersistent); override;
public
property MeasureUnit: TMeasureUnit read FMeasureUnit write FMeasureUnit;
property Values: TParameterValuesByWell read GetValues write FValues;
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
end;
TParametersByWell = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TParameterByWell;
public
property Items[Index: integer]: TParameterByWell read GetItems;
constructor Create; override;
end;
// группы параметров по скважине
TParametersGroupByWell = class(TRegisteredIDObject)
private
FParameters: TParametersByWell;
function GetParameters: TParametersByWell;
public
property Parameters: TParametersByWell read GetParameters;
constructor Create(ACollection: TIDObjects); override;
end;
TParametersGroupsByWell = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TParametersGroupByWell;
public
property Items[Index: integer]: TParametersGroupByWell read GetItems;
procedure MakeList(ATreeView: TTreeView; NeedsRegistering: boolean = true; NeedsClearing: boolean = false; CreateFakeNode: Boolean = true); override;
constructor Create; override;
end;
TParameterValueByWell = class(TRegisteredIDObject)
private
FINTValue: integer;
FVCHValue: String;
FDTMValue: TDateTime;
FParametrWell: TParameterByWell;
protected
procedure AssignTo(Dest: TPersistent); override;
public
// числовое значение
property INTValue: integer read FINTValue write FINTValue;
// строковое значение
property VCHValue: String read FVCHValue write FVCHValue;
// дата
property DTMValue: TDateTime read FDTMValue write FDTMValue;
// тип параметра
property ParametrWell: TParameterByWell read FParametrWell write FParametrWell;
//WELL_UIN,
//REASON_CHANGE_ID,
//DICT_VALUE_ID,
//TABLE_ID
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
end;
TParameterValuesByWell = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TParameterValueByWell;
public
property Items[Index: integer]: TParameterValueByWell read GetItems;
constructor Create; override;
end;
implementation
uses Facade, ParameterPoster, Variants, Contnrs;
{ TParameter }
procedure TParameter.AssignTo(Dest: TPersistent);
begin
inherited;
(Dest as TParameter).FMeasureUnit := FMeasureUnit;
end;
constructor TParameter.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Параметр';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParameterDataPoster];
end;
function TParameter.List(AListOption: TListOption = loBrief): string;
begin
Result := Name;
if Assigned(MeasureUnit) then
Result := Result + '(' + MeasureUnit.Name + ')';
end;
procedure TParameter.SetMeasureUnit(const Value: TMeasureUnit);
begin
if FMeasureUnit <> Value then
begin
FMeasureUnit := Value;
if Assigned(Registrator) then Registrator.Update(Self, Self.Collection.Owner, ukUpdate);
end;
end;
{ TParameters }
constructor TParameters.Create;
begin
inherited;
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParameterDataPoster];
FObjectClass := TParameter;
end;
function TParameters.GetItems(Index: integer): TParameter;
begin
Result := inherited Items[Index] as TParameter;
end;
{ TParameterValue }
procedure TParameterValue.AssignTo(Dest: TPersistent);
var pv: TParameterValue;
begin
inherited;
pv := Dest as TParameterValue;
pv.Value := Value;
pv.Parameter := Parameter;
pv.NumValue := NumValue;
pv.Number := Number;
end;
function TParameterValue.AsString: string;
begin
Result := varAsType(Value, varOleStr);
end;
constructor TParameterValue.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Значение параметра';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParameterValueDataPoster];
end;
{ TParamterValues }
function TParameterValues.Add: TIDObject;
begin
Result := inherited Add as TIDObject;
end;
constructor TParameterValues.Create;
begin
inherited;
FObjectClass := TParameterValue;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TParameterValueDataPoster];
end;
procedure TParameterValues.Delete(Index: integer);
begin
if Assigned(Items[Index].Parameter) then Items[Index].Parameter.RefCount := Items[Index].Parameter.RefCount - 1;
inherited;
end;
function TParameterValues.GetItems(Index: integer): TParameterValue;
begin
Result := inherited Items[Index] as TParameterValue;
end;
function TParameterValues.ParameterValueByParameter(
AParameter: TParameter): TParameterValue;
var i: integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if Items[i].Parameter = AParameter then
begin
Result := Items[i];
break;
end;
end;
function TParameterValue.List(AListOption: TListOption = loBrief): string;
begin
if Assigned(Parameter) then
Result := Parameter.List + '[' + IntToStr(Number) + ']' + ' = ' + AsString
else
Result := '';
end;
procedure TParameterValue.SetParameter(const Value: TParameter);
var i, iNum: integer;
begin
if FParameter <> Value then
begin
FParameter := Value;
FParameter.RefCount := FParameter.RefCount + 1;
if Assigned(Collection) then
begin
iNum := 0;
for i := 0 to Collection.Count - 1 do
if (Collection.Items[i] as TParameterValue).Parameter = FParameter then
inc(iNum);
Number := iNum + 1;
end;
end;
end;
function TParameterValues.Remove(AObject: TObject): Integer;
begin
if Assigned((AObject as TParameterValue).Parameter) then (AObject as TParameterValue).Parameter.RefCount := (AObject as TParameterValue).Parameter.RefCount - 1;
Result := inherited Remove(AObject);
end;
procedure TParameterValue.SetValue(const Value: variant);
begin
if FValue <> Value then
begin
FValue := Value;
FNumValue := ExtractFloat(FValue);
end;
end;
{ TParameterValuesByWell }
constructor TParameterValuesByWell.Create;
begin
inherited;
FObjectClass := TParameterValueByWell;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TParameterValueByWellDataPoster];
end;
function TParameterValuesByWell.GetItems(
Index: integer): TParameterValueByWell;
begin
Result := inherited Items[Index] as TParameterValueByWell;
end;
{ TParameterValueByWell }
procedure TParameterValueByWell.AssignTo(Dest: TPersistent);
var p: TParameterValueByWell;
begin
inherited;
p := Dest as TParameterValueByWell;
p.INTValue := INTValue;
p.VCHValue := VCHValue;
p.DTMValue := DTMValue;
p.ParametrWell := ParametrWell;
end;
constructor TParameterValueByWell.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Значение параметра по скважине';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParameterValueByWellDataPoster];
end;
function TParameterValueByWell.List(AListOption: TListOption): string;
begin
Result := Name;
end;
{ TParametersByWell }
constructor TParametersByWell.Create;
begin
inherited;
FObjectClass := TParameterByWell;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TParameterByWellDataPoster];
end;
function TParametersByWell.GetItems(Index: integer): TParameterByWell;
begin
Result := inherited Items[Index] as TParameterByWell;
end;
{ TParameterByWell }
procedure TParameterByWell.AssignTo(Dest: TPersistent);
var o : TParameterByWell;
begin
inherited;
o := Dest as TParameterByWell;
o.FMeasureUnit := MeasureUnit;
end;
constructor TParameterByWell.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Параметр скважины';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParameterByWellDataPoster];
end;
function TParameterByWell.GetValues: TParameterValuesByWell;
begin
if not Assigned (FValues) then
begin
FValues := TParameterValuesByWell.Create;
FValues.Owner := Self;
FValues.Reload('PARAMETR_ID = ' + IntToStr(ID));
end;
Result := FValues;
end;
function TParameterByWell.List(AListOption: TListOption): string;
begin
Result := Name;
end;
{ TParametersGroupByWell }
constructor TParametersGroupByWell.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Группа параметров';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TParametersGroupByWellDataPoster];
end;
function TParametersGroupByWell.GetParameters: TParametersByWell;
begin
if not Assigned (FParameters) then
begin
FParameters := TParametersByWell.Create;
FParameters.Owner := Self;
FParameters.OwnsObjects := true;
FParameters.Reload('PARAMETR_GROUPS_ID = ' + IntToStr(ID));
end;
Result := FParameters;
end;
{ TParametersGroupsByWell }
constructor TParametersGroupsByWell.Create;
begin
inherited;
FObjectClass := TParametersGroupByWell;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TParametersGroupByWellDataPoster];
end;
function TParametersGroupsByWell.GetItems(
Index: integer): TParametersGroupByWell;
begin
Result := inherited Items[Index] as TParametersGroupByWell;
end;
procedure TParametersGroupsByWell.MakeList(ATreeView: TTreeView;
NeedsRegistering, NeedsClearing, CreateFakeNode: boolean);
var i, j : integer;
Node: TTreeNode;
begin
if NeedsClearing then ATreeView.Items.Clear;
for i := 0 to Count - 1 do
begin
Node := ATreeView.Items.AddObject(nil, Items[i].List, Items[i]);
for j := 0 to Items[i].Parameters.Count - 1 do
ATreeView.Items.AddChildObject(Node, Items[i].Parameters.Items[j].List, Items[i].Parameters.Items[j]);
// if Assigned(FOnObjectViewAdd) then FOnObjectViewAdd(Node, Items[i]);
end;
if Assigned(Registrator) and NeedsRegistering then Registrator.Add(TTreeViewRegisteredObject, ATreeView, Self);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.